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.

278632 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. #include <Carbon/Carbon.h>
  727. #endif
  728. #include <sys/dir.h>
  729. #endif
  730. #include <sys/socket.h>
  731. #include <sys/sysctl.h>
  732. #include <sys/stat.h>
  733. #include <sys/param.h>
  734. #include <sys/mount.h>
  735. #include <fnmatch.h>
  736. #include <utime.h>
  737. #include <dlfcn.h>
  738. #include <ifaddrs.h>
  739. #include <net/if_dl.h>
  740. #include <mach/mach_time.h>
  741. #include <mach-o/dyld.h>
  742. #if MACOS_10_4_OR_EARLIER
  743. #include <GLUT/glut.h>
  744. #endif
  745. #if ! CGFLOAT_DEFINED
  746. #define CGFloat float
  747. #endif
  748. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  749. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  750. #else
  751. #error "Unknown platform!"
  752. #endif
  753. #endif
  754. //==============================================================================
  755. #define DONT_SET_USING_JUCE_NAMESPACE 1
  756. #undef max
  757. #undef min
  758. #define NO_DUMMY_DECL
  759. #if JUCE_BUILD_NATIVE
  760. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  761. #endif
  762. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  763. #pragma warning (disable: 4309 4305)
  764. #endif
  765. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  766. BEGIN_JUCE_NAMESPACE
  767. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  768. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  769. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  770. /**
  771. Creates a floating carbon window that can be used to hold a carbon UI.
  772. This is a handy class that's designed to be inlined where needed, e.g.
  773. in the audio plugin hosting code.
  774. */
  775. class CarbonViewWrapperComponent : public Component,
  776. public ComponentMovementWatcher,
  777. public Timer
  778. {
  779. public:
  780. CarbonViewWrapperComponent()
  781. : ComponentMovementWatcher (this),
  782. wrapperWindow (0),
  783. carbonWindow (0),
  784. embeddedView (0),
  785. recursiveResize (false)
  786. {
  787. }
  788. virtual ~CarbonViewWrapperComponent()
  789. {
  790. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  791. }
  792. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  793. virtual void removeView (HIViewRef embeddedView) = 0;
  794. virtual void mouseDown (int, int) {}
  795. virtual void paint() {}
  796. virtual bool getEmbeddedViewSize (int& w, int& h)
  797. {
  798. if (embeddedView == 0)
  799. return false;
  800. HIRect bounds;
  801. HIViewGetBounds (embeddedView, &bounds);
  802. w = jmax (1, roundToInt (bounds.size.width));
  803. h = jmax (1, roundToInt (bounds.size.height));
  804. return true;
  805. }
  806. void createWindow()
  807. {
  808. if (wrapperWindow == 0)
  809. {
  810. Rect r;
  811. r.left = getScreenX();
  812. r.top = getScreenY();
  813. r.right = r.left + getWidth();
  814. r.bottom = r.top + getHeight();
  815. CreateNewWindow (kDocumentWindowClass,
  816. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  817. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  818. &r, &wrapperWindow);
  819. jassert (wrapperWindow != 0);
  820. if (wrapperWindow == 0)
  821. return;
  822. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  823. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  824. [ownerWindow addChildWindow: carbonWindow
  825. ordered: NSWindowAbove];
  826. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  827. EventTypeSpec windowEventTypes[] =
  828. {
  829. { kEventClassWindow, kEventWindowGetClickActivation },
  830. { kEventClassWindow, kEventWindowHandleDeactivate },
  831. { kEventClassWindow, kEventWindowBoundsChanging },
  832. { kEventClassMouse, kEventMouseDown },
  833. { kEventClassMouse, kEventMouseMoved },
  834. { kEventClassMouse, kEventMouseDragged },
  835. { kEventClassMouse, kEventMouseUp},
  836. { kEventClassWindow, kEventWindowDrawContent },
  837. { kEventClassWindow, kEventWindowShown },
  838. { kEventClassWindow, kEventWindowHidden }
  839. };
  840. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  841. InstallWindowEventHandler (wrapperWindow, upp,
  842. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  843. windowEventTypes, this, &eventHandlerRef);
  844. setOurSizeToEmbeddedViewSize();
  845. setEmbeddedWindowToOurSize();
  846. creationTime = Time::getCurrentTime();
  847. }
  848. }
  849. void deleteWindow()
  850. {
  851. removeView (embeddedView);
  852. embeddedView = 0;
  853. if (wrapperWindow != 0)
  854. {
  855. RemoveEventHandler (eventHandlerRef);
  856. DisposeWindow (wrapperWindow);
  857. wrapperWindow = 0;
  858. }
  859. }
  860. void setOurSizeToEmbeddedViewSize()
  861. {
  862. int w, h;
  863. if (getEmbeddedViewSize (w, h))
  864. {
  865. if (w != getWidth() || h != getHeight())
  866. {
  867. startTimer (50);
  868. setSize (w, h);
  869. if (getParentComponent() != 0)
  870. getParentComponent()->setSize (w, h);
  871. }
  872. else
  873. {
  874. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  875. }
  876. }
  877. else
  878. {
  879. stopTimer();
  880. }
  881. }
  882. void setEmbeddedWindowToOurSize()
  883. {
  884. if (! recursiveResize)
  885. {
  886. recursiveResize = true;
  887. if (embeddedView != 0)
  888. {
  889. HIRect r;
  890. r.origin.x = 0;
  891. r.origin.y = 0;
  892. r.size.width = (float) getWidth();
  893. r.size.height = (float) getHeight();
  894. HIViewSetFrame (embeddedView, &r);
  895. }
  896. if (wrapperWindow != 0)
  897. {
  898. Rect wr;
  899. wr.left = getScreenX();
  900. wr.top = getScreenY();
  901. wr.right = wr.left + getWidth();
  902. wr.bottom = wr.top + getHeight();
  903. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  904. ShowWindow (wrapperWindow);
  905. }
  906. recursiveResize = false;
  907. }
  908. }
  909. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  910. {
  911. setEmbeddedWindowToOurSize();
  912. }
  913. void componentPeerChanged()
  914. {
  915. deleteWindow();
  916. createWindow();
  917. }
  918. void componentVisibilityChanged (Component&)
  919. {
  920. if (isShowing())
  921. createWindow();
  922. else
  923. deleteWindow();
  924. setEmbeddedWindowToOurSize();
  925. }
  926. static void recursiveHIViewRepaint (HIViewRef view)
  927. {
  928. HIViewSetNeedsDisplay (view, true);
  929. HIViewRef child = HIViewGetFirstSubview (view);
  930. while (child != 0)
  931. {
  932. recursiveHIViewRepaint (child);
  933. child = HIViewGetNextView (child);
  934. }
  935. }
  936. void timerCallback()
  937. {
  938. setOurSizeToEmbeddedViewSize();
  939. // To avoid strange overpainting problems when the UI is first opened, we'll
  940. // repaint it a few times during the first second that it's on-screen..
  941. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  942. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  943. }
  944. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  945. {
  946. switch (GetEventKind (event))
  947. {
  948. case kEventWindowHandleDeactivate:
  949. ActivateWindow (wrapperWindow, TRUE);
  950. return noErr;
  951. case kEventWindowGetClickActivation:
  952. {
  953. getTopLevelComponent()->toFront (false);
  954. [carbonWindow makeKeyAndOrderFront: nil];
  955. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  956. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  957. sizeof (ClickActivationResult), &howToHandleClick);
  958. HIViewSetNeedsDisplay (embeddedView, true);
  959. return noErr;
  960. }
  961. }
  962. return eventNotHandledErr;
  963. }
  964. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  965. {
  966. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  967. }
  968. protected:
  969. WindowRef wrapperWindow;
  970. NSWindow* carbonWindow;
  971. HIViewRef embeddedView;
  972. bool recursiveResize;
  973. Time creationTime;
  974. EventHandlerRef eventHandlerRef;
  975. };
  976. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  977. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  978. END_JUCE_NAMESPACE
  979. #endif
  980. #define JUCE_AMALGAMATED_TEMPLATE 1
  981. //==============================================================================
  982. #if JUCE_BUILD_CORE
  983. /*** Start of inlined file: juce_FileLogger.cpp ***/
  984. BEGIN_JUCE_NAMESPACE
  985. FileLogger::FileLogger (const File& logFile_,
  986. const String& welcomeMessage,
  987. const int maxInitialFileSizeBytes)
  988. : logFile (logFile_)
  989. {
  990. if (maxInitialFileSizeBytes >= 0)
  991. trimFileSize (maxInitialFileSizeBytes);
  992. if (! logFile_.exists())
  993. {
  994. // do this so that the parent directories get created..
  995. logFile_.create();
  996. }
  997. String welcome;
  998. welcome << newLine
  999. << "**********************************************************" << newLine
  1000. << welcomeMessage << newLine
  1001. << "Log started: " << Time::getCurrentTime().toString (true, true) << newLine;
  1002. logMessage (welcome);
  1003. }
  1004. FileLogger::~FileLogger()
  1005. {
  1006. }
  1007. void FileLogger::logMessage (const String& message)
  1008. {
  1009. DBG (message);
  1010. const ScopedLock sl (logLock);
  1011. FileOutputStream out (logFile, 256);
  1012. out << message << newLine;
  1013. }
  1014. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1015. {
  1016. if (maxFileSizeBytes <= 0)
  1017. {
  1018. logFile.deleteFile();
  1019. }
  1020. else
  1021. {
  1022. const int64 fileSize = logFile.getSize();
  1023. if (fileSize > maxFileSizeBytes)
  1024. {
  1025. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1026. jassert (in != 0);
  1027. if (in != 0)
  1028. {
  1029. in->setPosition (fileSize - maxFileSizeBytes);
  1030. String content;
  1031. {
  1032. MemoryBlock contentToSave;
  1033. contentToSave.setSize (maxFileSizeBytes + 4);
  1034. contentToSave.fillWith (0);
  1035. in->read (contentToSave.getData(), maxFileSizeBytes);
  1036. in = 0;
  1037. content = contentToSave.toString();
  1038. }
  1039. int newStart = 0;
  1040. while (newStart < fileSize
  1041. && content[newStart] != '\n'
  1042. && content[newStart] != '\r')
  1043. ++newStart;
  1044. logFile.deleteFile();
  1045. logFile.appendText (content.substring (newStart), false, false);
  1046. }
  1047. }
  1048. }
  1049. }
  1050. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1051. const String& logFileName,
  1052. const String& welcomeMessage,
  1053. const int maxInitialFileSizeBytes)
  1054. {
  1055. #if JUCE_MAC
  1056. File logFile ("~/Library/Logs");
  1057. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1058. .getChildFile (logFileName);
  1059. #else
  1060. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1061. if (logFile.isDirectory())
  1062. {
  1063. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1064. .getChildFile (logFileName);
  1065. }
  1066. #endif
  1067. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1068. }
  1069. END_JUCE_NAMESPACE
  1070. /*** End of inlined file: juce_FileLogger.cpp ***/
  1071. /*** Start of inlined file: juce_Logger.cpp ***/
  1072. BEGIN_JUCE_NAMESPACE
  1073. Logger::Logger()
  1074. {
  1075. }
  1076. Logger::~Logger()
  1077. {
  1078. }
  1079. Logger* Logger::currentLogger = 0;
  1080. void Logger::setCurrentLogger (Logger* const newLogger,
  1081. const bool deleteOldLogger)
  1082. {
  1083. Logger* const oldLogger = currentLogger;
  1084. currentLogger = newLogger;
  1085. if (deleteOldLogger)
  1086. delete oldLogger;
  1087. }
  1088. void Logger::writeToLog (const String& message)
  1089. {
  1090. if (currentLogger != 0)
  1091. currentLogger->logMessage (message);
  1092. else
  1093. outputDebugString (message);
  1094. }
  1095. #if JUCE_LOG_ASSERTIONS
  1096. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1097. {
  1098. String m ("JUCE Assertion failure in ");
  1099. m << filename << ", line " << lineNum;
  1100. Logger::writeToLog (m);
  1101. }
  1102. #endif
  1103. END_JUCE_NAMESPACE
  1104. /*** End of inlined file: juce_Logger.cpp ***/
  1105. /*** Start of inlined file: juce_Random.cpp ***/
  1106. BEGIN_JUCE_NAMESPACE
  1107. Random::Random (const int64 seedValue) throw()
  1108. : seed (seedValue)
  1109. {
  1110. }
  1111. Random::~Random() throw()
  1112. {
  1113. }
  1114. void Random::setSeed (const int64 newSeed) throw()
  1115. {
  1116. seed = newSeed;
  1117. }
  1118. void Random::combineSeed (const int64 seedValue) throw()
  1119. {
  1120. seed ^= nextInt64() ^ seedValue;
  1121. }
  1122. void Random::setSeedRandomly()
  1123. {
  1124. combineSeed ((int64) (pointer_sized_int) this);
  1125. combineSeed (Time::getMillisecondCounter());
  1126. combineSeed (Time::getHighResolutionTicks());
  1127. combineSeed (Time::getHighResolutionTicksPerSecond());
  1128. combineSeed (Time::currentTimeMillis());
  1129. }
  1130. int Random::nextInt() throw()
  1131. {
  1132. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1133. return (int) (seed >> 16);
  1134. }
  1135. int Random::nextInt (const int maxValue) throw()
  1136. {
  1137. jassert (maxValue > 0);
  1138. return (nextInt() & 0x7fffffff) % maxValue;
  1139. }
  1140. int64 Random::nextInt64() throw()
  1141. {
  1142. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1143. }
  1144. bool Random::nextBool() throw()
  1145. {
  1146. return (nextInt() & 0x80000000) != 0;
  1147. }
  1148. float Random::nextFloat() throw()
  1149. {
  1150. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1151. }
  1152. double Random::nextDouble() throw()
  1153. {
  1154. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1155. }
  1156. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1157. {
  1158. BigInteger n;
  1159. do
  1160. {
  1161. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1162. }
  1163. while (n >= maximumValue);
  1164. return n;
  1165. }
  1166. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1167. {
  1168. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1169. while ((startBit & 31) != 0 && numBits > 0)
  1170. {
  1171. arrayToChange.setBit (startBit++, nextBool());
  1172. --numBits;
  1173. }
  1174. while (numBits >= 32)
  1175. {
  1176. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1177. startBit += 32;
  1178. numBits -= 32;
  1179. }
  1180. while (--numBits >= 0)
  1181. arrayToChange.setBit (startBit + numBits, nextBool());
  1182. }
  1183. Random& Random::getSystemRandom() throw()
  1184. {
  1185. static Random sysRand (1);
  1186. return sysRand;
  1187. }
  1188. END_JUCE_NAMESPACE
  1189. /*** End of inlined file: juce_Random.cpp ***/
  1190. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1191. BEGIN_JUCE_NAMESPACE
  1192. RelativeTime::RelativeTime (const double seconds_) throw()
  1193. : seconds (seconds_)
  1194. {
  1195. }
  1196. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1197. : seconds (other.seconds)
  1198. {
  1199. }
  1200. RelativeTime::~RelativeTime() throw()
  1201. {
  1202. }
  1203. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1204. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1205. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw() { return RelativeTime (numberOfMinutes * 60.0); }
  1206. const RelativeTime RelativeTime::hours (const double numberOfHours) throw() { return RelativeTime (numberOfHours * (60.0 * 60.0)); }
  1207. const RelativeTime RelativeTime::days (const double numberOfDays) throw() { return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); }
  1208. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw() { return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); }
  1209. int64 RelativeTime::inMilliseconds() const throw() { return (int64) (seconds * 1000.0); }
  1210. double RelativeTime::inMinutes() const throw() { return seconds / 60.0; }
  1211. double RelativeTime::inHours() const throw() { return seconds / (60.0 * 60.0); }
  1212. double RelativeTime::inDays() const throw() { return seconds / (60.0 * 60.0 * 24.0); }
  1213. double RelativeTime::inWeeks() const throw() { return seconds / (60.0 * 60.0 * 24.0 * 7.0); }
  1214. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1215. {
  1216. if (seconds < 0.001 && seconds > -0.001)
  1217. return returnValueForZeroTime;
  1218. String result;
  1219. result.preallocateStorage (16);
  1220. if (seconds < 0)
  1221. result << '-';
  1222. int fieldsShown = 0;
  1223. int n = std::abs ((int) inWeeks());
  1224. if (n > 0)
  1225. {
  1226. result << n << (n == 1 ? TRANS(" week ")
  1227. : TRANS(" weeks "));
  1228. ++fieldsShown;
  1229. }
  1230. n = std::abs ((int) inDays()) % 7;
  1231. if (n > 0)
  1232. {
  1233. result << n << (n == 1 ? TRANS(" day ")
  1234. : TRANS(" days "));
  1235. ++fieldsShown;
  1236. }
  1237. if (fieldsShown < 2)
  1238. {
  1239. n = std::abs ((int) inHours()) % 24;
  1240. if (n > 0)
  1241. {
  1242. result << n << (n == 1 ? TRANS(" hr ")
  1243. : TRANS(" hrs "));
  1244. ++fieldsShown;
  1245. }
  1246. if (fieldsShown < 2)
  1247. {
  1248. n = std::abs ((int) inMinutes()) % 60;
  1249. if (n > 0)
  1250. {
  1251. result << n << (n == 1 ? TRANS(" min ")
  1252. : TRANS(" mins "));
  1253. ++fieldsShown;
  1254. }
  1255. if (fieldsShown < 2)
  1256. {
  1257. n = std::abs ((int) inSeconds()) % 60;
  1258. if (n > 0)
  1259. {
  1260. result << n << (n == 1 ? TRANS(" sec ")
  1261. : TRANS(" secs "));
  1262. ++fieldsShown;
  1263. }
  1264. if (fieldsShown == 0)
  1265. {
  1266. n = std::abs ((int) inMilliseconds()) % 1000;
  1267. if (n > 0)
  1268. result << n << TRANS(" ms");
  1269. }
  1270. }
  1271. }
  1272. }
  1273. return result.trimEnd();
  1274. }
  1275. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1276. {
  1277. seconds = other.seconds;
  1278. return *this;
  1279. }
  1280. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1281. {
  1282. seconds += timeToAdd.seconds;
  1283. return *this;
  1284. }
  1285. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1286. {
  1287. seconds -= timeToSubtract.seconds;
  1288. return *this;
  1289. }
  1290. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1291. {
  1292. seconds += secondsToAdd;
  1293. return *this;
  1294. }
  1295. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1296. {
  1297. seconds -= secondsToSubtract;
  1298. return *this;
  1299. }
  1300. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() == t2.inSeconds(); }
  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. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t += t2; }
  1307. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t -= t2; }
  1308. END_JUCE_NAMESPACE
  1309. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1310. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1311. BEGIN_JUCE_NAMESPACE
  1312. SystemStats::CPUFlags SystemStats::cpuFlags;
  1313. const String SystemStats::getJUCEVersion()
  1314. {
  1315. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1316. + "." + String (JUCE_MINOR_VERSION)
  1317. + "." + String (JUCE_BUILDNUMBER);
  1318. }
  1319. #ifdef JUCE_DLL
  1320. void* juce_Malloc (int size) { return malloc (size); }
  1321. void* juce_Calloc (int size) { return calloc (1, size); }
  1322. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1323. void juce_Free (void* block) { free (block); }
  1324. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1325. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1326. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1327. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1328. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1329. #endif
  1330. #endif
  1331. END_JUCE_NAMESPACE
  1332. /*** End of inlined file: juce_SystemStats.cpp ***/
  1333. /*** Start of inlined file: juce_Time.cpp ***/
  1334. #if JUCE_MSVC
  1335. #pragma warning (push)
  1336. #pragma warning (disable: 4514)
  1337. #endif
  1338. #ifndef JUCE_WINDOWS
  1339. #include <sys/time.h>
  1340. #else
  1341. #include <ctime>
  1342. #endif
  1343. #include <sys/timeb.h>
  1344. #if JUCE_MSVC
  1345. #pragma warning (pop)
  1346. #ifdef _INC_TIME_INL
  1347. #define USE_NEW_SECURE_TIME_FNS
  1348. #endif
  1349. #endif
  1350. BEGIN_JUCE_NAMESPACE
  1351. namespace TimeHelpers
  1352. {
  1353. static struct tm millisToLocal (const int64 millis) throw()
  1354. {
  1355. struct tm result;
  1356. const int64 seconds = millis / 1000;
  1357. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1358. {
  1359. // use extended maths for dates beyond 1970 to 2037..
  1360. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1361. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1362. const int days = (int) (jdm / literal64bit (86400));
  1363. const int a = 32044 + days;
  1364. const int b = (4 * a + 3) / 146097;
  1365. const int c = a - (b * 146097) / 4;
  1366. const int d = (4 * c + 3) / 1461;
  1367. const int e = c - (d * 1461) / 4;
  1368. const int m = (5 * e + 2) / 153;
  1369. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1370. result.tm_mon = m + 2 - 12 * (m / 10);
  1371. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1372. result.tm_wday = (days + 1) % 7;
  1373. result.tm_yday = -1;
  1374. int t = (int) (jdm % literal64bit (86400));
  1375. result.tm_hour = t / 3600;
  1376. t %= 3600;
  1377. result.tm_min = t / 60;
  1378. result.tm_sec = t % 60;
  1379. result.tm_isdst = -1;
  1380. }
  1381. else
  1382. {
  1383. time_t now = static_cast <time_t> (seconds);
  1384. #if JUCE_WINDOWS
  1385. #ifdef USE_NEW_SECURE_TIME_FNS
  1386. if (now >= 0 && now <= 0x793406fff)
  1387. localtime_s (&result, &now);
  1388. else
  1389. zeromem (&result, sizeof (result));
  1390. #else
  1391. result = *localtime (&now);
  1392. #endif
  1393. #else
  1394. // more thread-safe
  1395. localtime_r (&now, &result);
  1396. #endif
  1397. }
  1398. return result;
  1399. }
  1400. static int extendedModulo (const int64 value, const int modulo) throw()
  1401. {
  1402. return (int) (value >= 0 ? (value % modulo)
  1403. : (value - ((value / modulo) + 1) * modulo));
  1404. }
  1405. static uint32 lastMSCounterValue = 0;
  1406. }
  1407. Time::Time() throw()
  1408. : millisSinceEpoch (0)
  1409. {
  1410. }
  1411. Time::Time (const Time& other) throw()
  1412. : millisSinceEpoch (other.millisSinceEpoch)
  1413. {
  1414. }
  1415. Time::Time (const int64 ms) throw()
  1416. : millisSinceEpoch (ms)
  1417. {
  1418. }
  1419. Time::Time (const int year,
  1420. const int month,
  1421. const int day,
  1422. const int hours,
  1423. const int minutes,
  1424. const int seconds,
  1425. const int milliseconds,
  1426. const bool useLocalTime) throw()
  1427. {
  1428. jassert (year > 100); // year must be a 4-digit version
  1429. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1430. {
  1431. // use extended maths for dates beyond 1970 to 2037..
  1432. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1433. : 0;
  1434. const int a = (13 - month) / 12;
  1435. const int y = year + 4800 - a;
  1436. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1437. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1438. - 32045;
  1439. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1440. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1441. + milliseconds;
  1442. }
  1443. else
  1444. {
  1445. struct tm t;
  1446. t.tm_year = year - 1900;
  1447. t.tm_mon = month;
  1448. t.tm_mday = day;
  1449. t.tm_hour = hours;
  1450. t.tm_min = minutes;
  1451. t.tm_sec = seconds;
  1452. t.tm_isdst = -1;
  1453. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1454. if (millisSinceEpoch < 0)
  1455. millisSinceEpoch = 0;
  1456. else
  1457. millisSinceEpoch += milliseconds;
  1458. }
  1459. }
  1460. Time::~Time() throw()
  1461. {
  1462. }
  1463. Time& Time::operator= (const Time& other) throw()
  1464. {
  1465. millisSinceEpoch = other.millisSinceEpoch;
  1466. return *this;
  1467. }
  1468. int64 Time::currentTimeMillis() throw()
  1469. {
  1470. static uint32 lastCounterResult = 0xffffffff;
  1471. static int64 correction = 0;
  1472. const uint32 now = getMillisecondCounter();
  1473. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1474. if (now < lastCounterResult)
  1475. {
  1476. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1477. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1478. {
  1479. // get the time once using normal library calls, and store the difference needed to
  1480. // turn the millisecond counter into a real time.
  1481. #if JUCE_WINDOWS
  1482. struct _timeb t;
  1483. #ifdef USE_NEW_SECURE_TIME_FNS
  1484. _ftime_s (&t);
  1485. #else
  1486. _ftime (&t);
  1487. #endif
  1488. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1489. #else
  1490. struct timeval tv;
  1491. struct timezone tz;
  1492. gettimeofday (&tv, &tz);
  1493. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1494. #endif
  1495. }
  1496. }
  1497. lastCounterResult = now;
  1498. return correction + now;
  1499. }
  1500. uint32 juce_millisecondsSinceStartup() throw();
  1501. uint32 Time::getMillisecondCounter() throw()
  1502. {
  1503. const uint32 now = juce_millisecondsSinceStartup();
  1504. if (now < TimeHelpers::lastMSCounterValue)
  1505. {
  1506. // in multi-threaded apps this might be called concurrently, so
  1507. // make sure that our last counter value only increases and doesn't
  1508. // go backwards..
  1509. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1510. TimeHelpers::lastMSCounterValue = now;
  1511. }
  1512. else
  1513. {
  1514. TimeHelpers::lastMSCounterValue = now;
  1515. }
  1516. return now;
  1517. }
  1518. uint32 Time::getApproximateMillisecondCounter() throw()
  1519. {
  1520. jassert (TimeHelpers::lastMSCounterValue != 0);
  1521. return TimeHelpers::lastMSCounterValue;
  1522. }
  1523. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1524. {
  1525. for (;;)
  1526. {
  1527. const uint32 now = getMillisecondCounter();
  1528. if (now >= targetTime)
  1529. break;
  1530. const int toWait = targetTime - now;
  1531. if (toWait > 2)
  1532. {
  1533. Thread::sleep (jmin (20, toWait >> 1));
  1534. }
  1535. else
  1536. {
  1537. // xxx should consider using mutex_pause on the mac as it apparently
  1538. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1539. for (int i = 10; --i >= 0;)
  1540. Thread::yield();
  1541. }
  1542. }
  1543. }
  1544. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1545. {
  1546. return ticks / (double) getHighResolutionTicksPerSecond();
  1547. }
  1548. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1549. {
  1550. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1551. }
  1552. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1553. {
  1554. return Time (currentTimeMillis());
  1555. }
  1556. const String Time::toString (const bool includeDate,
  1557. const bool includeTime,
  1558. const bool includeSeconds,
  1559. const bool use24HourClock) const throw()
  1560. {
  1561. String result;
  1562. if (includeDate)
  1563. {
  1564. result << getDayOfMonth() << ' '
  1565. << getMonthName (true) << ' '
  1566. << getYear();
  1567. if (includeTime)
  1568. result << ' ';
  1569. }
  1570. if (includeTime)
  1571. {
  1572. const int mins = getMinutes();
  1573. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1574. << (mins < 10 ? ":0" : ":") << mins;
  1575. if (includeSeconds)
  1576. {
  1577. const int secs = getSeconds();
  1578. result << (secs < 10 ? ":0" : ":") << secs;
  1579. }
  1580. if (! use24HourClock)
  1581. result << (isAfternoon() ? "pm" : "am");
  1582. }
  1583. return result.trimEnd();
  1584. }
  1585. const String Time::formatted (const String& format) const
  1586. {
  1587. String buffer;
  1588. int bufferSize = 128;
  1589. buffer.preallocateStorage (bufferSize);
  1590. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1591. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1592. {
  1593. bufferSize += 128;
  1594. buffer.preallocateStorage (bufferSize);
  1595. }
  1596. return buffer;
  1597. }
  1598. int Time::getYear() const throw()
  1599. {
  1600. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1601. }
  1602. int Time::getMonth() const throw()
  1603. {
  1604. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1605. }
  1606. int Time::getDayOfMonth() const throw()
  1607. {
  1608. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1609. }
  1610. int Time::getDayOfWeek() const throw()
  1611. {
  1612. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1613. }
  1614. int Time::getHours() const throw()
  1615. {
  1616. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1617. }
  1618. int Time::getHoursInAmPmFormat() const throw()
  1619. {
  1620. const int hours = getHours();
  1621. if (hours == 0)
  1622. return 12;
  1623. else if (hours <= 12)
  1624. return hours;
  1625. else
  1626. return hours - 12;
  1627. }
  1628. bool Time::isAfternoon() const throw()
  1629. {
  1630. return getHours() >= 12;
  1631. }
  1632. int Time::getMinutes() const throw()
  1633. {
  1634. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1635. }
  1636. int Time::getSeconds() const throw()
  1637. {
  1638. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1639. }
  1640. int Time::getMilliseconds() const throw()
  1641. {
  1642. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1643. }
  1644. bool Time::isDaylightSavingTime() const throw()
  1645. {
  1646. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1647. }
  1648. const String Time::getTimeZone() const throw()
  1649. {
  1650. String zone[2];
  1651. #if JUCE_WINDOWS
  1652. _tzset();
  1653. #ifdef USE_NEW_SECURE_TIME_FNS
  1654. {
  1655. char name [128];
  1656. size_t length;
  1657. for (int i = 0; i < 2; ++i)
  1658. {
  1659. zeromem (name, sizeof (name));
  1660. _get_tzname (&length, name, 127, i);
  1661. zone[i] = name;
  1662. }
  1663. }
  1664. #else
  1665. const char** const zonePtr = (const char**) _tzname;
  1666. zone[0] = zonePtr[0];
  1667. zone[1] = zonePtr[1];
  1668. #endif
  1669. #else
  1670. tzset();
  1671. const char** const zonePtr = (const char**) tzname;
  1672. zone[0] = zonePtr[0];
  1673. zone[1] = zonePtr[1];
  1674. #endif
  1675. if (isDaylightSavingTime())
  1676. {
  1677. zone[0] = zone[1];
  1678. if (zone[0].length() > 3
  1679. && zone[0].containsIgnoreCase ("daylight")
  1680. && zone[0].contains ("GMT"))
  1681. zone[0] = "BST";
  1682. }
  1683. return zone[0].substring (0, 3);
  1684. }
  1685. const String Time::getMonthName (const bool threeLetterVersion) const
  1686. {
  1687. return getMonthName (getMonth(), threeLetterVersion);
  1688. }
  1689. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1690. {
  1691. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1692. }
  1693. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1694. {
  1695. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1696. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1697. monthNumber %= 12;
  1698. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1699. : longMonthNames [monthNumber]);
  1700. }
  1701. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1702. {
  1703. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1704. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1705. day %= 7;
  1706. return TRANS (threeLetterVersion ? shortDayNames [day]
  1707. : longDayNames [day]);
  1708. }
  1709. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  1710. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  1711. const Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  1712. const Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  1713. const Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  1714. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  1715. bool operator== (const Time& time1, const Time& time2) { return 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. END_JUCE_NAMESPACE
  1722. /*** End of inlined file: juce_Time.cpp ***/
  1723. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1724. BEGIN_JUCE_NAMESPACE
  1725. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1726. #endif
  1727. #if JUCE_WINDOWS
  1728. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1729. #endif
  1730. #if JUCE_DEBUG
  1731. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1732. #endif
  1733. static bool juceInitialisedNonGUI = false;
  1734. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1735. {
  1736. if (! juceInitialisedNonGUI)
  1737. {
  1738. juceInitialisedNonGUI = true;
  1739. JUCE_AUTORELEASEPOOL
  1740. DBG (SystemStats::getJUCEVersion());
  1741. SystemStats::initialiseStats();
  1742. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1743. }
  1744. // Some basic tests, to keep an eye on things and make sure these types work ok
  1745. // on all platforms. Let me know if any of these assertions fail on your system!
  1746. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1747. static_jassert (sizeof (int8) == 1);
  1748. static_jassert (sizeof (uint8) == 1);
  1749. static_jassert (sizeof (int16) == 2);
  1750. static_jassert (sizeof (uint16) == 2);
  1751. static_jassert (sizeof (int32) == 4);
  1752. static_jassert (sizeof (uint32) == 4);
  1753. static_jassert (sizeof (int64) == 8);
  1754. static_jassert (sizeof (uint64) == 8);
  1755. }
  1756. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1757. {
  1758. if (juceInitialisedNonGUI)
  1759. {
  1760. juceInitialisedNonGUI = false;
  1761. JUCE_AUTORELEASEPOOL
  1762. LocalisedStrings::setCurrentMappings (0);
  1763. Thread::stopAllThreads (3000);
  1764. #if JUCE_WINDOWS
  1765. juce_shutdownWin32Sockets();
  1766. #endif
  1767. #if JUCE_DEBUG
  1768. juce_CheckForDanglingStreams();
  1769. #endif
  1770. }
  1771. }
  1772. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1773. static bool juceInitialisedGUI = false;
  1774. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1775. {
  1776. if (! juceInitialisedGUI)
  1777. {
  1778. juceInitialisedGUI = true;
  1779. JUCE_AUTORELEASEPOOL
  1780. initialiseJuce_NonGUI();
  1781. MessageManager::getInstance();
  1782. LookAndFeel::setDefaultLookAndFeel (0);
  1783. #if JUCE_DEBUG
  1784. try // This section is just a safety-net for catching builds without RTTI enabled..
  1785. {
  1786. MemoryOutputStream mo;
  1787. OutputStream* o = &mo;
  1788. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1789. o = dynamic_cast <MemoryOutputStream*> (o);
  1790. jassert (o != 0);
  1791. }
  1792. catch (...)
  1793. {
  1794. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1795. jassertfalse;
  1796. }
  1797. #endif
  1798. }
  1799. }
  1800. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1801. {
  1802. if (juceInitialisedGUI)
  1803. {
  1804. juceInitialisedGUI = false;
  1805. JUCE_AUTORELEASEPOOL
  1806. DeletedAtShutdown::deleteAll();
  1807. LookAndFeel::clearDefaultLookAndFeel();
  1808. delete MessageManager::getInstance();
  1809. shutdownJuce_NonGUI();
  1810. }
  1811. }
  1812. #endif
  1813. #if JUCE_UNIT_TESTS
  1814. class AtomicTests : public UnitTest
  1815. {
  1816. public:
  1817. AtomicTests() : UnitTest ("Atomics") {}
  1818. void runTest()
  1819. {
  1820. beginTest ("Misc");
  1821. char a1[7];
  1822. expect (numElementsInArray(a1) == 7);
  1823. int a2[3];
  1824. expect (numElementsInArray(a2) == 3);
  1825. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1826. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1827. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1828. beginTest ("Atomic types");
  1829. AtomicTester <int>::testInteger (*this);
  1830. AtomicTester <unsigned int>::testInteger (*this);
  1831. AtomicTester <int32>::testInteger (*this);
  1832. AtomicTester <uint32>::testInteger (*this);
  1833. AtomicTester <long>::testInteger (*this);
  1834. AtomicTester <void*>::testInteger (*this);
  1835. AtomicTester <int*>::testInteger (*this);
  1836. AtomicTester <float>::testFloat (*this);
  1837. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1838. AtomicTester <int64>::testInteger (*this);
  1839. AtomicTester <uint64>::testInteger (*this);
  1840. AtomicTester <double>::testFloat (*this);
  1841. #endif
  1842. }
  1843. template <typename Type>
  1844. class AtomicTester
  1845. {
  1846. public:
  1847. AtomicTester() {}
  1848. static void testInteger (UnitTest& test)
  1849. {
  1850. Atomic<Type> a, b;
  1851. a.set ((Type) 10);
  1852. a += (Type) 15;
  1853. a.memoryBarrier();
  1854. a -= (Type) 5;
  1855. ++a; ++a; --a;
  1856. a.memoryBarrier();
  1857. testFloat (test);
  1858. }
  1859. static void testFloat (UnitTest& test)
  1860. {
  1861. Atomic<Type> a, b;
  1862. a = (Type) 21;
  1863. a.memoryBarrier();
  1864. /* These are some simple test cases to check the atomics - let me know
  1865. if any of these assertions fail on your system!
  1866. */
  1867. test.expect (a.get() == (Type) 21);
  1868. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1869. test.expect (a.get() == (Type) 21);
  1870. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1871. test.expect (a.get() == (Type) 101);
  1872. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1873. test.expect (a.get() == (Type) 101);
  1874. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1875. test.expect (a.get() == (Type) 200);
  1876. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1877. test.expect (a.get() == (Type) 300);
  1878. b = a;
  1879. test.expect (b.get() == a.get());
  1880. }
  1881. };
  1882. };
  1883. static AtomicTests atomicUnitTests;
  1884. #endif
  1885. END_JUCE_NAMESPACE
  1886. /*** End of inlined file: juce_Initialisation.cpp ***/
  1887. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1888. BEGIN_JUCE_NAMESPACE
  1889. AbstractFifo::AbstractFifo (const int capacity) throw()
  1890. : bufferSize (capacity)
  1891. {
  1892. jassert (bufferSize > 0);
  1893. }
  1894. AbstractFifo::~AbstractFifo() {}
  1895. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1896. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1897. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1898. void AbstractFifo::reset() throw()
  1899. {
  1900. validEnd = 0;
  1901. validStart = 0;
  1902. }
  1903. void AbstractFifo::setTotalSize (int newSize) throw()
  1904. {
  1905. jassert (newSize > 0);
  1906. reset();
  1907. bufferSize = newSize;
  1908. }
  1909. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1910. {
  1911. const int vs = validStart.get();
  1912. const int ve = validEnd.get();
  1913. const int freeSpace = bufferSize - (ve - vs);
  1914. numToWrite = jmin (numToWrite, freeSpace);
  1915. if (numToWrite <= 0)
  1916. {
  1917. startIndex1 = 0;
  1918. startIndex2 = 0;
  1919. blockSize1 = 0;
  1920. blockSize2 = 0;
  1921. }
  1922. else
  1923. {
  1924. startIndex1 = (int) (ve % bufferSize);
  1925. startIndex2 = 0;
  1926. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1927. numToWrite -= blockSize1;
  1928. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  1929. }
  1930. }
  1931. void AbstractFifo::finishedWrite (int numWritten) throw()
  1932. {
  1933. jassert (numWritten >= 0 && numWritten < bufferSize);
  1934. validEnd += numWritten;
  1935. }
  1936. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1937. {
  1938. const int vs = validStart.get();
  1939. const int ve = validEnd.get();
  1940. const int numReady = ve - vs;
  1941. numWanted = jmin (numWanted, numReady);
  1942. if (numWanted <= 0)
  1943. {
  1944. startIndex1 = 0;
  1945. startIndex2 = 0;
  1946. blockSize1 = 0;
  1947. blockSize2 = 0;
  1948. }
  1949. else
  1950. {
  1951. startIndex1 = (int) (vs % bufferSize);
  1952. startIndex2 = 0;
  1953. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  1954. numWanted -= blockSize1;
  1955. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  1956. }
  1957. }
  1958. void AbstractFifo::finishedRead (int numRead) throw()
  1959. {
  1960. jassert (numRead >= 0 && numRead < bufferSize);
  1961. validStart += numRead;
  1962. }
  1963. END_JUCE_NAMESPACE
  1964. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  1965. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1966. BEGIN_JUCE_NAMESPACE
  1967. BigInteger::BigInteger()
  1968. : numValues (4),
  1969. highestBit (-1),
  1970. negative (false)
  1971. {
  1972. values.calloc (numValues + 1);
  1973. }
  1974. BigInteger::BigInteger (const int32 value)
  1975. : numValues (4),
  1976. highestBit (31),
  1977. negative (value < 0)
  1978. {
  1979. values.calloc (numValues + 1);
  1980. values[0] = abs (value);
  1981. highestBit = getHighestBit();
  1982. }
  1983. BigInteger::BigInteger (const uint32 value)
  1984. : numValues (4),
  1985. highestBit (31),
  1986. negative (false)
  1987. {
  1988. values.calloc (numValues + 1);
  1989. values[0] = value;
  1990. highestBit = getHighestBit();
  1991. }
  1992. BigInteger::BigInteger (int64 value)
  1993. : numValues (4),
  1994. highestBit (63),
  1995. negative (value < 0)
  1996. {
  1997. values.calloc (numValues + 1);
  1998. if (value < 0)
  1999. value = -value;
  2000. values[0] = (uint32) value;
  2001. values[1] = (uint32) (value >> 32);
  2002. highestBit = getHighestBit();
  2003. }
  2004. BigInteger::BigInteger (const BigInteger& other)
  2005. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2006. highestBit (other.getHighestBit()),
  2007. negative (other.negative)
  2008. {
  2009. values.malloc (numValues + 1);
  2010. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2011. }
  2012. BigInteger::~BigInteger()
  2013. {
  2014. }
  2015. void BigInteger::swapWith (BigInteger& other) throw()
  2016. {
  2017. values.swapWith (other.values);
  2018. swapVariables (numValues, other.numValues);
  2019. swapVariables (highestBit, other.highestBit);
  2020. swapVariables (negative, other.negative);
  2021. }
  2022. BigInteger& BigInteger::operator= (const BigInteger& other)
  2023. {
  2024. if (this != &other)
  2025. {
  2026. highestBit = other.getHighestBit();
  2027. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2028. negative = other.negative;
  2029. values.malloc (numValues + 1);
  2030. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2031. }
  2032. return *this;
  2033. }
  2034. void BigInteger::ensureSize (const int numVals)
  2035. {
  2036. if (numVals + 2 >= numValues)
  2037. {
  2038. int oldSize = numValues;
  2039. numValues = ((numVals + 2) * 3) / 2;
  2040. values.realloc (numValues + 1);
  2041. while (oldSize < numValues)
  2042. values [oldSize++] = 0;
  2043. }
  2044. }
  2045. bool BigInteger::operator[] (const int bit) const throw()
  2046. {
  2047. return bit <= highestBit && bit >= 0
  2048. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2049. }
  2050. int BigInteger::toInteger() const throw()
  2051. {
  2052. const int n = (int) (values[0] & 0x7fffffff);
  2053. return negative ? -n : n;
  2054. }
  2055. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2056. {
  2057. BigInteger r;
  2058. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2059. r.ensureSize (bitToIndex (numBits));
  2060. r.highestBit = numBits;
  2061. int i = 0;
  2062. while (numBits > 0)
  2063. {
  2064. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2065. numBits -= 32;
  2066. startBit += 32;
  2067. }
  2068. r.highestBit = r.getHighestBit();
  2069. return r;
  2070. }
  2071. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2072. {
  2073. if (numBits > 32)
  2074. {
  2075. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2076. numBits = 32;
  2077. }
  2078. numBits = jmin (numBits, highestBit + 1 - startBit);
  2079. if (numBits <= 0)
  2080. return 0;
  2081. const int pos = bitToIndex (startBit);
  2082. const int offset = startBit & 31;
  2083. const int endSpace = 32 - numBits;
  2084. uint32 n = ((uint32) values [pos]) >> offset;
  2085. if (offset > endSpace)
  2086. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2087. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2088. }
  2089. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2090. {
  2091. if (numBits > 32)
  2092. {
  2093. jassertfalse;
  2094. numBits = 32;
  2095. }
  2096. for (int i = 0; i < numBits; ++i)
  2097. {
  2098. setBit (startBit + i, (valueToSet & 1) != 0);
  2099. valueToSet >>= 1;
  2100. }
  2101. }
  2102. void BigInteger::clear()
  2103. {
  2104. if (numValues > 16)
  2105. {
  2106. numValues = 4;
  2107. values.calloc (numValues + 1);
  2108. }
  2109. else
  2110. {
  2111. zeromem (values, sizeof (uint32) * (numValues + 1));
  2112. }
  2113. highestBit = -1;
  2114. negative = false;
  2115. }
  2116. void BigInteger::setBit (const int bit)
  2117. {
  2118. if (bit >= 0)
  2119. {
  2120. if (bit > highestBit)
  2121. {
  2122. ensureSize (bitToIndex (bit));
  2123. highestBit = bit;
  2124. }
  2125. values [bitToIndex (bit)] |= bitToMask (bit);
  2126. }
  2127. }
  2128. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2129. {
  2130. if (shouldBeSet)
  2131. setBit (bit);
  2132. else
  2133. clearBit (bit);
  2134. }
  2135. void BigInteger::clearBit (const int bit) throw()
  2136. {
  2137. if (bit >= 0 && bit <= highestBit)
  2138. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2139. }
  2140. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2141. {
  2142. while (--numBits >= 0)
  2143. setBit (startBit++, shouldBeSet);
  2144. }
  2145. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2146. {
  2147. if (bit >= 0)
  2148. shiftBits (1, bit);
  2149. setBit (bit, shouldBeSet);
  2150. }
  2151. bool BigInteger::isZero() const throw()
  2152. {
  2153. return getHighestBit() < 0;
  2154. }
  2155. bool BigInteger::isOne() const throw()
  2156. {
  2157. return getHighestBit() == 0 && ! negative;
  2158. }
  2159. bool BigInteger::isNegative() const throw()
  2160. {
  2161. return negative && ! isZero();
  2162. }
  2163. void BigInteger::setNegative (const bool neg) throw()
  2164. {
  2165. negative = neg;
  2166. }
  2167. void BigInteger::negate() throw()
  2168. {
  2169. negative = (! negative) && ! isZero();
  2170. }
  2171. #if JUCE_USE_INTRINSICS
  2172. #pragma intrinsic (_BitScanReverse)
  2173. #endif
  2174. namespace BitFunctions
  2175. {
  2176. inline int countBitsInInt32 (uint32 n) throw()
  2177. {
  2178. n -= ((n >> 1) & 0x55555555);
  2179. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2180. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2181. n += (n >> 8);
  2182. n += (n >> 16);
  2183. return n & 0x3f;
  2184. }
  2185. inline int highestBitInInt (uint32 n) throw()
  2186. {
  2187. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2188. #if JUCE_GCC
  2189. return 31 - __builtin_clz (n);
  2190. #elif JUCE_USE_INTRINSICS
  2191. unsigned long highest;
  2192. _BitScanReverse (&highest, n);
  2193. return (int) highest;
  2194. #else
  2195. n |= (n >> 1);
  2196. n |= (n >> 2);
  2197. n |= (n >> 4);
  2198. n |= (n >> 8);
  2199. n |= (n >> 16);
  2200. return countBitsInInt32 (n >> 1);
  2201. #endif
  2202. }
  2203. }
  2204. int BigInteger::countNumberOfSetBits() const throw()
  2205. {
  2206. int total = 0;
  2207. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2208. total += BitFunctions::countBitsInInt32 (values[i]);
  2209. return total;
  2210. }
  2211. int BigInteger::getHighestBit() const throw()
  2212. {
  2213. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2214. {
  2215. const uint32 n = values[i];
  2216. if (n != 0)
  2217. return BitFunctions::highestBitInInt (n) + (i << 5);
  2218. }
  2219. return -1;
  2220. }
  2221. int BigInteger::findNextSetBit (int i) const throw()
  2222. {
  2223. for (; i <= highestBit; ++i)
  2224. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2225. return i;
  2226. return -1;
  2227. }
  2228. int BigInteger::findNextClearBit (int i) const throw()
  2229. {
  2230. for (; i <= highestBit; ++i)
  2231. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2232. break;
  2233. return i;
  2234. }
  2235. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2236. {
  2237. if (other.isNegative())
  2238. return operator-= (-other);
  2239. if (isNegative())
  2240. {
  2241. if (compareAbsolute (other) < 0)
  2242. {
  2243. BigInteger temp (*this);
  2244. temp.negate();
  2245. *this = other;
  2246. operator-= (temp);
  2247. }
  2248. else
  2249. {
  2250. negate();
  2251. operator-= (other);
  2252. negate();
  2253. }
  2254. }
  2255. else
  2256. {
  2257. if (other.highestBit > highestBit)
  2258. highestBit = other.highestBit;
  2259. ++highestBit;
  2260. const int numInts = bitToIndex (highestBit) + 1;
  2261. ensureSize (numInts);
  2262. int64 remainder = 0;
  2263. for (int i = 0; i <= numInts; ++i)
  2264. {
  2265. if (i < numValues)
  2266. remainder += values[i];
  2267. if (i < other.numValues)
  2268. remainder += other.values[i];
  2269. values[i] = (uint32) remainder;
  2270. remainder >>= 32;
  2271. }
  2272. jassert (remainder == 0);
  2273. highestBit = getHighestBit();
  2274. }
  2275. return *this;
  2276. }
  2277. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2278. {
  2279. if (other.isNegative())
  2280. return operator+= (-other);
  2281. if (! isNegative())
  2282. {
  2283. if (compareAbsolute (other) < 0)
  2284. {
  2285. BigInteger temp (other);
  2286. swapWith (temp);
  2287. operator-= (temp);
  2288. negate();
  2289. return *this;
  2290. }
  2291. }
  2292. else
  2293. {
  2294. negate();
  2295. operator+= (other);
  2296. negate();
  2297. return *this;
  2298. }
  2299. const int numInts = bitToIndex (highestBit) + 1;
  2300. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2301. int64 amountToSubtract = 0;
  2302. for (int i = 0; i <= numInts; ++i)
  2303. {
  2304. if (i <= maxOtherInts)
  2305. amountToSubtract += (int64) other.values[i];
  2306. if (values[i] >= amountToSubtract)
  2307. {
  2308. values[i] = (uint32) (values[i] - amountToSubtract);
  2309. amountToSubtract = 0;
  2310. }
  2311. else
  2312. {
  2313. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2314. values[i] = (uint32) n;
  2315. amountToSubtract = 1;
  2316. }
  2317. }
  2318. return *this;
  2319. }
  2320. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2321. {
  2322. BigInteger total;
  2323. highestBit = getHighestBit();
  2324. const bool wasNegative = isNegative();
  2325. setNegative (false);
  2326. for (int i = 0; i <= highestBit; ++i)
  2327. {
  2328. if (operator[](i))
  2329. {
  2330. BigInteger n (other);
  2331. n.setNegative (false);
  2332. n <<= i;
  2333. total += n;
  2334. }
  2335. }
  2336. total.setNegative (wasNegative ^ other.isNegative());
  2337. swapWith (total);
  2338. return *this;
  2339. }
  2340. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2341. {
  2342. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2343. const int divHB = divisor.getHighestBit();
  2344. const int ourHB = getHighestBit();
  2345. if (divHB < 0 || ourHB < 0)
  2346. {
  2347. // division by zero
  2348. remainder.clear();
  2349. clear();
  2350. }
  2351. else
  2352. {
  2353. const bool wasNegative = isNegative();
  2354. swapWith (remainder);
  2355. remainder.setNegative (false);
  2356. clear();
  2357. BigInteger temp (divisor);
  2358. temp.setNegative (false);
  2359. int leftShift = ourHB - divHB;
  2360. temp <<= leftShift;
  2361. while (leftShift >= 0)
  2362. {
  2363. if (remainder.compareAbsolute (temp) >= 0)
  2364. {
  2365. remainder -= temp;
  2366. setBit (leftShift);
  2367. }
  2368. if (--leftShift >= 0)
  2369. temp >>= 1;
  2370. }
  2371. negative = wasNegative ^ divisor.isNegative();
  2372. remainder.setNegative (wasNegative);
  2373. }
  2374. }
  2375. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2376. {
  2377. BigInteger remainder;
  2378. divideBy (other, remainder);
  2379. return *this;
  2380. }
  2381. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2382. {
  2383. // this operation doesn't take into account negative values..
  2384. jassert (isNegative() == other.isNegative());
  2385. if (other.highestBit >= 0)
  2386. {
  2387. ensureSize (bitToIndex (other.highestBit));
  2388. int n = bitToIndex (other.highestBit) + 1;
  2389. while (--n >= 0)
  2390. values[n] |= other.values[n];
  2391. if (other.highestBit > highestBit)
  2392. highestBit = other.highestBit;
  2393. highestBit = getHighestBit();
  2394. }
  2395. return *this;
  2396. }
  2397. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2398. {
  2399. // this operation doesn't take into account negative values..
  2400. jassert (isNegative() == other.isNegative());
  2401. int n = numValues;
  2402. while (n > other.numValues)
  2403. values[--n] = 0;
  2404. while (--n >= 0)
  2405. values[n] &= other.values[n];
  2406. if (other.highestBit < highestBit)
  2407. highestBit = other.highestBit;
  2408. highestBit = getHighestBit();
  2409. return *this;
  2410. }
  2411. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2412. {
  2413. // this operation will only work with the absolute values
  2414. jassert (isNegative() == other.isNegative());
  2415. if (other.highestBit >= 0)
  2416. {
  2417. ensureSize (bitToIndex (other.highestBit));
  2418. int n = bitToIndex (other.highestBit) + 1;
  2419. while (--n >= 0)
  2420. values[n] ^= other.values[n];
  2421. if (other.highestBit > highestBit)
  2422. highestBit = other.highestBit;
  2423. highestBit = getHighestBit();
  2424. }
  2425. return *this;
  2426. }
  2427. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2428. {
  2429. BigInteger remainder;
  2430. divideBy (divisor, remainder);
  2431. swapWith (remainder);
  2432. return *this;
  2433. }
  2434. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2435. {
  2436. shiftBits (numBitsToShift, 0);
  2437. return *this;
  2438. }
  2439. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2440. {
  2441. return operator<<= (-numBitsToShift);
  2442. }
  2443. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2444. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2445. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2446. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2447. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  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 int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2456. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2457. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2458. int BigInteger::compare (const BigInteger& other) const throw()
  2459. {
  2460. if (isNegative() == other.isNegative())
  2461. {
  2462. const int absComp = compareAbsolute (other);
  2463. return isNegative() ? -absComp : absComp;
  2464. }
  2465. else
  2466. {
  2467. return isNegative() ? -1 : 1;
  2468. }
  2469. }
  2470. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2471. {
  2472. const int h1 = getHighestBit();
  2473. const int h2 = other.getHighestBit();
  2474. if (h1 > h2)
  2475. return 1;
  2476. else if (h1 < h2)
  2477. return -1;
  2478. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2479. if (values[i] != other.values[i])
  2480. return (values[i] > other.values[i]) ? 1 : -1;
  2481. return 0;
  2482. }
  2483. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  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. void BigInteger::shiftBits (int bits, const int startBit)
  2490. {
  2491. if (highestBit < 0)
  2492. return;
  2493. if (startBit > 0)
  2494. {
  2495. if (bits < 0)
  2496. {
  2497. // right shift
  2498. for (int i = startBit; i <= highestBit; ++i)
  2499. setBit (i, operator[] (i - bits));
  2500. highestBit = getHighestBit();
  2501. }
  2502. else if (bits > 0)
  2503. {
  2504. // left shift
  2505. for (int i = highestBit + 1; --i >= startBit;)
  2506. setBit (i + bits, operator[] (i));
  2507. while (--bits >= 0)
  2508. clearBit (bits + startBit);
  2509. }
  2510. }
  2511. else
  2512. {
  2513. if (bits < 0)
  2514. {
  2515. // right shift
  2516. bits = -bits;
  2517. if (bits > highestBit)
  2518. {
  2519. clear();
  2520. }
  2521. else
  2522. {
  2523. const int wordsToMove = bitToIndex (bits);
  2524. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2525. highestBit -= bits;
  2526. if (wordsToMove > 0)
  2527. {
  2528. int i;
  2529. for (i = 0; i < top; ++i)
  2530. values [i] = values [i + wordsToMove];
  2531. for (i = 0; i < wordsToMove; ++i)
  2532. values [top + i] = 0;
  2533. bits &= 31;
  2534. }
  2535. if (bits != 0)
  2536. {
  2537. const int invBits = 32 - bits;
  2538. --top;
  2539. for (int i = 0; i < top; ++i)
  2540. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2541. values[top] = (values[top] >> bits);
  2542. }
  2543. highestBit = getHighestBit();
  2544. }
  2545. }
  2546. else if (bits > 0)
  2547. {
  2548. // left shift
  2549. ensureSize (bitToIndex (highestBit + bits) + 1);
  2550. const int wordsToMove = bitToIndex (bits);
  2551. int top = 1 + bitToIndex (highestBit);
  2552. highestBit += bits;
  2553. if (wordsToMove > 0)
  2554. {
  2555. int i;
  2556. for (i = top; --i >= 0;)
  2557. values [i + wordsToMove] = values [i];
  2558. for (i = 0; i < wordsToMove; ++i)
  2559. values [i] = 0;
  2560. bits &= 31;
  2561. }
  2562. if (bits != 0)
  2563. {
  2564. const int invBits = 32 - bits;
  2565. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2566. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2567. values [wordsToMove] = values [wordsToMove] << bits;
  2568. }
  2569. highestBit = getHighestBit();
  2570. }
  2571. }
  2572. }
  2573. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2574. {
  2575. while (! m->isZero())
  2576. {
  2577. if (n->compareAbsolute (*m) > 0)
  2578. swapVariables (m, n);
  2579. *m -= *n;
  2580. }
  2581. return *n;
  2582. }
  2583. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2584. {
  2585. BigInteger m (*this);
  2586. while (! n.isZero())
  2587. {
  2588. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2589. return simpleGCD (&m, &n);
  2590. BigInteger temp1 (m), temp2;
  2591. temp1.divideBy (n, temp2);
  2592. m = n;
  2593. n = temp2;
  2594. }
  2595. return m;
  2596. }
  2597. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2598. {
  2599. BigInteger exp (exponent);
  2600. exp %= modulus;
  2601. BigInteger value (1);
  2602. swapWith (value);
  2603. value %= modulus;
  2604. while (! exp.isZero())
  2605. {
  2606. if (exp [0])
  2607. {
  2608. operator*= (value);
  2609. operator%= (modulus);
  2610. }
  2611. value *= value;
  2612. value %= modulus;
  2613. exp >>= 1;
  2614. }
  2615. }
  2616. void BigInteger::inverseModulo (const BigInteger& modulus)
  2617. {
  2618. if (modulus.isOne() || modulus.isNegative())
  2619. {
  2620. clear();
  2621. return;
  2622. }
  2623. if (isNegative() || compareAbsolute (modulus) >= 0)
  2624. operator%= (modulus);
  2625. if (isOne())
  2626. return;
  2627. if (! (*this)[0])
  2628. {
  2629. // not invertible
  2630. clear();
  2631. return;
  2632. }
  2633. BigInteger a1 (modulus);
  2634. BigInteger a2 (*this);
  2635. BigInteger b1 (modulus);
  2636. BigInteger b2 (1);
  2637. while (! a2.isOne())
  2638. {
  2639. BigInteger temp1, temp2, multiplier (a1);
  2640. multiplier.divideBy (a2, temp1);
  2641. temp1 = a2;
  2642. temp1 *= multiplier;
  2643. temp2 = a1;
  2644. temp2 -= temp1;
  2645. a1 = a2;
  2646. a2 = temp2;
  2647. temp1 = b2;
  2648. temp1 *= multiplier;
  2649. temp2 = b1;
  2650. temp2 -= temp1;
  2651. b1 = b2;
  2652. b2 = temp2;
  2653. }
  2654. while (b2.isNegative())
  2655. b2 += modulus;
  2656. b2 %= modulus;
  2657. swapWith (b2);
  2658. }
  2659. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2660. {
  2661. return stream << value.toString (10);
  2662. }
  2663. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2664. {
  2665. String s;
  2666. BigInteger v (*this);
  2667. if (base == 2 || base == 8 || base == 16)
  2668. {
  2669. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2670. static const char* const hexDigits = "0123456789abcdef";
  2671. for (;;)
  2672. {
  2673. const int remainder = v.getBitRangeAsInt (0, bits);
  2674. v >>= bits;
  2675. if (remainder == 0 && v.isZero())
  2676. break;
  2677. s = String::charToString (hexDigits [remainder]) + s;
  2678. }
  2679. }
  2680. else if (base == 10)
  2681. {
  2682. const BigInteger ten (10);
  2683. BigInteger remainder;
  2684. for (;;)
  2685. {
  2686. v.divideBy (ten, remainder);
  2687. if (remainder.isZero() && v.isZero())
  2688. break;
  2689. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2690. }
  2691. }
  2692. else
  2693. {
  2694. jassertfalse; // can't do the specified base!
  2695. return String::empty;
  2696. }
  2697. s = s.paddedLeft ('0', minimumNumCharacters);
  2698. return isNegative() ? "-" + s : s;
  2699. }
  2700. void BigInteger::parseString (const String& text, const int base)
  2701. {
  2702. clear();
  2703. const juce_wchar* t = text;
  2704. if (base == 2 || base == 8 || base == 16)
  2705. {
  2706. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2707. for (;;)
  2708. {
  2709. const juce_wchar c = *t++;
  2710. const int digit = CharacterFunctions::getHexDigitValue (c);
  2711. if (((uint32) digit) < (uint32) base)
  2712. {
  2713. operator<<= (bits);
  2714. operator+= (digit);
  2715. }
  2716. else if (c == 0)
  2717. {
  2718. break;
  2719. }
  2720. }
  2721. }
  2722. else if (base == 10)
  2723. {
  2724. const BigInteger ten ((uint32) 10);
  2725. for (;;)
  2726. {
  2727. const juce_wchar c = *t++;
  2728. if (c >= '0' && c <= '9')
  2729. {
  2730. operator*= (ten);
  2731. operator+= ((int) (c - '0'));
  2732. }
  2733. else if (c == 0)
  2734. {
  2735. break;
  2736. }
  2737. }
  2738. }
  2739. setNegative (text.trimStart().startsWithChar ('-'));
  2740. }
  2741. const MemoryBlock BigInteger::toMemoryBlock() const
  2742. {
  2743. const int numBytes = (getHighestBit() + 8) >> 3;
  2744. MemoryBlock mb ((size_t) numBytes);
  2745. for (int i = 0; i < numBytes; ++i)
  2746. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2747. return mb;
  2748. }
  2749. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2750. {
  2751. clear();
  2752. for (int i = (int) data.getSize(); --i >= 0;)
  2753. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2754. }
  2755. END_JUCE_NAMESPACE
  2756. /*** End of inlined file: juce_BigInteger.cpp ***/
  2757. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2758. BEGIN_JUCE_NAMESPACE
  2759. MemoryBlock::MemoryBlock() throw()
  2760. : size (0)
  2761. {
  2762. }
  2763. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2764. {
  2765. if (initialSize > 0)
  2766. {
  2767. size = initialSize;
  2768. data.allocate (initialSize, initialiseToZero);
  2769. }
  2770. else
  2771. {
  2772. size = 0;
  2773. }
  2774. }
  2775. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2776. : size (other.size)
  2777. {
  2778. if (size > 0)
  2779. {
  2780. jassert (other.data != 0);
  2781. data.malloc (size);
  2782. memcpy (data, other.data, size);
  2783. }
  2784. }
  2785. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2786. : size (jmax ((size_t) 0, sizeInBytes))
  2787. {
  2788. jassert (sizeInBytes >= 0);
  2789. if (size > 0)
  2790. {
  2791. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2792. data.malloc (size);
  2793. if (dataToInitialiseFrom != 0)
  2794. memcpy (data, dataToInitialiseFrom, size);
  2795. }
  2796. }
  2797. MemoryBlock::~MemoryBlock() throw()
  2798. {
  2799. jassert (size >= 0); // should never happen
  2800. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2801. }
  2802. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2803. {
  2804. if (this != &other)
  2805. {
  2806. setSize (other.size, false);
  2807. memcpy (data, other.data, size);
  2808. }
  2809. return *this;
  2810. }
  2811. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2812. {
  2813. return matches (other.data, other.size);
  2814. }
  2815. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2816. {
  2817. return ! operator== (other);
  2818. }
  2819. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2820. {
  2821. return size == dataSize
  2822. && memcmp (data, dataToCompare, size) == 0;
  2823. }
  2824. // this will resize the block to this size
  2825. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2826. {
  2827. if (size != newSize)
  2828. {
  2829. if (newSize <= 0)
  2830. {
  2831. data.free();
  2832. size = 0;
  2833. }
  2834. else
  2835. {
  2836. if (data != 0)
  2837. {
  2838. data.realloc (newSize);
  2839. if (initialiseToZero && (newSize > size))
  2840. zeromem (data + size, newSize - size);
  2841. }
  2842. else
  2843. {
  2844. data.allocate (newSize, initialiseToZero);
  2845. }
  2846. size = newSize;
  2847. }
  2848. }
  2849. }
  2850. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2851. {
  2852. if (size < minimumSize)
  2853. setSize (minimumSize, initialiseToZero);
  2854. }
  2855. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2856. {
  2857. swapVariables (size, other.size);
  2858. data.swapWith (other.data);
  2859. }
  2860. void MemoryBlock::fillWith (const uint8 value) throw()
  2861. {
  2862. memset (data, (int) value, size);
  2863. }
  2864. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2865. {
  2866. if (numBytes > 0)
  2867. {
  2868. const size_t oldSize = size;
  2869. setSize (size + numBytes);
  2870. memcpy (data + oldSize, srcData, numBytes);
  2871. }
  2872. }
  2873. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2874. {
  2875. const char* d = static_cast<const char*> (src);
  2876. if (offset < 0)
  2877. {
  2878. d -= offset;
  2879. num -= offset;
  2880. offset = 0;
  2881. }
  2882. if (offset + num > size)
  2883. num = size - offset;
  2884. if (num > 0)
  2885. memcpy (data + offset, d, num);
  2886. }
  2887. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2888. {
  2889. char* d = static_cast<char*> (dst);
  2890. if (offset < 0)
  2891. {
  2892. zeromem (d, -offset);
  2893. d -= offset;
  2894. num += offset;
  2895. offset = 0;
  2896. }
  2897. if (offset + num > size)
  2898. {
  2899. const size_t newNum = size - offset;
  2900. zeromem (d + newNum, num - newNum);
  2901. num = newNum;
  2902. }
  2903. if (num > 0)
  2904. memcpy (d, data + offset, num);
  2905. }
  2906. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2907. {
  2908. if (startByte < 0)
  2909. {
  2910. numBytesToRemove += startByte;
  2911. startByte = 0;
  2912. }
  2913. if (startByte + numBytesToRemove >= size)
  2914. {
  2915. setSize (startByte);
  2916. }
  2917. else if (numBytesToRemove > 0)
  2918. {
  2919. memmove (data + startByte,
  2920. data + startByte + numBytesToRemove,
  2921. size - (startByte + numBytesToRemove));
  2922. setSize (size - numBytesToRemove);
  2923. }
  2924. }
  2925. const String MemoryBlock::toString() const
  2926. {
  2927. return String (static_cast <const char*> (getData()), size);
  2928. }
  2929. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2930. {
  2931. int res = 0;
  2932. size_t byte = bitRangeStart >> 3;
  2933. int offsetInByte = (int) bitRangeStart & 7;
  2934. size_t bitsSoFar = 0;
  2935. while (numBits > 0 && (size_t) byte < size)
  2936. {
  2937. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2938. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2939. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2940. bitsSoFar += bitsThisTime;
  2941. numBits -= bitsThisTime;
  2942. ++byte;
  2943. offsetInByte = 0;
  2944. }
  2945. return res;
  2946. }
  2947. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2948. {
  2949. size_t byte = bitRangeStart >> 3;
  2950. int offsetInByte = (int) bitRangeStart & 7;
  2951. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2952. while (numBits > 0 && (size_t) byte < size)
  2953. {
  2954. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2955. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2956. const unsigned int tempBits = bitsToSet << offsetInByte;
  2957. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2958. ++byte;
  2959. numBits -= bitsThisTime;
  2960. bitsToSet >>= bitsThisTime;
  2961. mask >>= bitsThisTime;
  2962. offsetInByte = 0;
  2963. }
  2964. }
  2965. void MemoryBlock::loadFromHexString (const String& hex)
  2966. {
  2967. ensureSize (hex.length() >> 1);
  2968. char* dest = data;
  2969. int i = 0;
  2970. for (;;)
  2971. {
  2972. int byte = 0;
  2973. for (int loop = 2; --loop >= 0;)
  2974. {
  2975. byte <<= 4;
  2976. for (;;)
  2977. {
  2978. const juce_wchar c = hex [i++];
  2979. if (c >= '0' && c <= '9')
  2980. {
  2981. byte |= c - '0';
  2982. break;
  2983. }
  2984. else if (c >= 'a' && c <= 'z')
  2985. {
  2986. byte |= c - ('a' - 10);
  2987. break;
  2988. }
  2989. else if (c >= 'A' && c <= 'Z')
  2990. {
  2991. byte |= c - ('A' - 10);
  2992. break;
  2993. }
  2994. else if (c == 0)
  2995. {
  2996. setSize (static_cast <size_t> (dest - data));
  2997. return;
  2998. }
  2999. }
  3000. }
  3001. *dest++ = (char) byte;
  3002. }
  3003. }
  3004. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3005. const String MemoryBlock::toBase64Encoding() const
  3006. {
  3007. const size_t numChars = ((size << 3) + 5) / 6;
  3008. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3009. const int initialLen = destString.length();
  3010. destString.preallocateStorage (initialLen + 2 + numChars);
  3011. juce_wchar* d = destString;
  3012. d += initialLen;
  3013. *d++ = '.';
  3014. for (size_t i = 0; i < numChars; ++i)
  3015. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3016. *d++ = 0;
  3017. return destString;
  3018. }
  3019. bool MemoryBlock::fromBase64Encoding (const String& s)
  3020. {
  3021. const int startPos = s.indexOfChar ('.') + 1;
  3022. if (startPos <= 0)
  3023. return false;
  3024. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3025. setSize (numBytesNeeded, true);
  3026. const int numChars = s.length() - startPos;
  3027. const juce_wchar* srcChars = s;
  3028. srcChars += startPos;
  3029. int pos = 0;
  3030. for (int i = 0; i < numChars; ++i)
  3031. {
  3032. const char c = (char) srcChars[i];
  3033. for (int j = 0; j < 64; ++j)
  3034. {
  3035. if (encodingTable[j] == c)
  3036. {
  3037. setBitRange (pos, 6, j);
  3038. pos += 6;
  3039. break;
  3040. }
  3041. }
  3042. }
  3043. return true;
  3044. }
  3045. END_JUCE_NAMESPACE
  3046. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3047. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3048. BEGIN_JUCE_NAMESPACE
  3049. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3050. : properties (ignoreCaseOfKeyNames),
  3051. fallbackProperties (0),
  3052. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3053. {
  3054. }
  3055. PropertySet::PropertySet (const PropertySet& other)
  3056. : properties (other.properties),
  3057. fallbackProperties (other.fallbackProperties),
  3058. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3059. {
  3060. }
  3061. PropertySet& PropertySet::operator= (const PropertySet& other)
  3062. {
  3063. properties = other.properties;
  3064. fallbackProperties = other.fallbackProperties;
  3065. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3066. propertyChanged();
  3067. return *this;
  3068. }
  3069. PropertySet::~PropertySet()
  3070. {
  3071. }
  3072. void PropertySet::clear()
  3073. {
  3074. const ScopedLock sl (lock);
  3075. if (properties.size() > 0)
  3076. {
  3077. properties.clear();
  3078. propertyChanged();
  3079. }
  3080. }
  3081. const String PropertySet::getValue (const String& keyName,
  3082. const String& defaultValue) const throw()
  3083. {
  3084. const ScopedLock sl (lock);
  3085. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3086. if (index >= 0)
  3087. return properties.getAllValues() [index];
  3088. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3089. : defaultValue;
  3090. }
  3091. int PropertySet::getIntValue (const String& keyName,
  3092. const int defaultValue) const throw()
  3093. {
  3094. const ScopedLock sl (lock);
  3095. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3096. if (index >= 0)
  3097. return properties.getAllValues() [index].getIntValue();
  3098. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3099. : defaultValue;
  3100. }
  3101. double PropertySet::getDoubleValue (const String& keyName,
  3102. const double defaultValue) const throw()
  3103. {
  3104. const ScopedLock sl (lock);
  3105. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3106. if (index >= 0)
  3107. return properties.getAllValues()[index].getDoubleValue();
  3108. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3109. : defaultValue;
  3110. }
  3111. bool PropertySet::getBoolValue (const String& keyName,
  3112. const bool defaultValue) const throw()
  3113. {
  3114. const ScopedLock sl (lock);
  3115. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3116. if (index >= 0)
  3117. return properties.getAllValues() [index].getIntValue() != 0;
  3118. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3119. : defaultValue;
  3120. }
  3121. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3122. {
  3123. return XmlDocument::parse (getValue (keyName));
  3124. }
  3125. void PropertySet::setValue (const String& keyName, const var& v)
  3126. {
  3127. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3128. if (keyName.isNotEmpty())
  3129. {
  3130. const String value (v.toString());
  3131. const ScopedLock sl (lock);
  3132. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3133. if (index < 0 || properties.getAllValues() [index] != value)
  3134. {
  3135. properties.set (keyName, value);
  3136. propertyChanged();
  3137. }
  3138. }
  3139. }
  3140. void PropertySet::removeValue (const String& keyName)
  3141. {
  3142. if (keyName.isNotEmpty())
  3143. {
  3144. const ScopedLock sl (lock);
  3145. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3146. if (index >= 0)
  3147. {
  3148. properties.remove (keyName);
  3149. propertyChanged();
  3150. }
  3151. }
  3152. }
  3153. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3154. {
  3155. setValue (keyName, xml == 0 ? var::null
  3156. : var (xml->createDocument (String::empty, true)));
  3157. }
  3158. bool PropertySet::containsKey (const String& keyName) const throw()
  3159. {
  3160. const ScopedLock sl (lock);
  3161. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3162. }
  3163. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3164. {
  3165. const ScopedLock sl (lock);
  3166. fallbackProperties = fallbackProperties_;
  3167. }
  3168. XmlElement* PropertySet::createXml (const String& nodeName) const
  3169. {
  3170. const ScopedLock sl (lock);
  3171. XmlElement* const xml = new XmlElement (nodeName);
  3172. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3173. {
  3174. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3175. e->setAttribute ("name", properties.getAllKeys()[i]);
  3176. e->setAttribute ("val", properties.getAllValues()[i]);
  3177. }
  3178. return xml;
  3179. }
  3180. void PropertySet::restoreFromXml (const XmlElement& xml)
  3181. {
  3182. const ScopedLock sl (lock);
  3183. clear();
  3184. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3185. {
  3186. if (e->hasAttribute ("name")
  3187. && e->hasAttribute ("val"))
  3188. {
  3189. properties.set (e->getStringAttribute ("name"),
  3190. e->getStringAttribute ("val"));
  3191. }
  3192. }
  3193. if (properties.size() > 0)
  3194. propertyChanged();
  3195. }
  3196. void PropertySet::propertyChanged()
  3197. {
  3198. }
  3199. END_JUCE_NAMESPACE
  3200. /*** End of inlined file: juce_PropertySet.cpp ***/
  3201. /*** Start of inlined file: juce_Identifier.cpp ***/
  3202. BEGIN_JUCE_NAMESPACE
  3203. StringPool& Identifier::getPool()
  3204. {
  3205. static StringPool pool;
  3206. return pool;
  3207. }
  3208. Identifier::Identifier() throw()
  3209. : name (0)
  3210. {
  3211. }
  3212. Identifier::Identifier (const Identifier& other) throw()
  3213. : name (other.name)
  3214. {
  3215. }
  3216. Identifier& Identifier::operator= (const Identifier& other) throw()
  3217. {
  3218. name = other.name;
  3219. return *this;
  3220. }
  3221. Identifier::Identifier (const String& name_)
  3222. : name (Identifier::getPool().getPooledString (name_))
  3223. {
  3224. /* An Identifier string must be suitable for use as a script variable or XML
  3225. attribute, so it can only contain this limited set of characters.. */
  3226. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3227. }
  3228. Identifier::Identifier (const char* const name_)
  3229. : name (Identifier::getPool().getPooledString (name_))
  3230. {
  3231. /* An Identifier string must be suitable for use as a script variable or XML
  3232. attribute, so it can only contain this limited set of characters.. */
  3233. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3234. }
  3235. Identifier::~Identifier()
  3236. {
  3237. }
  3238. END_JUCE_NAMESPACE
  3239. /*** End of inlined file: juce_Identifier.cpp ***/
  3240. /*** Start of inlined file: juce_Variant.cpp ***/
  3241. BEGIN_JUCE_NAMESPACE
  3242. class var::VariantType
  3243. {
  3244. public:
  3245. VariantType() {}
  3246. virtual ~VariantType() {}
  3247. virtual int toInt (const ValueUnion&) const { return 0; }
  3248. virtual double toDouble (const ValueUnion&) const { return 0; }
  3249. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3250. virtual bool toBool (const ValueUnion&) const { return false; }
  3251. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3252. virtual bool isVoid() const throw() { return false; }
  3253. virtual bool isInt() const throw() { return false; }
  3254. virtual bool isBool() const throw() { return false; }
  3255. virtual bool isDouble() const throw() { return false; }
  3256. virtual bool isString() const throw() { return false; }
  3257. virtual bool isObject() const throw() { return false; }
  3258. virtual bool isMethod() const throw() { return false; }
  3259. virtual void cleanUp (ValueUnion&) const throw() {}
  3260. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3261. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3262. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3263. };
  3264. class var::VariantType_Void : public var::VariantType
  3265. {
  3266. public:
  3267. VariantType_Void() {}
  3268. static const VariantType_Void instance;
  3269. bool isVoid() const throw() { return true; }
  3270. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3271. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3272. };
  3273. class var::VariantType_Int : public var::VariantType
  3274. {
  3275. public:
  3276. VariantType_Int() {}
  3277. static const VariantType_Int instance;
  3278. int toInt (const ValueUnion& data) const { return data.intValue; };
  3279. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3280. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3281. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3282. bool isInt() const throw() { return true; }
  3283. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3284. {
  3285. return otherType.toInt (otherData) == data.intValue;
  3286. }
  3287. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3288. {
  3289. output.writeCompressedInt (5);
  3290. output.writeByte (1);
  3291. output.writeInt (data.intValue);
  3292. }
  3293. };
  3294. class var::VariantType_Double : public var::VariantType
  3295. {
  3296. public:
  3297. VariantType_Double() {}
  3298. static const VariantType_Double instance;
  3299. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3300. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3301. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3302. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3303. bool isDouble() const throw() { return true; }
  3304. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3305. {
  3306. return otherType.toDouble (otherData) == data.doubleValue;
  3307. }
  3308. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3309. {
  3310. output.writeCompressedInt (9);
  3311. output.writeByte (4);
  3312. output.writeDouble (data.doubleValue);
  3313. }
  3314. };
  3315. class var::VariantType_Bool : public var::VariantType
  3316. {
  3317. public:
  3318. VariantType_Bool() {}
  3319. static const VariantType_Bool instance;
  3320. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3321. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3322. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3323. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3324. bool isBool() const throw() { return true; }
  3325. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3326. {
  3327. return otherType.toBool (otherData) == data.boolValue;
  3328. }
  3329. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3330. {
  3331. output.writeCompressedInt (1);
  3332. output.writeByte (data.boolValue ? 2 : 3);
  3333. }
  3334. };
  3335. class var::VariantType_String : public var::VariantType
  3336. {
  3337. public:
  3338. VariantType_String() {}
  3339. static const VariantType_String instance;
  3340. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3341. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3342. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3343. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3344. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3345. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3346. || data.stringValue->trim().equalsIgnoreCase ("true")
  3347. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3348. bool isString() const throw() { return true; }
  3349. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3350. {
  3351. return otherType.toString (otherData) == *data.stringValue;
  3352. }
  3353. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3354. {
  3355. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3356. output.writeCompressedInt (len + 1);
  3357. output.writeByte (5);
  3358. HeapBlock<char> temp (len);
  3359. data.stringValue->copyToUTF8 (temp, len);
  3360. output.write (temp, len);
  3361. }
  3362. };
  3363. class var::VariantType_Object : public var::VariantType
  3364. {
  3365. public:
  3366. VariantType_Object() {}
  3367. static const VariantType_Object instance;
  3368. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3369. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3370. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3371. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3372. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3373. bool isObject() const throw() { return true; }
  3374. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3375. {
  3376. return otherType.toObject (otherData) == data.objectValue;
  3377. }
  3378. void writeToStream (const ValueUnion&, OutputStream& output) const
  3379. {
  3380. jassertfalse; // Can't write an object to a stream!
  3381. output.writeCompressedInt (0);
  3382. }
  3383. };
  3384. class var::VariantType_Method : public var::VariantType
  3385. {
  3386. public:
  3387. VariantType_Method() {}
  3388. static const VariantType_Method instance;
  3389. const String toString (const ValueUnion&) const { return "Method"; }
  3390. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3391. bool isMethod() const throw() { return true; }
  3392. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3393. {
  3394. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3395. }
  3396. void writeToStream (const ValueUnion&, OutputStream& output) const
  3397. {
  3398. jassertfalse; // Can't write a method to a stream!
  3399. output.writeCompressedInt (0);
  3400. }
  3401. };
  3402. const var::VariantType_Void var::VariantType_Void::instance;
  3403. const var::VariantType_Int var::VariantType_Int::instance;
  3404. const var::VariantType_Bool var::VariantType_Bool::instance;
  3405. const var::VariantType_Double var::VariantType_Double::instance;
  3406. const var::VariantType_String var::VariantType_String::instance;
  3407. const var::VariantType_Object var::VariantType_Object::instance;
  3408. const var::VariantType_Method var::VariantType_Method::instance;
  3409. var::var() throw() : type (&VariantType_Void::instance)
  3410. {
  3411. }
  3412. var::~var() throw()
  3413. {
  3414. type->cleanUp (value);
  3415. }
  3416. const var var::null;
  3417. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3418. {
  3419. type->createCopy (value, valueToCopy.value);
  3420. }
  3421. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3422. {
  3423. value.intValue = value_;
  3424. }
  3425. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3426. {
  3427. value.boolValue = value_;
  3428. }
  3429. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3430. {
  3431. value.doubleValue = value_;
  3432. }
  3433. var::var (const String& value_) : type (&VariantType_String::instance)
  3434. {
  3435. value.stringValue = new String (value_);
  3436. }
  3437. var::var (const char* const value_) : type (&VariantType_String::instance)
  3438. {
  3439. value.stringValue = new String (value_);
  3440. }
  3441. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3442. {
  3443. value.stringValue = new String (value_);
  3444. }
  3445. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3446. {
  3447. value.objectValue = object;
  3448. if (object != 0)
  3449. object->incReferenceCount();
  3450. }
  3451. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3452. {
  3453. value.methodValue = method_;
  3454. }
  3455. bool var::isVoid() const throw() { return type->isVoid(); }
  3456. bool var::isInt() const throw() { return type->isInt(); }
  3457. bool var::isBool() const throw() { return type->isBool(); }
  3458. bool var::isDouble() const throw() { return type->isDouble(); }
  3459. bool var::isString() const throw() { return type->isString(); }
  3460. bool var::isObject() const throw() { return type->isObject(); }
  3461. bool var::isMethod() const throw() { return type->isMethod(); }
  3462. var::operator int() const { return type->toInt (value); }
  3463. var::operator bool() const { return type->toBool (value); }
  3464. var::operator float() const { return (float) type->toDouble (value); }
  3465. var::operator double() const { return type->toDouble (value); }
  3466. const String var::toString() const { return type->toString (value); }
  3467. var::operator const String() const { return type->toString (value); }
  3468. DynamicObject* var::getObject() const { return type->toObject (value); }
  3469. void var::swapWith (var& other) throw()
  3470. {
  3471. swapVariables (type, other.type);
  3472. swapVariables (value, other.value);
  3473. }
  3474. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3475. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3476. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3477. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3478. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3479. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3480. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3481. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3482. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3483. bool var::equals (const var& other) const throw()
  3484. {
  3485. return type->equals (value, other.value, *other.type);
  3486. }
  3487. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3488. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3489. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3490. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3491. void var::writeToStream (OutputStream& output) const
  3492. {
  3493. type->writeToStream (value, output);
  3494. }
  3495. const var var::readFromStream (InputStream& input)
  3496. {
  3497. const int numBytes = input.readCompressedInt();
  3498. if (numBytes > 0)
  3499. {
  3500. switch (input.readByte())
  3501. {
  3502. case 1: return var (input.readInt());
  3503. case 2: return var (true);
  3504. case 3: return var (false);
  3505. case 4: return var (input.readDouble());
  3506. case 5:
  3507. {
  3508. MemoryOutputStream mo;
  3509. mo.writeFromInputStream (input, numBytes - 1);
  3510. return var (mo.toUTF8());
  3511. }
  3512. default: input.skipNextBytes (numBytes - 1); break;
  3513. }
  3514. }
  3515. return var::null;
  3516. }
  3517. const var var::operator[] (const Identifier& propertyName) const
  3518. {
  3519. DynamicObject* const o = getObject();
  3520. return o != 0 ? o->getProperty (propertyName) : var::null;
  3521. }
  3522. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3523. {
  3524. DynamicObject* const o = getObject();
  3525. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3526. }
  3527. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3528. {
  3529. if (isMethod())
  3530. {
  3531. DynamicObject* const target = targetObject.getObject();
  3532. if (target != 0)
  3533. return (target->*(value.methodValue)) (arguments, numArguments);
  3534. }
  3535. return var::null;
  3536. }
  3537. const var var::call (const Identifier& method) const
  3538. {
  3539. return invoke (method, 0, 0);
  3540. }
  3541. const var var::call (const Identifier& method, const var& arg1) const
  3542. {
  3543. return invoke (method, &arg1, 1);
  3544. }
  3545. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3546. {
  3547. var args[] = { arg1, arg2 };
  3548. return invoke (method, args, 2);
  3549. }
  3550. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3551. {
  3552. var args[] = { arg1, arg2, arg3 };
  3553. return invoke (method, args, 3);
  3554. }
  3555. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3556. {
  3557. var args[] = { arg1, arg2, arg3, arg4 };
  3558. return invoke (method, args, 4);
  3559. }
  3560. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3561. {
  3562. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3563. return invoke (method, args, 5);
  3564. }
  3565. END_JUCE_NAMESPACE
  3566. /*** End of inlined file: juce_Variant.cpp ***/
  3567. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3568. BEGIN_JUCE_NAMESPACE
  3569. NamedValueSet::NamedValue::NamedValue() throw()
  3570. {
  3571. }
  3572. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3573. : name (name_), value (value_)
  3574. {
  3575. }
  3576. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3577. {
  3578. return name == other.name && value == other.value;
  3579. }
  3580. NamedValueSet::NamedValueSet() throw()
  3581. {
  3582. }
  3583. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3584. : values (other.values)
  3585. {
  3586. }
  3587. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3588. {
  3589. values = other.values;
  3590. return *this;
  3591. }
  3592. NamedValueSet::~NamedValueSet()
  3593. {
  3594. }
  3595. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3596. {
  3597. return values == other.values;
  3598. }
  3599. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3600. {
  3601. return ! operator== (other);
  3602. }
  3603. int NamedValueSet::size() const throw()
  3604. {
  3605. return values.size();
  3606. }
  3607. const var& NamedValueSet::operator[] (const Identifier& name) const
  3608. {
  3609. for (int i = values.size(); --i >= 0;)
  3610. {
  3611. const NamedValue& v = values.getReference(i);
  3612. if (v.name == name)
  3613. return v.value;
  3614. }
  3615. return var::null;
  3616. }
  3617. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3618. {
  3619. const var* v = getVarPointer (name);
  3620. return v != 0 ? *v : defaultReturnValue;
  3621. }
  3622. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3623. {
  3624. for (int i = values.size(); --i >= 0;)
  3625. {
  3626. NamedValue& v = values.getReference(i);
  3627. if (v.name == name)
  3628. return &(v.value);
  3629. }
  3630. return 0;
  3631. }
  3632. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3633. {
  3634. for (int i = values.size(); --i >= 0;)
  3635. {
  3636. NamedValue& v = values.getReference(i);
  3637. if (v.name == name)
  3638. {
  3639. if (v.value == newValue)
  3640. return false;
  3641. v.value = newValue;
  3642. return true;
  3643. }
  3644. }
  3645. values.add (NamedValue (name, newValue));
  3646. return true;
  3647. }
  3648. bool NamedValueSet::contains (const Identifier& name) const
  3649. {
  3650. return getVarPointer (name) != 0;
  3651. }
  3652. bool NamedValueSet::remove (const Identifier& name)
  3653. {
  3654. for (int i = values.size(); --i >= 0;)
  3655. {
  3656. if (values.getReference(i).name == name)
  3657. {
  3658. values.remove (i);
  3659. return true;
  3660. }
  3661. }
  3662. return false;
  3663. }
  3664. const Identifier NamedValueSet::getName (const int index) const
  3665. {
  3666. jassert (isPositiveAndBelow (index, values.size()));
  3667. return values [index].name;
  3668. }
  3669. const var NamedValueSet::getValueAt (const int index) const
  3670. {
  3671. jassert (isPositiveAndBelow (index, values.size()));
  3672. return values [index].value;
  3673. }
  3674. void NamedValueSet::clear()
  3675. {
  3676. values.clear();
  3677. }
  3678. END_JUCE_NAMESPACE
  3679. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3680. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3681. BEGIN_JUCE_NAMESPACE
  3682. DynamicObject::DynamicObject()
  3683. {
  3684. }
  3685. DynamicObject::~DynamicObject()
  3686. {
  3687. }
  3688. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3689. {
  3690. var* const v = properties.getVarPointer (propertyName);
  3691. return v != 0 && ! v->isMethod();
  3692. }
  3693. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3694. {
  3695. return properties [propertyName];
  3696. }
  3697. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3698. {
  3699. properties.set (propertyName, newValue);
  3700. }
  3701. void DynamicObject::removeProperty (const Identifier& propertyName)
  3702. {
  3703. properties.remove (propertyName);
  3704. }
  3705. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3706. {
  3707. return getProperty (methodName).isMethod();
  3708. }
  3709. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3710. const var* parameters,
  3711. int numParameters)
  3712. {
  3713. return properties [methodName].invoke (var (this), parameters, numParameters);
  3714. }
  3715. void DynamicObject::setMethod (const Identifier& name,
  3716. var::MethodFunction methodFunction)
  3717. {
  3718. properties.set (name, var (methodFunction));
  3719. }
  3720. void DynamicObject::clear()
  3721. {
  3722. properties.clear();
  3723. }
  3724. END_JUCE_NAMESPACE
  3725. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3726. /*** Start of inlined file: juce_Expression.cpp ***/
  3727. BEGIN_JUCE_NAMESPACE
  3728. class Expression::Helpers
  3729. {
  3730. public:
  3731. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3732. // This helper function is needed to work around VC6 scoping bugs
  3733. static const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3734. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3735. class Constant : public Term
  3736. {
  3737. public:
  3738. Constant (const double value_, bool isResolutionTarget_)
  3739. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3740. Type getType() const throw() { return constantType; }
  3741. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3742. double evaluate (const EvaluationContext&, int) const { return value; }
  3743. int getNumInputs() const { return 0; }
  3744. Term* getInput (int) const { return 0; }
  3745. const TermPtr negated()
  3746. {
  3747. return new Constant (-value, isResolutionTarget);
  3748. }
  3749. const String toString() const
  3750. {
  3751. if (isResolutionTarget)
  3752. return "@" + String (value);
  3753. return String (value);
  3754. }
  3755. double value;
  3756. bool isResolutionTarget;
  3757. };
  3758. class Symbol : public Term
  3759. {
  3760. public:
  3761. explicit Symbol (const String& symbol_)
  3762. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3763. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3764. {}
  3765. Symbol (const String& symbol_, const String& member_)
  3766. : mainSymbol (symbol_),
  3767. member (member_)
  3768. {}
  3769. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3770. {
  3771. if (++recursionDepth > 256)
  3772. throw EvaluationError ("Recursive symbol references");
  3773. try
  3774. {
  3775. return getTermFor (c.getSymbolValue (mainSymbol, member))->evaluate (c, recursionDepth);
  3776. }
  3777. catch (...)
  3778. {}
  3779. return 0;
  3780. }
  3781. Type getType() const throw() { return symbolType; }
  3782. Term* clone() const { return new Symbol (mainSymbol, member); }
  3783. int getNumInputs() const { return 0; }
  3784. Term* getInput (int) const { return 0; }
  3785. const String getSymbolName() const { return toString(); }
  3786. const String toString() const
  3787. {
  3788. return member.isEmpty() ? mainSymbol
  3789. : mainSymbol + "." + member;
  3790. }
  3791. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3792. {
  3793. if (s == mainSymbol)
  3794. return true;
  3795. if (++recursionDepth > 256)
  3796. throw EvaluationError ("Recursive symbol references");
  3797. try
  3798. {
  3799. return c != 0 && getTermFor (c->getSymbolValue (mainSymbol, member))->referencesSymbol (s, c, recursionDepth);
  3800. }
  3801. catch (EvaluationError&)
  3802. {
  3803. return false;
  3804. }
  3805. }
  3806. String mainSymbol, member;
  3807. };
  3808. class Function : public Term
  3809. {
  3810. public:
  3811. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3812. : functionName (functionName_), parameters (parameters_)
  3813. {}
  3814. Term* clone() const { return new Function (functionName, parameters); }
  3815. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3816. {
  3817. HeapBlock <double> params (parameters.size());
  3818. for (int i = 0; i < parameters.size(); ++i)
  3819. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3820. return c.evaluateFunction (functionName, params, parameters.size());
  3821. }
  3822. Type getType() const throw() { return functionType; }
  3823. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3824. int getNumInputs() const { return parameters.size(); }
  3825. Term* getInput (int i) const { return parameters [i]; }
  3826. const String getFunctionName() const { return functionName; }
  3827. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3828. {
  3829. for (int i = 0; i < parameters.size(); ++i)
  3830. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3831. return true;
  3832. return false;
  3833. }
  3834. const String toString() const
  3835. {
  3836. if (parameters.size() == 0)
  3837. return functionName + "()";
  3838. String s (functionName + " (");
  3839. for (int i = 0; i < parameters.size(); ++i)
  3840. {
  3841. s << parameters.getUnchecked(i)->toString();
  3842. if (i < parameters.size() - 1)
  3843. s << ", ";
  3844. }
  3845. s << ')';
  3846. return s;
  3847. }
  3848. const String functionName;
  3849. ReferenceCountedArray<Term> parameters;
  3850. };
  3851. class Negate : public Term
  3852. {
  3853. public:
  3854. Negate (const TermPtr& input_) : input (input_)
  3855. {
  3856. jassert (input_ != 0);
  3857. }
  3858. Type getType() const throw() { return operatorType; }
  3859. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3860. int getNumInputs() const { return 1; }
  3861. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3862. Term* clone() const { return new Negate (input->clone()); }
  3863. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3864. const String getFunctionName() const { return "-"; }
  3865. const TermPtr negated()
  3866. {
  3867. return input;
  3868. }
  3869. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3870. {
  3871. (void) input_;
  3872. jassert (input_ == input);
  3873. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3874. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3875. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3876. }
  3877. const String toString() const
  3878. {
  3879. if (input->getOperatorPrecedence() > 0)
  3880. return "-(" + input->toString() + ")";
  3881. else
  3882. return "-" + input->toString();
  3883. }
  3884. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3885. {
  3886. return input->referencesSymbol (s, c, recursionDepth);
  3887. }
  3888. private:
  3889. const TermPtr input;
  3890. };
  3891. class BinaryTerm : public Term
  3892. {
  3893. public:
  3894. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3895. {
  3896. jassert (left_ != 0 && right_ != 0);
  3897. }
  3898. int getInputIndexFor (const Term* possibleInput) const
  3899. {
  3900. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3901. }
  3902. Type getType() const throw() { return operatorType; }
  3903. int getNumInputs() const { return 2; }
  3904. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3905. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3906. {
  3907. return left->referencesSymbol (s, c, recursionDepth)
  3908. || right->referencesSymbol (s, c, recursionDepth);
  3909. }
  3910. const String toString() const
  3911. {
  3912. String s;
  3913. const int ourPrecendence = getOperatorPrecedence();
  3914. if (left->getOperatorPrecedence() > ourPrecendence)
  3915. s << '(' << left->toString() << ')';
  3916. else
  3917. s = left->toString();
  3918. s << ' ' << getFunctionName() << ' ';
  3919. if (right->getOperatorPrecedence() >= ourPrecendence)
  3920. s << '(' << right->toString() << ')';
  3921. else
  3922. s << right->toString();
  3923. return s;
  3924. }
  3925. protected:
  3926. const TermPtr left, right;
  3927. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3928. {
  3929. jassert (input == left || input == right);
  3930. if (input != left && input != right)
  3931. return 0;
  3932. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3933. if (dest == 0)
  3934. return new Constant (overallTarget, false);
  3935. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3936. }
  3937. };
  3938. class Add : public BinaryTerm
  3939. {
  3940. public:
  3941. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3942. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3943. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3944. int getOperatorPrecedence() const { return 2; }
  3945. const String getFunctionName() const { return "+"; }
  3946. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3947. {
  3948. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3949. if (newDest == 0)
  3950. return 0;
  3951. return new Subtract (newDest, (input == left ? right : left)->clone());
  3952. }
  3953. private:
  3954. JUCE_DECLARE_NON_COPYABLE (Add);
  3955. };
  3956. class Subtract : public BinaryTerm
  3957. {
  3958. public:
  3959. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3960. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3961. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3962. int getOperatorPrecedence() const { return 2; }
  3963. const String getFunctionName() const { return "-"; }
  3964. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3965. {
  3966. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3967. if (newDest == 0)
  3968. return 0;
  3969. if (input == left)
  3970. return new Add (newDest, right->clone());
  3971. else
  3972. return new Subtract (left->clone(), newDest);
  3973. }
  3974. private:
  3975. JUCE_DECLARE_NON_COPYABLE (Subtract);
  3976. };
  3977. class Multiply : public BinaryTerm
  3978. {
  3979. public:
  3980. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3981. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  3982. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  3983. const String getFunctionName() const { return "*"; }
  3984. int getOperatorPrecedence() const { return 1; }
  3985. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3986. {
  3987. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3988. if (newDest == 0)
  3989. return 0;
  3990. return new Divide (newDest, (input == left ? right : left)->clone());
  3991. }
  3992. private:
  3993. JUCE_DECLARE_NON_COPYABLE (Multiply);
  3994. };
  3995. class Divide : public BinaryTerm
  3996. {
  3997. public:
  3998. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3999. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4000. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4001. const String getFunctionName() const { return "/"; }
  4002. int getOperatorPrecedence() const { return 1; }
  4003. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4004. {
  4005. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4006. if (newDest == 0)
  4007. return 0;
  4008. if (input == left)
  4009. return new Multiply (newDest, right->clone());
  4010. else
  4011. return new Divide (left->clone(), newDest);
  4012. }
  4013. private:
  4014. JUCE_DECLARE_NON_COPYABLE (Divide);
  4015. };
  4016. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4017. {
  4018. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4019. if (inputIndex >= 0)
  4020. return topLevel;
  4021. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4022. {
  4023. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4024. if (t != 0)
  4025. return t;
  4026. }
  4027. return 0;
  4028. }
  4029. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4030. {
  4031. Constant* c = dynamic_cast<Constant*> (term);
  4032. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4033. return c;
  4034. if (dynamic_cast<Function*> (term) != 0)
  4035. return 0;
  4036. int i;
  4037. const int numIns = term->getNumInputs();
  4038. for (i = 0; i < numIns; ++i)
  4039. {
  4040. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4041. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4042. return c;
  4043. }
  4044. for (i = 0; i < numIns; ++i)
  4045. {
  4046. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4047. if (c != 0)
  4048. return c;
  4049. }
  4050. return 0;
  4051. }
  4052. static bool containsAnySymbols (const Term* const t)
  4053. {
  4054. if (dynamic_cast <const Symbol*> (t) != 0)
  4055. return true;
  4056. for (int i = t->getNumInputs(); --i >= 0;)
  4057. if (containsAnySymbols (t->getInput (i)))
  4058. return true;
  4059. return false;
  4060. }
  4061. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4062. {
  4063. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4064. if (sym != 0 && sym->mainSymbol == oldName)
  4065. {
  4066. sym->mainSymbol = newName;
  4067. return true;
  4068. }
  4069. bool anyChanged = false;
  4070. for (int i = t->getNumInputs(); --i >= 0;)
  4071. if (renameSymbol (t->getInput (i), oldName, newName))
  4072. anyChanged = true;
  4073. return anyChanged;
  4074. }
  4075. class Parser
  4076. {
  4077. public:
  4078. Parser (const String& stringToParse, int& textIndex_)
  4079. : textString (stringToParse), textIndex (textIndex_)
  4080. {
  4081. text = textString;
  4082. }
  4083. const TermPtr readExpression()
  4084. {
  4085. TermPtr lhs (readMultiplyOrDivideExpression());
  4086. char opType;
  4087. while (lhs != 0 && readOperator ("+-", &opType))
  4088. {
  4089. TermPtr rhs (readMultiplyOrDivideExpression());
  4090. if (rhs == 0)
  4091. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4092. if (opType == '+')
  4093. lhs = new Add (lhs, rhs);
  4094. else
  4095. lhs = new Subtract (lhs, rhs);
  4096. }
  4097. return lhs;
  4098. }
  4099. private:
  4100. const String textString;
  4101. const juce_wchar* text;
  4102. int& textIndex;
  4103. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4104. {
  4105. return c >= '0' && c <= '9';
  4106. }
  4107. void skipWhitespace (int& i)
  4108. {
  4109. while (CharacterFunctions::isWhitespace (text [i]))
  4110. ++i;
  4111. }
  4112. bool readChar (const juce_wchar required)
  4113. {
  4114. if (text[textIndex] == required)
  4115. {
  4116. ++textIndex;
  4117. return true;
  4118. }
  4119. return false;
  4120. }
  4121. bool readOperator (const char* ops, char* const opType = 0)
  4122. {
  4123. skipWhitespace (textIndex);
  4124. while (*ops != 0)
  4125. {
  4126. if (readChar (*ops))
  4127. {
  4128. if (opType != 0)
  4129. *opType = *ops;
  4130. return true;
  4131. }
  4132. ++ops;
  4133. }
  4134. return false;
  4135. }
  4136. bool readIdentifier (String& identifier)
  4137. {
  4138. skipWhitespace (textIndex);
  4139. int i = textIndex;
  4140. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4141. {
  4142. ++i;
  4143. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4144. ++i;
  4145. }
  4146. if (i > textIndex)
  4147. {
  4148. identifier = String (text + textIndex, i - textIndex);
  4149. textIndex = i;
  4150. return true;
  4151. }
  4152. return false;
  4153. }
  4154. Term* readNumber()
  4155. {
  4156. skipWhitespace (textIndex);
  4157. int i = textIndex;
  4158. const bool isResolutionTarget = (text[i] == '@');
  4159. if (isResolutionTarget)
  4160. {
  4161. ++i;
  4162. skipWhitespace (i);
  4163. textIndex = i;
  4164. }
  4165. if (text[i] == '-')
  4166. {
  4167. ++i;
  4168. skipWhitespace (i);
  4169. }
  4170. int numDigits = 0;
  4171. while (isDecimalDigit (text[i]))
  4172. {
  4173. ++i;
  4174. ++numDigits;
  4175. }
  4176. const bool hasPoint = (text[i] == '.');
  4177. if (hasPoint)
  4178. {
  4179. ++i;
  4180. while (isDecimalDigit (text[i]))
  4181. {
  4182. ++i;
  4183. ++numDigits;
  4184. }
  4185. }
  4186. if (numDigits == 0)
  4187. return 0;
  4188. juce_wchar c = text[i];
  4189. const bool hasExponent = (c == 'e' || c == 'E');
  4190. if (hasExponent)
  4191. {
  4192. ++i;
  4193. c = text[i];
  4194. if (c == '+' || c == '-')
  4195. ++i;
  4196. int numExpDigits = 0;
  4197. while (isDecimalDigit (text[i]))
  4198. {
  4199. ++i;
  4200. ++numExpDigits;
  4201. }
  4202. if (numExpDigits == 0)
  4203. return 0;
  4204. }
  4205. const int start = textIndex;
  4206. textIndex = i;
  4207. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4208. }
  4209. const TermPtr readMultiplyOrDivideExpression()
  4210. {
  4211. TermPtr lhs (readUnaryExpression());
  4212. char opType;
  4213. while (lhs != 0 && readOperator ("*/", &opType))
  4214. {
  4215. TermPtr rhs (readUnaryExpression());
  4216. if (rhs == 0)
  4217. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4218. if (opType == '*')
  4219. lhs = new Multiply (lhs, rhs);
  4220. else
  4221. lhs = new Divide (lhs, rhs);
  4222. }
  4223. return lhs;
  4224. }
  4225. const TermPtr readUnaryExpression()
  4226. {
  4227. char opType;
  4228. if (readOperator ("+-", &opType))
  4229. {
  4230. TermPtr term (readUnaryExpression());
  4231. if (term == 0)
  4232. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4233. if (opType == '-')
  4234. term = term->negated();
  4235. return term;
  4236. }
  4237. return readPrimaryExpression();
  4238. }
  4239. const TermPtr readPrimaryExpression()
  4240. {
  4241. TermPtr e (readParenthesisedExpression());
  4242. if (e != 0)
  4243. return e;
  4244. e = readNumber();
  4245. if (e != 0)
  4246. return e;
  4247. String identifier;
  4248. if (readIdentifier (identifier))
  4249. {
  4250. if (readOperator ("(")) // method call...
  4251. {
  4252. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4253. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4254. TermPtr param (readExpression());
  4255. if (param == 0)
  4256. {
  4257. if (readOperator (")"))
  4258. return func.release();
  4259. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4260. }
  4261. f->parameters.add (param);
  4262. while (readOperator (","))
  4263. {
  4264. param = readExpression();
  4265. if (param == 0)
  4266. throw ParseError ("Expected expression after \",\"");
  4267. f->parameters.add (param);
  4268. }
  4269. if (readOperator (")"))
  4270. return func.release();
  4271. throw ParseError ("Expected \")\"");
  4272. }
  4273. else // just a symbol..
  4274. {
  4275. return new Symbol (identifier);
  4276. }
  4277. }
  4278. return 0;
  4279. }
  4280. const TermPtr readParenthesisedExpression()
  4281. {
  4282. if (! readOperator ("("))
  4283. return 0;
  4284. const TermPtr e (readExpression());
  4285. if (e == 0 || ! readOperator (")"))
  4286. return 0;
  4287. return e;
  4288. }
  4289. JUCE_DECLARE_NON_COPYABLE (Parser);
  4290. };
  4291. };
  4292. Expression::Expression()
  4293. : term (new Expression::Helpers::Constant (0, false))
  4294. {
  4295. }
  4296. Expression::~Expression()
  4297. {
  4298. }
  4299. Expression::Expression (Term* const term_)
  4300. : term (term_)
  4301. {
  4302. jassert (term != 0);
  4303. }
  4304. Expression::Expression (const double constant)
  4305. : term (new Expression::Helpers::Constant (constant, false))
  4306. {
  4307. }
  4308. Expression::Expression (const Expression& other)
  4309. : term (other.term)
  4310. {
  4311. }
  4312. Expression& Expression::operator= (const Expression& other)
  4313. {
  4314. term = other.term;
  4315. return *this;
  4316. }
  4317. Expression::Expression (const String& stringToParse)
  4318. {
  4319. int i = 0;
  4320. Helpers::Parser parser (stringToParse, i);
  4321. term = parser.readExpression();
  4322. if (term == 0)
  4323. term = new Helpers::Constant (0, false);
  4324. }
  4325. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4326. {
  4327. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4328. const Helpers::TermPtr term (parser.readExpression());
  4329. if (term != 0)
  4330. return Expression (term);
  4331. return Expression();
  4332. }
  4333. double Expression::evaluate() const
  4334. {
  4335. return evaluate (Expression::EvaluationContext());
  4336. }
  4337. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4338. {
  4339. return term->evaluate (context, 0);
  4340. }
  4341. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4342. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4343. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4344. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4345. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4346. const String Expression::toString() const
  4347. {
  4348. return term->toString();
  4349. }
  4350. const Expression Expression::symbol (const String& symbol)
  4351. {
  4352. return Expression (new Helpers::Symbol (symbol));
  4353. }
  4354. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4355. {
  4356. ReferenceCountedArray<Term> params;
  4357. for (int i = 0; i < parameters.size(); ++i)
  4358. params.add (parameters.getReference(i).term);
  4359. return Expression (new Helpers::Function (functionName, params));
  4360. }
  4361. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4362. const Expression::EvaluationContext& context) const
  4363. {
  4364. ScopedPointer<Term> newTerm (term->clone());
  4365. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4366. if (termToAdjust == 0)
  4367. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4368. if (termToAdjust == 0)
  4369. {
  4370. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4371. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4372. }
  4373. jassert (termToAdjust != 0);
  4374. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4375. if (parent == 0)
  4376. {
  4377. termToAdjust->value = targetValue;
  4378. }
  4379. else
  4380. {
  4381. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4382. if (reverseTerm == 0)
  4383. return Expression (targetValue);
  4384. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4385. }
  4386. return Expression (newTerm.release());
  4387. }
  4388. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4389. {
  4390. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4391. Expression newExpression (term->clone());
  4392. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4393. return newExpression;
  4394. }
  4395. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4396. {
  4397. return term->referencesSymbol (symbol, context, 0);
  4398. }
  4399. bool Expression::usesAnySymbols() const
  4400. {
  4401. return Helpers::containsAnySymbols (term);
  4402. }
  4403. Expression::Type Expression::getType() const throw()
  4404. {
  4405. return term->getType();
  4406. }
  4407. const String Expression::getSymbol() const
  4408. {
  4409. return term->getSymbolName();
  4410. }
  4411. const String Expression::getFunction() const
  4412. {
  4413. return term->getFunctionName();
  4414. }
  4415. const String Expression::getOperator() const
  4416. {
  4417. return term->getFunctionName();
  4418. }
  4419. int Expression::getNumInputs() const
  4420. {
  4421. return term->getNumInputs();
  4422. }
  4423. const Expression Expression::getInput (int index) const
  4424. {
  4425. return Expression (term->getInput (index));
  4426. }
  4427. int Expression::Term::getOperatorPrecedence() const
  4428. {
  4429. return 0;
  4430. }
  4431. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4432. {
  4433. return false;
  4434. }
  4435. int Expression::Term::getInputIndexFor (const Term*) const
  4436. {
  4437. return -1;
  4438. }
  4439. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4440. {
  4441. jassertfalse;
  4442. return 0;
  4443. }
  4444. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4445. {
  4446. return new Helpers::Negate (this);
  4447. }
  4448. const String Expression::Term::getSymbolName() const
  4449. {
  4450. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4451. return String::empty;
  4452. }
  4453. const String Expression::Term::getFunctionName() const
  4454. {
  4455. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4456. return String::empty;
  4457. }
  4458. Expression::ParseError::ParseError (const String& message)
  4459. : description (message)
  4460. {
  4461. DBG ("Expression::ParseError: " + message);
  4462. }
  4463. Expression::EvaluationError::EvaluationError (const String& message)
  4464. : description (message)
  4465. {
  4466. DBG ("Expression::EvaluationError: " + description);
  4467. }
  4468. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4469. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4470. {
  4471. DBG ("Expression::EvaluationError: " + description);
  4472. }
  4473. Expression::EvaluationContext::EvaluationContext() {}
  4474. Expression::EvaluationContext::~EvaluationContext() {}
  4475. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4476. {
  4477. throw EvaluationError (symbol, member);
  4478. }
  4479. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4480. {
  4481. if (numParams > 0)
  4482. {
  4483. if (functionName == "min")
  4484. {
  4485. double v = parameters[0];
  4486. for (int i = 1; i < numParams; ++i)
  4487. v = jmin (v, parameters[i]);
  4488. return v;
  4489. }
  4490. else if (functionName == "max")
  4491. {
  4492. double v = parameters[0];
  4493. for (int i = 1; i < numParams; ++i)
  4494. v = jmax (v, parameters[i]);
  4495. return v;
  4496. }
  4497. else if (numParams == 1)
  4498. {
  4499. if (functionName == "sin") return sin (parameters[0]);
  4500. else if (functionName == "cos") return cos (parameters[0]);
  4501. else if (functionName == "tan") return tan (parameters[0]);
  4502. else if (functionName == "abs") return std::abs (parameters[0]);
  4503. }
  4504. }
  4505. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4506. }
  4507. END_JUCE_NAMESPACE
  4508. /*** End of inlined file: juce_Expression.cpp ***/
  4509. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4510. BEGIN_JUCE_NAMESPACE
  4511. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4512. {
  4513. jassert (keyData != 0);
  4514. jassert (keyBytes > 0);
  4515. static const uint32 initialPValues [18] =
  4516. {
  4517. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4518. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4519. 0x9216d5d9, 0x8979fb1b
  4520. };
  4521. static const uint32 initialSValues [4 * 256] =
  4522. {
  4523. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4524. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4525. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4526. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4527. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4528. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4529. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4530. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4531. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4532. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4533. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4534. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4535. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4536. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4537. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4538. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4539. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4540. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4541. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4542. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4543. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4544. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4545. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4546. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4547. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4548. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4549. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4550. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4551. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4552. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4553. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4554. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4555. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4556. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4557. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4558. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4559. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4560. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4561. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4562. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4563. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4564. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4565. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4566. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4567. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4568. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4569. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4570. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4571. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4572. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4573. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4574. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4575. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4576. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4577. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4578. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4579. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4580. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4581. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4582. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4583. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4584. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4585. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4586. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4587. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4588. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4589. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4590. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4591. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4592. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4593. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4594. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4595. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4596. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4597. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4598. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4599. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4600. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4601. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4602. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4603. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4604. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4605. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4606. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4607. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4608. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4609. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4610. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4611. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4612. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4613. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4614. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4615. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4616. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4617. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4618. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4619. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4620. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4621. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4622. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4623. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4624. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4625. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4626. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4627. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4628. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4629. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4630. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4631. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4632. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4633. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4634. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4635. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4636. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4637. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4638. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4639. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4640. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4641. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4642. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4643. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4644. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4645. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4646. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4647. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4648. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4649. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4650. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4651. };
  4652. memcpy (p, initialPValues, sizeof (p));
  4653. int i, j = 0;
  4654. for (i = 4; --i >= 0;)
  4655. {
  4656. s[i].malloc (256);
  4657. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4658. }
  4659. for (i = 0; i < 18; ++i)
  4660. {
  4661. uint32 d = 0;
  4662. for (int k = 0; k < 4; ++k)
  4663. {
  4664. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4665. if (++j >= keyBytes)
  4666. j = 0;
  4667. }
  4668. p[i] = initialPValues[i] ^ d;
  4669. }
  4670. uint32 l = 0, r = 0;
  4671. for (i = 0; i < 18; i += 2)
  4672. {
  4673. encrypt (l, r);
  4674. p[i] = l;
  4675. p[i + 1] = r;
  4676. }
  4677. for (i = 0; i < 4; ++i)
  4678. {
  4679. for (j = 0; j < 256; j += 2)
  4680. {
  4681. encrypt (l, r);
  4682. s[i][j] = l;
  4683. s[i][j + 1] = r;
  4684. }
  4685. }
  4686. }
  4687. BlowFish::BlowFish (const BlowFish& other)
  4688. {
  4689. for (int i = 4; --i >= 0;)
  4690. s[i].malloc (256);
  4691. operator= (other);
  4692. }
  4693. BlowFish& BlowFish::operator= (const BlowFish& other)
  4694. {
  4695. memcpy (p, other.p, sizeof (p));
  4696. for (int i = 4; --i >= 0;)
  4697. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4698. return *this;
  4699. }
  4700. BlowFish::~BlowFish()
  4701. {
  4702. }
  4703. uint32 BlowFish::F (const uint32 x) const throw()
  4704. {
  4705. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4706. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4707. }
  4708. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4709. {
  4710. uint32 l = data1;
  4711. uint32 r = data2;
  4712. for (int i = 0; i < 16; ++i)
  4713. {
  4714. l ^= p[i];
  4715. r ^= F(l);
  4716. swapVariables (l, r);
  4717. }
  4718. data1 = r ^ p[17];
  4719. data2 = l ^ p[16];
  4720. }
  4721. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4722. {
  4723. uint32 l = data1;
  4724. uint32 r = data2;
  4725. for (int i = 17; i > 1; --i)
  4726. {
  4727. l ^= p[i];
  4728. r ^= F(l);
  4729. swapVariables (l, r);
  4730. }
  4731. data1 = r ^ p[0];
  4732. data2 = l ^ p[1];
  4733. }
  4734. END_JUCE_NAMESPACE
  4735. /*** End of inlined file: juce_BlowFish.cpp ***/
  4736. /*** Start of inlined file: juce_MD5.cpp ***/
  4737. BEGIN_JUCE_NAMESPACE
  4738. MD5::MD5()
  4739. {
  4740. zerostruct (result);
  4741. }
  4742. MD5::MD5 (const MD5& other)
  4743. {
  4744. memcpy (result, other.result, sizeof (result));
  4745. }
  4746. MD5& MD5::operator= (const MD5& other)
  4747. {
  4748. memcpy (result, other.result, sizeof (result));
  4749. return *this;
  4750. }
  4751. MD5::MD5 (const MemoryBlock& data)
  4752. {
  4753. ProcessContext context;
  4754. context.processBlock (data.getData(), data.getSize());
  4755. context.finish (result);
  4756. }
  4757. MD5::MD5 (const void* data, const size_t numBytes)
  4758. {
  4759. ProcessContext context;
  4760. context.processBlock (data, numBytes);
  4761. context.finish (result);
  4762. }
  4763. MD5::MD5 (const String& text)
  4764. {
  4765. ProcessContext context;
  4766. const int len = text.length();
  4767. const juce_wchar* const t = text;
  4768. for (int i = 0; i < len; ++i)
  4769. {
  4770. // force the string into integer-sized unicode characters, to try to make it
  4771. // get the same results on all platforms + compilers.
  4772. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4773. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4774. }
  4775. context.finish (result);
  4776. }
  4777. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4778. {
  4779. ProcessContext context;
  4780. if (numBytesToRead < 0)
  4781. numBytesToRead = std::numeric_limits<int64>::max();
  4782. while (numBytesToRead > 0)
  4783. {
  4784. uint8 tempBuffer [512];
  4785. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4786. if (bytesRead <= 0)
  4787. break;
  4788. numBytesToRead -= bytesRead;
  4789. context.processBlock (tempBuffer, bytesRead);
  4790. }
  4791. context.finish (result);
  4792. }
  4793. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4794. {
  4795. processStream (input, numBytesToRead);
  4796. }
  4797. MD5::MD5 (const File& file)
  4798. {
  4799. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4800. if (fin != 0)
  4801. processStream (*fin, -1);
  4802. else
  4803. zerostruct (result);
  4804. }
  4805. MD5::~MD5()
  4806. {
  4807. }
  4808. namespace MD5Functions
  4809. {
  4810. void encode (void* const output, const void* const input, const int numBytes) throw()
  4811. {
  4812. for (int i = 0; i < (numBytes >> 2); ++i)
  4813. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4814. }
  4815. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4816. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4817. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4818. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4819. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4820. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4821. {
  4822. a += F (b, c, d) + x + ac;
  4823. a = rotateLeft (a, s) + b;
  4824. }
  4825. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4826. {
  4827. a += G (b, c, d) + x + ac;
  4828. a = rotateLeft (a, s) + b;
  4829. }
  4830. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4831. {
  4832. a += H (b, c, d) + x + ac;
  4833. a = rotateLeft (a, s) + b;
  4834. }
  4835. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4836. {
  4837. a += I (b, c, d) + x + ac;
  4838. a = rotateLeft (a, s) + b;
  4839. }
  4840. }
  4841. MD5::ProcessContext::ProcessContext()
  4842. {
  4843. state[0] = 0x67452301;
  4844. state[1] = 0xefcdab89;
  4845. state[2] = 0x98badcfe;
  4846. state[3] = 0x10325476;
  4847. count[0] = 0;
  4848. count[1] = 0;
  4849. }
  4850. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4851. {
  4852. int bufferPos = ((count[0] >> 3) & 0x3F);
  4853. count[0] += (uint32) (dataSize << 3);
  4854. if (count[0] < ((uint32) dataSize << 3))
  4855. count[1]++;
  4856. count[1] += (uint32) (dataSize >> 29);
  4857. const size_t spaceLeft = 64 - bufferPos;
  4858. size_t i = 0;
  4859. if (dataSize >= spaceLeft)
  4860. {
  4861. memcpy (buffer + bufferPos, data, spaceLeft);
  4862. transform (buffer);
  4863. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4864. transform (static_cast <const char*> (data) + i);
  4865. bufferPos = 0;
  4866. }
  4867. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4868. }
  4869. void MD5::ProcessContext::finish (void* const result)
  4870. {
  4871. unsigned char encodedLength[8];
  4872. MD5Functions::encode (encodedLength, count, 8);
  4873. // Pad out to 56 mod 64.
  4874. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4875. const int paddingLength = (index < 56) ? (56 - index)
  4876. : (120 - index);
  4877. uint8 paddingBuffer [64];
  4878. zeromem (paddingBuffer, paddingLength);
  4879. paddingBuffer [0] = 0x80;
  4880. processBlock (paddingBuffer, paddingLength);
  4881. processBlock (encodedLength, 8);
  4882. MD5Functions::encode (result, state, 16);
  4883. zerostruct (buffer);
  4884. }
  4885. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4886. {
  4887. using namespace MD5Functions;
  4888. uint32 a = state[0];
  4889. uint32 b = state[1];
  4890. uint32 c = state[2];
  4891. uint32 d = state[3];
  4892. uint32 x[16];
  4893. encode (x, bufferToTransform, 64);
  4894. enum Constants
  4895. {
  4896. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4897. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4898. };
  4899. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4900. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4901. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4902. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4903. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4904. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4905. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4906. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4907. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4908. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4909. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4910. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4911. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4912. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4913. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4914. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4915. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4916. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4917. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4918. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4919. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4920. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4921. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4922. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4923. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4924. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4925. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4926. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4927. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4928. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4929. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4930. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4931. state[0] += a;
  4932. state[1] += b;
  4933. state[2] += c;
  4934. state[3] += d;
  4935. zerostruct (x);
  4936. }
  4937. const MemoryBlock MD5::getRawChecksumData() const
  4938. {
  4939. return MemoryBlock (result, sizeof (result));
  4940. }
  4941. const String MD5::toHexString() const
  4942. {
  4943. return String::toHexString (result, sizeof (result), 0);
  4944. }
  4945. bool MD5::operator== (const MD5& other) const
  4946. {
  4947. return memcmp (result, other.result, sizeof (result)) == 0;
  4948. }
  4949. bool MD5::operator!= (const MD5& other) const
  4950. {
  4951. return ! operator== (other);
  4952. }
  4953. END_JUCE_NAMESPACE
  4954. /*** End of inlined file: juce_MD5.cpp ***/
  4955. /*** Start of inlined file: juce_Primes.cpp ***/
  4956. BEGIN_JUCE_NAMESPACE
  4957. namespace PrimesHelpers
  4958. {
  4959. void createSmallSieve (const int numBits, BigInteger& result)
  4960. {
  4961. result.setBit (numBits);
  4962. result.clearBit (numBits); // to enlarge the array
  4963. result.setBit (0);
  4964. int n = 2;
  4965. do
  4966. {
  4967. for (int i = n + n; i < numBits; i += n)
  4968. result.setBit (i);
  4969. n = result.findNextClearBit (n + 1);
  4970. }
  4971. while (n <= (numBits >> 1));
  4972. }
  4973. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4974. const BigInteger& smallSieve, const int smallSieveSize)
  4975. {
  4976. jassert (! base[0]); // must be even!
  4977. result.setBit (numBits);
  4978. result.clearBit (numBits); // to enlarge the array
  4979. int index = smallSieve.findNextClearBit (0);
  4980. do
  4981. {
  4982. const int prime = (index << 1) + 1;
  4983. BigInteger r (base), remainder;
  4984. r.divideBy (prime, remainder);
  4985. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4986. if (r.isZero())
  4987. i += prime;
  4988. if ((i & 1) == 0)
  4989. i += prime;
  4990. i = (i - 1) >> 1;
  4991. while (i < numBits)
  4992. {
  4993. result.setBit (i);
  4994. i += prime;
  4995. }
  4996. index = smallSieve.findNextClearBit (index + 1);
  4997. }
  4998. while (index < smallSieveSize);
  4999. }
  5000. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5001. const int numBits, BigInteger& result, const int certainty)
  5002. {
  5003. for (int i = 0; i < numBits; ++i)
  5004. {
  5005. if (! sieve[i])
  5006. {
  5007. result = base + (unsigned int) ((i << 1) + 1);
  5008. if (Primes::isProbablyPrime (result, certainty))
  5009. return true;
  5010. }
  5011. }
  5012. return false;
  5013. }
  5014. bool passesMillerRabin (const BigInteger& n, int iterations)
  5015. {
  5016. const BigInteger one (1), two (2);
  5017. const BigInteger nMinusOne (n - one);
  5018. BigInteger d (nMinusOne);
  5019. const int s = d.findNextSetBit (0);
  5020. d >>= s;
  5021. BigInteger smallPrimes;
  5022. int numBitsInSmallPrimes = 0;
  5023. for (;;)
  5024. {
  5025. numBitsInSmallPrimes += 256;
  5026. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5027. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5028. if (numPrimesFound > iterations + 1)
  5029. break;
  5030. }
  5031. int smallPrime = 2;
  5032. while (--iterations >= 0)
  5033. {
  5034. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5035. BigInteger r (smallPrime);
  5036. r.exponentModulo (d, n);
  5037. if (r != one && r != nMinusOne)
  5038. {
  5039. for (int j = 0; j < s; ++j)
  5040. {
  5041. r.exponentModulo (two, n);
  5042. if (r == nMinusOne)
  5043. break;
  5044. }
  5045. if (r != nMinusOne)
  5046. return false;
  5047. }
  5048. }
  5049. return true;
  5050. }
  5051. }
  5052. const BigInteger Primes::createProbablePrime (const int bitLength,
  5053. const int certainty,
  5054. const int* randomSeeds,
  5055. int numRandomSeeds)
  5056. {
  5057. using namespace PrimesHelpers;
  5058. int defaultSeeds [16];
  5059. if (numRandomSeeds <= 0)
  5060. {
  5061. randomSeeds = defaultSeeds;
  5062. numRandomSeeds = numElementsInArray (defaultSeeds);
  5063. Random r (0);
  5064. for (int j = 10; --j >= 0;)
  5065. {
  5066. r.setSeedRandomly();
  5067. for (int i = numRandomSeeds; --i >= 0;)
  5068. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5069. }
  5070. }
  5071. BigInteger smallSieve;
  5072. const int smallSieveSize = 15000;
  5073. createSmallSieve (smallSieveSize, smallSieve);
  5074. BigInteger p;
  5075. for (int i = numRandomSeeds; --i >= 0;)
  5076. {
  5077. BigInteger p2;
  5078. Random r (randomSeeds[i]);
  5079. r.fillBitsRandomly (p2, 0, bitLength);
  5080. p ^= p2;
  5081. }
  5082. p.setBit (bitLength - 1);
  5083. p.clearBit (0);
  5084. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5085. while (p.getHighestBit() < bitLength)
  5086. {
  5087. p += 2 * searchLen;
  5088. BigInteger sieve;
  5089. bigSieve (p, searchLen, sieve,
  5090. smallSieve, smallSieveSize);
  5091. BigInteger candidate;
  5092. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5093. return candidate;
  5094. }
  5095. jassertfalse;
  5096. return BigInteger();
  5097. }
  5098. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5099. {
  5100. using namespace PrimesHelpers;
  5101. if (! number[0])
  5102. return false;
  5103. if (number.getHighestBit() <= 10)
  5104. {
  5105. const int num = number.getBitRangeAsInt (0, 10);
  5106. for (int i = num / 2; --i > 1;)
  5107. if (num % i == 0)
  5108. return false;
  5109. return true;
  5110. }
  5111. else
  5112. {
  5113. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5114. return false;
  5115. return passesMillerRabin (number, certainty);
  5116. }
  5117. }
  5118. END_JUCE_NAMESPACE
  5119. /*** End of inlined file: juce_Primes.cpp ***/
  5120. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5121. BEGIN_JUCE_NAMESPACE
  5122. RSAKey::RSAKey()
  5123. {
  5124. }
  5125. RSAKey::RSAKey (const String& s)
  5126. {
  5127. if (s.containsChar (','))
  5128. {
  5129. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5130. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5131. }
  5132. else
  5133. {
  5134. // the string needs to be two hex numbers, comma-separated..
  5135. jassertfalse;
  5136. }
  5137. }
  5138. RSAKey::~RSAKey()
  5139. {
  5140. }
  5141. bool RSAKey::operator== (const RSAKey& other) const throw()
  5142. {
  5143. return part1 == other.part1 && part2 == other.part2;
  5144. }
  5145. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5146. {
  5147. return ! operator== (other);
  5148. }
  5149. const String RSAKey::toString() const
  5150. {
  5151. return part1.toString (16) + "," + part2.toString (16);
  5152. }
  5153. bool RSAKey::applyToValue (BigInteger& value) const
  5154. {
  5155. if (part1.isZero() || part2.isZero() || value <= 0)
  5156. {
  5157. jassertfalse; // using an uninitialised key
  5158. value.clear();
  5159. return false;
  5160. }
  5161. BigInteger result;
  5162. while (! value.isZero())
  5163. {
  5164. result *= part2;
  5165. BigInteger remainder;
  5166. value.divideBy (part2, remainder);
  5167. remainder.exponentModulo (part1, part2);
  5168. result += remainder;
  5169. }
  5170. value.swapWith (result);
  5171. return true;
  5172. }
  5173. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5174. {
  5175. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5176. // are fast to divide + multiply
  5177. for (int i = 2; i <= 65536; i *= 2)
  5178. {
  5179. const BigInteger e (1 + i);
  5180. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5181. return e;
  5182. }
  5183. BigInteger e (4);
  5184. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5185. ++e;
  5186. return e;
  5187. }
  5188. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5189. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5190. {
  5191. jassert (numBits > 16); // not much point using less than this..
  5192. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5193. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5194. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5195. const BigInteger n (p * q);
  5196. const BigInteger m (--p * --q);
  5197. const BigInteger e (findBestCommonDivisor (p, q));
  5198. BigInteger d (e);
  5199. d.inverseModulo (m);
  5200. publicKey.part1 = e;
  5201. publicKey.part2 = n;
  5202. privateKey.part1 = d;
  5203. privateKey.part2 = n;
  5204. }
  5205. END_JUCE_NAMESPACE
  5206. /*** End of inlined file: juce_RSAKey.cpp ***/
  5207. /*** Start of inlined file: juce_InputStream.cpp ***/
  5208. BEGIN_JUCE_NAMESPACE
  5209. char InputStream::readByte()
  5210. {
  5211. char temp = 0;
  5212. read (&temp, 1);
  5213. return temp;
  5214. }
  5215. bool InputStream::readBool()
  5216. {
  5217. return readByte() != 0;
  5218. }
  5219. short InputStream::readShort()
  5220. {
  5221. char temp[2];
  5222. if (read (temp, 2) == 2)
  5223. return (short) ByteOrder::littleEndianShort (temp);
  5224. return 0;
  5225. }
  5226. short InputStream::readShortBigEndian()
  5227. {
  5228. char temp[2];
  5229. if (read (temp, 2) == 2)
  5230. return (short) ByteOrder::bigEndianShort (temp);
  5231. return 0;
  5232. }
  5233. int InputStream::readInt()
  5234. {
  5235. char temp[4];
  5236. if (read (temp, 4) == 4)
  5237. return (int) ByteOrder::littleEndianInt (temp);
  5238. return 0;
  5239. }
  5240. int InputStream::readIntBigEndian()
  5241. {
  5242. char temp[4];
  5243. if (read (temp, 4) == 4)
  5244. return (int) ByteOrder::bigEndianInt (temp);
  5245. return 0;
  5246. }
  5247. int InputStream::readCompressedInt()
  5248. {
  5249. const unsigned char sizeByte = readByte();
  5250. if (sizeByte == 0)
  5251. return 0;
  5252. const int numBytes = (sizeByte & 0x7f);
  5253. if (numBytes > 4)
  5254. {
  5255. jassertfalse; // trying to read corrupt data - this method must only be used
  5256. // to read data that was written by OutputStream::writeCompressedInt()
  5257. return 0;
  5258. }
  5259. char bytes[4] = { 0, 0, 0, 0 };
  5260. if (read (bytes, numBytes) != numBytes)
  5261. return 0;
  5262. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5263. return (sizeByte >> 7) ? -num : num;
  5264. }
  5265. int64 InputStream::readInt64()
  5266. {
  5267. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5268. if (read (n.asBytes, 8) == 8)
  5269. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5270. return 0;
  5271. }
  5272. int64 InputStream::readInt64BigEndian()
  5273. {
  5274. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5275. if (read (n.asBytes, 8) == 8)
  5276. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5277. return 0;
  5278. }
  5279. float InputStream::readFloat()
  5280. {
  5281. // the union below relies on these types being the same size...
  5282. static_jassert (sizeof (int32) == sizeof (float));
  5283. union { int32 asInt; float asFloat; } n;
  5284. n.asInt = (int32) readInt();
  5285. return n.asFloat;
  5286. }
  5287. float InputStream::readFloatBigEndian()
  5288. {
  5289. union { int32 asInt; float asFloat; } n;
  5290. n.asInt = (int32) readIntBigEndian();
  5291. return n.asFloat;
  5292. }
  5293. double InputStream::readDouble()
  5294. {
  5295. union { int64 asInt; double asDouble; } n;
  5296. n.asInt = readInt64();
  5297. return n.asDouble;
  5298. }
  5299. double InputStream::readDoubleBigEndian()
  5300. {
  5301. union { int64 asInt; double asDouble; } n;
  5302. n.asInt = readInt64BigEndian();
  5303. return n.asDouble;
  5304. }
  5305. const String InputStream::readString()
  5306. {
  5307. MemoryBlock buffer (256);
  5308. char* data = static_cast<char*> (buffer.getData());
  5309. size_t i = 0;
  5310. while ((data[i] = readByte()) != 0)
  5311. {
  5312. if (++i >= buffer.getSize())
  5313. {
  5314. buffer.setSize (buffer.getSize() + 512);
  5315. data = static_cast<char*> (buffer.getData());
  5316. }
  5317. }
  5318. return String::fromUTF8 (data, (int) i);
  5319. }
  5320. const String InputStream::readNextLine()
  5321. {
  5322. MemoryBlock buffer (256);
  5323. char* data = static_cast<char*> (buffer.getData());
  5324. size_t i = 0;
  5325. while ((data[i] = readByte()) != 0)
  5326. {
  5327. if (data[i] == '\n')
  5328. break;
  5329. if (data[i] == '\r')
  5330. {
  5331. const int64 lastPos = getPosition();
  5332. if (readByte() != '\n')
  5333. setPosition (lastPos);
  5334. break;
  5335. }
  5336. if (++i >= buffer.getSize())
  5337. {
  5338. buffer.setSize (buffer.getSize() + 512);
  5339. data = static_cast<char*> (buffer.getData());
  5340. }
  5341. }
  5342. return String::fromUTF8 (data, (int) i);
  5343. }
  5344. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5345. {
  5346. MemoryOutputStream mo (block, true);
  5347. return mo.writeFromInputStream (*this, numBytes);
  5348. }
  5349. const String InputStream::readEntireStreamAsString()
  5350. {
  5351. MemoryOutputStream mo;
  5352. mo.writeFromInputStream (*this, -1);
  5353. return mo.toString();
  5354. }
  5355. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5356. {
  5357. if (numBytesToSkip > 0)
  5358. {
  5359. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5360. HeapBlock<char> temp (skipBufferSize);
  5361. while (numBytesToSkip > 0 && ! isExhausted())
  5362. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5363. }
  5364. }
  5365. END_JUCE_NAMESPACE
  5366. /*** End of inlined file: juce_InputStream.cpp ***/
  5367. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5368. BEGIN_JUCE_NAMESPACE
  5369. #if JUCE_DEBUG
  5370. static Array<void*, CriticalSection> activeStreams;
  5371. void juce_CheckForDanglingStreams()
  5372. {
  5373. /*
  5374. It's always a bad idea to leak any object, but if you're leaking output
  5375. streams, then there's a good chance that you're failing to flush a file
  5376. to disk properly, which could result in corrupted data and other similar
  5377. nastiness..
  5378. */
  5379. jassert (activeStreams.size() == 0);
  5380. };
  5381. #endif
  5382. OutputStream::OutputStream()
  5383. : newLineString (NewLine::getDefault())
  5384. {
  5385. #if JUCE_DEBUG
  5386. activeStreams.add (this);
  5387. #endif
  5388. }
  5389. OutputStream::~OutputStream()
  5390. {
  5391. #if JUCE_DEBUG
  5392. activeStreams.removeValue (this);
  5393. #endif
  5394. }
  5395. void OutputStream::writeBool (const bool b)
  5396. {
  5397. writeByte (b ? (char) 1
  5398. : (char) 0);
  5399. }
  5400. void OutputStream::writeByte (char byte)
  5401. {
  5402. write (&byte, 1);
  5403. }
  5404. void OutputStream::writeShort (short value)
  5405. {
  5406. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5407. write (&v, 2);
  5408. }
  5409. void OutputStream::writeShortBigEndian (short value)
  5410. {
  5411. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5412. write (&v, 2);
  5413. }
  5414. void OutputStream::writeInt (int value)
  5415. {
  5416. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5417. write (&v, 4);
  5418. }
  5419. void OutputStream::writeIntBigEndian (int value)
  5420. {
  5421. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5422. write (&v, 4);
  5423. }
  5424. void OutputStream::writeCompressedInt (int value)
  5425. {
  5426. unsigned int un = (value < 0) ? (unsigned int) -value
  5427. : (unsigned int) value;
  5428. uint8 data[5];
  5429. int num = 0;
  5430. while (un > 0)
  5431. {
  5432. data[++num] = (uint8) un;
  5433. un >>= 8;
  5434. }
  5435. data[0] = (uint8) num;
  5436. if (value < 0)
  5437. data[0] |= 0x80;
  5438. write (data, num + 1);
  5439. }
  5440. void OutputStream::writeInt64 (int64 value)
  5441. {
  5442. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5443. write (&v, 8);
  5444. }
  5445. void OutputStream::writeInt64BigEndian (int64 value)
  5446. {
  5447. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5448. write (&v, 8);
  5449. }
  5450. void OutputStream::writeFloat (float value)
  5451. {
  5452. union { int asInt; float asFloat; } n;
  5453. n.asFloat = value;
  5454. writeInt (n.asInt);
  5455. }
  5456. void OutputStream::writeFloatBigEndian (float value)
  5457. {
  5458. union { int asInt; float asFloat; } n;
  5459. n.asFloat = value;
  5460. writeIntBigEndian (n.asInt);
  5461. }
  5462. void OutputStream::writeDouble (double value)
  5463. {
  5464. union { int64 asInt; double asDouble; } n;
  5465. n.asDouble = value;
  5466. writeInt64 (n.asInt);
  5467. }
  5468. void OutputStream::writeDoubleBigEndian (double value)
  5469. {
  5470. union { int64 asInt; double asDouble; } n;
  5471. n.asDouble = value;
  5472. writeInt64BigEndian (n.asInt);
  5473. }
  5474. void OutputStream::writeString (const String& text)
  5475. {
  5476. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5477. // if lots of large, persistent strings were to be written to streams).
  5478. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5479. HeapBlock<char> temp (numBytes);
  5480. text.copyToUTF8 (temp, numBytes);
  5481. write (temp, numBytes);
  5482. }
  5483. void OutputStream::writeText (const String& text, const bool asUnicode,
  5484. const bool writeUnicodeHeaderBytes)
  5485. {
  5486. if (asUnicode)
  5487. {
  5488. if (writeUnicodeHeaderBytes)
  5489. write ("\x0ff\x0fe", 2);
  5490. const juce_wchar* src = text;
  5491. bool lastCharWasReturn = false;
  5492. while (*src != 0)
  5493. {
  5494. if (*src == L'\n' && ! lastCharWasReturn)
  5495. writeShort ((short) L'\r');
  5496. lastCharWasReturn = (*src == L'\r');
  5497. writeShort ((short) *src++);
  5498. }
  5499. }
  5500. else
  5501. {
  5502. const char* src = text.toUTF8();
  5503. const char* t = src;
  5504. for (;;)
  5505. {
  5506. if (*t == '\n')
  5507. {
  5508. if (t > src)
  5509. write (src, (int) (t - src));
  5510. write ("\r\n", 2);
  5511. src = t + 1;
  5512. }
  5513. else if (*t == '\r')
  5514. {
  5515. if (t[1] == '\n')
  5516. ++t;
  5517. }
  5518. else if (*t == 0)
  5519. {
  5520. if (t > src)
  5521. write (src, (int) (t - src));
  5522. break;
  5523. }
  5524. ++t;
  5525. }
  5526. }
  5527. }
  5528. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5529. {
  5530. if (numBytesToWrite < 0)
  5531. numBytesToWrite = std::numeric_limits<int64>::max();
  5532. int numWritten = 0;
  5533. while (numBytesToWrite > 0 && ! source.isExhausted())
  5534. {
  5535. char buffer [8192];
  5536. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5537. if (num <= 0)
  5538. break;
  5539. write (buffer, num);
  5540. numBytesToWrite -= num;
  5541. numWritten += num;
  5542. }
  5543. return numWritten;
  5544. }
  5545. void OutputStream::setNewLineString (const String& newLineString_)
  5546. {
  5547. newLineString = newLineString_;
  5548. }
  5549. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5550. {
  5551. return stream << String (number);
  5552. }
  5553. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5554. {
  5555. return stream << String (number);
  5556. }
  5557. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5558. {
  5559. stream.writeByte (character);
  5560. return stream;
  5561. }
  5562. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5563. {
  5564. stream.write (text, (int) strlen (text));
  5565. return stream;
  5566. }
  5567. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5568. {
  5569. stream.write (data.getData(), (int) data.getSize());
  5570. return stream;
  5571. }
  5572. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5573. {
  5574. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5575. if (in != 0)
  5576. stream.writeFromInputStream (*in, -1);
  5577. return stream;
  5578. }
  5579. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5580. {
  5581. return stream << stream.getNewLineString();
  5582. }
  5583. END_JUCE_NAMESPACE
  5584. /*** End of inlined file: juce_OutputStream.cpp ***/
  5585. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5586. BEGIN_JUCE_NAMESPACE
  5587. DirectoryIterator::DirectoryIterator (const File& directory,
  5588. bool isRecursive_,
  5589. const String& wildCard_,
  5590. const int whatToLookFor_)
  5591. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5592. wildCard (wildCard_),
  5593. path (File::addTrailingSeparator (directory.getFullPathName())),
  5594. index (-1),
  5595. totalNumFiles (-1),
  5596. whatToLookFor (whatToLookFor_),
  5597. isRecursive (isRecursive_),
  5598. hasBeenAdvanced (false)
  5599. {
  5600. // you have to specify the type of files you're looking for!
  5601. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5602. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5603. }
  5604. DirectoryIterator::~DirectoryIterator()
  5605. {
  5606. }
  5607. bool DirectoryIterator::next()
  5608. {
  5609. return next (0, 0, 0, 0, 0, 0);
  5610. }
  5611. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5612. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5613. {
  5614. hasBeenAdvanced = true;
  5615. if (subIterator != 0)
  5616. {
  5617. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5618. return true;
  5619. subIterator = 0;
  5620. }
  5621. String filename;
  5622. bool isDirectory, isHidden;
  5623. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5624. {
  5625. ++index;
  5626. if (! filename.containsOnly ("."))
  5627. {
  5628. const File fileFound (path + filename, 0);
  5629. bool matches = false;
  5630. if (isDirectory)
  5631. {
  5632. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5633. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5634. matches = (whatToLookFor & File::findDirectories) != 0;
  5635. }
  5636. else
  5637. {
  5638. matches = (whatToLookFor & File::findFiles) != 0;
  5639. }
  5640. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5641. if (matches && isRecursive)
  5642. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5643. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5644. matches = ! isHidden;
  5645. if (matches)
  5646. {
  5647. currentFile = fileFound;
  5648. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5649. if (isDirResult != 0) *isDirResult = isDirectory;
  5650. return true;
  5651. }
  5652. else if (subIterator != 0)
  5653. {
  5654. return next();
  5655. }
  5656. }
  5657. }
  5658. return false;
  5659. }
  5660. const File DirectoryIterator::getFile() const
  5661. {
  5662. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5663. return subIterator->getFile();
  5664. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5665. jassert (hasBeenAdvanced);
  5666. return currentFile;
  5667. }
  5668. float DirectoryIterator::getEstimatedProgress() const
  5669. {
  5670. if (totalNumFiles < 0)
  5671. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5672. if (totalNumFiles <= 0)
  5673. return 0.0f;
  5674. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5675. : (float) index;
  5676. return detailedIndex / totalNumFiles;
  5677. }
  5678. END_JUCE_NAMESPACE
  5679. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5680. /*** Start of inlined file: juce_File.cpp ***/
  5681. #if ! JUCE_WINDOWS
  5682. #include <pwd.h>
  5683. #endif
  5684. BEGIN_JUCE_NAMESPACE
  5685. File::File (const String& fullPathName)
  5686. : fullPath (parseAbsolutePath (fullPathName))
  5687. {
  5688. }
  5689. File::File (const String& path, int)
  5690. : fullPath (path)
  5691. {
  5692. }
  5693. const File File::createFileWithoutCheckingPath (const String& path)
  5694. {
  5695. return File (path, 0);
  5696. }
  5697. File::File (const File& other)
  5698. : fullPath (other.fullPath)
  5699. {
  5700. }
  5701. File& File::operator= (const String& newPath)
  5702. {
  5703. fullPath = parseAbsolutePath (newPath);
  5704. return *this;
  5705. }
  5706. File& File::operator= (const File& other)
  5707. {
  5708. fullPath = other.fullPath;
  5709. return *this;
  5710. }
  5711. const File File::nonexistent;
  5712. const String File::parseAbsolutePath (const String& p)
  5713. {
  5714. if (p.isEmpty())
  5715. return String::empty;
  5716. #if JUCE_WINDOWS
  5717. // Windows..
  5718. String path (p.replaceCharacter ('/', '\\'));
  5719. if (path.startsWithChar (File::separator))
  5720. {
  5721. if (path[1] != File::separator)
  5722. {
  5723. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5724. If you're trying to parse a string that may be either a relative path or an absolute path,
  5725. you MUST provide a context against which the partial path can be evaluated - you can do
  5726. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5727. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5728. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5729. */
  5730. jassertfalse;
  5731. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5732. }
  5733. }
  5734. else if (! path.containsChar (':'))
  5735. {
  5736. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5737. If you're trying to parse a string that may be either a relative path or an absolute path,
  5738. you MUST provide a context against which the partial path can be evaluated - you can do
  5739. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5740. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5741. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5742. */
  5743. jassertfalse;
  5744. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5745. }
  5746. #else
  5747. // Mac or Linux..
  5748. String path (p.replaceCharacter ('\\', '/'));
  5749. if (path.startsWithChar ('~'))
  5750. {
  5751. if (path[1] == File::separator || path[1] == 0)
  5752. {
  5753. // expand a name of the form "~/abc"
  5754. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5755. + path.substring (1);
  5756. }
  5757. else
  5758. {
  5759. // expand a name of type "~dave/abc"
  5760. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5761. struct passwd* const pw = getpwnam (userName.toUTF8());
  5762. if (pw != 0)
  5763. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5764. }
  5765. }
  5766. else if (! path.startsWithChar (File::separator))
  5767. {
  5768. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5769. If you're trying to parse a string that may be either a relative path or an absolute path,
  5770. you MUST provide a context against which the partial path can be evaluated - you can do
  5771. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5772. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5773. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5774. */
  5775. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5776. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5777. }
  5778. #endif
  5779. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5780. path = path.dropLastCharacters (1);
  5781. return path;
  5782. }
  5783. const String File::addTrailingSeparator (const String& path)
  5784. {
  5785. return path.endsWithChar (File::separator) ? path
  5786. : path + File::separator;
  5787. }
  5788. #if JUCE_LINUX
  5789. #define NAMES_ARE_CASE_SENSITIVE 1
  5790. #endif
  5791. bool File::areFileNamesCaseSensitive()
  5792. {
  5793. #if NAMES_ARE_CASE_SENSITIVE
  5794. return true;
  5795. #else
  5796. return false;
  5797. #endif
  5798. }
  5799. bool File::operator== (const File& other) const
  5800. {
  5801. #if NAMES_ARE_CASE_SENSITIVE
  5802. return fullPath == other.fullPath;
  5803. #else
  5804. return fullPath.equalsIgnoreCase (other.fullPath);
  5805. #endif
  5806. }
  5807. bool File::operator!= (const File& other) const
  5808. {
  5809. return ! operator== (other);
  5810. }
  5811. bool File::operator< (const File& other) const
  5812. {
  5813. #if NAMES_ARE_CASE_SENSITIVE
  5814. return fullPath < other.fullPath;
  5815. #else
  5816. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5817. #endif
  5818. }
  5819. bool File::operator> (const File& other) const
  5820. {
  5821. #if NAMES_ARE_CASE_SENSITIVE
  5822. return fullPath > other.fullPath;
  5823. #else
  5824. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5825. #endif
  5826. }
  5827. bool File::setReadOnly (const bool shouldBeReadOnly,
  5828. const bool applyRecursively) const
  5829. {
  5830. bool worked = true;
  5831. if (applyRecursively && isDirectory())
  5832. {
  5833. Array <File> subFiles;
  5834. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5835. for (int i = subFiles.size(); --i >= 0;)
  5836. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5837. }
  5838. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5839. }
  5840. bool File::deleteRecursively() const
  5841. {
  5842. bool worked = true;
  5843. if (isDirectory())
  5844. {
  5845. Array<File> subFiles;
  5846. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5847. for (int i = subFiles.size(); --i >= 0;)
  5848. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5849. }
  5850. return deleteFile() && worked;
  5851. }
  5852. bool File::moveFileTo (const File& newFile) const
  5853. {
  5854. if (newFile.fullPath == fullPath)
  5855. return true;
  5856. #if ! NAMES_ARE_CASE_SENSITIVE
  5857. if (*this != newFile)
  5858. #endif
  5859. if (! newFile.deleteFile())
  5860. return false;
  5861. return moveInternal (newFile);
  5862. }
  5863. bool File::copyFileTo (const File& newFile) const
  5864. {
  5865. return (*this == newFile)
  5866. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5867. }
  5868. bool File::copyDirectoryTo (const File& newDirectory) const
  5869. {
  5870. if (isDirectory() && newDirectory.createDirectory())
  5871. {
  5872. Array<File> subFiles;
  5873. findChildFiles (subFiles, File::findFiles, false);
  5874. int i;
  5875. for (i = 0; i < subFiles.size(); ++i)
  5876. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5877. return false;
  5878. subFiles.clear();
  5879. findChildFiles (subFiles, File::findDirectories, false);
  5880. for (i = 0; i < subFiles.size(); ++i)
  5881. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5882. return false;
  5883. return true;
  5884. }
  5885. return false;
  5886. }
  5887. const String File::getPathUpToLastSlash() const
  5888. {
  5889. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5890. if (lastSlash > 0)
  5891. return fullPath.substring (0, lastSlash);
  5892. else if (lastSlash == 0)
  5893. return separatorString;
  5894. else
  5895. return fullPath;
  5896. }
  5897. const File File::getParentDirectory() const
  5898. {
  5899. return File (getPathUpToLastSlash(), (int) 0);
  5900. }
  5901. const String File::getFileName() const
  5902. {
  5903. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5904. }
  5905. int File::hashCode() const
  5906. {
  5907. return fullPath.hashCode();
  5908. }
  5909. int64 File::hashCode64() const
  5910. {
  5911. return fullPath.hashCode64();
  5912. }
  5913. const String File::getFileNameWithoutExtension() const
  5914. {
  5915. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5916. const int lastDot = fullPath.lastIndexOfChar ('.');
  5917. if (lastDot > lastSlash)
  5918. return fullPath.substring (lastSlash, lastDot);
  5919. else
  5920. return fullPath.substring (lastSlash);
  5921. }
  5922. bool File::isAChildOf (const File& potentialParent) const
  5923. {
  5924. if (potentialParent == File::nonexistent)
  5925. return false;
  5926. const String ourPath (getPathUpToLastSlash());
  5927. #if NAMES_ARE_CASE_SENSITIVE
  5928. if (potentialParent.fullPath == ourPath)
  5929. #else
  5930. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5931. #endif
  5932. {
  5933. return true;
  5934. }
  5935. else if (potentialParent.fullPath.length() >= ourPath.length())
  5936. {
  5937. return false;
  5938. }
  5939. else
  5940. {
  5941. return getParentDirectory().isAChildOf (potentialParent);
  5942. }
  5943. }
  5944. bool File::isAbsolutePath (const String& path)
  5945. {
  5946. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5947. #if JUCE_WINDOWS
  5948. || (path.isNotEmpty() && path[1] == ':');
  5949. #else
  5950. || path.startsWithChar ('~');
  5951. #endif
  5952. }
  5953. const File File::getChildFile (String relativePath) const
  5954. {
  5955. if (isAbsolutePath (relativePath))
  5956. {
  5957. // the path is really absolute..
  5958. return File (relativePath);
  5959. }
  5960. else
  5961. {
  5962. // it's relative, so remove any ../ or ./ bits at the start.
  5963. String path (fullPath);
  5964. if (relativePath[0] == '.')
  5965. {
  5966. #if JUCE_WINDOWS
  5967. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5968. #else
  5969. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5970. #endif
  5971. while (relativePath[0] == '.')
  5972. {
  5973. if (relativePath[1] == '.')
  5974. {
  5975. if (relativePath [2] == 0 || relativePath[2] == separator)
  5976. {
  5977. const int lastSlash = path.lastIndexOfChar (separator);
  5978. if (lastSlash >= 0)
  5979. path = path.substring (0, lastSlash);
  5980. relativePath = relativePath.substring (3);
  5981. }
  5982. else
  5983. {
  5984. break;
  5985. }
  5986. }
  5987. else if (relativePath[1] == separator)
  5988. {
  5989. relativePath = relativePath.substring (2);
  5990. }
  5991. else
  5992. {
  5993. break;
  5994. }
  5995. }
  5996. }
  5997. return File (addTrailingSeparator (path) + relativePath);
  5998. }
  5999. }
  6000. const File File::getSiblingFile (const String& fileName) const
  6001. {
  6002. return getParentDirectory().getChildFile (fileName);
  6003. }
  6004. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6005. {
  6006. if (bytes == 1)
  6007. {
  6008. return "1 byte";
  6009. }
  6010. else if (bytes < 1024)
  6011. {
  6012. return String ((int) bytes) + " bytes";
  6013. }
  6014. else if (bytes < 1024 * 1024)
  6015. {
  6016. return String (bytes / 1024.0, 1) + " KB";
  6017. }
  6018. else if (bytes < 1024 * 1024 * 1024)
  6019. {
  6020. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6021. }
  6022. else
  6023. {
  6024. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6025. }
  6026. }
  6027. bool File::create() const
  6028. {
  6029. if (exists())
  6030. return true;
  6031. {
  6032. const File parentDir (getParentDirectory());
  6033. if (parentDir == *this || ! parentDir.createDirectory())
  6034. return false;
  6035. FileOutputStream fo (*this, 8);
  6036. }
  6037. return exists();
  6038. }
  6039. bool File::createDirectory() const
  6040. {
  6041. if (! isDirectory())
  6042. {
  6043. const File parentDir (getParentDirectory());
  6044. if (parentDir == *this || ! parentDir.createDirectory())
  6045. return false;
  6046. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6047. return isDirectory();
  6048. }
  6049. return true;
  6050. }
  6051. const Time File::getCreationTime() const
  6052. {
  6053. int64 m, a, c;
  6054. getFileTimesInternal (m, a, c);
  6055. return Time (c);
  6056. }
  6057. const Time File::getLastModificationTime() const
  6058. {
  6059. int64 m, a, c;
  6060. getFileTimesInternal (m, a, c);
  6061. return Time (m);
  6062. }
  6063. const Time File::getLastAccessTime() const
  6064. {
  6065. int64 m, a, c;
  6066. getFileTimesInternal (m, a, c);
  6067. return Time (a);
  6068. }
  6069. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6070. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6071. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6072. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6073. {
  6074. if (! existsAsFile())
  6075. return false;
  6076. FileInputStream in (*this);
  6077. return getSize() == in.readIntoMemoryBlock (destBlock);
  6078. }
  6079. const String File::loadFileAsString() const
  6080. {
  6081. if (! existsAsFile())
  6082. return String::empty;
  6083. FileInputStream in (*this);
  6084. return in.readEntireStreamAsString();
  6085. }
  6086. int File::findChildFiles (Array<File>& results,
  6087. const int whatToLookFor,
  6088. const bool searchRecursively,
  6089. const String& wildCardPattern) const
  6090. {
  6091. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6092. int total = 0;
  6093. while (di.next())
  6094. {
  6095. results.add (di.getFile());
  6096. ++total;
  6097. }
  6098. return total;
  6099. }
  6100. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6101. {
  6102. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6103. int total = 0;
  6104. while (di.next())
  6105. ++total;
  6106. return total;
  6107. }
  6108. bool File::containsSubDirectories() const
  6109. {
  6110. if (isDirectory())
  6111. {
  6112. DirectoryIterator di (*this, false, "*", findDirectories);
  6113. return di.next();
  6114. }
  6115. return false;
  6116. }
  6117. const File File::getNonexistentChildFile (const String& prefix_,
  6118. const String& suffix,
  6119. bool putNumbersInBrackets) const
  6120. {
  6121. File f (getChildFile (prefix_ + suffix));
  6122. if (f.exists())
  6123. {
  6124. int num = 2;
  6125. String prefix (prefix_);
  6126. // remove any bracketed numbers that may already be on the end..
  6127. if (prefix.trim().endsWithChar (')'))
  6128. {
  6129. putNumbersInBrackets = true;
  6130. const int openBracks = prefix.lastIndexOfChar ('(');
  6131. const int closeBracks = prefix.lastIndexOfChar (')');
  6132. if (openBracks > 0
  6133. && closeBracks > openBracks
  6134. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6135. {
  6136. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6137. prefix = prefix.substring (0, openBracks);
  6138. }
  6139. }
  6140. // also use brackets if it ends in a digit.
  6141. putNumbersInBrackets = putNumbersInBrackets
  6142. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6143. do
  6144. {
  6145. if (putNumbersInBrackets)
  6146. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6147. else
  6148. f = getChildFile (prefix + String (num++) + suffix);
  6149. } while (f.exists());
  6150. }
  6151. return f;
  6152. }
  6153. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6154. {
  6155. if (exists())
  6156. {
  6157. return getParentDirectory()
  6158. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6159. getFileExtension(),
  6160. putNumbersInBrackets);
  6161. }
  6162. else
  6163. {
  6164. return *this;
  6165. }
  6166. }
  6167. const String File::getFileExtension() const
  6168. {
  6169. String ext;
  6170. if (! isDirectory())
  6171. {
  6172. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6173. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6174. ext = fullPath.substring (indexOfDot);
  6175. }
  6176. return ext;
  6177. }
  6178. bool File::hasFileExtension (const String& possibleSuffix) const
  6179. {
  6180. if (possibleSuffix.isEmpty())
  6181. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6182. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6183. if (semicolon >= 0)
  6184. {
  6185. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6186. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6187. }
  6188. else
  6189. {
  6190. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6191. {
  6192. if (possibleSuffix.startsWithChar ('.'))
  6193. return true;
  6194. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6195. if (dotPos >= 0)
  6196. return fullPath [dotPos] == '.';
  6197. }
  6198. }
  6199. return false;
  6200. }
  6201. const File File::withFileExtension (const String& newExtension) const
  6202. {
  6203. if (fullPath.isEmpty())
  6204. return File::nonexistent;
  6205. String filePart (getFileName());
  6206. int i = filePart.lastIndexOfChar ('.');
  6207. if (i >= 0)
  6208. filePart = filePart.substring (0, i);
  6209. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6210. filePart << '.';
  6211. return getSiblingFile (filePart + newExtension);
  6212. }
  6213. bool File::startAsProcess (const String& parameters) const
  6214. {
  6215. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6216. }
  6217. FileInputStream* File::createInputStream() const
  6218. {
  6219. if (existsAsFile())
  6220. return new FileInputStream (*this);
  6221. return 0;
  6222. }
  6223. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6224. {
  6225. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6226. if (out->failedToOpen())
  6227. return 0;
  6228. return out.release();
  6229. }
  6230. bool File::appendData (const void* const dataToAppend,
  6231. const int numberOfBytes) const
  6232. {
  6233. if (numberOfBytes > 0)
  6234. {
  6235. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6236. if (out == 0)
  6237. return false;
  6238. out->write (dataToAppend, numberOfBytes);
  6239. }
  6240. return true;
  6241. }
  6242. bool File::replaceWithData (const void* const dataToWrite,
  6243. const int numberOfBytes) const
  6244. {
  6245. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6246. if (numberOfBytes <= 0)
  6247. return deleteFile();
  6248. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6249. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6250. return tempFile.overwriteTargetFileWithTemporary();
  6251. }
  6252. bool File::appendText (const String& text,
  6253. const bool asUnicode,
  6254. const bool writeUnicodeHeaderBytes) const
  6255. {
  6256. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6257. if (out != 0)
  6258. {
  6259. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6260. return true;
  6261. }
  6262. return false;
  6263. }
  6264. bool File::replaceWithText (const String& textToWrite,
  6265. const bool asUnicode,
  6266. const bool writeUnicodeHeaderBytes) const
  6267. {
  6268. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6269. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6270. return tempFile.overwriteTargetFileWithTemporary();
  6271. }
  6272. bool File::hasIdenticalContentTo (const File& other) const
  6273. {
  6274. if (other == *this)
  6275. return true;
  6276. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6277. {
  6278. FileInputStream in1 (*this), in2 (other);
  6279. const int bufferSize = 4096;
  6280. HeapBlock <char> buffer1, buffer2;
  6281. buffer1.malloc (bufferSize);
  6282. buffer2.malloc (bufferSize);
  6283. for (;;)
  6284. {
  6285. const int num1 = in1.read (buffer1, bufferSize);
  6286. const int num2 = in2.read (buffer2, bufferSize);
  6287. if (num1 != num2)
  6288. break;
  6289. if (num1 <= 0)
  6290. return true;
  6291. if (memcmp (buffer1, buffer2, num1) != 0)
  6292. break;
  6293. }
  6294. }
  6295. return false;
  6296. }
  6297. const String File::createLegalPathName (const String& original)
  6298. {
  6299. String s (original);
  6300. String start;
  6301. if (s[1] == ':')
  6302. {
  6303. start = s.substring (0, 2);
  6304. s = s.substring (2);
  6305. }
  6306. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6307. .substring (0, 1024);
  6308. }
  6309. const String File::createLegalFileName (const String& original)
  6310. {
  6311. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6312. const int maxLength = 128; // only the length of the filename, not the whole path
  6313. const int len = s.length();
  6314. if (len > maxLength)
  6315. {
  6316. const int lastDot = s.lastIndexOfChar ('.');
  6317. if (lastDot > jmax (0, len - 12))
  6318. {
  6319. s = s.substring (0, maxLength - (len - lastDot))
  6320. + s.substring (lastDot);
  6321. }
  6322. else
  6323. {
  6324. s = s.substring (0, maxLength);
  6325. }
  6326. }
  6327. return s;
  6328. }
  6329. const String File::getRelativePathFrom (const File& dir) const
  6330. {
  6331. String thisPath (fullPath);
  6332. {
  6333. int len = thisPath.length();
  6334. while (--len >= 0 && thisPath [len] == File::separator)
  6335. thisPath [len] = 0;
  6336. }
  6337. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6338. : dir.fullPath));
  6339. const int len = jmin (thisPath.length(), dirPath.length());
  6340. int commonBitLength = 0;
  6341. for (int i = 0; i < len; ++i)
  6342. {
  6343. #if NAMES_ARE_CASE_SENSITIVE
  6344. if (thisPath[i] != dirPath[i])
  6345. #else
  6346. if (CharacterFunctions::toLowerCase (thisPath[i])
  6347. != CharacterFunctions::toLowerCase (dirPath[i]))
  6348. #endif
  6349. {
  6350. break;
  6351. }
  6352. ++commonBitLength;
  6353. }
  6354. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6355. --commonBitLength;
  6356. // if the only common bit is the root, then just return the full path..
  6357. if (commonBitLength <= 0
  6358. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6359. return fullPath;
  6360. thisPath = thisPath.substring (commonBitLength);
  6361. dirPath = dirPath.substring (commonBitLength);
  6362. while (dirPath.isNotEmpty())
  6363. {
  6364. #if JUCE_WINDOWS
  6365. thisPath = "..\\" + thisPath;
  6366. #else
  6367. thisPath = "../" + thisPath;
  6368. #endif
  6369. const int sep = dirPath.indexOfChar (separator);
  6370. if (sep >= 0)
  6371. dirPath = dirPath.substring (sep + 1);
  6372. else
  6373. dirPath = String::empty;
  6374. }
  6375. return thisPath;
  6376. }
  6377. const File File::createTempFile (const String& fileNameEnding)
  6378. {
  6379. const File tempFile (getSpecialLocation (tempDirectory)
  6380. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6381. .withFileExtension (fileNameEnding));
  6382. if (tempFile.exists())
  6383. return createTempFile (fileNameEnding);
  6384. else
  6385. return tempFile;
  6386. }
  6387. #if JUCE_UNIT_TESTS
  6388. class FileTests : public UnitTest
  6389. {
  6390. public:
  6391. FileTests() : UnitTest ("Files") {}
  6392. void runTest()
  6393. {
  6394. beginTest ("Reading");
  6395. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6396. const File temp (File::getSpecialLocation (File::tempDirectory));
  6397. expect (! File::nonexistent.exists());
  6398. expect (home.isDirectory());
  6399. expect (home.exists());
  6400. expect (! home.existsAsFile());
  6401. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6402. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6403. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6404. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6405. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6406. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6407. expect (home.getBytesFreeOnVolume() > 0);
  6408. expect (! home.isHidden());
  6409. expect (home.isOnHardDisk());
  6410. expect (! home.isOnCDRomDrive());
  6411. expect (File::getCurrentWorkingDirectory().exists());
  6412. expect (home.setAsCurrentWorkingDirectory());
  6413. expect (File::getCurrentWorkingDirectory() == home);
  6414. {
  6415. Array<File> roots;
  6416. File::findFileSystemRoots (roots);
  6417. expect (roots.size() > 0);
  6418. int numRootsExisting = 0;
  6419. for (int i = 0; i < roots.size(); ++i)
  6420. if (roots[i].exists())
  6421. ++numRootsExisting;
  6422. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6423. expect (numRootsExisting > 0);
  6424. }
  6425. beginTest ("Writing");
  6426. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6427. expect (demoFolder.deleteRecursively());
  6428. expect (demoFolder.createDirectory());
  6429. expect (demoFolder.isDirectory());
  6430. expect (demoFolder.getParentDirectory() == temp);
  6431. expect (temp.isDirectory());
  6432. {
  6433. Array<File> files;
  6434. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6435. expect (files.contains (demoFolder));
  6436. }
  6437. {
  6438. Array<File> files;
  6439. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6440. expect (files.contains (demoFolder));
  6441. }
  6442. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6443. expect (tempFile.getFileExtension() == ".txt");
  6444. expect (tempFile.hasFileExtension (".txt"));
  6445. expect (tempFile.hasFileExtension ("txt"));
  6446. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6447. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6448. expect (tempFile.hasWriteAccess());
  6449. {
  6450. FileOutputStream fo (tempFile);
  6451. fo.write ("0123456789", 10);
  6452. }
  6453. expect (tempFile.exists());
  6454. expect (tempFile.getSize() == 10);
  6455. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6456. expect (tempFile.loadFileAsString() == "0123456789");
  6457. expect (! demoFolder.containsSubDirectories());
  6458. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6459. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6460. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6461. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6462. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6463. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6464. expect (demoFolder.containsSubDirectories());
  6465. expect (tempFile.hasWriteAccess());
  6466. tempFile.setReadOnly (true);
  6467. expect (! tempFile.hasWriteAccess());
  6468. tempFile.setReadOnly (false);
  6469. expect (tempFile.hasWriteAccess());
  6470. Time t (Time::getCurrentTime());
  6471. tempFile.setLastModificationTime (t);
  6472. Time t2 = tempFile.getLastModificationTime();
  6473. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6474. {
  6475. MemoryBlock mb;
  6476. tempFile.loadFileAsData (mb);
  6477. expect (mb.getSize() == 10);
  6478. expect (mb[0] == '0');
  6479. }
  6480. expect (tempFile.appendData ("abcdefghij", 10));
  6481. expect (tempFile.getSize() == 20);
  6482. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6483. expect (tempFile.getSize() == 10);
  6484. File tempFile2 (tempFile.getNonexistentSibling (false));
  6485. expect (tempFile.copyFileTo (tempFile2));
  6486. expect (tempFile2.exists());
  6487. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6488. expect (tempFile.deleteFile());
  6489. expect (! tempFile.exists());
  6490. expect (tempFile2.moveFileTo (tempFile));
  6491. expect (tempFile.exists());
  6492. expect (! tempFile2.exists());
  6493. expect (demoFolder.deleteRecursively());
  6494. expect (! demoFolder.exists());
  6495. }
  6496. };
  6497. static FileTests fileUnitTests;
  6498. #endif
  6499. END_JUCE_NAMESPACE
  6500. /*** End of inlined file: juce_File.cpp ***/
  6501. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6502. BEGIN_JUCE_NAMESPACE
  6503. int64 juce_fileSetPosition (void* handle, int64 pos);
  6504. FileInputStream::FileInputStream (const File& f)
  6505. : file (f),
  6506. fileHandle (0),
  6507. currentPosition (0),
  6508. totalSize (0),
  6509. needToSeek (true)
  6510. {
  6511. openHandle();
  6512. }
  6513. FileInputStream::~FileInputStream()
  6514. {
  6515. closeHandle();
  6516. }
  6517. int64 FileInputStream::getTotalLength()
  6518. {
  6519. return totalSize;
  6520. }
  6521. int FileInputStream::read (void* buffer, int bytesToRead)
  6522. {
  6523. int num = 0;
  6524. if (needToSeek)
  6525. {
  6526. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6527. return 0;
  6528. needToSeek = false;
  6529. }
  6530. num = readInternal (buffer, bytesToRead);
  6531. currentPosition += num;
  6532. return num;
  6533. }
  6534. bool FileInputStream::isExhausted()
  6535. {
  6536. return currentPosition >= totalSize;
  6537. }
  6538. int64 FileInputStream::getPosition()
  6539. {
  6540. return currentPosition;
  6541. }
  6542. bool FileInputStream::setPosition (int64 pos)
  6543. {
  6544. pos = jlimit ((int64) 0, totalSize, pos);
  6545. needToSeek |= (currentPosition != pos);
  6546. currentPosition = pos;
  6547. return true;
  6548. }
  6549. END_JUCE_NAMESPACE
  6550. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6551. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6552. BEGIN_JUCE_NAMESPACE
  6553. int64 juce_fileSetPosition (void* handle, int64 pos);
  6554. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6555. : file (f),
  6556. fileHandle (0),
  6557. currentPosition (0),
  6558. bufferSize (bufferSize_),
  6559. bytesInBuffer (0),
  6560. buffer (jmax (bufferSize_, 16))
  6561. {
  6562. openHandle();
  6563. }
  6564. FileOutputStream::~FileOutputStream()
  6565. {
  6566. flush();
  6567. closeHandle();
  6568. }
  6569. int64 FileOutputStream::getPosition()
  6570. {
  6571. return currentPosition;
  6572. }
  6573. bool FileOutputStream::setPosition (int64 newPosition)
  6574. {
  6575. if (newPosition != currentPosition)
  6576. {
  6577. flush();
  6578. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6579. }
  6580. return newPosition == currentPosition;
  6581. }
  6582. void FileOutputStream::flush()
  6583. {
  6584. if (bytesInBuffer > 0)
  6585. {
  6586. writeInternal (buffer, bytesInBuffer);
  6587. bytesInBuffer = 0;
  6588. }
  6589. flushInternal();
  6590. }
  6591. bool FileOutputStream::write (const void* const src, const int numBytes)
  6592. {
  6593. if (bytesInBuffer + numBytes < bufferSize)
  6594. {
  6595. memcpy (buffer + bytesInBuffer, src, numBytes);
  6596. bytesInBuffer += numBytes;
  6597. currentPosition += numBytes;
  6598. }
  6599. else
  6600. {
  6601. if (bytesInBuffer > 0)
  6602. {
  6603. // flush the reservoir
  6604. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6605. bytesInBuffer = 0;
  6606. if (! wroteOk)
  6607. return false;
  6608. }
  6609. if (numBytes < bufferSize)
  6610. {
  6611. memcpy (buffer + bytesInBuffer, src, numBytes);
  6612. bytesInBuffer += numBytes;
  6613. currentPosition += numBytes;
  6614. }
  6615. else
  6616. {
  6617. const int bytesWritten = writeInternal (src, numBytes);
  6618. if (bytesWritten < 0)
  6619. return false;
  6620. currentPosition += bytesWritten;
  6621. return bytesWritten == numBytes;
  6622. }
  6623. }
  6624. return true;
  6625. }
  6626. END_JUCE_NAMESPACE
  6627. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6628. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6629. BEGIN_JUCE_NAMESPACE
  6630. FileSearchPath::FileSearchPath()
  6631. {
  6632. }
  6633. FileSearchPath::FileSearchPath (const String& path)
  6634. {
  6635. init (path);
  6636. }
  6637. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6638. : directories (other.directories)
  6639. {
  6640. }
  6641. FileSearchPath::~FileSearchPath()
  6642. {
  6643. }
  6644. FileSearchPath& FileSearchPath::operator= (const String& path)
  6645. {
  6646. init (path);
  6647. return *this;
  6648. }
  6649. void FileSearchPath::init (const String& path)
  6650. {
  6651. directories.clear();
  6652. directories.addTokens (path, ";", "\"");
  6653. directories.trim();
  6654. directories.removeEmptyStrings();
  6655. for (int i = directories.size(); --i >= 0;)
  6656. directories.set (i, directories[i].unquoted());
  6657. }
  6658. int FileSearchPath::getNumPaths() const
  6659. {
  6660. return directories.size();
  6661. }
  6662. const File FileSearchPath::operator[] (const int index) const
  6663. {
  6664. return File (directories [index]);
  6665. }
  6666. const String FileSearchPath::toString() const
  6667. {
  6668. StringArray directories2 (directories);
  6669. for (int i = directories2.size(); --i >= 0;)
  6670. if (directories2[i].containsChar (';'))
  6671. directories2.set (i, directories2[i].quoted());
  6672. return directories2.joinIntoString (";");
  6673. }
  6674. void FileSearchPath::add (const File& dir, const int insertIndex)
  6675. {
  6676. directories.insert (insertIndex, dir.getFullPathName());
  6677. }
  6678. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6679. {
  6680. for (int i = 0; i < directories.size(); ++i)
  6681. if (File (directories[i]) == dir)
  6682. return;
  6683. add (dir);
  6684. }
  6685. void FileSearchPath::remove (const int index)
  6686. {
  6687. directories.remove (index);
  6688. }
  6689. void FileSearchPath::addPath (const FileSearchPath& other)
  6690. {
  6691. for (int i = 0; i < other.getNumPaths(); ++i)
  6692. addIfNotAlreadyThere (other[i]);
  6693. }
  6694. void FileSearchPath::removeRedundantPaths()
  6695. {
  6696. for (int i = directories.size(); --i >= 0;)
  6697. {
  6698. const File d1 (directories[i]);
  6699. for (int j = directories.size(); --j >= 0;)
  6700. {
  6701. const File d2 (directories[j]);
  6702. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6703. {
  6704. directories.remove (i);
  6705. break;
  6706. }
  6707. }
  6708. }
  6709. }
  6710. void FileSearchPath::removeNonExistentPaths()
  6711. {
  6712. for (int i = directories.size(); --i >= 0;)
  6713. if (! File (directories[i]).isDirectory())
  6714. directories.remove (i);
  6715. }
  6716. int FileSearchPath::findChildFiles (Array<File>& results,
  6717. const int whatToLookFor,
  6718. const bool searchRecursively,
  6719. const String& wildCardPattern) const
  6720. {
  6721. int total = 0;
  6722. for (int i = 0; i < directories.size(); ++i)
  6723. total += operator[] (i).findChildFiles (results,
  6724. whatToLookFor,
  6725. searchRecursively,
  6726. wildCardPattern);
  6727. return total;
  6728. }
  6729. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6730. const bool checkRecursively) const
  6731. {
  6732. for (int i = directories.size(); --i >= 0;)
  6733. {
  6734. const File d (directories[i]);
  6735. if (checkRecursively)
  6736. {
  6737. if (fileToCheck.isAChildOf (d))
  6738. return true;
  6739. }
  6740. else
  6741. {
  6742. if (fileToCheck.getParentDirectory() == d)
  6743. return true;
  6744. }
  6745. }
  6746. return false;
  6747. }
  6748. END_JUCE_NAMESPACE
  6749. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6750. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6751. BEGIN_JUCE_NAMESPACE
  6752. NamedPipe::NamedPipe()
  6753. : internal (0)
  6754. {
  6755. }
  6756. NamedPipe::~NamedPipe()
  6757. {
  6758. close();
  6759. }
  6760. bool NamedPipe::openExisting (const String& pipeName)
  6761. {
  6762. currentPipeName = pipeName;
  6763. return openInternal (pipeName, false);
  6764. }
  6765. bool NamedPipe::createNewPipe (const String& pipeName)
  6766. {
  6767. currentPipeName = pipeName;
  6768. return openInternal (pipeName, true);
  6769. }
  6770. bool NamedPipe::isOpen() const
  6771. {
  6772. return internal != 0;
  6773. }
  6774. const String NamedPipe::getName() const
  6775. {
  6776. return currentPipeName;
  6777. }
  6778. // other methods for this class are implemented in the platform-specific files
  6779. END_JUCE_NAMESPACE
  6780. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6781. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6782. BEGIN_JUCE_NAMESPACE
  6783. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6784. {
  6785. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6786. "temp_" + String (Random::getSystemRandom().nextInt()),
  6787. suffix,
  6788. optionFlags);
  6789. }
  6790. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6791. : targetFile (targetFile_)
  6792. {
  6793. // If you use this constructor, you need to give it a valid target file!
  6794. jassert (targetFile != File::nonexistent);
  6795. createTempFile (targetFile.getParentDirectory(),
  6796. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6797. targetFile.getFileExtension(),
  6798. optionFlags);
  6799. }
  6800. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6801. const String& suffix, const int optionFlags)
  6802. {
  6803. if ((optionFlags & useHiddenFile) != 0)
  6804. name = "." + name;
  6805. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6806. }
  6807. TemporaryFile::~TemporaryFile()
  6808. {
  6809. if (! deleteTemporaryFile())
  6810. {
  6811. /* Failed to delete our temporary file! The most likely reason for this would be
  6812. that you've not closed an output stream that was being used to write to file.
  6813. If you find that something beyond your control is changing permissions on
  6814. your temporary files and preventing them from being deleted, you may want to
  6815. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6816. handle them appropriately.
  6817. */
  6818. jassertfalse;
  6819. }
  6820. }
  6821. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6822. {
  6823. // This method only works if you created this object with the constructor
  6824. // that takes a target file!
  6825. jassert (targetFile != File::nonexistent);
  6826. if (temporaryFile.exists())
  6827. {
  6828. // Have a few attempts at overwriting the file before giving up..
  6829. for (int i = 5; --i >= 0;)
  6830. {
  6831. if (temporaryFile.moveFileTo (targetFile))
  6832. return true;
  6833. Thread::sleep (100);
  6834. }
  6835. }
  6836. else
  6837. {
  6838. // There's no temporary file to use. If your write failed, you should
  6839. // probably check, and not bother calling this method.
  6840. jassertfalse;
  6841. }
  6842. return false;
  6843. }
  6844. bool TemporaryFile::deleteTemporaryFile() const
  6845. {
  6846. // Have a few attempts at deleting the file before giving up..
  6847. for (int i = 5; --i >= 0;)
  6848. {
  6849. if (temporaryFile.deleteFile())
  6850. return true;
  6851. Thread::sleep (50);
  6852. }
  6853. return false;
  6854. }
  6855. END_JUCE_NAMESPACE
  6856. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6857. /*** Start of inlined file: juce_Socket.cpp ***/
  6858. #if JUCE_WINDOWS
  6859. #include <winsock2.h>
  6860. #if JUCE_MSVC
  6861. #pragma warning (push)
  6862. #pragma warning (disable : 4127 4389 4018)
  6863. #endif
  6864. #else
  6865. #if JUCE_LINUX
  6866. #include <sys/types.h>
  6867. #include <sys/socket.h>
  6868. #include <sys/errno.h>
  6869. #include <unistd.h>
  6870. #include <netinet/in.h>
  6871. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6872. #include <CoreServices/CoreServices.h>
  6873. #endif
  6874. #include <fcntl.h>
  6875. #include <netdb.h>
  6876. #include <arpa/inet.h>
  6877. #include <netinet/tcp.h>
  6878. #endif
  6879. BEGIN_JUCE_NAMESPACE
  6880. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6881. typedef socklen_t juce_socklen_t;
  6882. #else
  6883. typedef int juce_socklen_t;
  6884. #endif
  6885. #if JUCE_WINDOWS
  6886. namespace SocketHelpers
  6887. {
  6888. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6889. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6890. void initWin32Sockets()
  6891. {
  6892. static CriticalSection lock;
  6893. const ScopedLock sl (lock);
  6894. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6895. {
  6896. WSADATA wsaData;
  6897. const WORD wVersionRequested = MAKEWORD (1, 1);
  6898. WSAStartup (wVersionRequested, &wsaData);
  6899. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6900. }
  6901. }
  6902. }
  6903. void juce_shutdownWin32Sockets()
  6904. {
  6905. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6906. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6907. }
  6908. #endif
  6909. namespace SocketHelpers
  6910. {
  6911. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6912. {
  6913. const int sndBufSize = 65536;
  6914. const int rcvBufSize = 65536;
  6915. const int one = 1;
  6916. return handle > 0
  6917. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6918. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6919. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6920. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6921. }
  6922. bool bindSocketToPort (const int handle, const int port) throw()
  6923. {
  6924. if (handle <= 0 || port <= 0)
  6925. return false;
  6926. struct sockaddr_in servTmpAddr;
  6927. zerostruct (servTmpAddr);
  6928. servTmpAddr.sin_family = PF_INET;
  6929. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6930. servTmpAddr.sin_port = htons ((uint16) port);
  6931. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6932. }
  6933. int readSocket (const int handle,
  6934. void* const destBuffer, const int maxBytesToRead,
  6935. bool volatile& connected,
  6936. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6937. {
  6938. int bytesRead = 0;
  6939. while (bytesRead < maxBytesToRead)
  6940. {
  6941. int bytesThisTime;
  6942. #if JUCE_WINDOWS
  6943. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6944. #else
  6945. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6946. && errno == EINTR
  6947. && connected)
  6948. {
  6949. }
  6950. #endif
  6951. if (bytesThisTime <= 0 || ! connected)
  6952. {
  6953. if (bytesRead == 0)
  6954. bytesRead = -1;
  6955. break;
  6956. }
  6957. bytesRead += bytesThisTime;
  6958. if (! blockUntilSpecifiedAmountHasArrived)
  6959. break;
  6960. }
  6961. return bytesRead;
  6962. }
  6963. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  6964. {
  6965. struct timeval timeout;
  6966. struct timeval* timeoutp;
  6967. if (timeoutMsecs >= 0)
  6968. {
  6969. timeout.tv_sec = timeoutMsecs / 1000;
  6970. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6971. timeoutp = &timeout;
  6972. }
  6973. else
  6974. {
  6975. timeoutp = 0;
  6976. }
  6977. fd_set rset, wset;
  6978. FD_ZERO (&rset);
  6979. FD_SET (handle, &rset);
  6980. FD_ZERO (&wset);
  6981. FD_SET (handle, &wset);
  6982. fd_set* const prset = forReading ? &rset : 0;
  6983. fd_set* const pwset = forReading ? 0 : &wset;
  6984. #if JUCE_WINDOWS
  6985. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6986. return -1;
  6987. #else
  6988. {
  6989. int result;
  6990. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6991. && errno == EINTR)
  6992. {
  6993. }
  6994. if (result < 0)
  6995. return -1;
  6996. }
  6997. #endif
  6998. {
  6999. int opt;
  7000. juce_socklen_t len = sizeof (opt);
  7001. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7002. || opt != 0)
  7003. return -1;
  7004. }
  7005. if ((forReading && FD_ISSET (handle, &rset))
  7006. || ((! forReading) && FD_ISSET (handle, &wset)))
  7007. return 1;
  7008. return 0;
  7009. }
  7010. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7011. {
  7012. #if JUCE_WINDOWS
  7013. u_long nonBlocking = shouldBlock ? 0 : 1;
  7014. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7015. return false;
  7016. #else
  7017. int socketFlags = fcntl (handle, F_GETFL, 0);
  7018. if (socketFlags == -1)
  7019. return false;
  7020. if (shouldBlock)
  7021. socketFlags &= ~O_NONBLOCK;
  7022. else
  7023. socketFlags |= O_NONBLOCK;
  7024. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7025. return false;
  7026. #endif
  7027. return true;
  7028. }
  7029. bool connectSocket (int volatile& handle,
  7030. const bool isDatagram,
  7031. void** serverAddress,
  7032. const String& hostName,
  7033. const int portNumber,
  7034. const int timeOutMillisecs) throw()
  7035. {
  7036. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7037. if (hostEnt == 0)
  7038. return false;
  7039. struct in_addr targetAddress;
  7040. memcpy (&targetAddress.s_addr,
  7041. *(hostEnt->h_addr_list),
  7042. sizeof (targetAddress.s_addr));
  7043. struct sockaddr_in servTmpAddr;
  7044. zerostruct (servTmpAddr);
  7045. servTmpAddr.sin_family = PF_INET;
  7046. servTmpAddr.sin_addr = targetAddress;
  7047. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7048. if (handle < 0)
  7049. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7050. if (handle < 0)
  7051. return false;
  7052. if (isDatagram)
  7053. {
  7054. *serverAddress = new struct sockaddr_in();
  7055. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7056. return true;
  7057. }
  7058. setSocketBlockingState (handle, false);
  7059. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7060. if (result < 0)
  7061. {
  7062. #if JUCE_WINDOWS
  7063. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7064. #else
  7065. if (errno == EINPROGRESS)
  7066. #endif
  7067. {
  7068. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7069. {
  7070. setSocketBlockingState (handle, true);
  7071. return false;
  7072. }
  7073. }
  7074. }
  7075. setSocketBlockingState (handle, true);
  7076. resetSocketOptions (handle, false, false);
  7077. return true;
  7078. }
  7079. }
  7080. StreamingSocket::StreamingSocket()
  7081. : portNumber (0),
  7082. handle (-1),
  7083. connected (false),
  7084. isListener (false)
  7085. {
  7086. #if JUCE_WINDOWS
  7087. SocketHelpers::initWin32Sockets();
  7088. #endif
  7089. }
  7090. StreamingSocket::StreamingSocket (const String& hostName_,
  7091. const int portNumber_,
  7092. const int handle_)
  7093. : hostName (hostName_),
  7094. portNumber (portNumber_),
  7095. handle (handle_),
  7096. connected (true),
  7097. isListener (false)
  7098. {
  7099. #if JUCE_WINDOWS
  7100. SocketHelpers::initWin32Sockets();
  7101. #endif
  7102. SocketHelpers::resetSocketOptions (handle_, false, false);
  7103. }
  7104. StreamingSocket::~StreamingSocket()
  7105. {
  7106. close();
  7107. }
  7108. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7109. {
  7110. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7111. : -1;
  7112. }
  7113. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7114. {
  7115. if (isListener || ! connected)
  7116. return -1;
  7117. #if JUCE_WINDOWS
  7118. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7119. #else
  7120. int result;
  7121. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7122. && errno == EINTR)
  7123. {
  7124. }
  7125. return result;
  7126. #endif
  7127. }
  7128. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7129. const int timeoutMsecs) const
  7130. {
  7131. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7132. : -1;
  7133. }
  7134. bool StreamingSocket::bindToPort (const int port)
  7135. {
  7136. return SocketHelpers::bindSocketToPort (handle, port);
  7137. }
  7138. bool StreamingSocket::connect (const String& remoteHostName,
  7139. const int remotePortNumber,
  7140. const int timeOutMillisecs)
  7141. {
  7142. if (isListener)
  7143. {
  7144. jassertfalse; // a listener socket can't connect to another one!
  7145. return false;
  7146. }
  7147. if (connected)
  7148. close();
  7149. hostName = remoteHostName;
  7150. portNumber = remotePortNumber;
  7151. isListener = false;
  7152. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7153. remotePortNumber, timeOutMillisecs);
  7154. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7155. {
  7156. close();
  7157. return false;
  7158. }
  7159. return true;
  7160. }
  7161. void StreamingSocket::close()
  7162. {
  7163. #if JUCE_WINDOWS
  7164. if (handle != SOCKET_ERROR || connected)
  7165. closesocket (handle);
  7166. connected = false;
  7167. #else
  7168. if (connected)
  7169. {
  7170. connected = false;
  7171. if (isListener)
  7172. {
  7173. // need to do this to interrupt the accept() function..
  7174. StreamingSocket temp;
  7175. temp.connect ("localhost", portNumber, 1000);
  7176. }
  7177. }
  7178. if (handle != -1)
  7179. ::close (handle);
  7180. #endif
  7181. hostName = String::empty;
  7182. portNumber = 0;
  7183. handle = -1;
  7184. isListener = false;
  7185. }
  7186. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7187. {
  7188. if (connected)
  7189. close();
  7190. hostName = "listener";
  7191. portNumber = newPortNumber;
  7192. isListener = true;
  7193. struct sockaddr_in servTmpAddr;
  7194. zerostruct (servTmpAddr);
  7195. servTmpAddr.sin_family = PF_INET;
  7196. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7197. if (localHostName.isNotEmpty())
  7198. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7199. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7200. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7201. if (handle < 0)
  7202. return false;
  7203. const int reuse = 1;
  7204. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7205. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7206. || listen (handle, SOMAXCONN) < 0)
  7207. {
  7208. close();
  7209. return false;
  7210. }
  7211. connected = true;
  7212. return true;
  7213. }
  7214. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7215. {
  7216. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7217. // prepare this socket as a listener.
  7218. if (connected && isListener)
  7219. {
  7220. struct sockaddr address;
  7221. juce_socklen_t len = sizeof (sockaddr);
  7222. const int newSocket = (int) accept (handle, &address, &len);
  7223. if (newSocket >= 0 && connected)
  7224. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7225. portNumber, newSocket);
  7226. }
  7227. return 0;
  7228. }
  7229. bool StreamingSocket::isLocal() const throw()
  7230. {
  7231. return hostName == "127.0.0.1";
  7232. }
  7233. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7234. : portNumber (0),
  7235. handle (-1),
  7236. connected (true),
  7237. allowBroadcast (allowBroadcast_),
  7238. serverAddress (0)
  7239. {
  7240. #if JUCE_WINDOWS
  7241. SocketHelpers::initWin32Sockets();
  7242. #endif
  7243. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7244. bindToPort (localPortNumber);
  7245. }
  7246. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7247. const int handle_, const int localPortNumber)
  7248. : hostName (hostName_),
  7249. portNumber (portNumber_),
  7250. handle (handle_),
  7251. connected (true),
  7252. allowBroadcast (false),
  7253. serverAddress (0)
  7254. {
  7255. #if JUCE_WINDOWS
  7256. SocketHelpers::initWin32Sockets();
  7257. #endif
  7258. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7259. bindToPort (localPortNumber);
  7260. }
  7261. DatagramSocket::~DatagramSocket()
  7262. {
  7263. close();
  7264. delete static_cast <struct sockaddr_in*> (serverAddress);
  7265. serverAddress = 0;
  7266. }
  7267. void DatagramSocket::close()
  7268. {
  7269. #if JUCE_WINDOWS
  7270. closesocket (handle);
  7271. connected = false;
  7272. #else
  7273. connected = false;
  7274. ::close (handle);
  7275. #endif
  7276. hostName = String::empty;
  7277. portNumber = 0;
  7278. handle = -1;
  7279. }
  7280. bool DatagramSocket::bindToPort (const int port)
  7281. {
  7282. return SocketHelpers::bindSocketToPort (handle, port);
  7283. }
  7284. bool DatagramSocket::connect (const String& remoteHostName,
  7285. const int remotePortNumber,
  7286. const int timeOutMillisecs)
  7287. {
  7288. if (connected)
  7289. close();
  7290. hostName = remoteHostName;
  7291. portNumber = remotePortNumber;
  7292. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7293. remoteHostName, remotePortNumber,
  7294. timeOutMillisecs);
  7295. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7296. {
  7297. close();
  7298. return false;
  7299. }
  7300. return true;
  7301. }
  7302. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7303. {
  7304. struct sockaddr address;
  7305. juce_socklen_t len = sizeof (sockaddr);
  7306. while (waitUntilReady (true, -1) == 1)
  7307. {
  7308. char buf[1];
  7309. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7310. {
  7311. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7312. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7313. -1, -1);
  7314. }
  7315. }
  7316. return 0;
  7317. }
  7318. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7319. const int timeoutMsecs) const
  7320. {
  7321. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7322. : -1;
  7323. }
  7324. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7325. {
  7326. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7327. : -1;
  7328. }
  7329. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7330. {
  7331. // You need to call connect() first to set the server address..
  7332. jassert (serverAddress != 0 && connected);
  7333. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7334. numBytesToWrite, 0,
  7335. (const struct sockaddr*) serverAddress,
  7336. sizeof (struct sockaddr_in))
  7337. : -1;
  7338. }
  7339. bool DatagramSocket::isLocal() const throw()
  7340. {
  7341. return hostName == "127.0.0.1";
  7342. }
  7343. #if JUCE_MSVC
  7344. #pragma warning (pop)
  7345. #endif
  7346. END_JUCE_NAMESPACE
  7347. /*** End of inlined file: juce_Socket.cpp ***/
  7348. /*** Start of inlined file: juce_URL.cpp ***/
  7349. BEGIN_JUCE_NAMESPACE
  7350. URL::URL()
  7351. {
  7352. }
  7353. URL::URL (const String& url_)
  7354. : url (url_)
  7355. {
  7356. int i = url.indexOfChar ('?');
  7357. if (i >= 0)
  7358. {
  7359. do
  7360. {
  7361. const int nextAmp = url.indexOfChar (i + 1, '&');
  7362. const int equalsPos = url.indexOfChar (i + 1, '=');
  7363. if (equalsPos > i + 1)
  7364. {
  7365. if (nextAmp < 0)
  7366. {
  7367. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7368. removeEscapeChars (url.substring (equalsPos + 1)));
  7369. }
  7370. else if (nextAmp > 0 && equalsPos < nextAmp)
  7371. {
  7372. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7373. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7374. }
  7375. }
  7376. i = nextAmp;
  7377. }
  7378. while (i >= 0);
  7379. url = url.upToFirstOccurrenceOf ("?", false, false);
  7380. }
  7381. }
  7382. URL::URL (const URL& other)
  7383. : url (other.url),
  7384. postData (other.postData),
  7385. parameters (other.parameters),
  7386. filesToUpload (other.filesToUpload),
  7387. mimeTypes (other.mimeTypes)
  7388. {
  7389. }
  7390. URL& URL::operator= (const URL& other)
  7391. {
  7392. url = other.url;
  7393. postData = other.postData;
  7394. parameters = other.parameters;
  7395. filesToUpload = other.filesToUpload;
  7396. mimeTypes = other.mimeTypes;
  7397. return *this;
  7398. }
  7399. URL::~URL()
  7400. {
  7401. }
  7402. namespace URLHelpers
  7403. {
  7404. const String getMangledParameters (const StringPairArray& parameters)
  7405. {
  7406. String p;
  7407. for (int i = 0; i < parameters.size(); ++i)
  7408. {
  7409. if (i > 0)
  7410. p << '&';
  7411. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7412. << '='
  7413. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7414. }
  7415. return p;
  7416. }
  7417. int findStartOfDomain (const String& url)
  7418. {
  7419. int i = 0;
  7420. while (CharacterFunctions::isLetterOrDigit (url[i])
  7421. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7422. ++i;
  7423. return url[i] == ':' ? i + 1 : 0;
  7424. }
  7425. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7426. {
  7427. MemoryOutputStream data (postData, false);
  7428. if (url.getFilesToUpload().size() > 0)
  7429. {
  7430. // need to upload some files, so do it as multi-part...
  7431. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7432. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7433. data << "--" << boundary;
  7434. int i;
  7435. for (i = 0; i < url.getParameters().size(); ++i)
  7436. {
  7437. data << "\r\nContent-Disposition: form-data; name=\""
  7438. << url.getParameters().getAllKeys() [i]
  7439. << "\"\r\n\r\n"
  7440. << url.getParameters().getAllValues() [i]
  7441. << "\r\n--"
  7442. << boundary;
  7443. }
  7444. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7445. {
  7446. const File file (url.getFilesToUpload().getAllValues() [i]);
  7447. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7448. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7449. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7450. const String mimeType (url.getMimeTypesOfUploadFiles()
  7451. .getValue (paramName, String::empty));
  7452. if (mimeType.isNotEmpty())
  7453. data << "Content-Type: " << mimeType << "\r\n";
  7454. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7455. << file << "\r\n--" << boundary;
  7456. }
  7457. data << "--\r\n";
  7458. data.flush();
  7459. }
  7460. else
  7461. {
  7462. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7463. data.flush();
  7464. // just a short text attachment, so use simple url encoding..
  7465. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7466. << postData.getSize() << "\r\n";
  7467. }
  7468. }
  7469. }
  7470. const String URL::toString (const bool includeGetParameters) const
  7471. {
  7472. if (includeGetParameters && parameters.size() > 0)
  7473. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7474. else
  7475. return url;
  7476. }
  7477. bool URL::isWellFormed() const
  7478. {
  7479. //xxx TODO
  7480. return url.isNotEmpty();
  7481. }
  7482. const String URL::getDomain() const
  7483. {
  7484. int start = URLHelpers::findStartOfDomain (url);
  7485. while (url[start] == '/')
  7486. ++start;
  7487. const int end1 = url.indexOfChar (start, '/');
  7488. const int end2 = url.indexOfChar (start, ':');
  7489. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7490. : jmin (end1, end2);
  7491. return url.substring (start, end);
  7492. }
  7493. const String URL::getSubPath() const
  7494. {
  7495. int start = URLHelpers::findStartOfDomain (url);
  7496. while (url[start] == '/')
  7497. ++start;
  7498. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7499. return startOfPath <= 0 ? String::empty
  7500. : url.substring (startOfPath);
  7501. }
  7502. const String URL::getScheme() const
  7503. {
  7504. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7505. }
  7506. const URL URL::withNewSubPath (const String& newPath) const
  7507. {
  7508. int start = URLHelpers::findStartOfDomain (url);
  7509. while (url[start] == '/')
  7510. ++start;
  7511. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7512. URL u (*this);
  7513. if (startOfPath > 0)
  7514. u.url = url.substring (0, startOfPath);
  7515. if (! u.url.endsWithChar ('/'))
  7516. u.url << '/';
  7517. if (newPath.startsWithChar ('/'))
  7518. u.url << newPath.substring (1);
  7519. else
  7520. u.url << newPath;
  7521. return u;
  7522. }
  7523. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7524. {
  7525. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7526. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7527. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7528. return true;
  7529. if (possibleURL.containsChar ('@')
  7530. || possibleURL.containsChar (' '))
  7531. return false;
  7532. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7533. .fromLastOccurrenceOf (".", false, false));
  7534. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7535. }
  7536. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7537. {
  7538. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7539. return atSign > 0
  7540. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7541. && (! possibleEmailAddress.endsWithChar ('.'));
  7542. }
  7543. InputStream* URL::createInputStream (const bool usePostCommand,
  7544. OpenStreamProgressCallback* const progressCallback,
  7545. void* const progressCallbackContext,
  7546. const String& extraHeaders,
  7547. const int timeOutMs,
  7548. StringPairArray* const responseHeaders) const
  7549. {
  7550. String headers;
  7551. MemoryBlock postData;
  7552. if (usePostCommand)
  7553. URLHelpers::createHeadersAndPostData (*this, headers, postData);
  7554. headers += extraHeaders;
  7555. if (! headers.endsWithChar ('\n'))
  7556. headers << "\r\n";
  7557. return createNativeStream (toString (! usePostCommand), usePostCommand, postData,
  7558. progressCallback, progressCallbackContext,
  7559. headers, timeOutMs, responseHeaders);
  7560. }
  7561. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7562. const bool usePostCommand) const
  7563. {
  7564. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7565. if (in != 0)
  7566. {
  7567. in->readIntoMemoryBlock (destData);
  7568. return true;
  7569. }
  7570. return false;
  7571. }
  7572. const String URL::readEntireTextStream (const bool usePostCommand) const
  7573. {
  7574. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7575. if (in != 0)
  7576. return in->readEntireStreamAsString();
  7577. return String::empty;
  7578. }
  7579. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7580. {
  7581. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7582. }
  7583. const URL URL::withParameter (const String& parameterName,
  7584. const String& parameterValue) const
  7585. {
  7586. URL u (*this);
  7587. u.parameters.set (parameterName, parameterValue);
  7588. return u;
  7589. }
  7590. const URL URL::withFileToUpload (const String& parameterName,
  7591. const File& fileToUpload,
  7592. const String& mimeType) const
  7593. {
  7594. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7595. URL u (*this);
  7596. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7597. u.mimeTypes.set (parameterName, mimeType);
  7598. return u;
  7599. }
  7600. const URL URL::withPOSTData (const String& postData_) const
  7601. {
  7602. URL u (*this);
  7603. u.postData = postData_;
  7604. return u;
  7605. }
  7606. const StringPairArray& URL::getParameters() const
  7607. {
  7608. return parameters;
  7609. }
  7610. const StringPairArray& URL::getFilesToUpload() const
  7611. {
  7612. return filesToUpload;
  7613. }
  7614. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7615. {
  7616. return mimeTypes;
  7617. }
  7618. const String URL::removeEscapeChars (const String& s)
  7619. {
  7620. String result (s.replaceCharacter ('+', ' '));
  7621. if (! result.containsChar ('%'))
  7622. return result;
  7623. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7624. // after all the replacements have been made, so that multi-byte chars are handled.
  7625. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7626. for (int i = 0; i < utf8.size(); ++i)
  7627. {
  7628. if (utf8.getUnchecked(i) == '%')
  7629. {
  7630. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7631. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7632. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7633. {
  7634. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7635. utf8.removeRange (i + 1, 2);
  7636. }
  7637. }
  7638. }
  7639. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7640. }
  7641. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7642. {
  7643. const char* const legalChars = isParameter ? "_-.*!'()"
  7644. : ",$_-.*!'()";
  7645. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7646. for (int i = 0; i < utf8.size(); ++i)
  7647. {
  7648. const char c = utf8.getUnchecked(i);
  7649. if (! (CharacterFunctions::isLetterOrDigit (c)
  7650. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7651. {
  7652. if (c == ' ')
  7653. {
  7654. utf8.set (i, '+');
  7655. }
  7656. else
  7657. {
  7658. static const char* const hexDigits = "0123456789abcdef";
  7659. utf8.set (i, '%');
  7660. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7661. utf8.insert (++i, hexDigits [c & 15]);
  7662. }
  7663. }
  7664. }
  7665. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7666. }
  7667. bool URL::launchInDefaultBrowser() const
  7668. {
  7669. String u (toString (true));
  7670. if (u.containsChar ('@') && ! u.containsChar (':'))
  7671. u = "mailto:" + u;
  7672. return PlatformUtilities::openDocument (u, String::empty);
  7673. }
  7674. END_JUCE_NAMESPACE
  7675. /*** End of inlined file: juce_URL.cpp ***/
  7676. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7677. BEGIN_JUCE_NAMESPACE
  7678. MACAddress::MACAddress()
  7679. : asInt64 (0)
  7680. {
  7681. }
  7682. MACAddress::MACAddress (const MACAddress& other)
  7683. : asInt64 (other.asInt64)
  7684. {
  7685. }
  7686. MACAddress& MACAddress::operator= (const MACAddress& other)
  7687. {
  7688. asInt64 = other.asInt64;
  7689. return *this;
  7690. }
  7691. MACAddress::MACAddress (const uint8 bytes[6])
  7692. : asInt64 (0)
  7693. {
  7694. memcpy (asBytes, bytes, sizeof (asBytes));
  7695. }
  7696. const String MACAddress::toString() const
  7697. {
  7698. String s;
  7699. s.preallocateStorage (18);
  7700. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7701. {
  7702. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7703. if (i < numElementsInArray (asBytes) - 1)
  7704. s << '-';
  7705. }
  7706. return s;
  7707. }
  7708. int64 MACAddress::toInt64() const throw()
  7709. {
  7710. int64 n = 0;
  7711. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7712. n = (n << 8) | asBytes[i];
  7713. return n;
  7714. }
  7715. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7716. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7717. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7718. END_JUCE_NAMESPACE
  7719. /*** End of inlined file: juce_MACAddress.cpp ***/
  7720. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7721. BEGIN_JUCE_NAMESPACE
  7722. namespace
  7723. {
  7724. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7725. {
  7726. // You need to supply a real stream when creating a BufferedInputStream
  7727. jassert (source != 0);
  7728. requestedSize = jmax (256, requestedSize);
  7729. const int64 sourceSize = source->getTotalLength();
  7730. if (sourceSize >= 0 && sourceSize < requestedSize)
  7731. requestedSize = jmax (32, (int) sourceSize);
  7732. return requestedSize;
  7733. }
  7734. }
  7735. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7736. const bool deleteSourceWhenDestroyed)
  7737. : source (sourceStream),
  7738. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  7739. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  7740. position (sourceStream->getPosition()),
  7741. lastReadPos (0),
  7742. bufferStart (position),
  7743. bufferOverlap (128)
  7744. {
  7745. buffer.malloc (bufferSize);
  7746. }
  7747. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  7748. : source (&sourceStream),
  7749. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  7750. position (sourceStream.getPosition()),
  7751. lastReadPos (0),
  7752. bufferStart (position),
  7753. bufferOverlap (128)
  7754. {
  7755. buffer.malloc (bufferSize);
  7756. }
  7757. BufferedInputStream::~BufferedInputStream()
  7758. {
  7759. }
  7760. int64 BufferedInputStream::getTotalLength()
  7761. {
  7762. return source->getTotalLength();
  7763. }
  7764. int64 BufferedInputStream::getPosition()
  7765. {
  7766. return position;
  7767. }
  7768. bool BufferedInputStream::setPosition (int64 newPosition)
  7769. {
  7770. position = jmax ((int64) 0, newPosition);
  7771. return true;
  7772. }
  7773. bool BufferedInputStream::isExhausted()
  7774. {
  7775. return (position >= lastReadPos)
  7776. && source->isExhausted();
  7777. }
  7778. void BufferedInputStream::ensureBuffered()
  7779. {
  7780. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7781. if (position < bufferStart || position >= bufferEndOverlap)
  7782. {
  7783. int bytesRead;
  7784. if (position < lastReadPos
  7785. && position >= bufferEndOverlap
  7786. && position >= bufferStart)
  7787. {
  7788. const int bytesToKeep = (int) (lastReadPos - position);
  7789. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7790. bufferStart = position;
  7791. bytesRead = source->read (buffer + bytesToKeep,
  7792. bufferSize - bytesToKeep);
  7793. lastReadPos += bytesRead;
  7794. bytesRead += bytesToKeep;
  7795. }
  7796. else
  7797. {
  7798. bufferStart = position;
  7799. source->setPosition (bufferStart);
  7800. bytesRead = source->read (buffer, bufferSize);
  7801. lastReadPos = bufferStart + bytesRead;
  7802. }
  7803. while (bytesRead < bufferSize)
  7804. buffer [bytesRead++] = 0;
  7805. }
  7806. }
  7807. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7808. {
  7809. if (position >= bufferStart
  7810. && position + maxBytesToRead <= lastReadPos)
  7811. {
  7812. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7813. position += maxBytesToRead;
  7814. return maxBytesToRead;
  7815. }
  7816. else
  7817. {
  7818. if (position < bufferStart || position >= lastReadPos)
  7819. ensureBuffered();
  7820. int bytesRead = 0;
  7821. while (maxBytesToRead > 0)
  7822. {
  7823. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7824. if (bytesAvailable > 0)
  7825. {
  7826. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7827. maxBytesToRead -= bytesAvailable;
  7828. bytesRead += bytesAvailable;
  7829. position += bytesAvailable;
  7830. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7831. }
  7832. const int64 oldLastReadPos = lastReadPos;
  7833. ensureBuffered();
  7834. if (oldLastReadPos == lastReadPos)
  7835. break; // if ensureBuffered() failed to read any more data, bail out
  7836. if (isExhausted())
  7837. break;
  7838. }
  7839. return bytesRead;
  7840. }
  7841. }
  7842. const String BufferedInputStream::readString()
  7843. {
  7844. if (position >= bufferStart
  7845. && position < lastReadPos)
  7846. {
  7847. const int maxChars = (int) (lastReadPos - position);
  7848. const char* const src = buffer + (int) (position - bufferStart);
  7849. for (int i = 0; i < maxChars; ++i)
  7850. {
  7851. if (src[i] == 0)
  7852. {
  7853. position += i + 1;
  7854. return String::fromUTF8 (src, i);
  7855. }
  7856. }
  7857. }
  7858. return InputStream::readString();
  7859. }
  7860. END_JUCE_NAMESPACE
  7861. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7862. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7863. BEGIN_JUCE_NAMESPACE
  7864. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  7865. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  7866. {
  7867. }
  7868. FileInputSource::~FileInputSource()
  7869. {
  7870. }
  7871. InputStream* FileInputSource::createInputStream()
  7872. {
  7873. return file.createInputStream();
  7874. }
  7875. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7876. {
  7877. return file.getSiblingFile (relatedItemPath).createInputStream();
  7878. }
  7879. int64 FileInputSource::hashCode() const
  7880. {
  7881. int64 h = file.hashCode();
  7882. if (useFileTimeInHashGeneration)
  7883. h ^= file.getLastModificationTime().toMilliseconds();
  7884. return h;
  7885. }
  7886. END_JUCE_NAMESPACE
  7887. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7888. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7889. BEGIN_JUCE_NAMESPACE
  7890. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7891. const size_t sourceDataSize,
  7892. const bool keepInternalCopy)
  7893. : data (static_cast <const char*> (sourceData)),
  7894. dataSize (sourceDataSize),
  7895. position (0)
  7896. {
  7897. if (keepInternalCopy)
  7898. {
  7899. internalCopy.append (data, sourceDataSize);
  7900. data = static_cast <const char*> (internalCopy.getData());
  7901. }
  7902. }
  7903. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7904. const bool keepInternalCopy)
  7905. : data (static_cast <const char*> (sourceData.getData())),
  7906. dataSize (sourceData.getSize()),
  7907. position (0)
  7908. {
  7909. if (keepInternalCopy)
  7910. {
  7911. internalCopy = sourceData;
  7912. data = static_cast <const char*> (internalCopy.getData());
  7913. }
  7914. }
  7915. MemoryInputStream::~MemoryInputStream()
  7916. {
  7917. }
  7918. int64 MemoryInputStream::getTotalLength()
  7919. {
  7920. return dataSize;
  7921. }
  7922. int MemoryInputStream::read (void* const buffer, const int howMany)
  7923. {
  7924. jassert (howMany >= 0);
  7925. const int num = jmin (howMany, (int) (dataSize - position));
  7926. memcpy (buffer, data + position, num);
  7927. position += num;
  7928. return (int) num;
  7929. }
  7930. bool MemoryInputStream::isExhausted()
  7931. {
  7932. return (position >= dataSize);
  7933. }
  7934. bool MemoryInputStream::setPosition (const int64 pos)
  7935. {
  7936. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7937. return true;
  7938. }
  7939. int64 MemoryInputStream::getPosition()
  7940. {
  7941. return position;
  7942. }
  7943. #if JUCE_UNIT_TESTS
  7944. class MemoryStreamTests : public UnitTest
  7945. {
  7946. public:
  7947. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  7948. void runTest()
  7949. {
  7950. beginTest ("Basics");
  7951. int randomInt = Random::getSystemRandom().nextInt();
  7952. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  7953. double randomDouble = Random::getSystemRandom().nextDouble();
  7954. String randomString;
  7955. for (int i = 50; --i >= 0;)
  7956. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  7957. MemoryOutputStream mo;
  7958. mo.writeInt (randomInt);
  7959. mo.writeIntBigEndian (randomInt);
  7960. mo.writeCompressedInt (randomInt);
  7961. mo.writeString (randomString);
  7962. mo.writeInt64 (randomInt64);
  7963. mo.writeInt64BigEndian (randomInt64);
  7964. mo.writeDouble (randomDouble);
  7965. mo.writeDoubleBigEndian (randomDouble);
  7966. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  7967. expect (mi.readInt() == randomInt);
  7968. expect (mi.readIntBigEndian() == randomInt);
  7969. expect (mi.readCompressedInt() == randomInt);
  7970. expect (mi.readString() == randomString);
  7971. expect (mi.readInt64() == randomInt64);
  7972. expect (mi.readInt64BigEndian() == randomInt64);
  7973. expect (mi.readDouble() == randomDouble);
  7974. expect (mi.readDoubleBigEndian() == randomDouble);
  7975. }
  7976. };
  7977. static MemoryStreamTests memoryInputStreamUnitTests;
  7978. #endif
  7979. END_JUCE_NAMESPACE
  7980. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7981. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7982. BEGIN_JUCE_NAMESPACE
  7983. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  7984. : data (internalBlock),
  7985. position (0),
  7986. size (0)
  7987. {
  7988. internalBlock.setSize (initialSize, false);
  7989. }
  7990. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  7991. const bool appendToExistingBlockContent)
  7992. : data (memoryBlockToWriteTo),
  7993. position (0),
  7994. size (0)
  7995. {
  7996. if (appendToExistingBlockContent)
  7997. position = size = memoryBlockToWriteTo.getSize();
  7998. }
  7999. MemoryOutputStream::~MemoryOutputStream()
  8000. {
  8001. flush();
  8002. }
  8003. void MemoryOutputStream::flush()
  8004. {
  8005. if (&data != &internalBlock)
  8006. data.setSize (size, false);
  8007. }
  8008. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8009. {
  8010. data.ensureSize (bytesToPreallocate + 1);
  8011. }
  8012. void MemoryOutputStream::reset() throw()
  8013. {
  8014. position = 0;
  8015. size = 0;
  8016. }
  8017. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8018. {
  8019. if (howMany > 0)
  8020. {
  8021. const size_t storageNeeded = position + howMany;
  8022. if (storageNeeded >= data.getSize())
  8023. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8024. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8025. position += howMany;
  8026. size = jmax (size, position);
  8027. }
  8028. return true;
  8029. }
  8030. const void* MemoryOutputStream::getData() const throw()
  8031. {
  8032. void* const d = data.getData();
  8033. if (data.getSize() > size)
  8034. static_cast <char*> (d) [size] = 0;
  8035. return d;
  8036. }
  8037. bool MemoryOutputStream::setPosition (int64 newPosition)
  8038. {
  8039. if (newPosition <= (int64) size)
  8040. {
  8041. // ok to seek backwards
  8042. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8043. return true;
  8044. }
  8045. else
  8046. {
  8047. // trying to make it bigger isn't a good thing to do..
  8048. return false;
  8049. }
  8050. }
  8051. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8052. {
  8053. // before writing from an input, see if we can preallocate to make it more efficient..
  8054. int64 availableData = source.getTotalLength() - source.getPosition();
  8055. if (availableData > 0)
  8056. {
  8057. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8058. availableData = maxNumBytesToWrite;
  8059. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8060. }
  8061. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8062. }
  8063. const String MemoryOutputStream::toUTF8() const
  8064. {
  8065. return String (static_cast <const char*> (getData()), getDataSize());
  8066. }
  8067. const String MemoryOutputStream::toString() const
  8068. {
  8069. return String::createStringFromData (getData(), getDataSize());
  8070. }
  8071. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8072. {
  8073. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8074. return stream;
  8075. }
  8076. END_JUCE_NAMESPACE
  8077. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8078. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8079. BEGIN_JUCE_NAMESPACE
  8080. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8081. const int64 startPositionInSourceStream_,
  8082. const int64 lengthOfSourceStream_,
  8083. const bool deleteSourceWhenDestroyed)
  8084. : source (sourceStream),
  8085. startPositionInSourceStream (startPositionInSourceStream_),
  8086. lengthOfSourceStream (lengthOfSourceStream_)
  8087. {
  8088. if (deleteSourceWhenDestroyed)
  8089. sourceToDelete = source;
  8090. setPosition (0);
  8091. }
  8092. SubregionStream::~SubregionStream()
  8093. {
  8094. }
  8095. int64 SubregionStream::getTotalLength()
  8096. {
  8097. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8098. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8099. : srcLen;
  8100. }
  8101. int64 SubregionStream::getPosition()
  8102. {
  8103. return source->getPosition() - startPositionInSourceStream;
  8104. }
  8105. bool SubregionStream::setPosition (int64 newPosition)
  8106. {
  8107. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8108. }
  8109. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8110. {
  8111. if (lengthOfSourceStream < 0)
  8112. {
  8113. return source->read (destBuffer, maxBytesToRead);
  8114. }
  8115. else
  8116. {
  8117. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8118. if (maxBytesToRead <= 0)
  8119. return 0;
  8120. return source->read (destBuffer, maxBytesToRead);
  8121. }
  8122. }
  8123. bool SubregionStream::isExhausted()
  8124. {
  8125. if (lengthOfSourceStream >= 0)
  8126. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8127. else
  8128. return source->isExhausted();
  8129. }
  8130. END_JUCE_NAMESPACE
  8131. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8132. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8133. BEGIN_JUCE_NAMESPACE
  8134. PerformanceCounter::PerformanceCounter (const String& name_,
  8135. int runsPerPrintout,
  8136. const File& loggingFile)
  8137. : name (name_),
  8138. numRuns (0),
  8139. runsPerPrint (runsPerPrintout),
  8140. totalTime (0),
  8141. outputFile (loggingFile)
  8142. {
  8143. if (outputFile != File::nonexistent)
  8144. {
  8145. String s ("**** Counter for \"");
  8146. s << name_ << "\" started at: "
  8147. << Time::getCurrentTime().toString (true, true)
  8148. << newLine;
  8149. outputFile.appendText (s, false, false);
  8150. }
  8151. }
  8152. PerformanceCounter::~PerformanceCounter()
  8153. {
  8154. printStatistics();
  8155. }
  8156. void PerformanceCounter::start()
  8157. {
  8158. started = Time::getHighResolutionTicks();
  8159. }
  8160. void PerformanceCounter::stop()
  8161. {
  8162. const int64 now = Time::getHighResolutionTicks();
  8163. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8164. if (++numRuns == runsPerPrint)
  8165. printStatistics();
  8166. }
  8167. void PerformanceCounter::printStatistics()
  8168. {
  8169. if (numRuns > 0)
  8170. {
  8171. String s ("Performance count for \"");
  8172. s << name << "\" - average over " << numRuns << " run(s) = ";
  8173. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8174. if (micros > 10000)
  8175. s << (micros/1000) << " millisecs";
  8176. else
  8177. s << micros << " microsecs";
  8178. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8179. Logger::outputDebugString (s);
  8180. s << newLine;
  8181. if (outputFile != File::nonexistent)
  8182. outputFile.appendText (s, false, false);
  8183. numRuns = 0;
  8184. totalTime = 0;
  8185. }
  8186. }
  8187. END_JUCE_NAMESPACE
  8188. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8189. /*** Start of inlined file: juce_Uuid.cpp ***/
  8190. BEGIN_JUCE_NAMESPACE
  8191. Uuid::Uuid()
  8192. {
  8193. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8194. // to make it very very unlikely that two UUIDs will ever be the same..
  8195. static int64 macAddresses[2];
  8196. static bool hasCheckedMacAddresses = false;
  8197. if (! hasCheckedMacAddresses)
  8198. {
  8199. hasCheckedMacAddresses = true;
  8200. Array<MACAddress> result;
  8201. MACAddress::findAllAddresses (result);
  8202. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8203. macAddresses[i] = result[i].toInt64();
  8204. }
  8205. value.asInt64[0] = macAddresses[0];
  8206. value.asInt64[1] = macAddresses[1];
  8207. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8208. // whose seed will carry over between calls to this method.
  8209. Random r (macAddresses[0] ^ macAddresses[1]
  8210. ^ Random::getSystemRandom().nextInt64());
  8211. for (int i = 4; --i >= 0;)
  8212. {
  8213. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8214. value.asInt[i] ^= r.nextInt();
  8215. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8216. }
  8217. }
  8218. Uuid::~Uuid() throw()
  8219. {
  8220. }
  8221. Uuid::Uuid (const Uuid& other)
  8222. : value (other.value)
  8223. {
  8224. }
  8225. Uuid& Uuid::operator= (const Uuid& other)
  8226. {
  8227. value = other.value;
  8228. return *this;
  8229. }
  8230. bool Uuid::operator== (const Uuid& other) const
  8231. {
  8232. return value.asInt64[0] == other.value.asInt64[0]
  8233. && value.asInt64[1] == other.value.asInt64[1];
  8234. }
  8235. bool Uuid::operator!= (const Uuid& other) const
  8236. {
  8237. return ! operator== (other);
  8238. }
  8239. bool Uuid::isNull() const throw()
  8240. {
  8241. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8242. }
  8243. const String Uuid::toString() const
  8244. {
  8245. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8246. }
  8247. Uuid::Uuid (const String& uuidString)
  8248. {
  8249. operator= (uuidString);
  8250. }
  8251. Uuid& Uuid::operator= (const String& uuidString)
  8252. {
  8253. MemoryBlock mb;
  8254. mb.loadFromHexString (uuidString);
  8255. mb.ensureSize (sizeof (value.asBytes), true);
  8256. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8257. return *this;
  8258. }
  8259. Uuid::Uuid (const uint8* const rawData)
  8260. {
  8261. operator= (rawData);
  8262. }
  8263. Uuid& Uuid::operator= (const uint8* const rawData)
  8264. {
  8265. if (rawData != 0)
  8266. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8267. else
  8268. zeromem (value.asBytes, sizeof (value.asBytes));
  8269. return *this;
  8270. }
  8271. END_JUCE_NAMESPACE
  8272. /*** End of inlined file: juce_Uuid.cpp ***/
  8273. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8274. BEGIN_JUCE_NAMESPACE
  8275. class ZipFile::ZipEntryInfo
  8276. {
  8277. public:
  8278. ZipFile::ZipEntry entry;
  8279. int streamOffset;
  8280. int compressedSize;
  8281. bool compressed;
  8282. };
  8283. class ZipFile::ZipInputStream : public InputStream
  8284. {
  8285. public:
  8286. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8287. : file (file_),
  8288. zipEntryInfo (zei),
  8289. pos (0),
  8290. headerSize (0),
  8291. inputStream (0)
  8292. {
  8293. inputStream = file_.inputStream;
  8294. if (file_.inputSource != 0)
  8295. {
  8296. inputStream = streamToDelete = file.inputSource->createInputStream();
  8297. }
  8298. else
  8299. {
  8300. #if JUCE_DEBUG
  8301. file_.numOpenStreams++;
  8302. #endif
  8303. }
  8304. char buffer [30];
  8305. if (inputStream != 0
  8306. && inputStream->setPosition (zei.streamOffset)
  8307. && inputStream->read (buffer, 30) == 30
  8308. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8309. {
  8310. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8311. + ByteOrder::littleEndianShort (buffer + 28);
  8312. }
  8313. }
  8314. ~ZipInputStream()
  8315. {
  8316. #if JUCE_DEBUG
  8317. if (inputStream != 0 && inputStream == file.inputStream)
  8318. file.numOpenStreams--;
  8319. #endif
  8320. }
  8321. int64 getTotalLength()
  8322. {
  8323. return zipEntryInfo.compressedSize;
  8324. }
  8325. int read (void* buffer, int howMany)
  8326. {
  8327. if (headerSize <= 0)
  8328. return 0;
  8329. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8330. if (inputStream == 0)
  8331. return 0;
  8332. int num;
  8333. if (inputStream == file.inputStream)
  8334. {
  8335. const ScopedLock sl (file.lock);
  8336. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8337. num = inputStream->read (buffer, howMany);
  8338. }
  8339. else
  8340. {
  8341. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8342. num = inputStream->read (buffer, howMany);
  8343. }
  8344. pos += num;
  8345. return num;
  8346. }
  8347. bool isExhausted()
  8348. {
  8349. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8350. }
  8351. int64 getPosition()
  8352. {
  8353. return pos;
  8354. }
  8355. bool setPosition (int64 newPos)
  8356. {
  8357. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8358. return true;
  8359. }
  8360. private:
  8361. ZipFile& file;
  8362. ZipEntryInfo zipEntryInfo;
  8363. int64 pos;
  8364. int headerSize;
  8365. InputStream* inputStream;
  8366. ScopedPointer<InputStream> streamToDelete;
  8367. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8368. };
  8369. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8370. : inputStream (source_)
  8371. #if JUCE_DEBUG
  8372. , numOpenStreams (0)
  8373. #endif
  8374. {
  8375. if (deleteStreamWhenDestroyed)
  8376. streamToDelete = inputStream;
  8377. init();
  8378. }
  8379. ZipFile::ZipFile (const File& file)
  8380. : inputStream (0)
  8381. #if JUCE_DEBUG
  8382. , numOpenStreams (0)
  8383. #endif
  8384. {
  8385. inputSource = new FileInputSource (file);
  8386. init();
  8387. }
  8388. ZipFile::ZipFile (InputSource* const inputSource_)
  8389. : inputStream (0),
  8390. inputSource (inputSource_)
  8391. #if JUCE_DEBUG
  8392. , numOpenStreams (0)
  8393. #endif
  8394. {
  8395. init();
  8396. }
  8397. ZipFile::~ZipFile()
  8398. {
  8399. #if JUCE_DEBUG
  8400. entries.clear();
  8401. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8402. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8403. Streams can't be kept open after the file is deleted because they need to share the input
  8404. stream that the file uses to read itself.
  8405. */
  8406. jassert (numOpenStreams == 0);
  8407. #endif
  8408. }
  8409. int ZipFile::getNumEntries() const throw()
  8410. {
  8411. return entries.size();
  8412. }
  8413. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8414. {
  8415. ZipEntryInfo* const zei = entries [index];
  8416. return zei != 0 ? &(zei->entry) : 0;
  8417. }
  8418. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8419. {
  8420. for (int i = 0; i < entries.size(); ++i)
  8421. if (entries.getUnchecked (i)->entry.filename == fileName)
  8422. return i;
  8423. return -1;
  8424. }
  8425. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8426. {
  8427. return getEntry (getIndexOfFileName (fileName));
  8428. }
  8429. InputStream* ZipFile::createStreamForEntry (const int index)
  8430. {
  8431. ZipEntryInfo* const zei = entries[index];
  8432. InputStream* stream = 0;
  8433. if (zei != 0)
  8434. {
  8435. stream = new ZipInputStream (*this, *zei);
  8436. if (zei->compressed)
  8437. {
  8438. stream = new GZIPDecompressorInputStream (stream, true, true,
  8439. zei->entry.uncompressedSize);
  8440. // (much faster to unzip in big blocks using a buffer..)
  8441. stream = new BufferedInputStream (stream, 32768, true);
  8442. }
  8443. }
  8444. return stream;
  8445. }
  8446. class ZipFile::ZipFilenameComparator
  8447. {
  8448. public:
  8449. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8450. {
  8451. return first->entry.filename.compare (second->entry.filename);
  8452. }
  8453. };
  8454. void ZipFile::sortEntriesByFilename()
  8455. {
  8456. ZipFilenameComparator sorter;
  8457. entries.sort (sorter);
  8458. }
  8459. void ZipFile::init()
  8460. {
  8461. ScopedPointer <InputStream> toDelete;
  8462. InputStream* in = inputStream;
  8463. if (inputSource != 0)
  8464. {
  8465. in = inputSource->createInputStream();
  8466. toDelete = in;
  8467. }
  8468. if (in != 0)
  8469. {
  8470. int numEntries = 0;
  8471. int pos = findEndOfZipEntryTable (*in, numEntries);
  8472. if (pos >= 0 && pos < in->getTotalLength())
  8473. {
  8474. const int size = (int) (in->getTotalLength() - pos);
  8475. in->setPosition (pos);
  8476. MemoryBlock headerData;
  8477. if (in->readIntoMemoryBlock (headerData, size) == size)
  8478. {
  8479. pos = 0;
  8480. for (int i = 0; i < numEntries; ++i)
  8481. {
  8482. if (pos + 46 > size)
  8483. break;
  8484. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8485. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8486. if (pos + 46 + fileNameLen > size)
  8487. break;
  8488. ZipEntryInfo* const zei = new ZipEntryInfo();
  8489. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8490. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8491. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8492. const int year = 1980 + (date >> 9);
  8493. const int month = ((date >> 5) & 15) - 1;
  8494. const int day = date & 31;
  8495. const int hours = time >> 11;
  8496. const int minutes = (time >> 5) & 63;
  8497. const int seconds = (time & 31) << 1;
  8498. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8499. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8500. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8501. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8502. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8503. entries.add (zei);
  8504. pos += 46 + fileNameLen
  8505. + ByteOrder::littleEndianShort (buffer + 30)
  8506. + ByteOrder::littleEndianShort (buffer + 32);
  8507. }
  8508. }
  8509. }
  8510. }
  8511. }
  8512. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8513. {
  8514. BufferedInputStream in (input, 8192);
  8515. in.setPosition (in.getTotalLength());
  8516. int64 pos = in.getPosition();
  8517. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8518. char buffer [32];
  8519. zeromem (buffer, sizeof (buffer));
  8520. while (pos > lowestPos)
  8521. {
  8522. in.setPosition (pos - 22);
  8523. pos = in.getPosition();
  8524. memcpy (buffer + 22, buffer, 4);
  8525. if (in.read (buffer, 22) != 22)
  8526. return 0;
  8527. for (int i = 0; i < 22; ++i)
  8528. {
  8529. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8530. {
  8531. in.setPosition (pos + i);
  8532. in.read (buffer, 22);
  8533. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8534. return ByteOrder::littleEndianInt (buffer + 16);
  8535. }
  8536. }
  8537. }
  8538. return 0;
  8539. }
  8540. bool ZipFile::uncompressTo (const File& targetDirectory,
  8541. const bool shouldOverwriteFiles)
  8542. {
  8543. for (int i = 0; i < entries.size(); ++i)
  8544. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8545. return false;
  8546. return true;
  8547. }
  8548. bool ZipFile::uncompressEntry (const int index,
  8549. const File& targetDirectory,
  8550. bool shouldOverwriteFiles)
  8551. {
  8552. const ZipEntryInfo* zei = entries [index];
  8553. if (zei != 0)
  8554. {
  8555. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8556. if (zei->entry.filename.endsWithChar ('/'))
  8557. {
  8558. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8559. }
  8560. else
  8561. {
  8562. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8563. if (in != 0)
  8564. {
  8565. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8566. return false;
  8567. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8568. {
  8569. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8570. if (out != 0)
  8571. {
  8572. out->writeFromInputStream (*in, -1);
  8573. out = 0;
  8574. targetFile.setCreationTime (zei->entry.fileTime);
  8575. targetFile.setLastModificationTime (zei->entry.fileTime);
  8576. targetFile.setLastAccessTime (zei->entry.fileTime);
  8577. return true;
  8578. }
  8579. }
  8580. }
  8581. }
  8582. }
  8583. return false;
  8584. }
  8585. END_JUCE_NAMESPACE
  8586. /*** End of inlined file: juce_ZipFile.cpp ***/
  8587. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8588. #if JUCE_MSVC
  8589. #pragma warning (push)
  8590. #pragma warning (disable: 4514 4996)
  8591. #endif
  8592. #include <cwctype>
  8593. #include <cctype>
  8594. #include <ctime>
  8595. BEGIN_JUCE_NAMESPACE
  8596. int CharacterFunctions::length (const char* const s) throw()
  8597. {
  8598. return (int) strlen (s);
  8599. }
  8600. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8601. {
  8602. return (int) wcslen (s);
  8603. }
  8604. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8605. {
  8606. strncpy (dest, src, maxChars);
  8607. }
  8608. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8609. {
  8610. wcsncpy (dest, src, maxChars);
  8611. }
  8612. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8613. {
  8614. mbstowcs (dest, src, maxChars);
  8615. }
  8616. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8617. {
  8618. wcstombs (dest, src, maxChars);
  8619. }
  8620. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8621. {
  8622. return (int) wcstombs (0, src, 0);
  8623. }
  8624. void CharacterFunctions::append (char* dest, const char* src) throw()
  8625. {
  8626. strcat (dest, src);
  8627. }
  8628. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8629. {
  8630. wcscat (dest, src);
  8631. }
  8632. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8633. {
  8634. return strcmp (s1, s2);
  8635. }
  8636. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8637. {
  8638. jassert (s1 != 0 && s2 != 0);
  8639. return wcscmp (s1, s2);
  8640. }
  8641. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8642. {
  8643. jassert (s1 != 0 && s2 != 0);
  8644. return strncmp (s1, s2, maxChars);
  8645. }
  8646. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8647. {
  8648. jassert (s1 != 0 && s2 != 0);
  8649. return wcsncmp (s1, s2, maxChars);
  8650. }
  8651. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8652. {
  8653. jassert (s1 != 0 && s2 != 0);
  8654. for (;;)
  8655. {
  8656. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8657. if (diff != 0)
  8658. return diff;
  8659. else if (*s1 == 0)
  8660. break;
  8661. ++s1;
  8662. ++s2;
  8663. }
  8664. return 0;
  8665. }
  8666. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8667. {
  8668. return -compare (s2, s1);
  8669. }
  8670. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8671. {
  8672. jassert (s1 != 0 && s2 != 0);
  8673. #if JUCE_WINDOWS
  8674. return stricmp (s1, s2);
  8675. #else
  8676. return strcasecmp (s1, s2);
  8677. #endif
  8678. }
  8679. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8680. {
  8681. jassert (s1 != 0 && s2 != 0);
  8682. #if JUCE_WINDOWS
  8683. return _wcsicmp (s1, s2);
  8684. #else
  8685. for (;;)
  8686. {
  8687. if (*s1 != *s2)
  8688. {
  8689. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8690. if (diff != 0)
  8691. return diff < 0 ? -1 : 1;
  8692. }
  8693. else if (*s1 == 0)
  8694. break;
  8695. ++s1;
  8696. ++s2;
  8697. }
  8698. return 0;
  8699. #endif
  8700. }
  8701. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8702. {
  8703. jassert (s1 != 0 && s2 != 0);
  8704. for (;;)
  8705. {
  8706. if (*s1 != *s2)
  8707. {
  8708. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8709. if (diff != 0)
  8710. return diff < 0 ? -1 : 1;
  8711. }
  8712. else if (*s1 == 0)
  8713. break;
  8714. ++s1;
  8715. ++s2;
  8716. }
  8717. return 0;
  8718. }
  8719. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8720. {
  8721. jassert (s1 != 0 && s2 != 0);
  8722. #if JUCE_WINDOWS
  8723. return strnicmp (s1, s2, maxChars);
  8724. #else
  8725. return strncasecmp (s1, s2, maxChars);
  8726. #endif
  8727. }
  8728. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8729. {
  8730. jassert (s1 != 0 && s2 != 0);
  8731. #if JUCE_WINDOWS
  8732. return _wcsnicmp (s1, s2, maxChars);
  8733. #else
  8734. while (--maxChars >= 0)
  8735. {
  8736. if (*s1 != *s2)
  8737. {
  8738. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8739. if (diff != 0)
  8740. return diff < 0 ? -1 : 1;
  8741. }
  8742. else if (*s1 == 0)
  8743. break;
  8744. ++s1;
  8745. ++s2;
  8746. }
  8747. return 0;
  8748. #endif
  8749. }
  8750. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8751. {
  8752. return strstr (haystack, needle);
  8753. }
  8754. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8755. {
  8756. return wcsstr (haystack, needle);
  8757. }
  8758. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8759. {
  8760. if (haystack != 0)
  8761. {
  8762. int i = 0;
  8763. if (ignoreCase)
  8764. {
  8765. const char n1 = toLowerCase (needle);
  8766. const char n2 = toUpperCase (needle);
  8767. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8768. {
  8769. while (haystack[i] != 0)
  8770. {
  8771. if (haystack[i] == n1 || haystack[i] == n2)
  8772. return i;
  8773. ++i;
  8774. }
  8775. return -1;
  8776. }
  8777. jassert (n1 == needle);
  8778. }
  8779. while (haystack[i] != 0)
  8780. {
  8781. if (haystack[i] == needle)
  8782. return i;
  8783. ++i;
  8784. }
  8785. }
  8786. return -1;
  8787. }
  8788. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8789. {
  8790. if (haystack != 0)
  8791. {
  8792. int i = 0;
  8793. if (ignoreCase)
  8794. {
  8795. const juce_wchar n1 = toLowerCase (needle);
  8796. const juce_wchar n2 = toUpperCase (needle);
  8797. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8798. {
  8799. while (haystack[i] != 0)
  8800. {
  8801. if (haystack[i] == n1 || haystack[i] == n2)
  8802. return i;
  8803. ++i;
  8804. }
  8805. return -1;
  8806. }
  8807. jassert (n1 == needle);
  8808. }
  8809. while (haystack[i] != 0)
  8810. {
  8811. if (haystack[i] == needle)
  8812. return i;
  8813. ++i;
  8814. }
  8815. }
  8816. return -1;
  8817. }
  8818. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8819. {
  8820. jassert (haystack != 0);
  8821. int i = 0;
  8822. while (haystack[i] != 0)
  8823. {
  8824. if (haystack[i] == needle)
  8825. return i;
  8826. ++i;
  8827. }
  8828. return -1;
  8829. }
  8830. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8831. {
  8832. jassert (haystack != 0);
  8833. int i = 0;
  8834. while (haystack[i] != 0)
  8835. {
  8836. if (haystack[i] == needle)
  8837. return i;
  8838. ++i;
  8839. }
  8840. return -1;
  8841. }
  8842. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8843. {
  8844. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8845. }
  8846. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8847. {
  8848. if (allowedChars == 0)
  8849. return 0;
  8850. int i = 0;
  8851. for (;;)
  8852. {
  8853. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8854. break;
  8855. ++i;
  8856. }
  8857. return i;
  8858. }
  8859. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8860. {
  8861. return (int) strftime (dest, maxChars, format, tm);
  8862. }
  8863. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8864. {
  8865. return (int) wcsftime (dest, maxChars, format, tm);
  8866. }
  8867. int CharacterFunctions::getIntValue (const char* const s) throw()
  8868. {
  8869. return atoi (s);
  8870. }
  8871. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8872. {
  8873. #if JUCE_WINDOWS
  8874. return _wtoi (s);
  8875. #else
  8876. int v = 0;
  8877. while (isWhitespace (*s))
  8878. ++s;
  8879. const bool isNeg = *s == '-';
  8880. if (isNeg)
  8881. ++s;
  8882. for (;;)
  8883. {
  8884. const wchar_t c = *s++;
  8885. if (c >= '0' && c <= '9')
  8886. v = v * 10 + (int) (c - '0');
  8887. else
  8888. break;
  8889. }
  8890. return isNeg ? -v : v;
  8891. #endif
  8892. }
  8893. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8894. {
  8895. #if JUCE_LINUX
  8896. return atoll (s);
  8897. #elif JUCE_WINDOWS
  8898. return _atoi64 (s);
  8899. #else
  8900. int64 v = 0;
  8901. while (isWhitespace (*s))
  8902. ++s;
  8903. const bool isNeg = *s == '-';
  8904. if (isNeg)
  8905. ++s;
  8906. for (;;)
  8907. {
  8908. const char c = *s++;
  8909. if (c >= '0' && c <= '9')
  8910. v = v * 10 + (int64) (c - '0');
  8911. else
  8912. break;
  8913. }
  8914. return isNeg ? -v : v;
  8915. #endif
  8916. }
  8917. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8918. {
  8919. #if JUCE_WINDOWS
  8920. return _wtoi64 (s);
  8921. #else
  8922. int64 v = 0;
  8923. while (isWhitespace (*s))
  8924. ++s;
  8925. const bool isNeg = *s == '-';
  8926. if (isNeg)
  8927. ++s;
  8928. for (;;)
  8929. {
  8930. const juce_wchar c = *s++;
  8931. if (c >= '0' && c <= '9')
  8932. v = v * 10 + (int64) (c - '0');
  8933. else
  8934. break;
  8935. }
  8936. return isNeg ? -v : v;
  8937. #endif
  8938. }
  8939. namespace
  8940. {
  8941. double juce_mulexp10 (const double value, int exponent) throw()
  8942. {
  8943. if (exponent == 0)
  8944. return value;
  8945. if (value == 0)
  8946. return 0;
  8947. const bool negative = (exponent < 0);
  8948. if (negative)
  8949. exponent = -exponent;
  8950. double result = 1.0, power = 10.0;
  8951. for (int bit = 1; exponent != 0; bit <<= 1)
  8952. {
  8953. if ((exponent & bit) != 0)
  8954. {
  8955. exponent ^= bit;
  8956. result *= power;
  8957. if (exponent == 0)
  8958. break;
  8959. }
  8960. power *= power;
  8961. }
  8962. return negative ? (value / result) : (value * result);
  8963. }
  8964. template <class CharType>
  8965. double juce_atof (const CharType* const original) throw()
  8966. {
  8967. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8968. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8969. int exponent = 0, decPointIndex = 0, digit = 0;
  8970. int lastDigit = 0, numSignificantDigits = 0;
  8971. bool isNegative = false, digitsFound = false;
  8972. const int maxSignificantDigits = 15 + 2;
  8973. const CharType* s = original;
  8974. while (CharacterFunctions::isWhitespace (*s))
  8975. ++s;
  8976. switch (*s)
  8977. {
  8978. case '-': isNegative = true; // fall-through..
  8979. case '+': ++s;
  8980. }
  8981. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8982. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8983. for (;;)
  8984. {
  8985. if (CharacterFunctions::isDigit (*s))
  8986. {
  8987. lastDigit = digit;
  8988. digit = *s++ - '0';
  8989. digitsFound = true;
  8990. if (decPointIndex != 0)
  8991. exponentAdjustment[1]++;
  8992. if (numSignificantDigits == 0 && digit == 0)
  8993. continue;
  8994. if (++numSignificantDigits > maxSignificantDigits)
  8995. {
  8996. if (digit > 5)
  8997. ++accumulator [decPointIndex];
  8998. else if (digit == 5 && (lastDigit & 1) != 0)
  8999. ++accumulator [decPointIndex];
  9000. if (decPointIndex > 0)
  9001. exponentAdjustment[1]--;
  9002. else
  9003. exponentAdjustment[0]++;
  9004. while (CharacterFunctions::isDigit (*s))
  9005. {
  9006. ++s;
  9007. if (decPointIndex == 0)
  9008. exponentAdjustment[0]++;
  9009. }
  9010. }
  9011. else
  9012. {
  9013. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9014. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9015. {
  9016. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9017. + accumulator [decPointIndex];
  9018. accumulator [decPointIndex] = 0;
  9019. exponentAccumulator [decPointIndex] = 0;
  9020. }
  9021. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9022. exponentAccumulator [decPointIndex]++;
  9023. }
  9024. }
  9025. else if (decPointIndex == 0 && *s == '.')
  9026. {
  9027. ++s;
  9028. decPointIndex = 1;
  9029. if (numSignificantDigits > maxSignificantDigits)
  9030. {
  9031. while (CharacterFunctions::isDigit (*s))
  9032. ++s;
  9033. break;
  9034. }
  9035. }
  9036. else
  9037. {
  9038. break;
  9039. }
  9040. }
  9041. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9042. if (decPointIndex != 0)
  9043. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9044. if ((*s == 'e' || *s == 'E') && digitsFound)
  9045. {
  9046. bool negativeExponent = false;
  9047. switch (*++s)
  9048. {
  9049. case '-': negativeExponent = true; // fall-through..
  9050. case '+': ++s;
  9051. }
  9052. while (CharacterFunctions::isDigit (*s))
  9053. exponent = (exponent * 10) + (*s++ - '0');
  9054. if (negativeExponent)
  9055. exponent = -exponent;
  9056. }
  9057. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9058. if (decPointIndex != 0)
  9059. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9060. return isNegative ? -r : r;
  9061. }
  9062. }
  9063. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9064. {
  9065. return juce_atof <char> (s);
  9066. }
  9067. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9068. {
  9069. return juce_atof <juce_wchar> (s);
  9070. }
  9071. char CharacterFunctions::toUpperCase (const char character) throw()
  9072. {
  9073. return (char) toupper (character);
  9074. }
  9075. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9076. {
  9077. return towupper (character);
  9078. }
  9079. void CharacterFunctions::toUpperCase (char* s) throw()
  9080. {
  9081. #if JUCE_WINDOWS
  9082. strupr (s);
  9083. #else
  9084. while (*s != 0)
  9085. {
  9086. *s = toUpperCase (*s);
  9087. ++s;
  9088. }
  9089. #endif
  9090. }
  9091. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9092. {
  9093. #if JUCE_WINDOWS
  9094. _wcsupr (s);
  9095. #else
  9096. while (*s != 0)
  9097. {
  9098. *s = toUpperCase (*s);
  9099. ++s;
  9100. }
  9101. #endif
  9102. }
  9103. bool CharacterFunctions::isUpperCase (const char character) throw()
  9104. {
  9105. return isupper (character) != 0;
  9106. }
  9107. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9108. {
  9109. #if JUCE_WINDOWS
  9110. return iswupper (character) != 0;
  9111. #else
  9112. return toLowerCase (character) != character;
  9113. #endif
  9114. }
  9115. char CharacterFunctions::toLowerCase (const char character) throw()
  9116. {
  9117. return (char) tolower (character);
  9118. }
  9119. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9120. {
  9121. return towlower (character);
  9122. }
  9123. void CharacterFunctions::toLowerCase (char* s) throw()
  9124. {
  9125. #if JUCE_WINDOWS
  9126. strlwr (s);
  9127. #else
  9128. while (*s != 0)
  9129. {
  9130. *s = toLowerCase (*s);
  9131. ++s;
  9132. }
  9133. #endif
  9134. }
  9135. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9136. {
  9137. #if JUCE_WINDOWS
  9138. _wcslwr (s);
  9139. #else
  9140. while (*s != 0)
  9141. {
  9142. *s = toLowerCase (*s);
  9143. ++s;
  9144. }
  9145. #endif
  9146. }
  9147. bool CharacterFunctions::isLowerCase (const char character) throw()
  9148. {
  9149. return islower (character) != 0;
  9150. }
  9151. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9152. {
  9153. #if JUCE_WINDOWS
  9154. return iswlower (character) != 0;
  9155. #else
  9156. return toUpperCase (character) != character;
  9157. #endif
  9158. }
  9159. bool CharacterFunctions::isWhitespace (const char character) throw()
  9160. {
  9161. return character == ' ' || (character <= 13 && character >= 9);
  9162. }
  9163. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9164. {
  9165. return iswspace (character) != 0;
  9166. }
  9167. bool CharacterFunctions::isDigit (const char character) throw()
  9168. {
  9169. return (character >= '0' && character <= '9');
  9170. }
  9171. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9172. {
  9173. return iswdigit (character) != 0;
  9174. }
  9175. bool CharacterFunctions::isLetter (const char character) throw()
  9176. {
  9177. return (character >= 'a' && character <= 'z')
  9178. || (character >= 'A' && character <= 'Z');
  9179. }
  9180. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9181. {
  9182. return iswalpha (character) != 0;
  9183. }
  9184. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9185. {
  9186. return (character >= 'a' && character <= 'z')
  9187. || (character >= 'A' && character <= 'Z')
  9188. || (character >= '0' && character <= '9');
  9189. }
  9190. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9191. {
  9192. return iswalnum (character) != 0;
  9193. }
  9194. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9195. {
  9196. unsigned int d = digit - '0';
  9197. if (d < (unsigned int) 10)
  9198. return (int) d;
  9199. d += (unsigned int) ('0' - 'a');
  9200. if (d < (unsigned int) 6)
  9201. return (int) d + 10;
  9202. d += (unsigned int) ('a' - 'A');
  9203. if (d < (unsigned int) 6)
  9204. return (int) d + 10;
  9205. return -1;
  9206. }
  9207. #if JUCE_MSVC
  9208. #pragma warning (pop)
  9209. #endif
  9210. END_JUCE_NAMESPACE
  9211. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9212. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9213. BEGIN_JUCE_NAMESPACE
  9214. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9215. {
  9216. loadFromText (fileContents);
  9217. }
  9218. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9219. {
  9220. loadFromText (fileToLoad.loadFileAsString());
  9221. }
  9222. LocalisedStrings::~LocalisedStrings()
  9223. {
  9224. }
  9225. const String LocalisedStrings::translate (const String& text) const
  9226. {
  9227. return translations.getValue (text, text);
  9228. }
  9229. namespace
  9230. {
  9231. CriticalSection currentMappingsLock;
  9232. LocalisedStrings* currentMappings = 0;
  9233. int findCloseQuote (const String& text, int startPos)
  9234. {
  9235. juce_wchar lastChar = 0;
  9236. for (;;)
  9237. {
  9238. const juce_wchar c = text [startPos];
  9239. if (c == 0 || (c == '"' && lastChar != '\\'))
  9240. break;
  9241. lastChar = c;
  9242. ++startPos;
  9243. }
  9244. return startPos;
  9245. }
  9246. const String unescapeString (const String& s)
  9247. {
  9248. return s.replace ("\\\"", "\"")
  9249. .replace ("\\\'", "\'")
  9250. .replace ("\\t", "\t")
  9251. .replace ("\\r", "\r")
  9252. .replace ("\\n", "\n");
  9253. }
  9254. }
  9255. void LocalisedStrings::loadFromText (const String& fileContents)
  9256. {
  9257. StringArray lines;
  9258. lines.addLines (fileContents);
  9259. for (int i = 0; i < lines.size(); ++i)
  9260. {
  9261. String line (lines[i].trim());
  9262. if (line.startsWithChar ('"'))
  9263. {
  9264. int closeQuote = findCloseQuote (line, 1);
  9265. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9266. if (originalText.isNotEmpty())
  9267. {
  9268. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9269. closeQuote = findCloseQuote (line, openingQuote + 1);
  9270. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9271. if (newText.isNotEmpty())
  9272. translations.set (originalText, newText);
  9273. }
  9274. }
  9275. else if (line.startsWithIgnoreCase ("language:"))
  9276. {
  9277. languageName = line.substring (9).trim();
  9278. }
  9279. else if (line.startsWithIgnoreCase ("countries:"))
  9280. {
  9281. countryCodes.addTokens (line.substring (10).trim(), true);
  9282. countryCodes.trim();
  9283. countryCodes.removeEmptyStrings();
  9284. }
  9285. }
  9286. }
  9287. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9288. {
  9289. translations.setIgnoresCase (shouldIgnoreCase);
  9290. }
  9291. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9292. {
  9293. const ScopedLock sl (currentMappingsLock);
  9294. delete currentMappings;
  9295. currentMappings = newTranslations;
  9296. }
  9297. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9298. {
  9299. return currentMappings;
  9300. }
  9301. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9302. {
  9303. const ScopedLock sl (currentMappingsLock);
  9304. if (currentMappings != 0)
  9305. return currentMappings->translate (text);
  9306. return text;
  9307. }
  9308. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9309. {
  9310. return translateWithCurrentMappings (String (text));
  9311. }
  9312. END_JUCE_NAMESPACE
  9313. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9314. /*** Start of inlined file: juce_String.cpp ***/
  9315. #if JUCE_MSVC
  9316. #pragma warning (push)
  9317. #pragma warning (disable: 4514)
  9318. #endif
  9319. #include <locale>
  9320. BEGIN_JUCE_NAMESPACE
  9321. #if JUCE_MSVC
  9322. #pragma warning (pop)
  9323. #endif
  9324. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9325. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9326. #endif
  9327. NewLine newLine;
  9328. class StringHolder
  9329. {
  9330. public:
  9331. StringHolder()
  9332. : refCount (0x3fffffff), allocatedNumChars (0)
  9333. {
  9334. text[0] = 0;
  9335. }
  9336. static juce_wchar* createUninitialised (const size_t numChars)
  9337. {
  9338. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9339. s->refCount.value = 0;
  9340. s->allocatedNumChars = numChars;
  9341. return &(s->text[0]);
  9342. }
  9343. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9344. {
  9345. juce_wchar* const dest = createUninitialised (numChars);
  9346. copyChars (dest, src, numChars);
  9347. return dest;
  9348. }
  9349. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9350. {
  9351. juce_wchar* const dest = createUninitialised (numChars);
  9352. CharacterFunctions::copy (dest, src, (int) numChars);
  9353. dest [numChars] = 0;
  9354. return dest;
  9355. }
  9356. static inline juce_wchar* getEmpty() throw()
  9357. {
  9358. return &(empty.text[0]);
  9359. }
  9360. static void retain (juce_wchar* const text) throw()
  9361. {
  9362. ++(bufferFromText (text)->refCount);
  9363. }
  9364. static inline void release (StringHolder* const b) throw()
  9365. {
  9366. if (--(b->refCount) == -1 && b != &empty)
  9367. delete[] reinterpret_cast <char*> (b);
  9368. }
  9369. static void release (juce_wchar* const text) throw()
  9370. {
  9371. release (bufferFromText (text));
  9372. }
  9373. static juce_wchar* makeUnique (juce_wchar* const text)
  9374. {
  9375. StringHolder* const b = bufferFromText (text);
  9376. if (b->refCount.get() <= 0)
  9377. return text;
  9378. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9379. release (b);
  9380. return newText;
  9381. }
  9382. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9383. {
  9384. StringHolder* const b = bufferFromText (text);
  9385. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9386. return text;
  9387. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9388. copyChars (newText, text, b->allocatedNumChars);
  9389. release (b);
  9390. return newText;
  9391. }
  9392. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9393. {
  9394. return bufferFromText (text)->allocatedNumChars;
  9395. }
  9396. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9397. {
  9398. jassert (src != 0 && dest != 0);
  9399. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9400. dest [numChars] = 0;
  9401. }
  9402. Atomic<int> refCount;
  9403. size_t allocatedNumChars;
  9404. juce_wchar text[1];
  9405. static StringHolder empty;
  9406. private:
  9407. static inline StringHolder* bufferFromText (void* const text) throw()
  9408. {
  9409. // (Can't use offsetof() here because of warnings about this not being a POD)
  9410. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9411. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9412. }
  9413. };
  9414. StringHolder StringHolder::empty;
  9415. const String String::empty;
  9416. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9417. {
  9418. jassert (t[numChars] == 0); // must have a null terminator
  9419. text = StringHolder::createCopy (t, numChars);
  9420. }
  9421. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9422. {
  9423. if (numExtraChars > 0)
  9424. {
  9425. const int oldLen = length();
  9426. const int newTotalLen = oldLen + numExtraChars;
  9427. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9428. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9429. }
  9430. }
  9431. void String::preallocateStorage (const size_t numChars)
  9432. {
  9433. text = StringHolder::makeUniqueWithSize (text, numChars);
  9434. }
  9435. String::String() throw()
  9436. : text (StringHolder::getEmpty())
  9437. {
  9438. }
  9439. String::~String() throw()
  9440. {
  9441. StringHolder::release (text);
  9442. }
  9443. String::String (const String& other) throw()
  9444. : text (other.text)
  9445. {
  9446. StringHolder::retain (text);
  9447. }
  9448. void String::swapWith (String& other) throw()
  9449. {
  9450. swapVariables (text, other.text);
  9451. }
  9452. String& String::operator= (const String& other) throw()
  9453. {
  9454. juce_wchar* const newText = other.text;
  9455. StringHolder::retain (newText);
  9456. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>&> (text).exchange (newText));
  9457. return *this;
  9458. }
  9459. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9460. String::String (const Preallocation& preallocationSize)
  9461. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9462. {
  9463. }
  9464. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9465. {
  9466. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9467. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9468. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9469. }
  9470. String::String (const char* const t)
  9471. {
  9472. if (t != 0 && *t != 0)
  9473. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9474. else
  9475. text = StringHolder::getEmpty();
  9476. }
  9477. String::String (const juce_wchar* const t)
  9478. {
  9479. if (t != 0 && *t != 0)
  9480. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9481. else
  9482. text = StringHolder::getEmpty();
  9483. }
  9484. String::String (const char* const t, const size_t maxChars)
  9485. {
  9486. int i;
  9487. for (i = 0; (size_t) i < maxChars; ++i)
  9488. if (t[i] == 0)
  9489. break;
  9490. if (i > 0)
  9491. text = StringHolder::createCopy (t, i);
  9492. else
  9493. text = StringHolder::getEmpty();
  9494. }
  9495. String::String (const juce_wchar* const t, const size_t maxChars)
  9496. {
  9497. int i;
  9498. for (i = 0; (size_t) i < maxChars; ++i)
  9499. if (t[i] == 0)
  9500. break;
  9501. if (i > 0)
  9502. text = StringHolder::createCopy (t, i);
  9503. else
  9504. text = StringHolder::getEmpty();
  9505. }
  9506. const String String::charToString (const juce_wchar character)
  9507. {
  9508. String result (Preallocation (1));
  9509. result.text[0] = character;
  9510. result.text[1] = 0;
  9511. return result;
  9512. }
  9513. namespace NumberToStringConverters
  9514. {
  9515. // pass in a pointer to the END of a buffer..
  9516. juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9517. {
  9518. *--t = 0;
  9519. int64 v = (n >= 0) ? n : -n;
  9520. do
  9521. {
  9522. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9523. v /= 10;
  9524. } while (v > 0);
  9525. if (n < 0)
  9526. *--t = '-';
  9527. return t;
  9528. }
  9529. juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9530. {
  9531. *--t = 0;
  9532. do
  9533. {
  9534. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9535. v /= 10;
  9536. } while (v > 0);
  9537. return t;
  9538. }
  9539. juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9540. {
  9541. if (n == (int) 0x80000000) // (would cause an overflow)
  9542. return int64ToString (t, n);
  9543. *--t = 0;
  9544. int v = abs (n);
  9545. do
  9546. {
  9547. *--t = (juce_wchar) ('0' + (v % 10));
  9548. v /= 10;
  9549. } while (v > 0);
  9550. if (n < 0)
  9551. *--t = '-';
  9552. return t;
  9553. }
  9554. juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9555. {
  9556. *--t = 0;
  9557. do
  9558. {
  9559. *--t = (juce_wchar) ('0' + (v % 10));
  9560. v /= 10;
  9561. } while (v > 0);
  9562. return t;
  9563. }
  9564. juce_wchar getDecimalPoint()
  9565. {
  9566. #if JUCE_VC7_OR_EARLIER
  9567. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9568. #else
  9569. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9570. #endif
  9571. return dp;
  9572. }
  9573. juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9574. {
  9575. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9576. {
  9577. juce_wchar* const end = buffer + numChars;
  9578. juce_wchar* t = end;
  9579. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9580. *--t = (juce_wchar) 0;
  9581. while (numDecPlaces >= 0 || v > 0)
  9582. {
  9583. if (numDecPlaces == 0)
  9584. *--t = getDecimalPoint();
  9585. *--t = (juce_wchar) ('0' + (v % 10));
  9586. v /= 10;
  9587. --numDecPlaces;
  9588. }
  9589. if (n < 0)
  9590. *--t = '-';
  9591. len = end - t - 1;
  9592. return t;
  9593. }
  9594. else
  9595. {
  9596. #if JUCE_WINDOWS
  9597. #if JUCE_VC7_OR_EARLIER || JUCE_MINGW
  9598. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9599. #else
  9600. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9601. #endif
  9602. #else
  9603. len = swprintf (buffer, numChars, L"%.9g", n);
  9604. #endif
  9605. return buffer;
  9606. }
  9607. }
  9608. }
  9609. String::String (const int number)
  9610. {
  9611. juce_wchar buffer [16];
  9612. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9613. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9614. createInternal (start, end - start - 1);
  9615. }
  9616. String::String (const unsigned int number)
  9617. {
  9618. juce_wchar buffer [16];
  9619. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9620. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9621. createInternal (start, end - start - 1);
  9622. }
  9623. String::String (const short number)
  9624. {
  9625. juce_wchar buffer [16];
  9626. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9627. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9628. createInternal (start, end - start - 1);
  9629. }
  9630. String::String (const unsigned short number)
  9631. {
  9632. juce_wchar buffer [16];
  9633. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9634. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9635. createInternal (start, end - start - 1);
  9636. }
  9637. String::String (const int64 number)
  9638. {
  9639. juce_wchar buffer [32];
  9640. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9641. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9642. createInternal (start, end - start - 1);
  9643. }
  9644. String::String (const uint64 number)
  9645. {
  9646. juce_wchar buffer [32];
  9647. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9648. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9649. createInternal (start, end - start - 1);
  9650. }
  9651. String::String (const float number, const int numberOfDecimalPlaces)
  9652. {
  9653. juce_wchar buffer [48];
  9654. size_t len;
  9655. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9656. createInternal (start, len);
  9657. }
  9658. String::String (const double number, const int numberOfDecimalPlaces)
  9659. {
  9660. juce_wchar buffer [48];
  9661. size_t len;
  9662. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9663. createInternal (start, len);
  9664. }
  9665. int String::length() const throw()
  9666. {
  9667. return CharacterFunctions::length (text);
  9668. }
  9669. int String::hashCode() const throw()
  9670. {
  9671. const juce_wchar* t = text;
  9672. int result = 0;
  9673. while (*t != (juce_wchar) 0)
  9674. result = 31 * result + *t++;
  9675. return result;
  9676. }
  9677. int64 String::hashCode64() const throw()
  9678. {
  9679. const juce_wchar* t = text;
  9680. int64 result = 0;
  9681. while (*t != (juce_wchar) 0)
  9682. result = 101 * result + *t++;
  9683. return result;
  9684. }
  9685. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9686. {
  9687. return string1.compare (string2) == 0;
  9688. }
  9689. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9690. {
  9691. return string1.compare (string2) == 0;
  9692. }
  9693. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9694. {
  9695. return string1.compare (string2) == 0;
  9696. }
  9697. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9698. {
  9699. return string1.compare (string2) != 0;
  9700. }
  9701. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9702. {
  9703. return string1.compare (string2) != 0;
  9704. }
  9705. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9706. {
  9707. return string1.compare (string2) != 0;
  9708. }
  9709. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9710. {
  9711. return string1.compare (string2) > 0;
  9712. }
  9713. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9714. {
  9715. return string1.compare (string2) < 0;
  9716. }
  9717. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9718. {
  9719. return string1.compare (string2) >= 0;
  9720. }
  9721. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9722. {
  9723. return string1.compare (string2) <= 0;
  9724. }
  9725. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9726. {
  9727. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9728. : isEmpty();
  9729. }
  9730. bool String::equalsIgnoreCase (const char* t) const throw()
  9731. {
  9732. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9733. : isEmpty();
  9734. }
  9735. bool String::equalsIgnoreCase (const String& other) const throw()
  9736. {
  9737. return text == other.text
  9738. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9739. }
  9740. int String::compare (const String& other) const throw()
  9741. {
  9742. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9743. }
  9744. int String::compare (const char* other) const throw()
  9745. {
  9746. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9747. }
  9748. int String::compare (const juce_wchar* other) const throw()
  9749. {
  9750. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9751. }
  9752. int String::compareIgnoreCase (const String& other) const throw()
  9753. {
  9754. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9755. }
  9756. int String::compareLexicographically (const String& other) const throw()
  9757. {
  9758. const juce_wchar* s1 = text;
  9759. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9760. ++s1;
  9761. const juce_wchar* s2 = other.text;
  9762. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9763. ++s2;
  9764. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9765. }
  9766. String& String::operator+= (const juce_wchar* const t)
  9767. {
  9768. if (t != 0)
  9769. appendInternal (t, CharacterFunctions::length (t));
  9770. return *this;
  9771. }
  9772. String& String::operator+= (const String& other)
  9773. {
  9774. if (isEmpty())
  9775. operator= (other);
  9776. else
  9777. appendInternal (other.text, other.length());
  9778. return *this;
  9779. }
  9780. String& String::operator+= (const char ch)
  9781. {
  9782. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9783. return operator+= (static_cast <const juce_wchar*> (asString));
  9784. }
  9785. String& String::operator+= (const juce_wchar ch)
  9786. {
  9787. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9788. return operator+= (static_cast <const juce_wchar*> (asString));
  9789. }
  9790. String& String::operator+= (const int number)
  9791. {
  9792. juce_wchar buffer [16];
  9793. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9794. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9795. appendInternal (start, (int) (end - start));
  9796. return *this;
  9797. }
  9798. String& String::operator+= (const unsigned int number)
  9799. {
  9800. juce_wchar buffer [16];
  9801. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9802. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9803. appendInternal (start, (int) (end - start));
  9804. return *this;
  9805. }
  9806. void String::append (const juce_wchar* const other, const int howMany)
  9807. {
  9808. if (howMany > 0)
  9809. {
  9810. int i;
  9811. for (i = 0; i < howMany; ++i)
  9812. if (other[i] == 0)
  9813. break;
  9814. appendInternal (other, i);
  9815. }
  9816. }
  9817. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9818. {
  9819. String s (string1);
  9820. return s += string2;
  9821. }
  9822. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9823. {
  9824. String s (string1);
  9825. return s += string2;
  9826. }
  9827. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9828. {
  9829. return String::charToString (string1) + string2;
  9830. }
  9831. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9832. {
  9833. return String::charToString (string1) + string2;
  9834. }
  9835. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9836. {
  9837. return string1 += string2;
  9838. }
  9839. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9840. {
  9841. return string1 += string2;
  9842. }
  9843. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9844. {
  9845. return string1 += string2;
  9846. }
  9847. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9848. {
  9849. return string1 += string2;
  9850. }
  9851. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9852. {
  9853. return string1 += string2;
  9854. }
  9855. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9856. {
  9857. return string1 += characterToAppend;
  9858. }
  9859. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9860. {
  9861. return string1 += characterToAppend;
  9862. }
  9863. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9864. {
  9865. return string1 += string2;
  9866. }
  9867. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9868. {
  9869. return string1 += string2;
  9870. }
  9871. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9872. {
  9873. return string1 += string2;
  9874. }
  9875. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9876. {
  9877. return string1 += (int) number;
  9878. }
  9879. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9880. {
  9881. return string1 += number;
  9882. }
  9883. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  9884. {
  9885. return string1 += number;
  9886. }
  9887. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9888. {
  9889. return string1 += (int) number;
  9890. }
  9891. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  9892. {
  9893. return string1 += (unsigned int) number;
  9894. }
  9895. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9896. {
  9897. return string1 += String (number);
  9898. }
  9899. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9900. {
  9901. return string1 += String (number);
  9902. }
  9903. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9904. {
  9905. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9906. // if lots of large, persistent strings were to be written to streams).
  9907. const int numBytes = text.getNumBytesAsUTF8();
  9908. HeapBlock<char> temp (numBytes + 1);
  9909. text.copyToUTF8 (temp, numBytes + 1);
  9910. stream.write (temp, numBytes);
  9911. return stream;
  9912. }
  9913. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9914. {
  9915. return string1 += NewLine::getDefault();
  9916. }
  9917. int String::indexOfChar (const juce_wchar character) const throw()
  9918. {
  9919. const juce_wchar* t = text;
  9920. for (;;)
  9921. {
  9922. if (*t == character)
  9923. return (int) (t - text);
  9924. if (*t++ == 0)
  9925. return -1;
  9926. }
  9927. }
  9928. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9929. {
  9930. for (int i = length(); --i >= 0;)
  9931. if (text[i] == character)
  9932. return i;
  9933. return -1;
  9934. }
  9935. int String::indexOf (const String& t) const throw()
  9936. {
  9937. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9938. return r == 0 ? -1 : (int) (r - text);
  9939. }
  9940. int String::indexOfChar (const int startIndex,
  9941. const juce_wchar character) const throw()
  9942. {
  9943. if (startIndex > 0 && startIndex >= length())
  9944. return -1;
  9945. const juce_wchar* t = text + jmax (0, startIndex);
  9946. for (;;)
  9947. {
  9948. if (*t == character)
  9949. return (int) (t - text);
  9950. if (*t == 0)
  9951. return -1;
  9952. ++t;
  9953. }
  9954. }
  9955. int String::indexOfAnyOf (const String& charactersToLookFor,
  9956. const int startIndex,
  9957. const bool ignoreCase) const throw()
  9958. {
  9959. if (startIndex > 0 && startIndex >= length())
  9960. return -1;
  9961. const juce_wchar* t = text + jmax (0, startIndex);
  9962. while (*t != 0)
  9963. {
  9964. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  9965. return (int) (t - text);
  9966. ++t;
  9967. }
  9968. return -1;
  9969. }
  9970. int String::indexOf (const int startIndex, const String& other) const throw()
  9971. {
  9972. if (startIndex > 0 && startIndex >= length())
  9973. return -1;
  9974. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  9975. return found == 0 ? -1 : (int) (found - text);
  9976. }
  9977. int String::indexOfIgnoreCase (const String& other) const throw()
  9978. {
  9979. if (other.isNotEmpty())
  9980. {
  9981. const int len = other.length();
  9982. const int end = length() - len;
  9983. for (int i = 0; i <= end; ++i)
  9984. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9985. return i;
  9986. }
  9987. return -1;
  9988. }
  9989. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9990. {
  9991. if (other.isNotEmpty())
  9992. {
  9993. const int len = other.length();
  9994. const int end = length() - len;
  9995. for (int i = jmax (0, startIndex); i <= end; ++i)
  9996. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9997. return i;
  9998. }
  9999. return -1;
  10000. }
  10001. int String::lastIndexOf (const String& other) const throw()
  10002. {
  10003. if (other.isNotEmpty())
  10004. {
  10005. const int len = other.length();
  10006. int i = length() - len;
  10007. if (i >= 0)
  10008. {
  10009. const juce_wchar* n = text + i;
  10010. while (i >= 0)
  10011. {
  10012. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10013. return i;
  10014. --i;
  10015. }
  10016. }
  10017. }
  10018. return -1;
  10019. }
  10020. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10021. {
  10022. if (other.isNotEmpty())
  10023. {
  10024. const int len = other.length();
  10025. int i = length() - len;
  10026. if (i >= 0)
  10027. {
  10028. const juce_wchar* n = text + i;
  10029. while (i >= 0)
  10030. {
  10031. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10032. return i;
  10033. --i;
  10034. }
  10035. }
  10036. }
  10037. return -1;
  10038. }
  10039. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10040. {
  10041. for (int i = length(); --i >= 0;)
  10042. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10043. return i;
  10044. return -1;
  10045. }
  10046. bool String::contains (const String& other) const throw()
  10047. {
  10048. return indexOf (other) >= 0;
  10049. }
  10050. bool String::containsChar (const juce_wchar character) const throw()
  10051. {
  10052. const juce_wchar* t = text;
  10053. for (;;)
  10054. {
  10055. if (*t == 0)
  10056. return false;
  10057. if (*t == character)
  10058. return true;
  10059. ++t;
  10060. }
  10061. }
  10062. bool String::containsIgnoreCase (const String& t) const throw()
  10063. {
  10064. return indexOfIgnoreCase (t) >= 0;
  10065. }
  10066. int String::indexOfWholeWord (const String& word) const throw()
  10067. {
  10068. if (word.isNotEmpty())
  10069. {
  10070. const int wordLen = word.length();
  10071. const int end = length() - wordLen;
  10072. const juce_wchar* t = text;
  10073. for (int i = 0; i <= end; ++i)
  10074. {
  10075. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10076. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10077. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10078. {
  10079. return i;
  10080. }
  10081. ++t;
  10082. }
  10083. }
  10084. return -1;
  10085. }
  10086. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10087. {
  10088. if (word.isNotEmpty())
  10089. {
  10090. const int wordLen = word.length();
  10091. const int end = length() - wordLen;
  10092. const juce_wchar* t = text;
  10093. for (int i = 0; i <= end; ++i)
  10094. {
  10095. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10096. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10097. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10098. {
  10099. return i;
  10100. }
  10101. ++t;
  10102. }
  10103. }
  10104. return -1;
  10105. }
  10106. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10107. {
  10108. return indexOfWholeWord (wordToLookFor) >= 0;
  10109. }
  10110. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10111. {
  10112. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10113. }
  10114. namespace WildCardHelpers
  10115. {
  10116. int indexOfMatch (const juce_wchar* const wildcard,
  10117. const juce_wchar* const test,
  10118. const bool ignoreCase) throw()
  10119. {
  10120. int start = 0;
  10121. while (test [start] != 0)
  10122. {
  10123. int i = 0;
  10124. for (;;)
  10125. {
  10126. const juce_wchar wc = wildcard [i];
  10127. const juce_wchar c = test [i + start];
  10128. if (wc == c
  10129. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10130. || (wc == '?' && c != 0))
  10131. {
  10132. if (wc == 0)
  10133. return start;
  10134. ++i;
  10135. }
  10136. else
  10137. {
  10138. if (wc == '*' && (wildcard [i + 1] == 0
  10139. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10140. {
  10141. return start;
  10142. }
  10143. break;
  10144. }
  10145. }
  10146. ++start;
  10147. }
  10148. return -1;
  10149. }
  10150. }
  10151. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10152. {
  10153. int i = 0;
  10154. for (;;)
  10155. {
  10156. const juce_wchar wc = wildcard.text [i];
  10157. const juce_wchar c = text [i];
  10158. if (wc == c
  10159. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10160. || (wc == '?' && c != 0))
  10161. {
  10162. if (wc == 0)
  10163. return true;
  10164. ++i;
  10165. }
  10166. else
  10167. {
  10168. return wc == '*' && (wildcard [i + 1] == 0
  10169. || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10170. }
  10171. }
  10172. }
  10173. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10174. {
  10175. const int len = stringToRepeat.length();
  10176. String result (Preallocation (len * numberOfTimesToRepeat + 1));
  10177. juce_wchar* n = result.text;
  10178. *n = 0;
  10179. while (--numberOfTimesToRepeat >= 0)
  10180. {
  10181. StringHolder::copyChars (n, stringToRepeat.text, len);
  10182. n += len;
  10183. }
  10184. return result;
  10185. }
  10186. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10187. {
  10188. jassert (padCharacter != 0);
  10189. const int len = length();
  10190. if (len >= minimumLength || padCharacter == 0)
  10191. return *this;
  10192. String result (Preallocation (minimumLength + 1));
  10193. juce_wchar* n = result.text;
  10194. minimumLength -= len;
  10195. while (--minimumLength >= 0)
  10196. *n++ = padCharacter;
  10197. StringHolder::copyChars (n, text, len);
  10198. return result;
  10199. }
  10200. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10201. {
  10202. jassert (padCharacter != 0);
  10203. const int len = length();
  10204. if (len >= minimumLength || padCharacter == 0)
  10205. return *this;
  10206. String result (*this, (size_t) minimumLength);
  10207. juce_wchar* n = result.text + len;
  10208. minimumLength -= len;
  10209. while (--minimumLength >= 0)
  10210. *n++ = padCharacter;
  10211. *n = 0;
  10212. return result;
  10213. }
  10214. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10215. {
  10216. if (index < 0)
  10217. {
  10218. // a negative index to replace from?
  10219. jassertfalse;
  10220. index = 0;
  10221. }
  10222. if (numCharsToReplace < 0)
  10223. {
  10224. // replacing a negative number of characters?
  10225. numCharsToReplace = 0;
  10226. jassertfalse;
  10227. }
  10228. const int len = length();
  10229. if (index + numCharsToReplace > len)
  10230. {
  10231. if (index > len)
  10232. {
  10233. // replacing beyond the end of the string?
  10234. index = len;
  10235. jassertfalse;
  10236. }
  10237. numCharsToReplace = len - index;
  10238. }
  10239. const int newStringLen = stringToInsert.length();
  10240. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10241. if (newTotalLen <= 0)
  10242. return String::empty;
  10243. String result (Preallocation ((size_t) newTotalLen));
  10244. StringHolder::copyChars (result.text, text, index);
  10245. if (newStringLen > 0)
  10246. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10247. const int endStringLen = newTotalLen - (index + newStringLen);
  10248. if (endStringLen > 0)
  10249. StringHolder::copyChars (result.text + (index + newStringLen),
  10250. text + (index + numCharsToReplace),
  10251. endStringLen);
  10252. return result;
  10253. }
  10254. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10255. {
  10256. const int stringToReplaceLen = stringToReplace.length();
  10257. const int stringToInsertLen = stringToInsert.length();
  10258. int i = 0;
  10259. String result (*this);
  10260. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10261. : result.indexOf (i, stringToReplace))) >= 0)
  10262. {
  10263. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10264. i += stringToInsertLen;
  10265. }
  10266. return result;
  10267. }
  10268. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10269. {
  10270. const int index = indexOfChar (charToReplace);
  10271. if (index < 0)
  10272. return *this;
  10273. String result (*this, size_t());
  10274. juce_wchar* t = result.text + index;
  10275. while (*t != 0)
  10276. {
  10277. if (*t == charToReplace)
  10278. *t = charToInsert;
  10279. ++t;
  10280. }
  10281. return result;
  10282. }
  10283. const String String::replaceCharacters (const String& charactersToReplace,
  10284. const String& charactersToInsertInstead) const
  10285. {
  10286. String result (*this, size_t());
  10287. juce_wchar* t = result.text;
  10288. const int len2 = charactersToInsertInstead.length();
  10289. // the two strings passed in are supposed to be the same length!
  10290. jassert (len2 == charactersToReplace.length());
  10291. while (*t != 0)
  10292. {
  10293. const int index = charactersToReplace.indexOfChar (*t);
  10294. if (isPositiveAndBelow (index, len2))
  10295. *t = charactersToInsertInstead [index];
  10296. ++t;
  10297. }
  10298. return result;
  10299. }
  10300. bool String::startsWith (const String& other) const throw()
  10301. {
  10302. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10303. }
  10304. bool String::startsWithIgnoreCase (const String& other) const throw()
  10305. {
  10306. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10307. }
  10308. bool String::startsWithChar (const juce_wchar character) const throw()
  10309. {
  10310. jassert (character != 0); // strings can't contain a null character!
  10311. return text[0] == character;
  10312. }
  10313. bool String::endsWithChar (const juce_wchar character) const throw()
  10314. {
  10315. jassert (character != 0); // strings can't contain a null character!
  10316. return text[0] != 0
  10317. && text [length() - 1] == character;
  10318. }
  10319. bool String::endsWith (const String& other) const throw()
  10320. {
  10321. const int thisLen = length();
  10322. const int otherLen = other.length();
  10323. return thisLen >= otherLen
  10324. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10325. }
  10326. bool String::endsWithIgnoreCase (const String& other) const throw()
  10327. {
  10328. const int thisLen = length();
  10329. const int otherLen = other.length();
  10330. return thisLen >= otherLen
  10331. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10332. }
  10333. const String String::toUpperCase() const
  10334. {
  10335. String result (*this, size_t());
  10336. CharacterFunctions::toUpperCase (result.text);
  10337. return result;
  10338. }
  10339. const String String::toLowerCase() const
  10340. {
  10341. String result (*this, size_t());
  10342. CharacterFunctions::toLowerCase (result.text);
  10343. return result;
  10344. }
  10345. juce_wchar& String::operator[] (const int index)
  10346. {
  10347. jassert (isPositiveAndNotGreaterThan (index, length()));
  10348. text = StringHolder::makeUnique (text);
  10349. return text [index];
  10350. }
  10351. juce_wchar String::getLastCharacter() const throw()
  10352. {
  10353. return isEmpty() ? juce_wchar() : text [length() - 1];
  10354. }
  10355. const String String::substring (int start, int end) const
  10356. {
  10357. if (start < 0)
  10358. start = 0;
  10359. else if (end <= start)
  10360. return empty;
  10361. int len = 0;
  10362. while (len <= end && text [len] != 0)
  10363. ++len;
  10364. if (end >= len)
  10365. {
  10366. if (start == 0)
  10367. return *this;
  10368. end = len;
  10369. }
  10370. return String (text + start, end - start);
  10371. }
  10372. const String String::substring (const int start) const
  10373. {
  10374. if (start <= 0)
  10375. return *this;
  10376. const int len = length();
  10377. if (start >= len)
  10378. return empty;
  10379. return String (text + start, len - start);
  10380. }
  10381. const String String::dropLastCharacters (const int numberToDrop) const
  10382. {
  10383. return String (text, jmax (0, length() - numberToDrop));
  10384. }
  10385. const String String::getLastCharacters (const int numCharacters) const
  10386. {
  10387. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10388. }
  10389. const String String::fromFirstOccurrenceOf (const String& sub,
  10390. const bool includeSubString,
  10391. const bool ignoreCase) const
  10392. {
  10393. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10394. : indexOf (sub);
  10395. if (i < 0)
  10396. return empty;
  10397. return substring (includeSubString ? i : i + sub.length());
  10398. }
  10399. const String String::fromLastOccurrenceOf (const String& sub,
  10400. const bool includeSubString,
  10401. const bool ignoreCase) const
  10402. {
  10403. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10404. : lastIndexOf (sub);
  10405. if (i < 0)
  10406. return *this;
  10407. return substring (includeSubString ? i : i + sub.length());
  10408. }
  10409. const String String::upToFirstOccurrenceOf (const String& sub,
  10410. const bool includeSubString,
  10411. const bool ignoreCase) const
  10412. {
  10413. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10414. : indexOf (sub);
  10415. if (i < 0)
  10416. return *this;
  10417. return substring (0, includeSubString ? i + sub.length() : i);
  10418. }
  10419. const String String::upToLastOccurrenceOf (const String& sub,
  10420. const bool includeSubString,
  10421. const bool ignoreCase) const
  10422. {
  10423. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10424. : lastIndexOf (sub);
  10425. if (i < 0)
  10426. return *this;
  10427. return substring (0, includeSubString ? i + sub.length() : i);
  10428. }
  10429. bool String::isQuotedString() const
  10430. {
  10431. const String trimmed (trimStart());
  10432. return trimmed[0] == '"'
  10433. || trimmed[0] == '\'';
  10434. }
  10435. const String String::unquoted() const
  10436. {
  10437. String s (*this);
  10438. if (s.text[0] == '"' || s.text[0] == '\'')
  10439. s = s.substring (1);
  10440. const int lastCharIndex = s.length() - 1;
  10441. if (lastCharIndex >= 0
  10442. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10443. s [lastCharIndex] = 0;
  10444. return s;
  10445. }
  10446. const String String::quoted (const juce_wchar quoteCharacter) const
  10447. {
  10448. if (isEmpty())
  10449. return charToString (quoteCharacter) + quoteCharacter;
  10450. String t (*this);
  10451. if (! t.startsWithChar (quoteCharacter))
  10452. t = charToString (quoteCharacter) + t;
  10453. if (! t.endsWithChar (quoteCharacter))
  10454. t += quoteCharacter;
  10455. return t;
  10456. }
  10457. const String String::trim() const
  10458. {
  10459. if (isEmpty())
  10460. return empty;
  10461. int start = 0;
  10462. while (CharacterFunctions::isWhitespace (text [start]))
  10463. ++start;
  10464. const int len = length();
  10465. int end = len - 1;
  10466. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10467. --end;
  10468. ++end;
  10469. if (end <= start)
  10470. return empty;
  10471. else if (start > 0 || end < len)
  10472. return String (text + start, end - start);
  10473. return *this;
  10474. }
  10475. const String String::trimStart() const
  10476. {
  10477. if (isEmpty())
  10478. return empty;
  10479. const juce_wchar* t = text;
  10480. while (CharacterFunctions::isWhitespace (*t))
  10481. ++t;
  10482. if (t == text)
  10483. return *this;
  10484. return String (t);
  10485. }
  10486. const String String::trimEnd() const
  10487. {
  10488. if (isEmpty())
  10489. return empty;
  10490. const juce_wchar* endT = text + (length() - 1);
  10491. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10492. --endT;
  10493. return String (text, (int) (++endT - text));
  10494. }
  10495. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10496. {
  10497. const juce_wchar* t = text;
  10498. while (charactersToTrim.containsChar (*t))
  10499. ++t;
  10500. return t == text ? *this : String (t);
  10501. }
  10502. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10503. {
  10504. if (isEmpty())
  10505. return empty;
  10506. const int len = length();
  10507. const juce_wchar* endT = text + (len - 1);
  10508. int numToRemove = 0;
  10509. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10510. {
  10511. ++numToRemove;
  10512. --endT;
  10513. }
  10514. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10515. }
  10516. const String String::retainCharacters (const String& charactersToRetain) const
  10517. {
  10518. if (isEmpty())
  10519. return empty;
  10520. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10521. juce_wchar* dst = result.text;
  10522. const juce_wchar* src = text;
  10523. while (*src != 0)
  10524. {
  10525. if (charactersToRetain.containsChar (*src))
  10526. *dst++ = *src;
  10527. ++src;
  10528. }
  10529. *dst = 0;
  10530. return result;
  10531. }
  10532. const String String::removeCharacters (const String& charactersToRemove) const
  10533. {
  10534. if (isEmpty())
  10535. return empty;
  10536. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10537. juce_wchar* dst = result.text;
  10538. const juce_wchar* src = text;
  10539. while (*src != 0)
  10540. {
  10541. if (! charactersToRemove.containsChar (*src))
  10542. *dst++ = *src;
  10543. ++src;
  10544. }
  10545. *dst = 0;
  10546. return result;
  10547. }
  10548. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10549. {
  10550. int i = 0;
  10551. for (;;)
  10552. {
  10553. if (! permittedCharacters.containsChar (text[i]))
  10554. break;
  10555. ++i;
  10556. }
  10557. return substring (0, i);
  10558. }
  10559. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10560. {
  10561. const juce_wchar* const t = text;
  10562. int i = 0;
  10563. while (t[i] != 0)
  10564. {
  10565. if (charactersToStopAt.containsChar (t[i]))
  10566. return String (text, i);
  10567. ++i;
  10568. }
  10569. return empty;
  10570. }
  10571. bool String::containsOnly (const String& chars) const throw()
  10572. {
  10573. const juce_wchar* t = text;
  10574. while (*t != 0)
  10575. if (! chars.containsChar (*t++))
  10576. return false;
  10577. return true;
  10578. }
  10579. bool String::containsAnyOf (const String& chars) const throw()
  10580. {
  10581. const juce_wchar* t = text;
  10582. while (*t != 0)
  10583. if (chars.containsChar (*t++))
  10584. return true;
  10585. return false;
  10586. }
  10587. bool String::containsNonWhitespaceChars() const throw()
  10588. {
  10589. const juce_wchar* t = text;
  10590. while (*t != 0)
  10591. if (! CharacterFunctions::isWhitespace (*t++))
  10592. return true;
  10593. return false;
  10594. }
  10595. const String String::formatted (const juce_wchar* const pf, ... )
  10596. {
  10597. jassert (pf != 0);
  10598. va_list args;
  10599. va_start (args, pf);
  10600. size_t bufferSize = 256;
  10601. String result (Preallocation ((size_t) bufferSize));
  10602. result.text[0] = 0;
  10603. for (;;)
  10604. {
  10605. #if JUCE_LINUX && JUCE_64BIT
  10606. va_list tempArgs;
  10607. va_copy (tempArgs, args);
  10608. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10609. va_end (tempArgs);
  10610. #elif JUCE_WINDOWS
  10611. #if JUCE_MSVC
  10612. #pragma warning (push)
  10613. #pragma warning (disable: 4996)
  10614. #endif
  10615. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10616. #if JUCE_MSVC
  10617. #pragma warning (pop)
  10618. #endif
  10619. #else
  10620. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10621. #endif
  10622. if (num > 0)
  10623. return result;
  10624. bufferSize += 256;
  10625. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10626. break; // returns -1 because of an error rather than because it needs more space.
  10627. result.preallocateStorage (bufferSize);
  10628. }
  10629. return empty;
  10630. }
  10631. int String::getIntValue() const throw()
  10632. {
  10633. return CharacterFunctions::getIntValue (text);
  10634. }
  10635. int String::getTrailingIntValue() const throw()
  10636. {
  10637. int n = 0;
  10638. int mult = 1;
  10639. const juce_wchar* t = text + length();
  10640. while (--t >= text)
  10641. {
  10642. const juce_wchar c = *t;
  10643. if (! CharacterFunctions::isDigit (c))
  10644. {
  10645. if (c == '-')
  10646. n = -n;
  10647. break;
  10648. }
  10649. n += mult * (c - '0');
  10650. mult *= 10;
  10651. }
  10652. return n;
  10653. }
  10654. int64 String::getLargeIntValue() const throw()
  10655. {
  10656. return CharacterFunctions::getInt64Value (text);
  10657. }
  10658. float String::getFloatValue() const throw()
  10659. {
  10660. return (float) CharacterFunctions::getDoubleValue (text);
  10661. }
  10662. double String::getDoubleValue() const throw()
  10663. {
  10664. return CharacterFunctions::getDoubleValue (text);
  10665. }
  10666. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10667. const String String::toHexString (const int number)
  10668. {
  10669. juce_wchar buffer[32];
  10670. juce_wchar* const end = buffer + 32;
  10671. juce_wchar* t = end;
  10672. *--t = 0;
  10673. unsigned int v = (unsigned int) number;
  10674. do
  10675. {
  10676. *--t = hexDigits [v & 15];
  10677. v >>= 4;
  10678. } while (v != 0);
  10679. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10680. }
  10681. const String String::toHexString (const int64 number)
  10682. {
  10683. juce_wchar buffer[32];
  10684. juce_wchar* const end = buffer + 32;
  10685. juce_wchar* t = end;
  10686. *--t = 0;
  10687. uint64 v = (uint64) number;
  10688. do
  10689. {
  10690. *--t = hexDigits [(int) (v & 15)];
  10691. v >>= 4;
  10692. } while (v != 0);
  10693. return String (t, (int) (((char*) end) - (char*) t));
  10694. }
  10695. const String String::toHexString (const short number)
  10696. {
  10697. return toHexString ((int) (unsigned short) number);
  10698. }
  10699. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10700. {
  10701. if (size <= 0)
  10702. return empty;
  10703. int numChars = (size * 2) + 2;
  10704. if (groupSize > 0)
  10705. numChars += size / groupSize;
  10706. String s (Preallocation ((size_t) numChars));
  10707. juce_wchar* d = s.text;
  10708. for (int i = 0; i < size; ++i)
  10709. {
  10710. *d++ = hexDigits [(*data) >> 4];
  10711. *d++ = hexDigits [(*data) & 0xf];
  10712. ++data;
  10713. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10714. *d++ = ' ';
  10715. }
  10716. *d = 0;
  10717. return s;
  10718. }
  10719. int String::getHexValue32() const throw()
  10720. {
  10721. int result = 0;
  10722. const juce_wchar* c = text;
  10723. for (;;)
  10724. {
  10725. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10726. if (hexValue >= 0)
  10727. result = (result << 4) | hexValue;
  10728. else if (*c == 0)
  10729. break;
  10730. ++c;
  10731. }
  10732. return result;
  10733. }
  10734. int64 String::getHexValue64() const throw()
  10735. {
  10736. int64 result = 0;
  10737. const juce_wchar* c = text;
  10738. for (;;)
  10739. {
  10740. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10741. if (hexValue >= 0)
  10742. result = (result << 4) | hexValue;
  10743. else if (*c == 0)
  10744. break;
  10745. ++c;
  10746. }
  10747. return result;
  10748. }
  10749. const String String::createStringFromData (const void* const data_, const int size)
  10750. {
  10751. const char* const data = static_cast <const char*> (data_);
  10752. if (size <= 0 || data == 0)
  10753. {
  10754. return empty;
  10755. }
  10756. else if (size < 2)
  10757. {
  10758. return charToString (data[0]);
  10759. }
  10760. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10761. || (data[0] == (char)-1 && data[1] == (char)-2))
  10762. {
  10763. // assume it's 16-bit unicode
  10764. const bool bigEndian = (data[0] == (char)-2);
  10765. const int numChars = size / 2 - 1;
  10766. String result;
  10767. result.preallocateStorage (numChars + 2);
  10768. const uint16* const src = (const uint16*) (data + 2);
  10769. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10770. if (bigEndian)
  10771. {
  10772. for (int i = 0; i < numChars; ++i)
  10773. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10774. }
  10775. else
  10776. {
  10777. for (int i = 0; i < numChars; ++i)
  10778. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10779. }
  10780. dst [numChars] = 0;
  10781. return result;
  10782. }
  10783. else
  10784. {
  10785. return String::fromUTF8 (data, size);
  10786. }
  10787. }
  10788. const char* String::toUTF8() const
  10789. {
  10790. if (isEmpty())
  10791. {
  10792. return reinterpret_cast <const char*> (text);
  10793. }
  10794. else
  10795. {
  10796. const int currentLen = length() + 1;
  10797. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10798. String* const mutableThis = const_cast <String*> (this);
  10799. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10800. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10801. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10802. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10803. #endif
  10804. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10805. return otherCopy;
  10806. }
  10807. }
  10808. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10809. {
  10810. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10811. int num = 0, index = 0;
  10812. for (;;)
  10813. {
  10814. const uint32 c = (uint32) text [index++];
  10815. if (c >= 0x80)
  10816. {
  10817. int numExtraBytes = 1;
  10818. if (c >= 0x800)
  10819. {
  10820. ++numExtraBytes;
  10821. if (c >= 0x10000)
  10822. {
  10823. ++numExtraBytes;
  10824. if (c >= 0x200000)
  10825. {
  10826. ++numExtraBytes;
  10827. if (c >= 0x4000000)
  10828. ++numExtraBytes;
  10829. }
  10830. }
  10831. }
  10832. if (buffer != 0)
  10833. {
  10834. if (num + numExtraBytes >= maxBufferSizeBytes)
  10835. {
  10836. buffer [num++] = 0;
  10837. break;
  10838. }
  10839. else
  10840. {
  10841. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10842. while (--numExtraBytes >= 0)
  10843. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10844. }
  10845. }
  10846. else
  10847. {
  10848. num += numExtraBytes + 1;
  10849. }
  10850. }
  10851. else
  10852. {
  10853. if (buffer != 0)
  10854. {
  10855. if (num + 1 >= maxBufferSizeBytes)
  10856. {
  10857. buffer [num++] = 0;
  10858. break;
  10859. }
  10860. buffer [num] = (uint8) c;
  10861. }
  10862. ++num;
  10863. }
  10864. if (c == 0)
  10865. break;
  10866. }
  10867. return num;
  10868. }
  10869. int String::getNumBytesAsUTF8() const throw()
  10870. {
  10871. int num = 0;
  10872. const juce_wchar* t = text;
  10873. for (;;)
  10874. {
  10875. const uint32 c = (uint32) *t;
  10876. if (c >= 0x80)
  10877. {
  10878. ++num;
  10879. if (c >= 0x800)
  10880. {
  10881. ++num;
  10882. if (c >= 0x10000)
  10883. {
  10884. ++num;
  10885. if (c >= 0x200000)
  10886. {
  10887. ++num;
  10888. if (c >= 0x4000000)
  10889. ++num;
  10890. }
  10891. }
  10892. }
  10893. }
  10894. else if (c == 0)
  10895. break;
  10896. ++num;
  10897. ++t;
  10898. }
  10899. return num;
  10900. }
  10901. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10902. {
  10903. if (buffer == 0)
  10904. return empty;
  10905. if (bufferSizeBytes < 0)
  10906. bufferSizeBytes = std::numeric_limits<int>::max();
  10907. size_t numBytes;
  10908. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10909. if (buffer [numBytes] == 0)
  10910. break;
  10911. String result (Preallocation (numBytes + 1));
  10912. juce_wchar* dest = result.text;
  10913. size_t i = 0;
  10914. while (i < numBytes)
  10915. {
  10916. const char c = buffer [i++];
  10917. if (c < 0)
  10918. {
  10919. unsigned int mask = 0x7f;
  10920. int bit = 0x40;
  10921. int numExtraValues = 0;
  10922. while (bit != 0 && (c & bit) != 0)
  10923. {
  10924. bit >>= 1;
  10925. mask >>= 1;
  10926. ++numExtraValues;
  10927. }
  10928. int n = (mask & (unsigned char) c);
  10929. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10930. {
  10931. const char nextByte = buffer[i];
  10932. if ((nextByte & 0xc0) != 0x80)
  10933. break;
  10934. n <<= 6;
  10935. n |= (nextByte & 0x3f);
  10936. ++i;
  10937. }
  10938. *dest++ = (juce_wchar) n;
  10939. }
  10940. else
  10941. {
  10942. *dest++ = (juce_wchar) c;
  10943. }
  10944. }
  10945. *dest = 0;
  10946. return result;
  10947. }
  10948. const char* String::toCString() const
  10949. {
  10950. if (isEmpty())
  10951. {
  10952. return reinterpret_cast <const char*> (text);
  10953. }
  10954. else
  10955. {
  10956. const int len = length();
  10957. String* const mutableThis = const_cast <String*> (this);
  10958. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  10959. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  10960. CharacterFunctions::copy (otherCopy, text, len);
  10961. otherCopy [len] = 0;
  10962. return otherCopy;
  10963. }
  10964. }
  10965. #if JUCE_MSVC
  10966. #pragma warning (push)
  10967. #pragma warning (disable: 4514 4996)
  10968. #endif
  10969. int String::getNumBytesAsCString() const throw()
  10970. {
  10971. return (int) wcstombs (0, text, 0);
  10972. }
  10973. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10974. {
  10975. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10976. if (destBuffer != 0 && numBytes >= 0)
  10977. destBuffer [numBytes] = 0;
  10978. return numBytes;
  10979. }
  10980. #if JUCE_MSVC
  10981. #pragma warning (pop)
  10982. #endif
  10983. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  10984. {
  10985. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  10986. if (destBuffer != 0 && maxCharsToCopy >= 0)
  10987. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  10988. }
  10989. String::Concatenator::Concatenator (String& stringToAppendTo)
  10990. : result (stringToAppendTo),
  10991. nextIndex (stringToAppendTo.length())
  10992. {
  10993. }
  10994. String::Concatenator::~Concatenator()
  10995. {
  10996. }
  10997. void String::Concatenator::append (const String& s)
  10998. {
  10999. const int len = s.length();
  11000. if (len > 0)
  11001. {
  11002. result.preallocateStorage (nextIndex + len);
  11003. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11004. nextIndex += len;
  11005. }
  11006. }
  11007. #if JUCE_UNIT_TESTS
  11008. class StringTests : public UnitTest
  11009. {
  11010. public:
  11011. StringTests() : UnitTest ("String class") {}
  11012. void runTest()
  11013. {
  11014. {
  11015. beginTest ("Basics");
  11016. expect (String().length() == 0);
  11017. expect (String() == String::empty);
  11018. String s1, s2 ("abcd");
  11019. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11020. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11021. expect (s2.length() == 4);
  11022. s1 = "abcd";
  11023. expect (s2 == s1 && s1 == s2);
  11024. expect (s1 == "abcd" && s1 == L"abcd");
  11025. expect (String ("abcd") == String (L"abcd"));
  11026. expect (String ("abcdefg", 4) == L"abcd");
  11027. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11028. expect (String::charToString ('x') == "x");
  11029. expect (String::charToString (0) == String::empty);
  11030. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11031. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11032. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11033. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11034. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11035. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11036. expect (s1.indexOf (String::empty) == 0);
  11037. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11038. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11039. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11040. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11041. }
  11042. {
  11043. beginTest ("Operations");
  11044. String s ("012345678");
  11045. expect (s.hashCode() != 0);
  11046. expect (s.hashCode64() != 0);
  11047. expect (s.hashCode() != (s + s).hashCode());
  11048. expect (s.hashCode64() != (s + s).hashCode64());
  11049. expect (s.compare (String ("012345678")) == 0);
  11050. expect (s.compare (String ("012345679")) < 0);
  11051. expect (s.compare (String ("012345676")) > 0);
  11052. expect (s.substring (2, 3) == String::charToString (s[2]));
  11053. expect (s.substring (0, 1) == String::charToString (s[0]));
  11054. expect (s.getLastCharacter() == s [s.length() - 1]);
  11055. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11056. expect (s.substring (0, 3) == L"012");
  11057. expect (s.substring (0, 100) == s);
  11058. expect (s.substring (-1, 100) == s);
  11059. expect (s.substring (3) == "345678");
  11060. expect (s.indexOf (L"45") == 4);
  11061. expect (String ("444445").indexOf ("45") == 4);
  11062. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11063. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11064. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11065. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11066. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11067. expect (s.indexOfChar (L'4') == 4);
  11068. expect (s + s == "012345678012345678");
  11069. expect (s.startsWith (s));
  11070. expect (s.startsWith (s.substring (0, 4)));
  11071. expect (s.startsWith (s.dropLastCharacters (4)));
  11072. expect (s.endsWith (s.substring (5)));
  11073. expect (s.endsWith (s));
  11074. expect (s.contains (s.substring (3, 6)));
  11075. expect (s.contains (s.substring (3)));
  11076. expect (s.startsWithChar (s[0]));
  11077. expect (s.endsWithChar (s.getLastCharacter()));
  11078. expect (s [s.length()] == 0);
  11079. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11080. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11081. String s2 ("123");
  11082. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11083. s2 += "xyz";
  11084. expect (s2 == "1234567890xyz");
  11085. beginTest ("Numeric conversions");
  11086. expect (String::empty.getIntValue() == 0);
  11087. expect (String::empty.getDoubleValue() == 0.0);
  11088. expect (String::empty.getFloatValue() == 0.0f);
  11089. expect (s.getIntValue() == 12345678);
  11090. expect (s.getLargeIntValue() == (int64) 12345678);
  11091. expect (s.getDoubleValue() == 12345678.0);
  11092. expect (s.getFloatValue() == 12345678.0f);
  11093. expect (String (-1234).getIntValue() == -1234);
  11094. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11095. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11096. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11097. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11098. expect (s.getHexValue32() == 0x12345678);
  11099. expect (s.getHexValue64() == (int64) 0x12345678);
  11100. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11101. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11102. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11103. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11104. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11105. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11106. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11107. beginTest ("Subsections");
  11108. String s3;
  11109. s3 = "abcdeFGHIJ";
  11110. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11111. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11112. expect (s3.containsIgnoreCase (s3.substring (3)));
  11113. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11114. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11115. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11116. expect (s3.containsAnyOf (L"zzzFs"));
  11117. expect (s3.startsWith ("abcd"));
  11118. expect (s3.startsWithIgnoreCase (L"abCD"));
  11119. expect (s3.startsWith (String::empty));
  11120. expect (s3.startsWithChar ('a'));
  11121. expect (s3.endsWith (String ("HIJ")));
  11122. expect (s3.endsWithIgnoreCase (L"Hij"));
  11123. expect (s3.endsWith (String::empty));
  11124. expect (s3.endsWithChar (L'J'));
  11125. expect (s3.indexOf ("HIJ") == 7);
  11126. expect (s3.indexOf (L"HIJK") == -1);
  11127. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11128. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11129. String s4 (s3);
  11130. s4.append (String ("xyz123"), 3);
  11131. expect (s4 == s3 + "xyz");
  11132. expect (String (1234) < String (1235));
  11133. expect (String (1235) > String (1234));
  11134. expect (String (1234) >= String (1234));
  11135. expect (String (1234) <= String (1234));
  11136. expect (String (1235) >= String (1234));
  11137. expect (String (1234) <= String (1235));
  11138. String s5 ("word word2 word3");
  11139. expect (s5.containsWholeWord (String ("word2")));
  11140. expect (s5.indexOfWholeWord ("word2") == 5);
  11141. expect (s5.containsWholeWord (L"word"));
  11142. expect (s5.containsWholeWord ("word3"));
  11143. expect (s5.containsWholeWord (s5));
  11144. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11145. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11146. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11147. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11148. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11149. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11150. expect (s5.containsNonWhitespaceChars());
  11151. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11152. expect (s5.matchesWildcard (L"wor*", false));
  11153. expect (s5.matchesWildcard ("wOr*", true));
  11154. expect (s5.matchesWildcard (L"*word3", true));
  11155. expect (s5.matchesWildcard ("*word?", true));
  11156. expect (s5.matchesWildcard (L"Word*3", true));
  11157. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11158. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11159. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11160. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11161. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11162. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11163. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11164. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11165. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11166. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11167. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11168. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11169. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11170. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11171. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11172. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11173. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11174. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11175. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11176. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11177. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11178. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11179. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11180. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11181. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11182. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11183. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11184. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11185. expect (s5.replace ("Word", "", true) == " 2 3");
  11186. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11187. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11188. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11189. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11190. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11191. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11192. expect (s5.retainCharacters (String::empty).isEmpty());
  11193. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11194. expect (s5.removeCharacters (String::empty) == s5);
  11195. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11196. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11197. expect (! s5.isQuotedString());
  11198. expect (s5.quoted().isQuotedString());
  11199. expect (! s5.quoted().unquoted().isQuotedString());
  11200. expect (! String ("x'").isQuotedString());
  11201. expect (String ("'x").isQuotedString());
  11202. String s6 (" \t xyz \t\r\n");
  11203. expect (s6.trim() == String ("xyz"));
  11204. expect (s6.trim().trim() == "xyz");
  11205. expect (s5.trim() == s5);
  11206. expect (s6.trimStart().trimEnd() == s6.trim());
  11207. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11208. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11209. expect (s6.trimStart() != s6.trimEnd());
  11210. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11211. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11212. }
  11213. {
  11214. beginTest ("UTF8");
  11215. String s ("word word2 word3");
  11216. {
  11217. char buffer [100];
  11218. memset (buffer, 0xff, sizeof (buffer));
  11219. s.copyToUTF8 (buffer, 100);
  11220. expect (String::fromUTF8 (buffer, 100) == s);
  11221. juce_wchar bufferUnicode [100];
  11222. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11223. s.copyToUnicode (bufferUnicode, 100);
  11224. expect (String (bufferUnicode, 100) == s);
  11225. }
  11226. {
  11227. juce_wchar wideBuffer [50];
  11228. zerostruct (wideBuffer);
  11229. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11230. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11231. String wide (wideBuffer);
  11232. expect (wide == (const juce_wchar*) wideBuffer);
  11233. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11234. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11235. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11236. }
  11237. }
  11238. }
  11239. };
  11240. static StringTests stringUnitTests;
  11241. #endif
  11242. END_JUCE_NAMESPACE
  11243. /*** End of inlined file: juce_String.cpp ***/
  11244. /*** Start of inlined file: juce_StringArray.cpp ***/
  11245. BEGIN_JUCE_NAMESPACE
  11246. StringArray::StringArray() throw()
  11247. {
  11248. }
  11249. StringArray::StringArray (const StringArray& other)
  11250. : strings (other.strings)
  11251. {
  11252. }
  11253. StringArray::StringArray (const String& firstValue)
  11254. {
  11255. strings.add (firstValue);
  11256. }
  11257. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11258. const int numberOfStrings)
  11259. {
  11260. for (int i = 0; i < numberOfStrings; ++i)
  11261. strings.add (initialStrings [i]);
  11262. }
  11263. StringArray::StringArray (const char* const* const initialStrings,
  11264. const int numberOfStrings)
  11265. {
  11266. for (int i = 0; i < numberOfStrings; ++i)
  11267. strings.add (initialStrings [i]);
  11268. }
  11269. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11270. {
  11271. int i = 0;
  11272. while (initialStrings[i] != 0)
  11273. strings.add (initialStrings [i++]);
  11274. }
  11275. StringArray::StringArray (const char* const* const initialStrings)
  11276. {
  11277. int i = 0;
  11278. while (initialStrings[i] != 0)
  11279. strings.add (initialStrings [i++]);
  11280. }
  11281. StringArray& StringArray::operator= (const StringArray& other)
  11282. {
  11283. strings = other.strings;
  11284. return *this;
  11285. }
  11286. StringArray::~StringArray()
  11287. {
  11288. }
  11289. bool StringArray::operator== (const StringArray& other) const throw()
  11290. {
  11291. if (other.size() != size())
  11292. return false;
  11293. for (int i = size(); --i >= 0;)
  11294. if (other.strings.getReference(i) != strings.getReference(i))
  11295. return false;
  11296. return true;
  11297. }
  11298. bool StringArray::operator!= (const StringArray& other) const throw()
  11299. {
  11300. return ! operator== (other);
  11301. }
  11302. void StringArray::clear()
  11303. {
  11304. strings.clear();
  11305. }
  11306. const String& StringArray::operator[] (const int index) const throw()
  11307. {
  11308. if (isPositiveAndBelow (index, strings.size()))
  11309. return strings.getReference (index);
  11310. return String::empty;
  11311. }
  11312. String& StringArray::getReference (const int index) throw()
  11313. {
  11314. jassert (isPositiveAndBelow (index, strings.size()));
  11315. return strings.getReference (index);
  11316. }
  11317. void StringArray::add (const String& newString)
  11318. {
  11319. strings.add (newString);
  11320. }
  11321. void StringArray::insert (const int index, const String& newString)
  11322. {
  11323. strings.insert (index, newString);
  11324. }
  11325. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11326. {
  11327. if (! contains (newString, ignoreCase))
  11328. add (newString);
  11329. }
  11330. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11331. {
  11332. if (startIndex < 0)
  11333. {
  11334. jassertfalse;
  11335. startIndex = 0;
  11336. }
  11337. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11338. numElementsToAdd = otherArray.size() - startIndex;
  11339. while (--numElementsToAdd >= 0)
  11340. strings.add (otherArray.strings.getReference (startIndex++));
  11341. }
  11342. void StringArray::set (const int index, const String& newString)
  11343. {
  11344. strings.set (index, newString);
  11345. }
  11346. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11347. {
  11348. if (ignoreCase)
  11349. {
  11350. for (int i = size(); --i >= 0;)
  11351. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11352. return true;
  11353. }
  11354. else
  11355. {
  11356. for (int i = size(); --i >= 0;)
  11357. if (stringToLookFor == strings.getReference(i))
  11358. return true;
  11359. }
  11360. return false;
  11361. }
  11362. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11363. {
  11364. if (i < 0)
  11365. i = 0;
  11366. const int numElements = size();
  11367. if (ignoreCase)
  11368. {
  11369. while (i < numElements)
  11370. {
  11371. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11372. return i;
  11373. ++i;
  11374. }
  11375. }
  11376. else
  11377. {
  11378. while (i < numElements)
  11379. {
  11380. if (stringToLookFor == strings.getReference (i))
  11381. return i;
  11382. ++i;
  11383. }
  11384. }
  11385. return -1;
  11386. }
  11387. void StringArray::remove (const int index)
  11388. {
  11389. strings.remove (index);
  11390. }
  11391. void StringArray::removeString (const String& stringToRemove,
  11392. const bool ignoreCase)
  11393. {
  11394. if (ignoreCase)
  11395. {
  11396. for (int i = size(); --i >= 0;)
  11397. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11398. strings.remove (i);
  11399. }
  11400. else
  11401. {
  11402. for (int i = size(); --i >= 0;)
  11403. if (stringToRemove == strings.getReference (i))
  11404. strings.remove (i);
  11405. }
  11406. }
  11407. void StringArray::removeRange (int startIndex, int numberToRemove)
  11408. {
  11409. strings.removeRange (startIndex, numberToRemove);
  11410. }
  11411. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11412. {
  11413. if (removeWhitespaceStrings)
  11414. {
  11415. for (int i = size(); --i >= 0;)
  11416. if (! strings.getReference(i).containsNonWhitespaceChars())
  11417. strings.remove (i);
  11418. }
  11419. else
  11420. {
  11421. for (int i = size(); --i >= 0;)
  11422. if (strings.getReference(i).isEmpty())
  11423. strings.remove (i);
  11424. }
  11425. }
  11426. void StringArray::trim()
  11427. {
  11428. for (int i = size(); --i >= 0;)
  11429. {
  11430. String& s = strings.getReference(i);
  11431. s = s.trim();
  11432. }
  11433. }
  11434. class InternalStringArrayComparator_CaseSensitive
  11435. {
  11436. public:
  11437. static int compareElements (String& first, String& second) { return first.compare (second); }
  11438. };
  11439. class InternalStringArrayComparator_CaseInsensitive
  11440. {
  11441. public:
  11442. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11443. };
  11444. void StringArray::sort (const bool ignoreCase)
  11445. {
  11446. if (ignoreCase)
  11447. {
  11448. InternalStringArrayComparator_CaseInsensitive comp;
  11449. strings.sort (comp);
  11450. }
  11451. else
  11452. {
  11453. InternalStringArrayComparator_CaseSensitive comp;
  11454. strings.sort (comp);
  11455. }
  11456. }
  11457. void StringArray::move (const int currentIndex, int newIndex) throw()
  11458. {
  11459. strings.move (currentIndex, newIndex);
  11460. }
  11461. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11462. {
  11463. const int last = (numberToJoin < 0) ? size()
  11464. : jmin (size(), start + numberToJoin);
  11465. if (start < 0)
  11466. start = 0;
  11467. if (start >= last)
  11468. return String::empty;
  11469. if (start == last - 1)
  11470. return strings.getReference (start);
  11471. const int separatorLen = separator.length();
  11472. int charsNeeded = separatorLen * (last - start - 1);
  11473. for (int i = start; i < last; ++i)
  11474. charsNeeded += strings.getReference(i).length();
  11475. String result;
  11476. result.preallocateStorage (charsNeeded);
  11477. juce_wchar* dest = result;
  11478. while (start < last)
  11479. {
  11480. const String& s = strings.getReference (start);
  11481. const int len = s.length();
  11482. if (len > 0)
  11483. {
  11484. s.copyToUnicode (dest, len);
  11485. dest += len;
  11486. }
  11487. if (++start < last && separatorLen > 0)
  11488. {
  11489. separator.copyToUnicode (dest, separatorLen);
  11490. dest += separatorLen;
  11491. }
  11492. }
  11493. *dest = 0;
  11494. return result;
  11495. }
  11496. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11497. {
  11498. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11499. }
  11500. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11501. {
  11502. int num = 0;
  11503. if (text.isNotEmpty())
  11504. {
  11505. bool insideQuotes = false;
  11506. juce_wchar currentQuoteChar = 0;
  11507. int i = 0;
  11508. int tokenStart = 0;
  11509. for (;;)
  11510. {
  11511. const juce_wchar c = text[i];
  11512. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11513. if (! isBreak)
  11514. {
  11515. if (quoteCharacters.containsChar (c))
  11516. {
  11517. if (insideQuotes)
  11518. {
  11519. // only break out of quotes-mode if we find a matching quote to the
  11520. // one that we opened with..
  11521. if (currentQuoteChar == c)
  11522. insideQuotes = false;
  11523. }
  11524. else
  11525. {
  11526. insideQuotes = true;
  11527. currentQuoteChar = c;
  11528. }
  11529. }
  11530. }
  11531. else
  11532. {
  11533. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11534. ++num;
  11535. tokenStart = i + 1;
  11536. }
  11537. if (c == 0)
  11538. break;
  11539. ++i;
  11540. }
  11541. }
  11542. return num;
  11543. }
  11544. int StringArray::addLines (const String& sourceText)
  11545. {
  11546. int numLines = 0;
  11547. const juce_wchar* text = sourceText;
  11548. while (*text != 0)
  11549. {
  11550. const juce_wchar* const startOfLine = text;
  11551. while (*text != 0)
  11552. {
  11553. if (*text == '\r')
  11554. {
  11555. ++text;
  11556. if (*text == '\n')
  11557. ++text;
  11558. break;
  11559. }
  11560. if (*text == '\n')
  11561. {
  11562. ++text;
  11563. break;
  11564. }
  11565. ++text;
  11566. }
  11567. const juce_wchar* endOfLine = text;
  11568. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11569. --endOfLine;
  11570. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11571. --endOfLine;
  11572. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11573. ++numLines;
  11574. }
  11575. return numLines;
  11576. }
  11577. void StringArray::removeDuplicates (const bool ignoreCase)
  11578. {
  11579. for (int i = 0; i < size() - 1; ++i)
  11580. {
  11581. const String s (strings.getReference(i));
  11582. int nextIndex = i + 1;
  11583. for (;;)
  11584. {
  11585. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11586. if (nextIndex < 0)
  11587. break;
  11588. strings.remove (nextIndex);
  11589. }
  11590. }
  11591. }
  11592. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11593. const bool appendNumberToFirstInstance,
  11594. const juce_wchar* preNumberString,
  11595. const juce_wchar* postNumberString)
  11596. {
  11597. if (preNumberString == 0)
  11598. preNumberString = L" (";
  11599. if (postNumberString == 0)
  11600. postNumberString = L")";
  11601. for (int i = 0; i < size() - 1; ++i)
  11602. {
  11603. String& s = strings.getReference(i);
  11604. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11605. if (nextIndex >= 0)
  11606. {
  11607. const String original (s);
  11608. int number = 0;
  11609. if (appendNumberToFirstInstance)
  11610. s = original + preNumberString + String (++number) + postNumberString;
  11611. else
  11612. ++number;
  11613. while (nextIndex >= 0)
  11614. {
  11615. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11616. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11617. }
  11618. }
  11619. }
  11620. }
  11621. void StringArray::minimiseStorageOverheads()
  11622. {
  11623. strings.minimiseStorageOverheads();
  11624. }
  11625. END_JUCE_NAMESPACE
  11626. /*** End of inlined file: juce_StringArray.cpp ***/
  11627. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11628. BEGIN_JUCE_NAMESPACE
  11629. StringPairArray::StringPairArray (const bool ignoreCase_)
  11630. : ignoreCase (ignoreCase_)
  11631. {
  11632. }
  11633. StringPairArray::StringPairArray (const StringPairArray& other)
  11634. : keys (other.keys),
  11635. values (other.values),
  11636. ignoreCase (other.ignoreCase)
  11637. {
  11638. }
  11639. StringPairArray::~StringPairArray()
  11640. {
  11641. }
  11642. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11643. {
  11644. keys = other.keys;
  11645. values = other.values;
  11646. return *this;
  11647. }
  11648. bool StringPairArray::operator== (const StringPairArray& other) const
  11649. {
  11650. for (int i = keys.size(); --i >= 0;)
  11651. if (other [keys[i]] != values[i])
  11652. return false;
  11653. return true;
  11654. }
  11655. bool StringPairArray::operator!= (const StringPairArray& other) const
  11656. {
  11657. return ! operator== (other);
  11658. }
  11659. const String& StringPairArray::operator[] (const String& key) const
  11660. {
  11661. return values [keys.indexOf (key, ignoreCase)];
  11662. }
  11663. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11664. {
  11665. const int i = keys.indexOf (key, ignoreCase);
  11666. if (i >= 0)
  11667. return values[i];
  11668. return defaultReturnValue;
  11669. }
  11670. void StringPairArray::set (const String& key, const String& value)
  11671. {
  11672. const int i = keys.indexOf (key, ignoreCase);
  11673. if (i >= 0)
  11674. {
  11675. values.set (i, value);
  11676. }
  11677. else
  11678. {
  11679. keys.add (key);
  11680. values.add (value);
  11681. }
  11682. }
  11683. void StringPairArray::addArray (const StringPairArray& other)
  11684. {
  11685. for (int i = 0; i < other.size(); ++i)
  11686. set (other.keys[i], other.values[i]);
  11687. }
  11688. void StringPairArray::clear()
  11689. {
  11690. keys.clear();
  11691. values.clear();
  11692. }
  11693. void StringPairArray::remove (const String& key)
  11694. {
  11695. remove (keys.indexOf (key, ignoreCase));
  11696. }
  11697. void StringPairArray::remove (const int index)
  11698. {
  11699. keys.remove (index);
  11700. values.remove (index);
  11701. }
  11702. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11703. {
  11704. ignoreCase = shouldIgnoreCase;
  11705. }
  11706. const String StringPairArray::getDescription() const
  11707. {
  11708. String s;
  11709. for (int i = 0; i < keys.size(); ++i)
  11710. {
  11711. s << keys[i] << " = " << values[i];
  11712. if (i < keys.size())
  11713. s << ", ";
  11714. }
  11715. return s;
  11716. }
  11717. void StringPairArray::minimiseStorageOverheads()
  11718. {
  11719. keys.minimiseStorageOverheads();
  11720. values.minimiseStorageOverheads();
  11721. }
  11722. END_JUCE_NAMESPACE
  11723. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11724. /*** Start of inlined file: juce_StringPool.cpp ***/
  11725. BEGIN_JUCE_NAMESPACE
  11726. StringPool::StringPool() throw() {}
  11727. StringPool::~StringPool() {}
  11728. namespace StringPoolHelpers
  11729. {
  11730. template <class StringType>
  11731. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11732. {
  11733. int start = 0;
  11734. int end = strings.size();
  11735. for (;;)
  11736. {
  11737. if (start >= end)
  11738. {
  11739. jassert (start <= end);
  11740. strings.insert (start, newString);
  11741. return strings.getReference (start);
  11742. }
  11743. else
  11744. {
  11745. const String& startString = strings.getReference (start);
  11746. if (startString == newString)
  11747. return startString;
  11748. const int halfway = (start + end) >> 1;
  11749. if (halfway == start)
  11750. {
  11751. if (startString.compare (newString) < 0)
  11752. ++start;
  11753. strings.insert (start, newString);
  11754. return strings.getReference (start);
  11755. }
  11756. const int comp = strings.getReference (halfway).compare (newString);
  11757. if (comp == 0)
  11758. return strings.getReference (halfway);
  11759. else if (comp < 0)
  11760. start = halfway;
  11761. else
  11762. end = halfway;
  11763. }
  11764. }
  11765. }
  11766. }
  11767. const juce_wchar* StringPool::getPooledString (const String& s)
  11768. {
  11769. if (s.isEmpty())
  11770. return String::empty;
  11771. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11772. }
  11773. const juce_wchar* StringPool::getPooledString (const char* const s)
  11774. {
  11775. if (s == 0 || *s == 0)
  11776. return String::empty;
  11777. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11778. }
  11779. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11780. {
  11781. if (s == 0 || *s == 0)
  11782. return String::empty;
  11783. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11784. }
  11785. int StringPool::size() const throw()
  11786. {
  11787. return strings.size();
  11788. }
  11789. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11790. {
  11791. return strings [index];
  11792. }
  11793. END_JUCE_NAMESPACE
  11794. /*** End of inlined file: juce_StringPool.cpp ***/
  11795. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11796. BEGIN_JUCE_NAMESPACE
  11797. XmlDocument::XmlDocument (const String& documentText)
  11798. : originalText (documentText),
  11799. ignoreEmptyTextElements (true)
  11800. {
  11801. }
  11802. XmlDocument::XmlDocument (const File& file)
  11803. : ignoreEmptyTextElements (true),
  11804. inputSource (new FileInputSource (file))
  11805. {
  11806. }
  11807. XmlDocument::~XmlDocument()
  11808. {
  11809. }
  11810. XmlElement* XmlDocument::parse (const File& file)
  11811. {
  11812. XmlDocument doc (file);
  11813. return doc.getDocumentElement();
  11814. }
  11815. XmlElement* XmlDocument::parse (const String& xmlData)
  11816. {
  11817. XmlDocument doc (xmlData);
  11818. return doc.getDocumentElement();
  11819. }
  11820. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11821. {
  11822. inputSource = newSource;
  11823. }
  11824. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11825. {
  11826. ignoreEmptyTextElements = shouldBeIgnored;
  11827. }
  11828. namespace XmlIdentifierChars
  11829. {
  11830. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11831. {
  11832. return CharacterFunctions::isLetterOrDigit (c)
  11833. || c == '_' || c == '-' || c == ':' || c == '.';
  11834. }
  11835. bool isIdentifierChar (const juce_wchar c) throw()
  11836. {
  11837. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11838. return (c < numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11839. : isIdentifierCharSlow (c);
  11840. }
  11841. /*static void generateIdentifierCharConstants()
  11842. {
  11843. uint32 n[8];
  11844. zerostruct (n);
  11845. for (int i = 0; i < 256; ++i)
  11846. if (isIdentifierCharSlow (i))
  11847. n[i >> 5] |= (1 << (i & 31));
  11848. String s;
  11849. for (int i = 0; i < 8; ++i)
  11850. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11851. DBG (s);
  11852. }*/
  11853. }
  11854. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11855. {
  11856. String textToParse (originalText);
  11857. if (textToParse.isEmpty() && inputSource != 0)
  11858. {
  11859. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11860. if (in != 0)
  11861. {
  11862. MemoryOutputStream data;
  11863. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11864. textToParse = data.toString();
  11865. if (! onlyReadOuterDocumentElement)
  11866. originalText = textToParse;
  11867. }
  11868. }
  11869. input = textToParse;
  11870. lastError = String::empty;
  11871. errorOccurred = false;
  11872. outOfData = false;
  11873. needToLoadDTD = true;
  11874. if (textToParse.isEmpty())
  11875. {
  11876. lastError = "not enough input";
  11877. }
  11878. else
  11879. {
  11880. skipHeader();
  11881. if (input != 0)
  11882. {
  11883. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11884. if (! errorOccurred)
  11885. return result.release();
  11886. }
  11887. else
  11888. {
  11889. lastError = "incorrect xml header";
  11890. }
  11891. }
  11892. return 0;
  11893. }
  11894. const String& XmlDocument::getLastParseError() const throw()
  11895. {
  11896. return lastError;
  11897. }
  11898. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11899. {
  11900. lastError = desc;
  11901. errorOccurred = ! carryOn;
  11902. }
  11903. const String XmlDocument::getFileContents (const String& filename) const
  11904. {
  11905. if (inputSource != 0)
  11906. {
  11907. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11908. if (in != 0)
  11909. return in->readEntireStreamAsString();
  11910. }
  11911. return String::empty;
  11912. }
  11913. juce_wchar XmlDocument::readNextChar() throw()
  11914. {
  11915. if (*input != 0)
  11916. return *input++;
  11917. outOfData = true;
  11918. return 0;
  11919. }
  11920. int XmlDocument::findNextTokenLength() throw()
  11921. {
  11922. int len = 0;
  11923. juce_wchar c = *input;
  11924. while (XmlIdentifierChars::isIdentifierChar (c))
  11925. c = input [++len];
  11926. return len;
  11927. }
  11928. void XmlDocument::skipHeader()
  11929. {
  11930. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11931. if (found != 0)
  11932. {
  11933. input = found;
  11934. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11935. if (input == 0)
  11936. return;
  11937. #if JUCE_DEBUG
  11938. const String header (found, input - found);
  11939. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11940. .fromFirstOccurrenceOf ("=", false, false)
  11941. .fromFirstOccurrenceOf ("\"", false, false)
  11942. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11943. /* If you load an XML document with a non-UTF encoding type, it may have been
  11944. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11945. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11946. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11947. read, use your own code to convert them to a unicode String, and pass that to the
  11948. XML parser.
  11949. */
  11950. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11951. #endif
  11952. input += 2;
  11953. }
  11954. skipNextWhiteSpace();
  11955. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11956. if (docType == 0)
  11957. return;
  11958. input = docType + 9;
  11959. int n = 1;
  11960. while (n > 0)
  11961. {
  11962. const juce_wchar c = readNextChar();
  11963. if (outOfData)
  11964. return;
  11965. if (c == '<')
  11966. ++n;
  11967. else if (c == '>')
  11968. --n;
  11969. }
  11970. docType += 9;
  11971. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11972. }
  11973. void XmlDocument::skipNextWhiteSpace()
  11974. {
  11975. for (;;)
  11976. {
  11977. juce_wchar c = *input;
  11978. while (CharacterFunctions::isWhitespace (c))
  11979. c = *++input;
  11980. if (c == 0)
  11981. {
  11982. outOfData = true;
  11983. break;
  11984. }
  11985. else if (c == '<')
  11986. {
  11987. if (input[1] == '!'
  11988. && input[2] == '-'
  11989. && input[3] == '-')
  11990. {
  11991. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  11992. if (closeComment == 0)
  11993. {
  11994. outOfData = true;
  11995. break;
  11996. }
  11997. input = closeComment + 3;
  11998. continue;
  11999. }
  12000. else if (input[1] == '?')
  12001. {
  12002. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12003. if (closeBracket == 0)
  12004. {
  12005. outOfData = true;
  12006. break;
  12007. }
  12008. input = closeBracket + 2;
  12009. continue;
  12010. }
  12011. }
  12012. break;
  12013. }
  12014. }
  12015. void XmlDocument::readQuotedString (String& result)
  12016. {
  12017. const juce_wchar quote = readNextChar();
  12018. while (! outOfData)
  12019. {
  12020. const juce_wchar c = readNextChar();
  12021. if (c == quote)
  12022. break;
  12023. if (c == '&')
  12024. {
  12025. --input;
  12026. readEntity (result);
  12027. }
  12028. else
  12029. {
  12030. --input;
  12031. const juce_wchar* const start = input;
  12032. for (;;)
  12033. {
  12034. const juce_wchar character = *input;
  12035. if (character == quote)
  12036. {
  12037. result.append (start, (int) (input - start));
  12038. ++input;
  12039. return;
  12040. }
  12041. else if (character == '&')
  12042. {
  12043. result.append (start, (int) (input - start));
  12044. break;
  12045. }
  12046. else if (character == 0)
  12047. {
  12048. outOfData = true;
  12049. setLastError ("unmatched quotes", false);
  12050. break;
  12051. }
  12052. ++input;
  12053. }
  12054. }
  12055. }
  12056. }
  12057. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12058. {
  12059. XmlElement* node = 0;
  12060. skipNextWhiteSpace();
  12061. if (outOfData)
  12062. return 0;
  12063. input = CharacterFunctions::find (input, JUCE_T("<"));
  12064. if (input != 0)
  12065. {
  12066. ++input;
  12067. int tagLen = findNextTokenLength();
  12068. if (tagLen == 0)
  12069. {
  12070. // no tag name - but allow for a gap after the '<' before giving an error
  12071. skipNextWhiteSpace();
  12072. tagLen = findNextTokenLength();
  12073. if (tagLen == 0)
  12074. {
  12075. setLastError ("tag name missing", false);
  12076. return node;
  12077. }
  12078. }
  12079. node = new XmlElement (String (input, tagLen));
  12080. input += tagLen;
  12081. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12082. // look for attributes
  12083. for (;;)
  12084. {
  12085. skipNextWhiteSpace();
  12086. const juce_wchar c = *input;
  12087. // empty tag..
  12088. if (c == '/' && input[1] == '>')
  12089. {
  12090. input += 2;
  12091. break;
  12092. }
  12093. // parse the guts of the element..
  12094. if (c == '>')
  12095. {
  12096. ++input;
  12097. if (alsoParseSubElements)
  12098. readChildElements (node);
  12099. break;
  12100. }
  12101. // get an attribute..
  12102. if (XmlIdentifierChars::isIdentifierChar (c))
  12103. {
  12104. const int attNameLen = findNextTokenLength();
  12105. if (attNameLen > 0)
  12106. {
  12107. const juce_wchar* attNameStart = input;
  12108. input += attNameLen;
  12109. skipNextWhiteSpace();
  12110. if (readNextChar() == '=')
  12111. {
  12112. skipNextWhiteSpace();
  12113. const juce_wchar nextChar = *input;
  12114. if (nextChar == '"' || nextChar == '\'')
  12115. {
  12116. XmlElement::XmlAttributeNode* const newAtt
  12117. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12118. String::empty);
  12119. readQuotedString (newAtt->value);
  12120. if (lastAttribute == 0)
  12121. node->attributes = newAtt;
  12122. else
  12123. lastAttribute->next = newAtt;
  12124. lastAttribute = newAtt;
  12125. continue;
  12126. }
  12127. }
  12128. }
  12129. }
  12130. else
  12131. {
  12132. if (! outOfData)
  12133. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12134. }
  12135. break;
  12136. }
  12137. }
  12138. return node;
  12139. }
  12140. void XmlDocument::readChildElements (XmlElement* parent)
  12141. {
  12142. XmlElement* lastChildNode = 0;
  12143. for (;;)
  12144. {
  12145. const juce_wchar* const preWhitespaceInput = input;
  12146. skipNextWhiteSpace();
  12147. if (outOfData)
  12148. {
  12149. setLastError ("unmatched tags", false);
  12150. break;
  12151. }
  12152. if (*input == '<')
  12153. {
  12154. if (input[1] == '/')
  12155. {
  12156. // our close tag..
  12157. input = CharacterFunctions::find (input, JUCE_T(">"));
  12158. ++input;
  12159. break;
  12160. }
  12161. else if (input[1] == '!'
  12162. && input[2] == '['
  12163. && input[3] == 'C'
  12164. && input[4] == 'D'
  12165. && input[5] == 'A'
  12166. && input[6] == 'T'
  12167. && input[7] == 'A'
  12168. && input[8] == '[')
  12169. {
  12170. input += 9;
  12171. const juce_wchar* const inputStart = input;
  12172. int len = 0;
  12173. for (;;)
  12174. {
  12175. if (*input == 0)
  12176. {
  12177. setLastError ("unterminated CDATA section", false);
  12178. outOfData = true;
  12179. break;
  12180. }
  12181. else if (input[0] == ']'
  12182. && input[1] == ']'
  12183. && input[2] == '>')
  12184. {
  12185. input += 3;
  12186. break;
  12187. }
  12188. ++input;
  12189. ++len;
  12190. }
  12191. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12192. if (lastChildNode != 0)
  12193. lastChildNode->nextElement = e;
  12194. else
  12195. parent->addChildElement (e);
  12196. lastChildNode = e;
  12197. }
  12198. else
  12199. {
  12200. // this is some other element, so parse and add it..
  12201. XmlElement* const n = readNextElement (true);
  12202. if (n != 0)
  12203. {
  12204. if (lastChildNode == 0)
  12205. parent->addChildElement (n);
  12206. else
  12207. lastChildNode->nextElement = n;
  12208. lastChildNode = n;
  12209. }
  12210. else
  12211. {
  12212. return;
  12213. }
  12214. }
  12215. }
  12216. else // must be a character block
  12217. {
  12218. input = preWhitespaceInput; // roll back to include the leading whitespace
  12219. String textElementContent;
  12220. for (;;)
  12221. {
  12222. const juce_wchar c = *input;
  12223. if (c == '<')
  12224. break;
  12225. if (c == 0)
  12226. {
  12227. setLastError ("unmatched tags", false);
  12228. outOfData = true;
  12229. return;
  12230. }
  12231. if (c == '&')
  12232. {
  12233. String entity;
  12234. readEntity (entity);
  12235. if (entity.startsWithChar ('<') && entity [1] != 0)
  12236. {
  12237. const juce_wchar* const oldInput = input;
  12238. const bool oldOutOfData = outOfData;
  12239. input = entity;
  12240. outOfData = false;
  12241. for (;;)
  12242. {
  12243. XmlElement* const n = readNextElement (true);
  12244. if (n == 0)
  12245. break;
  12246. if (lastChildNode == 0)
  12247. parent->addChildElement (n);
  12248. else
  12249. lastChildNode->nextElement = n;
  12250. lastChildNode = n;
  12251. }
  12252. input = oldInput;
  12253. outOfData = oldOutOfData;
  12254. }
  12255. else
  12256. {
  12257. textElementContent += entity;
  12258. }
  12259. }
  12260. else
  12261. {
  12262. const juce_wchar* start = input;
  12263. int len = 0;
  12264. for (;;)
  12265. {
  12266. const juce_wchar nextChar = *input;
  12267. if (nextChar == '<' || nextChar == '&')
  12268. {
  12269. break;
  12270. }
  12271. else if (nextChar == 0)
  12272. {
  12273. setLastError ("unmatched tags", false);
  12274. outOfData = true;
  12275. return;
  12276. }
  12277. ++input;
  12278. ++len;
  12279. }
  12280. textElementContent.append (start, len);
  12281. }
  12282. }
  12283. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12284. {
  12285. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12286. if (lastChildNode != 0)
  12287. lastChildNode->nextElement = textElement;
  12288. else
  12289. parent->addChildElement (textElement);
  12290. lastChildNode = textElement;
  12291. }
  12292. }
  12293. }
  12294. }
  12295. void XmlDocument::readEntity (String& result)
  12296. {
  12297. // skip over the ampersand
  12298. ++input;
  12299. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12300. {
  12301. input += 4;
  12302. result += '&';
  12303. }
  12304. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12305. {
  12306. input += 5;
  12307. result += '"';
  12308. }
  12309. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12310. {
  12311. input += 5;
  12312. result += '\'';
  12313. }
  12314. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12315. {
  12316. input += 3;
  12317. result += '<';
  12318. }
  12319. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12320. {
  12321. input += 3;
  12322. result += '>';
  12323. }
  12324. else if (*input == '#')
  12325. {
  12326. int charCode = 0;
  12327. ++input;
  12328. if (*input == 'x' || *input == 'X')
  12329. {
  12330. ++input;
  12331. int numChars = 0;
  12332. while (input[0] != ';')
  12333. {
  12334. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12335. if (hexValue < 0 || ++numChars > 8)
  12336. {
  12337. setLastError ("illegal escape sequence", true);
  12338. break;
  12339. }
  12340. charCode = (charCode << 4) | hexValue;
  12341. ++input;
  12342. }
  12343. ++input;
  12344. }
  12345. else if (input[0] >= '0' && input[0] <= '9')
  12346. {
  12347. int numChars = 0;
  12348. while (input[0] != ';')
  12349. {
  12350. if (++numChars > 12)
  12351. {
  12352. setLastError ("illegal escape sequence", true);
  12353. break;
  12354. }
  12355. charCode = charCode * 10 + (input[0] - '0');
  12356. ++input;
  12357. }
  12358. ++input;
  12359. }
  12360. else
  12361. {
  12362. setLastError ("illegal escape sequence", true);
  12363. result += '&';
  12364. return;
  12365. }
  12366. result << (juce_wchar) charCode;
  12367. }
  12368. else
  12369. {
  12370. const juce_wchar* const entityNameStart = input;
  12371. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12372. if (closingSemiColon == 0)
  12373. {
  12374. outOfData = true;
  12375. result += '&';
  12376. }
  12377. else
  12378. {
  12379. input = closingSemiColon + 1;
  12380. result += expandExternalEntity (String (entityNameStart,
  12381. (int) (closingSemiColon - entityNameStart)));
  12382. }
  12383. }
  12384. }
  12385. const String XmlDocument::expandEntity (const String& ent)
  12386. {
  12387. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12388. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12389. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12390. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12391. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12392. if (ent[0] == '#')
  12393. {
  12394. if (ent[1] == 'x' || ent[1] == 'X')
  12395. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12396. if (ent[1] >= '0' && ent[1] <= '9')
  12397. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12398. setLastError ("illegal escape sequence", false);
  12399. return String::charToString ('&');
  12400. }
  12401. return expandExternalEntity (ent);
  12402. }
  12403. const String XmlDocument::expandExternalEntity (const String& entity)
  12404. {
  12405. if (needToLoadDTD)
  12406. {
  12407. if (dtdText.isNotEmpty())
  12408. {
  12409. dtdText = dtdText.trimCharactersAtEnd (">");
  12410. tokenisedDTD.addTokens (dtdText, true);
  12411. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12412. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12413. {
  12414. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12415. tokenisedDTD.clear();
  12416. tokenisedDTD.addTokens (getFileContents (fn), true);
  12417. }
  12418. else
  12419. {
  12420. tokenisedDTD.clear();
  12421. const int openBracket = dtdText.indexOfChar ('[');
  12422. if (openBracket > 0)
  12423. {
  12424. const int closeBracket = dtdText.lastIndexOfChar (']');
  12425. if (closeBracket > openBracket)
  12426. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12427. closeBracket), true);
  12428. }
  12429. }
  12430. for (int i = tokenisedDTD.size(); --i >= 0;)
  12431. {
  12432. if (tokenisedDTD[i].startsWithChar ('%')
  12433. && tokenisedDTD[i].endsWithChar (';'))
  12434. {
  12435. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12436. StringArray newToks;
  12437. newToks.addTokens (parsed, true);
  12438. tokenisedDTD.remove (i);
  12439. for (int j = newToks.size(); --j >= 0;)
  12440. tokenisedDTD.insert (i, newToks[j]);
  12441. }
  12442. }
  12443. }
  12444. needToLoadDTD = false;
  12445. }
  12446. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12447. {
  12448. if (tokenisedDTD[i] == entity)
  12449. {
  12450. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12451. {
  12452. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12453. // check for sub-entities..
  12454. int ampersand = ent.indexOfChar ('&');
  12455. while (ampersand >= 0)
  12456. {
  12457. const int semiColon = ent.indexOf (i + 1, ";");
  12458. if (semiColon < 0)
  12459. {
  12460. setLastError ("entity without terminating semi-colon", false);
  12461. break;
  12462. }
  12463. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12464. ent = ent.substring (0, ampersand)
  12465. + resolved
  12466. + ent.substring (semiColon + 1);
  12467. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12468. }
  12469. return ent;
  12470. }
  12471. }
  12472. }
  12473. setLastError ("unknown entity", true);
  12474. return entity;
  12475. }
  12476. const String XmlDocument::getParameterEntity (const String& entity)
  12477. {
  12478. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12479. {
  12480. if (tokenisedDTD[i] == entity)
  12481. {
  12482. if (tokenisedDTD [i - 1] == "%"
  12483. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12484. {
  12485. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12486. if (ent.equalsIgnoreCase ("system"))
  12487. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12488. else
  12489. return ent.trim().unquoted();
  12490. }
  12491. }
  12492. }
  12493. return entity;
  12494. }
  12495. END_JUCE_NAMESPACE
  12496. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12497. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12498. BEGIN_JUCE_NAMESPACE
  12499. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12500. : name (other.name),
  12501. value (other.value),
  12502. next (0)
  12503. {
  12504. }
  12505. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12506. : name (name_),
  12507. value (value_),
  12508. next (0)
  12509. {
  12510. #if JUCE_DEBUG
  12511. // this checks whether the attribute name string contains any illegals characters..
  12512. for (const juce_wchar* t = name; *t != 0; ++t)
  12513. jassert (CharacterFunctions::isLetterOrDigit (*t) || *t == '_' || *t == '-' || *t == ':');
  12514. #endif
  12515. }
  12516. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12517. {
  12518. return name.equalsIgnoreCase (nameToMatch);
  12519. }
  12520. XmlElement::XmlElement (const String& tagName_) throw()
  12521. : tagName (tagName_),
  12522. firstChildElement (0),
  12523. nextElement (0),
  12524. attributes (0)
  12525. {
  12526. // the tag name mustn't be empty, or it'll look like a text element!
  12527. jassert (tagName_.containsNonWhitespaceChars())
  12528. // The tag can't contain spaces or other characters that would create invalid XML!
  12529. jassert (! tagName_.containsAnyOf (" <>/&"));
  12530. }
  12531. XmlElement::XmlElement (int /*dummy*/) throw()
  12532. : firstChildElement (0),
  12533. nextElement (0),
  12534. attributes (0)
  12535. {
  12536. }
  12537. XmlElement::XmlElement (const XmlElement& other)
  12538. : tagName (other.tagName),
  12539. firstChildElement (0),
  12540. nextElement (0),
  12541. attributes (0)
  12542. {
  12543. copyChildrenAndAttributesFrom (other);
  12544. }
  12545. XmlElement& XmlElement::operator= (const XmlElement& other)
  12546. {
  12547. if (this != &other)
  12548. {
  12549. removeAllAttributes();
  12550. deleteAllChildElements();
  12551. tagName = other.tagName;
  12552. copyChildrenAndAttributesFrom (other);
  12553. }
  12554. return *this;
  12555. }
  12556. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12557. {
  12558. XmlElement* child = other.firstChildElement;
  12559. XmlElement* lastChild = 0;
  12560. while (child != 0)
  12561. {
  12562. XmlElement* const copiedChild = new XmlElement (*child);
  12563. if (lastChild != 0)
  12564. lastChild->nextElement = copiedChild;
  12565. else
  12566. firstChildElement = copiedChild;
  12567. lastChild = copiedChild;
  12568. child = child->nextElement;
  12569. }
  12570. const XmlAttributeNode* att = other.attributes;
  12571. XmlAttributeNode* lastAtt = 0;
  12572. while (att != 0)
  12573. {
  12574. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12575. if (lastAtt != 0)
  12576. lastAtt->next = newAtt;
  12577. else
  12578. attributes = newAtt;
  12579. lastAtt = newAtt;
  12580. att = att->next;
  12581. }
  12582. }
  12583. XmlElement::~XmlElement() throw()
  12584. {
  12585. XmlElement* child = firstChildElement;
  12586. while (child != 0)
  12587. {
  12588. XmlElement* const nextChild = child->nextElement;
  12589. delete child;
  12590. child = nextChild;
  12591. }
  12592. XmlAttributeNode* att = attributes;
  12593. while (att != 0)
  12594. {
  12595. XmlAttributeNode* const nextAtt = att->next;
  12596. delete att;
  12597. att = nextAtt;
  12598. }
  12599. }
  12600. namespace XmlOutputFunctions
  12601. {
  12602. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12603. {
  12604. if ((character >= 'a' && character <= 'z')
  12605. || (character >= 'A' && character <= 'Z')
  12606. || (character >= '0' && character <= '9'))
  12607. return true;
  12608. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12609. do
  12610. {
  12611. if (((juce_wchar) (uint8) *t) == character)
  12612. return true;
  12613. }
  12614. while (*++t != 0);
  12615. return false;
  12616. }
  12617. void generateLegalCharConstants()
  12618. {
  12619. uint8 n[32];
  12620. zerostruct (n);
  12621. for (int i = 0; i < 256; ++i)
  12622. if (isLegalXmlCharSlow (i))
  12623. n[i >> 3] |= (1 << (i & 7));
  12624. String s;
  12625. for (int i = 0; i < 32; ++i)
  12626. s << (int) n[i] << ", ";
  12627. DBG (s);
  12628. }*/
  12629. bool isLegalXmlChar (const uint32 c) throw()
  12630. {
  12631. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12632. return c < sizeof (legalChars) * 8
  12633. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12634. }
  12635. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12636. {
  12637. const juce_wchar* t = text;
  12638. for (;;)
  12639. {
  12640. const juce_wchar character = *t++;
  12641. if (character == 0)
  12642. break;
  12643. if (isLegalXmlChar ((uint32) character))
  12644. {
  12645. outputStream << (char) character;
  12646. }
  12647. else
  12648. {
  12649. switch (character)
  12650. {
  12651. case '&': outputStream << "&amp;"; break;
  12652. case '"': outputStream << "&quot;"; break;
  12653. case '>': outputStream << "&gt;"; break;
  12654. case '<': outputStream << "&lt;"; break;
  12655. case '\n':
  12656. case '\r':
  12657. if (! changeNewLines)
  12658. {
  12659. outputStream << (char) character;
  12660. break;
  12661. }
  12662. // Note: deliberate fall-through here!
  12663. default:
  12664. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12665. break;
  12666. }
  12667. }
  12668. }
  12669. }
  12670. void writeSpaces (OutputStream& out, int numSpaces)
  12671. {
  12672. if (numSpaces > 0)
  12673. {
  12674. const char blanks[] = " ";
  12675. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12676. while (numSpaces > blankSize)
  12677. {
  12678. out.write (blanks, blankSize);
  12679. numSpaces -= blankSize;
  12680. }
  12681. out.write (blanks, numSpaces);
  12682. }
  12683. }
  12684. }
  12685. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12686. const int indentationLevel,
  12687. const int lineWrapLength) const
  12688. {
  12689. using namespace XmlOutputFunctions;
  12690. writeSpaces (outputStream, indentationLevel);
  12691. if (! isTextElement())
  12692. {
  12693. outputStream.writeByte ('<');
  12694. outputStream << tagName;
  12695. {
  12696. const int attIndent = indentationLevel + tagName.length() + 1;
  12697. int lineLen = 0;
  12698. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12699. {
  12700. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12701. {
  12702. outputStream << newLine;
  12703. writeSpaces (outputStream, attIndent);
  12704. lineLen = 0;
  12705. }
  12706. const int64 startPos = outputStream.getPosition();
  12707. outputStream.writeByte (' ');
  12708. outputStream << att->name;
  12709. outputStream.write ("=\"", 2);
  12710. escapeIllegalXmlChars (outputStream, att->value, true);
  12711. outputStream.writeByte ('"');
  12712. lineLen += (int) (outputStream.getPosition() - startPos);
  12713. }
  12714. }
  12715. if (firstChildElement != 0)
  12716. {
  12717. outputStream.writeByte ('>');
  12718. XmlElement* child = firstChildElement;
  12719. bool lastWasTextNode = false;
  12720. while (child != 0)
  12721. {
  12722. if (child->isTextElement())
  12723. {
  12724. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12725. lastWasTextNode = true;
  12726. }
  12727. else
  12728. {
  12729. if (indentationLevel >= 0 && ! lastWasTextNode)
  12730. outputStream << newLine;
  12731. child->writeElementAsText (outputStream,
  12732. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12733. lastWasTextNode = false;
  12734. }
  12735. child = child->nextElement;
  12736. }
  12737. if (indentationLevel >= 0 && ! lastWasTextNode)
  12738. {
  12739. outputStream << newLine;
  12740. writeSpaces (outputStream, indentationLevel);
  12741. }
  12742. outputStream.write ("</", 2);
  12743. outputStream << tagName;
  12744. outputStream.writeByte ('>');
  12745. }
  12746. else
  12747. {
  12748. outputStream.write ("/>", 2);
  12749. }
  12750. }
  12751. else
  12752. {
  12753. escapeIllegalXmlChars (outputStream, getText(), false);
  12754. }
  12755. }
  12756. const String XmlElement::createDocument (const String& dtdToUse,
  12757. const bool allOnOneLine,
  12758. const bool includeXmlHeader,
  12759. const String& encodingType,
  12760. const int lineWrapLength) const
  12761. {
  12762. MemoryOutputStream mem (2048);
  12763. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12764. return mem.toUTF8();
  12765. }
  12766. void XmlElement::writeToStream (OutputStream& output,
  12767. const String& dtdToUse,
  12768. const bool allOnOneLine,
  12769. const bool includeXmlHeader,
  12770. const String& encodingType,
  12771. const int lineWrapLength) const
  12772. {
  12773. using namespace XmlOutputFunctions;
  12774. if (includeXmlHeader)
  12775. {
  12776. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12777. if (allOnOneLine)
  12778. output.writeByte (' ');
  12779. else
  12780. output << newLine << newLine;
  12781. }
  12782. if (dtdToUse.isNotEmpty())
  12783. {
  12784. output << dtdToUse;
  12785. if (allOnOneLine)
  12786. output.writeByte (' ');
  12787. else
  12788. output << newLine;
  12789. }
  12790. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12791. if (! allOnOneLine)
  12792. output << newLine;
  12793. }
  12794. bool XmlElement::writeToFile (const File& file,
  12795. const String& dtdToUse,
  12796. const String& encodingType,
  12797. const int lineWrapLength) const
  12798. {
  12799. if (file.hasWriteAccess())
  12800. {
  12801. TemporaryFile tempFile (file);
  12802. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12803. if (out != 0)
  12804. {
  12805. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12806. out = 0;
  12807. return tempFile.overwriteTargetFileWithTemporary();
  12808. }
  12809. }
  12810. return false;
  12811. }
  12812. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12813. {
  12814. #if JUCE_DEBUG
  12815. // if debugging, check that the case is actually the same, because
  12816. // valid xml is case-sensitive, and although this lets it pass, it's
  12817. // better not to..
  12818. if (tagName.equalsIgnoreCase (tagNameWanted))
  12819. {
  12820. jassert (tagName == tagNameWanted);
  12821. return true;
  12822. }
  12823. else
  12824. {
  12825. return false;
  12826. }
  12827. #else
  12828. return tagName.equalsIgnoreCase (tagNameWanted);
  12829. #endif
  12830. }
  12831. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12832. {
  12833. XmlElement* e = nextElement;
  12834. while (e != 0 && ! e->hasTagName (requiredTagName))
  12835. e = e->nextElement;
  12836. return e;
  12837. }
  12838. int XmlElement::getNumAttributes() const throw()
  12839. {
  12840. int count = 0;
  12841. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12842. ++count;
  12843. return count;
  12844. }
  12845. const String& XmlElement::getAttributeName (const int index) const throw()
  12846. {
  12847. int count = 0;
  12848. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12849. {
  12850. if (count == index)
  12851. return att->name;
  12852. ++count;
  12853. }
  12854. return String::empty;
  12855. }
  12856. const String& XmlElement::getAttributeValue (const int index) const throw()
  12857. {
  12858. int count = 0;
  12859. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12860. {
  12861. if (count == index)
  12862. return att->value;
  12863. ++count;
  12864. }
  12865. return String::empty;
  12866. }
  12867. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12868. {
  12869. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12870. if (att->hasName (attributeName))
  12871. return true;
  12872. return false;
  12873. }
  12874. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12875. {
  12876. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12877. if (att->hasName (attributeName))
  12878. return att->value;
  12879. return String::empty;
  12880. }
  12881. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12882. {
  12883. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12884. if (att->hasName (attributeName))
  12885. return att->value;
  12886. return defaultReturnValue;
  12887. }
  12888. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12889. {
  12890. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12891. if (att->hasName (attributeName))
  12892. return att->value.getIntValue();
  12893. return defaultReturnValue;
  12894. }
  12895. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12896. {
  12897. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12898. if (att->hasName (attributeName))
  12899. return att->value.getDoubleValue();
  12900. return defaultReturnValue;
  12901. }
  12902. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12903. {
  12904. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12905. {
  12906. if (att->hasName (attributeName))
  12907. {
  12908. juce_wchar firstChar = att->value[0];
  12909. if (CharacterFunctions::isWhitespace (firstChar))
  12910. firstChar = att->value.trimStart() [0];
  12911. return firstChar == '1'
  12912. || firstChar == 't'
  12913. || firstChar == 'y'
  12914. || firstChar == 'T'
  12915. || firstChar == 'Y';
  12916. }
  12917. }
  12918. return defaultReturnValue;
  12919. }
  12920. bool XmlElement::compareAttribute (const String& attributeName,
  12921. const String& stringToCompareAgainst,
  12922. const bool ignoreCase) const throw()
  12923. {
  12924. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12925. if (att->hasName (attributeName))
  12926. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12927. : att->value == stringToCompareAgainst;
  12928. return false;
  12929. }
  12930. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12931. {
  12932. if (attributes == 0)
  12933. {
  12934. attributes = new XmlAttributeNode (attributeName, value);
  12935. }
  12936. else
  12937. {
  12938. XmlAttributeNode* att = attributes;
  12939. for (;;)
  12940. {
  12941. if (att->hasName (attributeName))
  12942. {
  12943. att->value = value;
  12944. break;
  12945. }
  12946. else if (att->next == 0)
  12947. {
  12948. att->next = new XmlAttributeNode (attributeName, value);
  12949. break;
  12950. }
  12951. att = att->next;
  12952. }
  12953. }
  12954. }
  12955. void XmlElement::setAttribute (const String& attributeName, const int number)
  12956. {
  12957. setAttribute (attributeName, String (number));
  12958. }
  12959. void XmlElement::setAttribute (const String& attributeName, const double number)
  12960. {
  12961. setAttribute (attributeName, String (number));
  12962. }
  12963. void XmlElement::removeAttribute (const String& attributeName) throw()
  12964. {
  12965. XmlAttributeNode* lastAtt = 0;
  12966. for (XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12967. {
  12968. if (att->hasName (attributeName))
  12969. {
  12970. if (lastAtt == 0)
  12971. attributes = att->next;
  12972. else
  12973. lastAtt->next = att->next;
  12974. delete att;
  12975. break;
  12976. }
  12977. lastAtt = att;
  12978. }
  12979. }
  12980. void XmlElement::removeAllAttributes() throw()
  12981. {
  12982. while (attributes != 0)
  12983. {
  12984. XmlAttributeNode* const nextAtt = attributes->next;
  12985. delete attributes;
  12986. attributes = nextAtt;
  12987. }
  12988. }
  12989. int XmlElement::getNumChildElements() const throw()
  12990. {
  12991. int count = 0;
  12992. const XmlElement* child = firstChildElement;
  12993. while (child != 0)
  12994. {
  12995. ++count;
  12996. child = child->nextElement;
  12997. }
  12998. return count;
  12999. }
  13000. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13001. {
  13002. int count = 0;
  13003. XmlElement* child = firstChildElement;
  13004. while (child != 0 && count < index)
  13005. {
  13006. child = child->nextElement;
  13007. ++count;
  13008. }
  13009. return child;
  13010. }
  13011. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13012. {
  13013. XmlElement* child = firstChildElement;
  13014. while (child != 0)
  13015. {
  13016. if (child->hasTagName (childName))
  13017. break;
  13018. child = child->nextElement;
  13019. }
  13020. return child;
  13021. }
  13022. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13023. {
  13024. if (newNode != 0)
  13025. {
  13026. if (firstChildElement == 0)
  13027. {
  13028. firstChildElement = newNode;
  13029. }
  13030. else
  13031. {
  13032. XmlElement* child = firstChildElement;
  13033. while (child->nextElement != 0)
  13034. child = child->nextElement;
  13035. child->nextElement = newNode;
  13036. // if this is non-zero, then something's probably
  13037. // gone wrong..
  13038. jassert (newNode->nextElement == 0);
  13039. }
  13040. }
  13041. }
  13042. void XmlElement::insertChildElement (XmlElement* const newNode,
  13043. int indexToInsertAt) throw()
  13044. {
  13045. if (newNode != 0)
  13046. {
  13047. removeChildElement (newNode, false);
  13048. if (indexToInsertAt == 0)
  13049. {
  13050. newNode->nextElement = firstChildElement;
  13051. firstChildElement = newNode;
  13052. }
  13053. else
  13054. {
  13055. if (firstChildElement == 0)
  13056. {
  13057. firstChildElement = newNode;
  13058. }
  13059. else
  13060. {
  13061. if (indexToInsertAt < 0)
  13062. indexToInsertAt = std::numeric_limits<int>::max();
  13063. XmlElement* child = firstChildElement;
  13064. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13065. child = child->nextElement;
  13066. newNode->nextElement = child->nextElement;
  13067. child->nextElement = newNode;
  13068. }
  13069. }
  13070. }
  13071. }
  13072. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13073. {
  13074. XmlElement* const newElement = new XmlElement (childTagName);
  13075. addChildElement (newElement);
  13076. return newElement;
  13077. }
  13078. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13079. XmlElement* const newNode) throw()
  13080. {
  13081. if (newNode != 0)
  13082. {
  13083. XmlElement* child = firstChildElement;
  13084. XmlElement* previousNode = 0;
  13085. while (child != 0)
  13086. {
  13087. if (child == currentChildElement)
  13088. {
  13089. if (child != newNode)
  13090. {
  13091. if (previousNode == 0)
  13092. firstChildElement = newNode;
  13093. else
  13094. previousNode->nextElement = newNode;
  13095. newNode->nextElement = child->nextElement;
  13096. delete child;
  13097. }
  13098. return true;
  13099. }
  13100. previousNode = child;
  13101. child = child->nextElement;
  13102. }
  13103. }
  13104. return false;
  13105. }
  13106. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13107. const bool shouldDeleteTheChild) throw()
  13108. {
  13109. if (childToRemove != 0)
  13110. {
  13111. if (firstChildElement == childToRemove)
  13112. {
  13113. firstChildElement = childToRemove->nextElement;
  13114. childToRemove->nextElement = 0;
  13115. }
  13116. else
  13117. {
  13118. XmlElement* child = firstChildElement;
  13119. XmlElement* last = 0;
  13120. while (child != 0)
  13121. {
  13122. if (child == childToRemove)
  13123. {
  13124. if (last == 0)
  13125. firstChildElement = child->nextElement;
  13126. else
  13127. last->nextElement = child->nextElement;
  13128. childToRemove->nextElement = 0;
  13129. break;
  13130. }
  13131. last = child;
  13132. child = child->nextElement;
  13133. }
  13134. }
  13135. if (shouldDeleteTheChild)
  13136. delete childToRemove;
  13137. }
  13138. }
  13139. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13140. const bool ignoreOrderOfAttributes) const throw()
  13141. {
  13142. if (this != other)
  13143. {
  13144. if (other == 0 || tagName != other->tagName)
  13145. return false;
  13146. if (ignoreOrderOfAttributes)
  13147. {
  13148. int totalAtts = 0;
  13149. const XmlAttributeNode* att = attributes;
  13150. while (att != 0)
  13151. {
  13152. if (! other->compareAttribute (att->name, att->value))
  13153. return false;
  13154. att = att->next;
  13155. ++totalAtts;
  13156. }
  13157. if (totalAtts != other->getNumAttributes())
  13158. return false;
  13159. }
  13160. else
  13161. {
  13162. const XmlAttributeNode* thisAtt = attributes;
  13163. const XmlAttributeNode* otherAtt = other->attributes;
  13164. for (;;)
  13165. {
  13166. if (thisAtt == 0 || otherAtt == 0)
  13167. {
  13168. if (thisAtt == otherAtt) // both 0, so it's a match
  13169. break;
  13170. return false;
  13171. }
  13172. if (thisAtt->name != otherAtt->name
  13173. || thisAtt->value != otherAtt->value)
  13174. {
  13175. return false;
  13176. }
  13177. thisAtt = thisAtt->next;
  13178. otherAtt = otherAtt->next;
  13179. }
  13180. }
  13181. const XmlElement* thisChild = firstChildElement;
  13182. const XmlElement* otherChild = other->firstChildElement;
  13183. for (;;)
  13184. {
  13185. if (thisChild == 0 || otherChild == 0)
  13186. {
  13187. if (thisChild == otherChild) // both 0, so it's a match
  13188. break;
  13189. return false;
  13190. }
  13191. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13192. return false;
  13193. thisChild = thisChild->nextElement;
  13194. otherChild = otherChild->nextElement;
  13195. }
  13196. }
  13197. return true;
  13198. }
  13199. void XmlElement::deleteAllChildElements() throw()
  13200. {
  13201. while (firstChildElement != 0)
  13202. {
  13203. XmlElement* const nextChild = firstChildElement->nextElement;
  13204. delete firstChildElement;
  13205. firstChildElement = nextChild;
  13206. }
  13207. }
  13208. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13209. {
  13210. XmlElement* child = firstChildElement;
  13211. while (child != 0)
  13212. {
  13213. if (child->hasTagName (name))
  13214. {
  13215. XmlElement* const nextChild = child->nextElement;
  13216. removeChildElement (child, true);
  13217. child = nextChild;
  13218. }
  13219. else
  13220. {
  13221. child = child->nextElement;
  13222. }
  13223. }
  13224. }
  13225. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13226. {
  13227. const XmlElement* child = firstChildElement;
  13228. while (child != 0)
  13229. {
  13230. if (child == possibleChild)
  13231. return true;
  13232. child = child->nextElement;
  13233. }
  13234. return false;
  13235. }
  13236. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13237. {
  13238. if (this == elementToLookFor || elementToLookFor == 0)
  13239. return 0;
  13240. XmlElement* child = firstChildElement;
  13241. while (child != 0)
  13242. {
  13243. if (elementToLookFor == child)
  13244. return this;
  13245. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13246. if (found != 0)
  13247. return found;
  13248. child = child->nextElement;
  13249. }
  13250. return 0;
  13251. }
  13252. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13253. {
  13254. XmlElement* e = firstChildElement;
  13255. while (e != 0)
  13256. {
  13257. *elems++ = e;
  13258. e = e->nextElement;
  13259. }
  13260. }
  13261. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13262. {
  13263. XmlElement* e = firstChildElement = elems[0];
  13264. for (int i = 1; i < num; ++i)
  13265. {
  13266. e->nextElement = elems[i];
  13267. e = e->nextElement;
  13268. }
  13269. e->nextElement = 0;
  13270. }
  13271. bool XmlElement::isTextElement() const throw()
  13272. {
  13273. return tagName.isEmpty();
  13274. }
  13275. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13276. const String& XmlElement::getText() const throw()
  13277. {
  13278. jassert (isTextElement()); // you're trying to get the text from an element that
  13279. // isn't actually a text element.. If this contains text sub-nodes, you
  13280. // probably want to use getAllSubText instead.
  13281. return getStringAttribute (juce_xmltextContentAttributeName);
  13282. }
  13283. void XmlElement::setText (const String& newText)
  13284. {
  13285. if (isTextElement())
  13286. setAttribute (juce_xmltextContentAttributeName, newText);
  13287. else
  13288. jassertfalse; // you can only change the text in a text element, not a normal one.
  13289. }
  13290. const String XmlElement::getAllSubText() const
  13291. {
  13292. if (isTextElement())
  13293. return getText();
  13294. String result;
  13295. String::Concatenator concatenator (result);
  13296. const XmlElement* child = firstChildElement;
  13297. while (child != 0)
  13298. {
  13299. concatenator.append (child->getAllSubText());
  13300. child = child->nextElement;
  13301. }
  13302. return result;
  13303. }
  13304. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13305. const String& defaultReturnValue) const
  13306. {
  13307. const XmlElement* const child = getChildByName (childTagName);
  13308. if (child != 0)
  13309. return child->getAllSubText();
  13310. return defaultReturnValue;
  13311. }
  13312. XmlElement* XmlElement::createTextElement (const String& text)
  13313. {
  13314. XmlElement* const e = new XmlElement ((int) 0);
  13315. e->setAttribute (juce_xmltextContentAttributeName, text);
  13316. return e;
  13317. }
  13318. void XmlElement::addTextElement (const String& text)
  13319. {
  13320. addChildElement (createTextElement (text));
  13321. }
  13322. void XmlElement::deleteAllTextElements() throw()
  13323. {
  13324. XmlElement* child = firstChildElement;
  13325. while (child != 0)
  13326. {
  13327. XmlElement* const next = child->nextElement;
  13328. if (child->isTextElement())
  13329. removeChildElement (child, true);
  13330. child = next;
  13331. }
  13332. }
  13333. END_JUCE_NAMESPACE
  13334. /*** End of inlined file: juce_XmlElement.cpp ***/
  13335. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13336. BEGIN_JUCE_NAMESPACE
  13337. ReadWriteLock::ReadWriteLock() throw()
  13338. : numWaitingWriters (0),
  13339. numWriters (0),
  13340. writerThreadId (0)
  13341. {
  13342. }
  13343. ReadWriteLock::~ReadWriteLock() throw()
  13344. {
  13345. jassert (readerThreads.size() == 0);
  13346. jassert (numWriters == 0);
  13347. }
  13348. void ReadWriteLock::enterRead() const throw()
  13349. {
  13350. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13351. const ScopedLock sl (accessLock);
  13352. for (;;)
  13353. {
  13354. jassert (readerThreads.size() % 2 == 0);
  13355. int i;
  13356. for (i = 0; i < readerThreads.size(); i += 2)
  13357. if (readerThreads.getUnchecked(i) == threadId)
  13358. break;
  13359. if (i < readerThreads.size()
  13360. || numWriters + numWaitingWriters == 0
  13361. || (threadId == writerThreadId && numWriters > 0))
  13362. {
  13363. if (i < readerThreads.size())
  13364. {
  13365. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13366. }
  13367. else
  13368. {
  13369. readerThreads.add (threadId);
  13370. readerThreads.add ((Thread::ThreadID) 1);
  13371. }
  13372. return;
  13373. }
  13374. const ScopedUnlock ul (accessLock);
  13375. waitEvent.wait (100);
  13376. }
  13377. }
  13378. void ReadWriteLock::exitRead() const throw()
  13379. {
  13380. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13381. const ScopedLock sl (accessLock);
  13382. for (int i = 0; i < readerThreads.size(); i += 2)
  13383. {
  13384. if (readerThreads.getUnchecked(i) == threadId)
  13385. {
  13386. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13387. if (newCount == 0)
  13388. {
  13389. readerThreads.removeRange (i, 2);
  13390. waitEvent.signal();
  13391. }
  13392. else
  13393. {
  13394. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13395. }
  13396. return;
  13397. }
  13398. }
  13399. jassertfalse; // unlocking a lock that wasn't locked..
  13400. }
  13401. void ReadWriteLock::enterWrite() const throw()
  13402. {
  13403. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13404. const ScopedLock sl (accessLock);
  13405. for (;;)
  13406. {
  13407. if (readerThreads.size() + numWriters == 0
  13408. || threadId == writerThreadId
  13409. || (readerThreads.size() == 2
  13410. && readerThreads.getUnchecked(0) == threadId))
  13411. {
  13412. writerThreadId = threadId;
  13413. ++numWriters;
  13414. break;
  13415. }
  13416. ++numWaitingWriters;
  13417. accessLock.exit();
  13418. waitEvent.wait (100);
  13419. accessLock.enter();
  13420. --numWaitingWriters;
  13421. }
  13422. }
  13423. bool ReadWriteLock::tryEnterWrite() const throw()
  13424. {
  13425. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13426. const ScopedLock sl (accessLock);
  13427. if (readerThreads.size() + numWriters == 0
  13428. || threadId == writerThreadId
  13429. || (readerThreads.size() == 2
  13430. && readerThreads.getUnchecked(0) == threadId))
  13431. {
  13432. writerThreadId = threadId;
  13433. ++numWriters;
  13434. return true;
  13435. }
  13436. return false;
  13437. }
  13438. void ReadWriteLock::exitWrite() const throw()
  13439. {
  13440. const ScopedLock sl (accessLock);
  13441. // check this thread actually had the lock..
  13442. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13443. if (--numWriters == 0)
  13444. {
  13445. writerThreadId = 0;
  13446. waitEvent.signal();
  13447. }
  13448. }
  13449. END_JUCE_NAMESPACE
  13450. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13451. /*** Start of inlined file: juce_Thread.cpp ***/
  13452. BEGIN_JUCE_NAMESPACE
  13453. class RunningThreadsList
  13454. {
  13455. public:
  13456. RunningThreadsList()
  13457. {
  13458. }
  13459. void add (Thread* const thread)
  13460. {
  13461. const ScopedLock sl (lock);
  13462. jassert (! threads.contains (thread));
  13463. threads.add (thread);
  13464. }
  13465. void remove (Thread* const thread)
  13466. {
  13467. const ScopedLock sl (lock);
  13468. jassert (threads.contains (thread));
  13469. threads.removeValue (thread);
  13470. }
  13471. int size() const throw()
  13472. {
  13473. return threads.size();
  13474. }
  13475. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13476. {
  13477. const ScopedLock sl (lock);
  13478. for (int i = threads.size(); --i >= 0;)
  13479. {
  13480. Thread* const t = threads.getUnchecked(i);
  13481. if (t->getThreadId() == targetID)
  13482. return t;
  13483. }
  13484. return 0;
  13485. }
  13486. void stopAll (const int timeOutMilliseconds)
  13487. {
  13488. signalAllThreadsToStop();
  13489. for (;;)
  13490. {
  13491. Thread* firstThread = getFirstThread();
  13492. if (firstThread != 0)
  13493. firstThread->stopThread (timeOutMilliseconds);
  13494. else
  13495. break;
  13496. }
  13497. }
  13498. static RunningThreadsList& getInstance()
  13499. {
  13500. static RunningThreadsList runningThreads;
  13501. return runningThreads;
  13502. }
  13503. private:
  13504. Array<Thread*> threads;
  13505. CriticalSection lock;
  13506. void signalAllThreadsToStop()
  13507. {
  13508. const ScopedLock sl (lock);
  13509. for (int i = threads.size(); --i >= 0;)
  13510. threads.getUnchecked(i)->signalThreadShouldExit();
  13511. }
  13512. Thread* getFirstThread() const
  13513. {
  13514. const ScopedLock sl (lock);
  13515. return threads.getFirst();
  13516. }
  13517. };
  13518. void Thread::threadEntryPoint()
  13519. {
  13520. RunningThreadsList::getInstance().add (this);
  13521. JUCE_TRY
  13522. {
  13523. if (threadName_.isNotEmpty())
  13524. setCurrentThreadName (threadName_);
  13525. if (startSuspensionEvent_.wait (10000))
  13526. {
  13527. jassert (getCurrentThreadId() == threadId_);
  13528. if (affinityMask_ != 0)
  13529. setCurrentThreadAffinityMask (affinityMask_);
  13530. run();
  13531. }
  13532. }
  13533. JUCE_CATCH_ALL_ASSERT
  13534. RunningThreadsList::getInstance().remove (this);
  13535. closeThreadHandle();
  13536. }
  13537. // used to wrap the incoming call from the platform-specific code
  13538. void JUCE_API juce_threadEntryPoint (void* userData)
  13539. {
  13540. static_cast <Thread*> (userData)->threadEntryPoint();
  13541. }
  13542. Thread::Thread (const String& threadName)
  13543. : threadName_ (threadName),
  13544. threadHandle_ (0),
  13545. threadId_ (0),
  13546. threadPriority_ (5),
  13547. affinityMask_ (0),
  13548. threadShouldExit_ (false)
  13549. {
  13550. }
  13551. Thread::~Thread()
  13552. {
  13553. /* If your thread class's destructor has been called without first stopping the thread, that
  13554. means that this partially destructed object is still performing some work - and that's
  13555. probably a Bad Thing!
  13556. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13557. your subclass's destructor.
  13558. */
  13559. jassert (! isThreadRunning());
  13560. stopThread (100);
  13561. }
  13562. void Thread::startThread()
  13563. {
  13564. const ScopedLock sl (startStopLock);
  13565. threadShouldExit_ = false;
  13566. if (threadHandle_ == 0)
  13567. {
  13568. launchThread();
  13569. setThreadPriority (threadHandle_, threadPriority_);
  13570. startSuspensionEvent_.signal();
  13571. }
  13572. }
  13573. void Thread::startThread (const int priority)
  13574. {
  13575. const ScopedLock sl (startStopLock);
  13576. if (threadHandle_ == 0)
  13577. {
  13578. threadPriority_ = priority;
  13579. startThread();
  13580. }
  13581. else
  13582. {
  13583. setPriority (priority);
  13584. }
  13585. }
  13586. bool Thread::isThreadRunning() const
  13587. {
  13588. return threadHandle_ != 0;
  13589. }
  13590. void Thread::signalThreadShouldExit()
  13591. {
  13592. threadShouldExit_ = true;
  13593. }
  13594. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13595. {
  13596. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13597. jassert (getThreadId() != getCurrentThreadId());
  13598. const int sleepMsPerIteration = 5;
  13599. int count = timeOutMilliseconds / sleepMsPerIteration;
  13600. while (isThreadRunning())
  13601. {
  13602. if (timeOutMilliseconds > 0 && --count < 0)
  13603. return false;
  13604. sleep (sleepMsPerIteration);
  13605. }
  13606. return true;
  13607. }
  13608. void Thread::stopThread (const int timeOutMilliseconds)
  13609. {
  13610. // agh! You can't stop the thread that's calling this method! How on earth
  13611. // would that work??
  13612. jassert (getCurrentThreadId() != getThreadId());
  13613. const ScopedLock sl (startStopLock);
  13614. if (isThreadRunning())
  13615. {
  13616. signalThreadShouldExit();
  13617. notify();
  13618. if (timeOutMilliseconds != 0)
  13619. waitForThreadToExit (timeOutMilliseconds);
  13620. if (isThreadRunning())
  13621. {
  13622. // very bad karma if this point is reached, as there are bound to be
  13623. // locks and events left in silly states when a thread is killed by force..
  13624. jassertfalse;
  13625. Logger::writeToLog ("!! killing thread by force !!");
  13626. killThread();
  13627. RunningThreadsList::getInstance().remove (this);
  13628. threadHandle_ = 0;
  13629. threadId_ = 0;
  13630. }
  13631. }
  13632. }
  13633. bool Thread::setPriority (const int priority)
  13634. {
  13635. const ScopedLock sl (startStopLock);
  13636. if (setThreadPriority (threadHandle_, priority))
  13637. {
  13638. threadPriority_ = priority;
  13639. return true;
  13640. }
  13641. return false;
  13642. }
  13643. bool Thread::setCurrentThreadPriority (const int priority)
  13644. {
  13645. return setThreadPriority (0, priority);
  13646. }
  13647. void Thread::setAffinityMask (const uint32 affinityMask)
  13648. {
  13649. affinityMask_ = affinityMask;
  13650. }
  13651. bool Thread::wait (const int timeOutMilliseconds) const
  13652. {
  13653. return defaultEvent_.wait (timeOutMilliseconds);
  13654. }
  13655. void Thread::notify() const
  13656. {
  13657. defaultEvent_.signal();
  13658. }
  13659. int Thread::getNumRunningThreads()
  13660. {
  13661. return RunningThreadsList::getInstance().size();
  13662. }
  13663. Thread* Thread::getCurrentThread()
  13664. {
  13665. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13666. }
  13667. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13668. {
  13669. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13670. }
  13671. END_JUCE_NAMESPACE
  13672. /*** End of inlined file: juce_Thread.cpp ***/
  13673. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13674. BEGIN_JUCE_NAMESPACE
  13675. ThreadPoolJob::ThreadPoolJob (const String& name)
  13676. : jobName (name),
  13677. pool (0),
  13678. shouldStop (false),
  13679. isActive (false),
  13680. shouldBeDeleted (false)
  13681. {
  13682. }
  13683. ThreadPoolJob::~ThreadPoolJob()
  13684. {
  13685. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13686. // to remove it first!
  13687. jassert (pool == 0 || ! pool->contains (this));
  13688. }
  13689. const String ThreadPoolJob::getJobName() const
  13690. {
  13691. return jobName;
  13692. }
  13693. void ThreadPoolJob::setJobName (const String& newName)
  13694. {
  13695. jobName = newName;
  13696. }
  13697. void ThreadPoolJob::signalJobShouldExit()
  13698. {
  13699. shouldStop = true;
  13700. }
  13701. class ThreadPool::ThreadPoolThread : public Thread
  13702. {
  13703. public:
  13704. ThreadPoolThread (ThreadPool& pool_)
  13705. : Thread ("Pool"),
  13706. pool (pool_),
  13707. busy (false)
  13708. {
  13709. }
  13710. void run()
  13711. {
  13712. while (! threadShouldExit())
  13713. {
  13714. if (! pool.runNextJob())
  13715. wait (500);
  13716. }
  13717. }
  13718. private:
  13719. ThreadPool& pool;
  13720. bool volatile busy;
  13721. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13722. };
  13723. ThreadPool::ThreadPool (const int numThreads,
  13724. const bool startThreadsOnlyWhenNeeded,
  13725. const int stopThreadsWhenNotUsedTimeoutMs)
  13726. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13727. priority (5)
  13728. {
  13729. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13730. for (int i = jmax (1, numThreads); --i >= 0;)
  13731. threads.add (new ThreadPoolThread (*this));
  13732. if (! startThreadsOnlyWhenNeeded)
  13733. for (int i = threads.size(); --i >= 0;)
  13734. threads.getUnchecked(i)->startThread (priority);
  13735. }
  13736. ThreadPool::~ThreadPool()
  13737. {
  13738. removeAllJobs (true, 4000);
  13739. int i;
  13740. for (i = threads.size(); --i >= 0;)
  13741. threads.getUnchecked(i)->signalThreadShouldExit();
  13742. for (i = threads.size(); --i >= 0;)
  13743. threads.getUnchecked(i)->stopThread (500);
  13744. }
  13745. void ThreadPool::addJob (ThreadPoolJob* const job)
  13746. {
  13747. jassert (job != 0);
  13748. jassert (job->pool == 0);
  13749. if (job->pool == 0)
  13750. {
  13751. job->pool = this;
  13752. job->shouldStop = false;
  13753. job->isActive = false;
  13754. {
  13755. const ScopedLock sl (lock);
  13756. jobs.add (job);
  13757. int numRunning = 0;
  13758. for (int i = threads.size(); --i >= 0;)
  13759. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13760. ++numRunning;
  13761. if (numRunning < threads.size())
  13762. {
  13763. bool startedOne = false;
  13764. int n = 1000;
  13765. while (--n >= 0 && ! startedOne)
  13766. {
  13767. for (int i = threads.size(); --i >= 0;)
  13768. {
  13769. if (! threads.getUnchecked(i)->isThreadRunning())
  13770. {
  13771. threads.getUnchecked(i)->startThread (priority);
  13772. startedOne = true;
  13773. break;
  13774. }
  13775. }
  13776. if (! startedOne)
  13777. Thread::sleep (2);
  13778. }
  13779. }
  13780. }
  13781. for (int i = threads.size(); --i >= 0;)
  13782. threads.getUnchecked(i)->notify();
  13783. }
  13784. }
  13785. int ThreadPool::getNumJobs() const
  13786. {
  13787. return jobs.size();
  13788. }
  13789. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13790. {
  13791. const ScopedLock sl (lock);
  13792. return jobs [index];
  13793. }
  13794. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13795. {
  13796. const ScopedLock sl (lock);
  13797. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13798. }
  13799. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13800. {
  13801. const ScopedLock sl (lock);
  13802. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13803. }
  13804. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13805. const int timeOutMs) const
  13806. {
  13807. if (job != 0)
  13808. {
  13809. const uint32 start = Time::getMillisecondCounter();
  13810. while (contains (job))
  13811. {
  13812. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13813. return false;
  13814. jobFinishedSignal.wait (2);
  13815. }
  13816. }
  13817. return true;
  13818. }
  13819. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13820. const bool interruptIfRunning,
  13821. const int timeOutMs)
  13822. {
  13823. bool dontWait = true;
  13824. if (job != 0)
  13825. {
  13826. const ScopedLock sl (lock);
  13827. if (jobs.contains (job))
  13828. {
  13829. if (job->isActive)
  13830. {
  13831. if (interruptIfRunning)
  13832. job->signalJobShouldExit();
  13833. dontWait = false;
  13834. }
  13835. else
  13836. {
  13837. jobs.removeValue (job);
  13838. job->pool = 0;
  13839. }
  13840. }
  13841. }
  13842. return dontWait || waitForJobToFinish (job, timeOutMs);
  13843. }
  13844. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13845. const int timeOutMs,
  13846. const bool deleteInactiveJobs,
  13847. ThreadPool::JobSelector* selectedJobsToRemove)
  13848. {
  13849. Array <ThreadPoolJob*> jobsToWaitFor;
  13850. {
  13851. const ScopedLock sl (lock);
  13852. for (int i = jobs.size(); --i >= 0;)
  13853. {
  13854. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13855. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13856. {
  13857. if (job->isActive)
  13858. {
  13859. jobsToWaitFor.add (job);
  13860. if (interruptRunningJobs)
  13861. job->signalJobShouldExit();
  13862. }
  13863. else
  13864. {
  13865. jobs.remove (i);
  13866. if (deleteInactiveJobs)
  13867. delete job;
  13868. else
  13869. job->pool = 0;
  13870. }
  13871. }
  13872. }
  13873. }
  13874. const uint32 start = Time::getMillisecondCounter();
  13875. for (;;)
  13876. {
  13877. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13878. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13879. jobsToWaitFor.remove (i);
  13880. if (jobsToWaitFor.size() == 0)
  13881. break;
  13882. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13883. return false;
  13884. jobFinishedSignal.wait (20);
  13885. }
  13886. return true;
  13887. }
  13888. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13889. {
  13890. StringArray s;
  13891. const ScopedLock sl (lock);
  13892. for (int i = 0; i < jobs.size(); ++i)
  13893. {
  13894. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13895. if (job->isActive || ! onlyReturnActiveJobs)
  13896. s.add (job->getJobName());
  13897. }
  13898. return s;
  13899. }
  13900. bool ThreadPool::setThreadPriorities (const int newPriority)
  13901. {
  13902. bool ok = true;
  13903. if (priority != newPriority)
  13904. {
  13905. priority = newPriority;
  13906. for (int i = threads.size(); --i >= 0;)
  13907. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13908. ok = false;
  13909. }
  13910. return ok;
  13911. }
  13912. bool ThreadPool::runNextJob()
  13913. {
  13914. ThreadPoolJob* job = 0;
  13915. {
  13916. const ScopedLock sl (lock);
  13917. for (int i = 0; i < jobs.size(); ++i)
  13918. {
  13919. job = jobs[i];
  13920. if (job != 0 && ! (job->isActive || job->shouldStop))
  13921. break;
  13922. job = 0;
  13923. }
  13924. if (job != 0)
  13925. job->isActive = true;
  13926. }
  13927. if (job != 0)
  13928. {
  13929. JUCE_TRY
  13930. {
  13931. ThreadPoolJob::JobStatus result = job->runJob();
  13932. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13933. const ScopedLock sl (lock);
  13934. if (jobs.contains (job))
  13935. {
  13936. job->isActive = false;
  13937. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13938. {
  13939. job->pool = 0;
  13940. job->shouldStop = true;
  13941. jobs.removeValue (job);
  13942. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13943. delete job;
  13944. jobFinishedSignal.signal();
  13945. }
  13946. else
  13947. {
  13948. // move the job to the end of the queue if it wants another go
  13949. jobs.move (jobs.indexOf (job), -1);
  13950. }
  13951. }
  13952. }
  13953. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13954. catch (...)
  13955. {
  13956. const ScopedLock sl (lock);
  13957. jobs.removeValue (job);
  13958. }
  13959. #endif
  13960. }
  13961. else
  13962. {
  13963. if (threadStopTimeout > 0
  13964. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13965. {
  13966. const ScopedLock sl (lock);
  13967. if (jobs.size() == 0)
  13968. for (int i = threads.size(); --i >= 0;)
  13969. threads.getUnchecked(i)->signalThreadShouldExit();
  13970. }
  13971. else
  13972. {
  13973. return false;
  13974. }
  13975. }
  13976. return true;
  13977. }
  13978. END_JUCE_NAMESPACE
  13979. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13980. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13981. BEGIN_JUCE_NAMESPACE
  13982. TimeSliceThread::TimeSliceThread (const String& threadName)
  13983. : Thread (threadName),
  13984. index (0),
  13985. clientBeingCalled (0),
  13986. clientsChanged (false)
  13987. {
  13988. }
  13989. TimeSliceThread::~TimeSliceThread()
  13990. {
  13991. stopThread (2000);
  13992. }
  13993. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  13994. {
  13995. const ScopedLock sl (listLock);
  13996. clients.addIfNotAlreadyThere (client);
  13997. clientsChanged = true;
  13998. notify();
  13999. }
  14000. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14001. {
  14002. const ScopedLock sl1 (listLock);
  14003. clientsChanged = true;
  14004. // if there's a chance we're in the middle of calling this client, we need to
  14005. // also lock the outer lock..
  14006. if (clientBeingCalled == client)
  14007. {
  14008. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14009. const ScopedLock sl2 (callbackLock);
  14010. const ScopedLock sl3 (listLock);
  14011. clients.removeValue (client);
  14012. }
  14013. else
  14014. {
  14015. clients.removeValue (client);
  14016. }
  14017. }
  14018. int TimeSliceThread::getNumClients() const
  14019. {
  14020. return clients.size();
  14021. }
  14022. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14023. {
  14024. const ScopedLock sl (listLock);
  14025. return clients [i];
  14026. }
  14027. void TimeSliceThread::run()
  14028. {
  14029. int numCallsSinceBusy = 0;
  14030. while (! threadShouldExit())
  14031. {
  14032. int timeToWait = 500;
  14033. {
  14034. const ScopedLock sl (callbackLock);
  14035. {
  14036. const ScopedLock sl2 (listLock);
  14037. if (clients.size() > 0)
  14038. {
  14039. index = (index + 1) % clients.size();
  14040. clientBeingCalled = clients [index];
  14041. }
  14042. else
  14043. {
  14044. index = 0;
  14045. clientBeingCalled = 0;
  14046. }
  14047. if (clientsChanged)
  14048. {
  14049. clientsChanged = false;
  14050. numCallsSinceBusy = 0;
  14051. }
  14052. }
  14053. if (clientBeingCalled != 0)
  14054. {
  14055. if (clientBeingCalled->useTimeSlice())
  14056. numCallsSinceBusy = 0;
  14057. else
  14058. ++numCallsSinceBusy;
  14059. if (numCallsSinceBusy >= clients.size())
  14060. timeToWait = 500;
  14061. else if (index == 0)
  14062. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14063. else
  14064. timeToWait = 0;
  14065. }
  14066. }
  14067. if (timeToWait > 0)
  14068. wait (timeToWait);
  14069. }
  14070. }
  14071. END_JUCE_NAMESPACE
  14072. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14073. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14074. BEGIN_JUCE_NAMESPACE
  14075. DeletedAtShutdown::DeletedAtShutdown()
  14076. {
  14077. const ScopedLock sl (getLock());
  14078. getObjects().add (this);
  14079. }
  14080. DeletedAtShutdown::~DeletedAtShutdown()
  14081. {
  14082. const ScopedLock sl (getLock());
  14083. getObjects().removeValue (this);
  14084. }
  14085. void DeletedAtShutdown::deleteAll()
  14086. {
  14087. // make a local copy of the array, so it can't get into a loop if something
  14088. // creates another DeletedAtShutdown object during its destructor.
  14089. Array <DeletedAtShutdown*> localCopy;
  14090. {
  14091. const ScopedLock sl (getLock());
  14092. localCopy = getObjects();
  14093. }
  14094. for (int i = localCopy.size(); --i >= 0;)
  14095. {
  14096. JUCE_TRY
  14097. {
  14098. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14099. // double-check that it's not already been deleted during another object's destructor.
  14100. {
  14101. const ScopedLock sl (getLock());
  14102. if (! getObjects().contains (deletee))
  14103. deletee = 0;
  14104. }
  14105. delete deletee;
  14106. }
  14107. JUCE_CATCH_EXCEPTION
  14108. }
  14109. // if no objects got re-created during shutdown, this should have been emptied by their
  14110. // destructors
  14111. jassert (getObjects().size() == 0);
  14112. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14113. }
  14114. CriticalSection& DeletedAtShutdown::getLock()
  14115. {
  14116. static CriticalSection lock;
  14117. return lock;
  14118. }
  14119. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14120. {
  14121. static Array <DeletedAtShutdown*> objects;
  14122. return objects;
  14123. }
  14124. END_JUCE_NAMESPACE
  14125. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14126. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14127. BEGIN_JUCE_NAMESPACE
  14128. UnitTest::UnitTest (const String& name_)
  14129. : name (name_), runner (0)
  14130. {
  14131. getAllTests().add (this);
  14132. }
  14133. UnitTest::~UnitTest()
  14134. {
  14135. getAllTests().removeValue (this);
  14136. }
  14137. Array<UnitTest*>& UnitTest::getAllTests()
  14138. {
  14139. static Array<UnitTest*> tests;
  14140. return tests;
  14141. }
  14142. void UnitTest::initialise() {}
  14143. void UnitTest::shutdown() {}
  14144. void UnitTest::performTest (UnitTestRunner* const runner_)
  14145. {
  14146. jassert (runner_ != 0);
  14147. runner = runner_;
  14148. initialise();
  14149. runTest();
  14150. shutdown();
  14151. }
  14152. void UnitTest::logMessage (const String& message)
  14153. {
  14154. runner->logMessage (message);
  14155. }
  14156. void UnitTest::beginTest (const String& testName)
  14157. {
  14158. runner->beginNewTest (this, testName);
  14159. }
  14160. void UnitTest::expect (const bool result, const String& failureMessage)
  14161. {
  14162. if (result)
  14163. runner->addPass();
  14164. else
  14165. runner->addFail (failureMessage);
  14166. }
  14167. UnitTestRunner::UnitTestRunner()
  14168. : currentTest (0), assertOnFailure (false)
  14169. {
  14170. }
  14171. UnitTestRunner::~UnitTestRunner()
  14172. {
  14173. }
  14174. int UnitTestRunner::getNumResults() const throw()
  14175. {
  14176. return results.size();
  14177. }
  14178. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14179. {
  14180. return results [index];
  14181. }
  14182. void UnitTestRunner::resultsUpdated()
  14183. {
  14184. }
  14185. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14186. {
  14187. results.clear();
  14188. assertOnFailure = assertOnFailure_;
  14189. resultsUpdated();
  14190. for (int i = 0; i < tests.size(); ++i)
  14191. {
  14192. try
  14193. {
  14194. tests.getUnchecked(i)->performTest (this);
  14195. }
  14196. catch (...)
  14197. {
  14198. addFail ("An unhandled exception was thrown!");
  14199. }
  14200. }
  14201. endTest();
  14202. }
  14203. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14204. {
  14205. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14206. }
  14207. void UnitTestRunner::logMessage (const String& message)
  14208. {
  14209. Logger::writeToLog (message);
  14210. }
  14211. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14212. {
  14213. endTest();
  14214. currentTest = test;
  14215. TestResult* const r = new TestResult();
  14216. r->unitTestName = test->getName();
  14217. r->subcategoryName = subCategory;
  14218. r->passes = 0;
  14219. r->failures = 0;
  14220. results.add (r);
  14221. logMessage ("-----------------------------------------------------------------");
  14222. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14223. resultsUpdated();
  14224. }
  14225. void UnitTestRunner::endTest()
  14226. {
  14227. if (results.size() > 0)
  14228. {
  14229. TestResult* const r = results.getLast();
  14230. if (r->failures > 0)
  14231. {
  14232. String m ("FAILED!!");
  14233. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14234. << " failed, out of a total of " << (r->passes + r->failures);
  14235. logMessage (String::empty);
  14236. logMessage (m);
  14237. logMessage (String::empty);
  14238. }
  14239. else
  14240. {
  14241. logMessage ("All tests completed successfully");
  14242. }
  14243. }
  14244. }
  14245. void UnitTestRunner::addPass()
  14246. {
  14247. {
  14248. const ScopedLock sl (results.getLock());
  14249. TestResult* const r = results.getLast();
  14250. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14251. r->passes++;
  14252. String message ("Test ");
  14253. message << (r->failures + r->passes) << " passed";
  14254. logMessage (message);
  14255. }
  14256. resultsUpdated();
  14257. }
  14258. void UnitTestRunner::addFail (const String& failureMessage)
  14259. {
  14260. {
  14261. const ScopedLock sl (results.getLock());
  14262. TestResult* const r = results.getLast();
  14263. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14264. r->failures++;
  14265. String message ("!!! Test ");
  14266. message << (r->failures + r->passes) << " failed";
  14267. if (failureMessage.isNotEmpty())
  14268. message << ": " << failureMessage;
  14269. r->messages.add (message);
  14270. logMessage (message);
  14271. }
  14272. resultsUpdated();
  14273. if (assertOnFailure) { jassertfalse }
  14274. }
  14275. END_JUCE_NAMESPACE
  14276. /*** End of inlined file: juce_UnitTest.cpp ***/
  14277. #endif
  14278. #if JUCE_BUILD_MISC
  14279. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14280. BEGIN_JUCE_NAMESPACE
  14281. class ValueTree::SetPropertyAction : public UndoableAction
  14282. {
  14283. public:
  14284. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14285. const var& newValue_, const var& oldValue_,
  14286. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14287. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14288. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14289. {
  14290. }
  14291. ~SetPropertyAction() {}
  14292. bool perform()
  14293. {
  14294. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14295. if (isDeletingProperty)
  14296. target->removeProperty (name, 0);
  14297. else
  14298. target->setProperty (name, newValue, 0);
  14299. return true;
  14300. }
  14301. bool undo()
  14302. {
  14303. if (isAddingNewProperty)
  14304. target->removeProperty (name, 0);
  14305. else
  14306. target->setProperty (name, oldValue, 0);
  14307. return true;
  14308. }
  14309. int getSizeInUnits()
  14310. {
  14311. return (int) sizeof (*this); //xxx should be more accurate
  14312. }
  14313. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14314. {
  14315. if (! (isAddingNewProperty || isDeletingProperty))
  14316. {
  14317. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14318. if (next != 0 && next->target == target && next->name == name
  14319. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14320. {
  14321. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14322. }
  14323. }
  14324. return 0;
  14325. }
  14326. private:
  14327. const SharedObjectPtr target;
  14328. const Identifier name;
  14329. const var newValue;
  14330. var oldValue;
  14331. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14332. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  14333. };
  14334. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14335. {
  14336. public:
  14337. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14338. const SharedObjectPtr& newChild_)
  14339. : target (target_),
  14340. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14341. childIndex (childIndex_),
  14342. isDeleting (newChild_ == 0)
  14343. {
  14344. jassert (child != 0);
  14345. }
  14346. ~AddOrRemoveChildAction() {}
  14347. bool perform()
  14348. {
  14349. if (isDeleting)
  14350. target->removeChild (childIndex, 0);
  14351. else
  14352. target->addChild (child, childIndex, 0);
  14353. return true;
  14354. }
  14355. bool undo()
  14356. {
  14357. if (isDeleting)
  14358. {
  14359. target->addChild (child, childIndex, 0);
  14360. }
  14361. else
  14362. {
  14363. // If you hit this, it seems that your object's state is getting confused - probably
  14364. // because you've interleaved some undoable and non-undoable operations?
  14365. jassert (childIndex < target->children.size());
  14366. target->removeChild (childIndex, 0);
  14367. }
  14368. return true;
  14369. }
  14370. int getSizeInUnits()
  14371. {
  14372. return (int) sizeof (*this); //xxx should be more accurate
  14373. }
  14374. private:
  14375. const SharedObjectPtr target, child;
  14376. const int childIndex;
  14377. const bool isDeleting;
  14378. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  14379. };
  14380. class ValueTree::MoveChildAction : public UndoableAction
  14381. {
  14382. public:
  14383. MoveChildAction (const SharedObjectPtr& parent_,
  14384. const int startIndex_, const int endIndex_)
  14385. : parent (parent_),
  14386. startIndex (startIndex_),
  14387. endIndex (endIndex_)
  14388. {
  14389. }
  14390. ~MoveChildAction() {}
  14391. bool perform()
  14392. {
  14393. parent->moveChild (startIndex, endIndex, 0);
  14394. return true;
  14395. }
  14396. bool undo()
  14397. {
  14398. parent->moveChild (endIndex, startIndex, 0);
  14399. return true;
  14400. }
  14401. int getSizeInUnits()
  14402. {
  14403. return (int) sizeof (*this); //xxx should be more accurate
  14404. }
  14405. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14406. {
  14407. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14408. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14409. return new MoveChildAction (parent, startIndex, next->endIndex);
  14410. return 0;
  14411. }
  14412. private:
  14413. const SharedObjectPtr parent;
  14414. const int startIndex, endIndex;
  14415. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  14416. };
  14417. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14418. : type (type_), parent (0)
  14419. {
  14420. }
  14421. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14422. : type (other.type), properties (other.properties), parent (0)
  14423. {
  14424. for (int i = 0; i < other.children.size(); ++i)
  14425. {
  14426. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14427. child->parent = this;
  14428. children.add (child);
  14429. }
  14430. }
  14431. ValueTree::SharedObject::~SharedObject()
  14432. {
  14433. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14434. for (int i = children.size(); --i >= 0;)
  14435. {
  14436. const SharedObjectPtr c (children.getUnchecked(i));
  14437. c->parent = 0;
  14438. children.remove (i);
  14439. c->sendParentChangeMessage();
  14440. }
  14441. }
  14442. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14443. {
  14444. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14445. {
  14446. ValueTree* const v = valueTreesWithListeners[i];
  14447. if (v != 0)
  14448. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14449. }
  14450. }
  14451. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14452. {
  14453. ValueTree tree (this);
  14454. ValueTree::SharedObject* t = this;
  14455. while (t != 0)
  14456. {
  14457. t->sendPropertyChangeMessage (tree, property);
  14458. t = t->parent;
  14459. }
  14460. }
  14461. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14462. {
  14463. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14464. {
  14465. ValueTree* const v = valueTreesWithListeners[i];
  14466. if (v != 0)
  14467. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14468. }
  14469. }
  14470. void ValueTree::SharedObject::sendChildChangeMessage()
  14471. {
  14472. ValueTree tree (this);
  14473. ValueTree::SharedObject* t = this;
  14474. while (t != 0)
  14475. {
  14476. t->sendChildChangeMessage (tree);
  14477. t = t->parent;
  14478. }
  14479. }
  14480. void ValueTree::SharedObject::sendParentChangeMessage()
  14481. {
  14482. ValueTree tree (this);
  14483. int i;
  14484. for (i = children.size(); --i >= 0;)
  14485. {
  14486. SharedObject* const t = children[i];
  14487. if (t != 0)
  14488. t->sendParentChangeMessage();
  14489. }
  14490. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14491. {
  14492. ValueTree* const v = valueTreesWithListeners[i];
  14493. if (v != 0)
  14494. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14495. }
  14496. }
  14497. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14498. {
  14499. return properties [name];
  14500. }
  14501. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14502. {
  14503. return properties.getWithDefault (name, defaultReturnValue);
  14504. }
  14505. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14506. {
  14507. if (undoManager == 0)
  14508. {
  14509. if (properties.set (name, newValue))
  14510. sendPropertyChangeMessage (name);
  14511. }
  14512. else
  14513. {
  14514. var* const existingValue = properties.getVarPointer (name);
  14515. if (existingValue != 0)
  14516. {
  14517. if (*existingValue != newValue)
  14518. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14519. }
  14520. else
  14521. {
  14522. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14523. }
  14524. }
  14525. }
  14526. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14527. {
  14528. return properties.contains (name);
  14529. }
  14530. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14531. {
  14532. if (undoManager == 0)
  14533. {
  14534. if (properties.remove (name))
  14535. sendPropertyChangeMessage (name);
  14536. }
  14537. else
  14538. {
  14539. if (properties.contains (name))
  14540. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14541. }
  14542. }
  14543. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14544. {
  14545. if (undoManager == 0)
  14546. {
  14547. while (properties.size() > 0)
  14548. {
  14549. const Identifier name (properties.getName (properties.size() - 1));
  14550. properties.remove (name);
  14551. sendPropertyChangeMessage (name);
  14552. }
  14553. }
  14554. else
  14555. {
  14556. for (int i = properties.size(); --i >= 0;)
  14557. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14558. }
  14559. }
  14560. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14561. {
  14562. for (int i = 0; i < children.size(); ++i)
  14563. if (children.getUnchecked(i)->type == typeToMatch)
  14564. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14565. return ValueTree::invalid;
  14566. }
  14567. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14568. {
  14569. for (int i = 0; i < children.size(); ++i)
  14570. if (children.getUnchecked(i)->type == typeToMatch)
  14571. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14572. SharedObject* const newObject = new SharedObject (typeToMatch);
  14573. addChild (newObject, -1, undoManager);
  14574. return ValueTree (newObject);
  14575. }
  14576. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14577. {
  14578. for (int i = 0; i < children.size(); ++i)
  14579. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14580. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14581. return ValueTree::invalid;
  14582. }
  14583. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14584. {
  14585. const SharedObject* p = parent;
  14586. while (p != 0)
  14587. {
  14588. if (p == possibleParent)
  14589. return true;
  14590. p = p->parent;
  14591. }
  14592. return false;
  14593. }
  14594. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14595. {
  14596. return children.indexOf (child.object);
  14597. }
  14598. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14599. {
  14600. if (child != 0 && child->parent != this)
  14601. {
  14602. if (child != this && ! isAChildOf (child))
  14603. {
  14604. // You should always make sure that a child is removed from its previous parent before
  14605. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14606. // undomanager should be used when removing it from its current parent..
  14607. jassert (child->parent == 0);
  14608. if (child->parent != 0)
  14609. {
  14610. jassert (child->parent->children.indexOf (child) >= 0);
  14611. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14612. }
  14613. if (undoManager == 0)
  14614. {
  14615. children.insert (index, child);
  14616. child->parent = this;
  14617. sendChildChangeMessage();
  14618. child->sendParentChangeMessage();
  14619. }
  14620. else
  14621. {
  14622. if (index < 0)
  14623. index = children.size();
  14624. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14625. }
  14626. }
  14627. else
  14628. {
  14629. // You're attempting to create a recursive loop! A node
  14630. // can't be a child of one of its own children!
  14631. jassertfalse;
  14632. }
  14633. }
  14634. }
  14635. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14636. {
  14637. const SharedObjectPtr child (children [childIndex]);
  14638. if (child != 0)
  14639. {
  14640. if (undoManager == 0)
  14641. {
  14642. children.remove (childIndex);
  14643. child->parent = 0;
  14644. sendChildChangeMessage();
  14645. child->sendParentChangeMessage();
  14646. }
  14647. else
  14648. {
  14649. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14650. }
  14651. }
  14652. }
  14653. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14654. {
  14655. while (children.size() > 0)
  14656. removeChild (children.size() - 1, undoManager);
  14657. }
  14658. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14659. {
  14660. // The source index must be a valid index!
  14661. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14662. if (currentIndex != newIndex
  14663. && isPositiveAndBelow (currentIndex, children.size()))
  14664. {
  14665. if (undoManager == 0)
  14666. {
  14667. children.move (currentIndex, newIndex);
  14668. sendChildChangeMessage();
  14669. }
  14670. else
  14671. {
  14672. if (! isPositiveAndBelow (newIndex, children.size()))
  14673. newIndex = children.size() - 1;
  14674. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14675. }
  14676. }
  14677. }
  14678. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14679. {
  14680. jassert (newOrder.size() == children.size());
  14681. if (undoManager == 0)
  14682. {
  14683. children = newOrder;
  14684. sendChildChangeMessage();
  14685. }
  14686. else
  14687. {
  14688. for (int i = 0; i < children.size(); ++i)
  14689. {
  14690. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14691. {
  14692. jassert (children.contains (newOrder.getUnchecked(i)));
  14693. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14694. }
  14695. }
  14696. }
  14697. }
  14698. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14699. {
  14700. if (type != other.type
  14701. || properties.size() != other.properties.size()
  14702. || children.size() != other.children.size()
  14703. || properties != other.properties)
  14704. return false;
  14705. for (int i = 0; i < children.size(); ++i)
  14706. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14707. return false;
  14708. return true;
  14709. }
  14710. ValueTree::ValueTree() throw()
  14711. : object (0)
  14712. {
  14713. }
  14714. const ValueTree ValueTree::invalid;
  14715. ValueTree::ValueTree (const Identifier& type_)
  14716. : object (new ValueTree::SharedObject (type_))
  14717. {
  14718. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14719. }
  14720. ValueTree::ValueTree (SharedObject* const object_)
  14721. : object (object_)
  14722. {
  14723. }
  14724. ValueTree::ValueTree (const ValueTree& other)
  14725. : object (other.object)
  14726. {
  14727. }
  14728. ValueTree& ValueTree::operator= (const ValueTree& other)
  14729. {
  14730. if (listeners.size() > 0)
  14731. {
  14732. if (object != 0)
  14733. object->valueTreesWithListeners.removeValue (this);
  14734. if (other.object != 0)
  14735. other.object->valueTreesWithListeners.add (this);
  14736. }
  14737. object = other.object;
  14738. return *this;
  14739. }
  14740. ValueTree::~ValueTree()
  14741. {
  14742. if (listeners.size() > 0 && object != 0)
  14743. object->valueTreesWithListeners.removeValue (this);
  14744. }
  14745. bool ValueTree::operator== (const ValueTree& other) const throw()
  14746. {
  14747. return object == other.object;
  14748. }
  14749. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14750. {
  14751. return object != other.object;
  14752. }
  14753. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14754. {
  14755. return object == other.object
  14756. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14757. }
  14758. ValueTree ValueTree::createCopy() const
  14759. {
  14760. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14761. }
  14762. bool ValueTree::hasType (const Identifier& typeName) const
  14763. {
  14764. return object != 0 && object->type == typeName;
  14765. }
  14766. const Identifier ValueTree::getType() const
  14767. {
  14768. return object != 0 ? object->type : Identifier();
  14769. }
  14770. ValueTree ValueTree::getParent() const
  14771. {
  14772. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14773. }
  14774. ValueTree ValueTree::getSibling (const int delta) const
  14775. {
  14776. if (object == 0 || object->parent == 0)
  14777. return invalid;
  14778. const int index = object->parent->indexOf (*this) + delta;
  14779. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14780. }
  14781. const var& ValueTree::operator[] (const Identifier& name) const
  14782. {
  14783. return object == 0 ? var::null : object->getProperty (name);
  14784. }
  14785. const var& ValueTree::getProperty (const Identifier& name) const
  14786. {
  14787. return object == 0 ? var::null : object->getProperty (name);
  14788. }
  14789. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14790. {
  14791. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14792. }
  14793. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14794. {
  14795. jassert (name.toString().isNotEmpty());
  14796. if (object != 0 && name.toString().isNotEmpty())
  14797. object->setProperty (name, newValue, undoManager);
  14798. }
  14799. bool ValueTree::hasProperty (const Identifier& name) const
  14800. {
  14801. return object != 0 && object->hasProperty (name);
  14802. }
  14803. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14804. {
  14805. if (object != 0)
  14806. object->removeProperty (name, undoManager);
  14807. }
  14808. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14809. {
  14810. if (object != 0)
  14811. object->removeAllProperties (undoManager);
  14812. }
  14813. int ValueTree::getNumProperties() const
  14814. {
  14815. return object == 0 ? 0 : object->properties.size();
  14816. }
  14817. const Identifier ValueTree::getPropertyName (const int index) const
  14818. {
  14819. return object == 0 ? Identifier()
  14820. : object->properties.getName (index);
  14821. }
  14822. class ValueTreePropertyValueSource : public Value::ValueSource,
  14823. public ValueTree::Listener
  14824. {
  14825. public:
  14826. ValueTreePropertyValueSource (const ValueTree& tree_,
  14827. const Identifier& property_,
  14828. UndoManager* const undoManager_)
  14829. : tree (tree_),
  14830. property (property_),
  14831. undoManager (undoManager_)
  14832. {
  14833. tree.addListener (this);
  14834. }
  14835. ~ValueTreePropertyValueSource()
  14836. {
  14837. tree.removeListener (this);
  14838. }
  14839. const var getValue() const
  14840. {
  14841. return tree [property];
  14842. }
  14843. void setValue (const var& newValue)
  14844. {
  14845. tree.setProperty (property, newValue, undoManager);
  14846. }
  14847. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14848. {
  14849. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14850. sendChangeMessage (false);
  14851. }
  14852. void valueTreeChildrenChanged (ValueTree&) {}
  14853. void valueTreeParentChanged (ValueTree&) {}
  14854. private:
  14855. ValueTree tree;
  14856. const Identifier property;
  14857. UndoManager* const undoManager;
  14858. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14859. };
  14860. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14861. {
  14862. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14863. }
  14864. int ValueTree::getNumChildren() const
  14865. {
  14866. return object == 0 ? 0 : object->children.size();
  14867. }
  14868. ValueTree ValueTree::getChild (int index) const
  14869. {
  14870. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14871. }
  14872. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14873. {
  14874. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14875. }
  14876. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14877. {
  14878. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14879. }
  14880. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14881. {
  14882. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14883. }
  14884. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14885. {
  14886. return object != 0 && object->isAChildOf (possibleParent.object);
  14887. }
  14888. int ValueTree::indexOf (const ValueTree& child) const
  14889. {
  14890. return object != 0 ? object->indexOf (child) : -1;
  14891. }
  14892. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14893. {
  14894. if (object != 0)
  14895. object->addChild (child.object, index, undoManager);
  14896. }
  14897. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14898. {
  14899. if (object != 0)
  14900. object->removeChild (childIndex, undoManager);
  14901. }
  14902. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14903. {
  14904. if (object != 0)
  14905. object->removeChild (object->children.indexOf (child.object), undoManager);
  14906. }
  14907. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14908. {
  14909. if (object != 0)
  14910. object->removeAllChildren (undoManager);
  14911. }
  14912. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14913. {
  14914. if (object != 0)
  14915. object->moveChild (currentIndex, newIndex, undoManager);
  14916. }
  14917. void ValueTree::addListener (Listener* listener)
  14918. {
  14919. if (listener != 0)
  14920. {
  14921. if (listeners.size() == 0 && object != 0)
  14922. object->valueTreesWithListeners.add (this);
  14923. listeners.add (listener);
  14924. }
  14925. }
  14926. void ValueTree::removeListener (Listener* listener)
  14927. {
  14928. listeners.remove (listener);
  14929. if (listeners.size() == 0 && object != 0)
  14930. object->valueTreesWithListeners.removeValue (this);
  14931. }
  14932. XmlElement* ValueTree::SharedObject::createXml() const
  14933. {
  14934. XmlElement* xml = new XmlElement (type.toString());
  14935. int i;
  14936. for (i = 0; i < properties.size(); ++i)
  14937. {
  14938. Identifier name (properties.getName(i));
  14939. const var& v = properties [name];
  14940. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  14941. xml->setAttribute (name.toString(), v.toString());
  14942. }
  14943. for (i = 0; i < children.size(); ++i)
  14944. xml->addChildElement (children.getUnchecked(i)->createXml());
  14945. return xml;
  14946. }
  14947. XmlElement* ValueTree::createXml() const
  14948. {
  14949. return object != 0 ? object->createXml() : 0;
  14950. }
  14951. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14952. {
  14953. ValueTree v (xml.getTagName());
  14954. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  14955. for (int i = 0; i < numAtts; ++i)
  14956. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  14957. forEachXmlChildElement (xml, e)
  14958. {
  14959. v.addChild (fromXml (*e), -1, 0);
  14960. }
  14961. return v;
  14962. }
  14963. void ValueTree::writeToStream (OutputStream& output)
  14964. {
  14965. output.writeString (getType().toString());
  14966. const int numProps = getNumProperties();
  14967. output.writeCompressedInt (numProps);
  14968. int i;
  14969. for (i = 0; i < numProps; ++i)
  14970. {
  14971. const Identifier name (getPropertyName(i));
  14972. output.writeString (name.toString());
  14973. getProperty(name).writeToStream (output);
  14974. }
  14975. const int numChildren = getNumChildren();
  14976. output.writeCompressedInt (numChildren);
  14977. for (i = 0; i < numChildren; ++i)
  14978. getChild (i).writeToStream (output);
  14979. }
  14980. ValueTree ValueTree::readFromStream (InputStream& input)
  14981. {
  14982. const String type (input.readString());
  14983. if (type.isEmpty())
  14984. return ValueTree::invalid;
  14985. ValueTree v (type);
  14986. const int numProps = input.readCompressedInt();
  14987. if (numProps < 0)
  14988. {
  14989. jassertfalse; // trying to read corrupted data!
  14990. return v;
  14991. }
  14992. int i;
  14993. for (i = 0; i < numProps; ++i)
  14994. {
  14995. const String name (input.readString());
  14996. jassert (name.isNotEmpty());
  14997. const var value (var::readFromStream (input));
  14998. v.setProperty (name, value, 0);
  14999. }
  15000. const int numChildren = input.readCompressedInt();
  15001. for (i = 0; i < numChildren; ++i)
  15002. v.addChild (readFromStream (input), -1, 0);
  15003. return v;
  15004. }
  15005. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15006. {
  15007. MemoryInputStream in (data, numBytes, false);
  15008. return readFromStream (in);
  15009. }
  15010. END_JUCE_NAMESPACE
  15011. /*** End of inlined file: juce_ValueTree.cpp ***/
  15012. /*** Start of inlined file: juce_Value.cpp ***/
  15013. BEGIN_JUCE_NAMESPACE
  15014. Value::ValueSource::ValueSource()
  15015. {
  15016. }
  15017. Value::ValueSource::~ValueSource()
  15018. {
  15019. }
  15020. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15021. {
  15022. if (synchronous)
  15023. {
  15024. for (int i = valuesWithListeners.size(); --i >= 0;)
  15025. {
  15026. Value* const v = valuesWithListeners[i];
  15027. if (v != 0)
  15028. v->callListeners();
  15029. }
  15030. }
  15031. else
  15032. {
  15033. triggerAsyncUpdate();
  15034. }
  15035. }
  15036. void Value::ValueSource::handleAsyncUpdate()
  15037. {
  15038. sendChangeMessage (true);
  15039. }
  15040. class SimpleValueSource : public Value::ValueSource
  15041. {
  15042. public:
  15043. SimpleValueSource()
  15044. {
  15045. }
  15046. SimpleValueSource (const var& initialValue)
  15047. : value (initialValue)
  15048. {
  15049. }
  15050. ~SimpleValueSource()
  15051. {
  15052. }
  15053. const var getValue() const
  15054. {
  15055. return value;
  15056. }
  15057. void setValue (const var& newValue)
  15058. {
  15059. if (newValue != value)
  15060. {
  15061. value = newValue;
  15062. sendChangeMessage (false);
  15063. }
  15064. }
  15065. private:
  15066. var value;
  15067. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  15068. };
  15069. Value::Value()
  15070. : value (new SimpleValueSource())
  15071. {
  15072. }
  15073. Value::Value (ValueSource* const value_)
  15074. : value (value_)
  15075. {
  15076. jassert (value_ != 0);
  15077. }
  15078. Value::Value (const var& initialValue)
  15079. : value (new SimpleValueSource (initialValue))
  15080. {
  15081. }
  15082. Value::Value (const Value& other)
  15083. : value (other.value)
  15084. {
  15085. }
  15086. Value& Value::operator= (const Value& other)
  15087. {
  15088. value = other.value;
  15089. return *this;
  15090. }
  15091. Value::~Value()
  15092. {
  15093. if (listeners.size() > 0)
  15094. value->valuesWithListeners.removeValue (this);
  15095. }
  15096. const var Value::getValue() const
  15097. {
  15098. return value->getValue();
  15099. }
  15100. Value::operator const var() const
  15101. {
  15102. return getValue();
  15103. }
  15104. void Value::setValue (const var& newValue)
  15105. {
  15106. value->setValue (newValue);
  15107. }
  15108. const String Value::toString() const
  15109. {
  15110. return value->getValue().toString();
  15111. }
  15112. Value& Value::operator= (const var& newValue)
  15113. {
  15114. value->setValue (newValue);
  15115. return *this;
  15116. }
  15117. void Value::referTo (const Value& valueToReferTo)
  15118. {
  15119. if (valueToReferTo.value != value)
  15120. {
  15121. if (listeners.size() > 0)
  15122. {
  15123. value->valuesWithListeners.removeValue (this);
  15124. valueToReferTo.value->valuesWithListeners.add (this);
  15125. }
  15126. value = valueToReferTo.value;
  15127. callListeners();
  15128. }
  15129. }
  15130. bool Value::refersToSameSourceAs (const Value& other) const
  15131. {
  15132. return value == other.value;
  15133. }
  15134. bool Value::operator== (const Value& other) const
  15135. {
  15136. return value == other.value || value->getValue() == other.getValue();
  15137. }
  15138. bool Value::operator!= (const Value& other) const
  15139. {
  15140. return value != other.value && value->getValue() != other.getValue();
  15141. }
  15142. void Value::addListener (ValueListener* const listener)
  15143. {
  15144. if (listener != 0)
  15145. {
  15146. if (listeners.size() == 0)
  15147. value->valuesWithListeners.add (this);
  15148. listeners.add (listener);
  15149. }
  15150. }
  15151. void Value::removeListener (ValueListener* const listener)
  15152. {
  15153. listeners.remove (listener);
  15154. if (listeners.size() == 0)
  15155. value->valuesWithListeners.removeValue (this);
  15156. }
  15157. void Value::callListeners()
  15158. {
  15159. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15160. listeners.call (&ValueListener::valueChanged, v);
  15161. }
  15162. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15163. {
  15164. return stream << value.toString();
  15165. }
  15166. END_JUCE_NAMESPACE
  15167. /*** End of inlined file: juce_Value.cpp ***/
  15168. /*** Start of inlined file: juce_Application.cpp ***/
  15169. BEGIN_JUCE_NAMESPACE
  15170. #if JUCE_MAC
  15171. extern void juce_initialiseMacMainMenu();
  15172. #endif
  15173. JUCEApplication::JUCEApplication()
  15174. : appReturnValue (0),
  15175. stillInitialising (true)
  15176. {
  15177. jassert (isStandaloneApp() && appInstance == 0);
  15178. appInstance = this;
  15179. }
  15180. JUCEApplication::~JUCEApplication()
  15181. {
  15182. if (appLock != 0)
  15183. {
  15184. appLock->exit();
  15185. appLock = 0;
  15186. }
  15187. jassert (appInstance == this);
  15188. appInstance = 0;
  15189. }
  15190. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15191. JUCEApplication* JUCEApplication::appInstance = 0;
  15192. bool JUCEApplication::moreThanOneInstanceAllowed()
  15193. {
  15194. return true;
  15195. }
  15196. void JUCEApplication::anotherInstanceStarted (const String&)
  15197. {
  15198. }
  15199. void JUCEApplication::systemRequestedQuit()
  15200. {
  15201. quit();
  15202. }
  15203. void JUCEApplication::quit()
  15204. {
  15205. MessageManager::getInstance()->stopDispatchLoop();
  15206. }
  15207. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15208. {
  15209. appReturnValue = newReturnValue;
  15210. }
  15211. void JUCEApplication::actionListenerCallback (const String& message)
  15212. {
  15213. if (message.startsWith (getApplicationName() + "/"))
  15214. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15215. }
  15216. void JUCEApplication::unhandledException (const std::exception*,
  15217. const String&,
  15218. const int)
  15219. {
  15220. jassertfalse;
  15221. }
  15222. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15223. const char* const sourceFile,
  15224. const int lineNumber)
  15225. {
  15226. if (appInstance != 0)
  15227. appInstance->unhandledException (e, sourceFile, lineNumber);
  15228. }
  15229. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15230. {
  15231. return 0;
  15232. }
  15233. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15234. {
  15235. commands.add (StandardApplicationCommandIDs::quit);
  15236. }
  15237. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15238. {
  15239. if (commandID == StandardApplicationCommandIDs::quit)
  15240. {
  15241. result.setInfo (TRANS("Quit"),
  15242. TRANS("Quits the application"),
  15243. "Application",
  15244. 0);
  15245. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15246. }
  15247. }
  15248. bool JUCEApplication::perform (const InvocationInfo& info)
  15249. {
  15250. if (info.commandID == StandardApplicationCommandIDs::quit)
  15251. {
  15252. systemRequestedQuit();
  15253. return true;
  15254. }
  15255. return false;
  15256. }
  15257. bool JUCEApplication::initialiseApp (const String& commandLine)
  15258. {
  15259. commandLineParameters = commandLine.trim();
  15260. #if ! JUCE_IOS
  15261. jassert (appLock == 0); // initialiseApp must only be called once!
  15262. if (! moreThanOneInstanceAllowed())
  15263. {
  15264. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15265. if (! appLock->enter(0))
  15266. {
  15267. appLock = 0;
  15268. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15269. DBG ("Another instance is running - quitting...");
  15270. return false;
  15271. }
  15272. }
  15273. #endif
  15274. // let the app do its setting-up..
  15275. initialise (commandLineParameters);
  15276. #if JUCE_MAC
  15277. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15278. #endif
  15279. // register for broadcast new app messages
  15280. MessageManager::getInstance()->registerBroadcastListener (this);
  15281. stillInitialising = false;
  15282. return true;
  15283. }
  15284. int JUCEApplication::shutdownApp()
  15285. {
  15286. jassert (appInstance == this);
  15287. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15288. JUCE_TRY
  15289. {
  15290. // give the app a chance to clean up..
  15291. shutdown();
  15292. }
  15293. JUCE_CATCH_EXCEPTION
  15294. return getApplicationReturnValue();
  15295. }
  15296. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15297. void JUCEApplication::appWillTerminateByForce()
  15298. {
  15299. {
  15300. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15301. if (app != 0)
  15302. app->shutdownApp();
  15303. }
  15304. shutdownJuce_GUI();
  15305. }
  15306. int JUCEApplication::main (const String& commandLine)
  15307. {
  15308. ScopedJuceInitialiser_GUI libraryInitialiser;
  15309. jassert (createInstance != 0);
  15310. int returnCode = 0;
  15311. {
  15312. const ScopedPointer<JUCEApplication> app (createInstance());
  15313. if (! app->initialiseApp (commandLine))
  15314. return 0;
  15315. JUCE_TRY
  15316. {
  15317. // loop until a quit message is received..
  15318. MessageManager::getInstance()->runDispatchLoop();
  15319. }
  15320. JUCE_CATCH_EXCEPTION
  15321. returnCode = app->shutdownApp();
  15322. }
  15323. return returnCode;
  15324. }
  15325. #if JUCE_IOS
  15326. extern int juce_iOSMain (int argc, const char* argv[]);
  15327. #endif
  15328. #if ! JUCE_WINDOWS
  15329. extern const char* juce_Argv0;
  15330. #endif
  15331. int JUCEApplication::main (int argc, const char* argv[])
  15332. {
  15333. JUCE_AUTORELEASEPOOL
  15334. #if ! JUCE_WINDOWS
  15335. jassert (createInstance != 0);
  15336. juce_Argv0 = argv[0];
  15337. #endif
  15338. #if JUCE_IOS
  15339. return juce_iOSMain (argc, argv);
  15340. #else
  15341. String cmd;
  15342. for (int i = 1; i < argc; ++i)
  15343. cmd << argv[i] << ' ';
  15344. return JUCEApplication::main (cmd);
  15345. #endif
  15346. }
  15347. END_JUCE_NAMESPACE
  15348. /*** End of inlined file: juce_Application.cpp ***/
  15349. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15350. BEGIN_JUCE_NAMESPACE
  15351. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15352. : commandID (commandID_),
  15353. flags (0)
  15354. {
  15355. }
  15356. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15357. const String& description_,
  15358. const String& categoryName_,
  15359. const int flags_) throw()
  15360. {
  15361. shortName = shortName_;
  15362. description = description_;
  15363. categoryName = categoryName_;
  15364. flags = flags_;
  15365. }
  15366. void ApplicationCommandInfo::setActive (const bool b) throw()
  15367. {
  15368. if (b)
  15369. flags &= ~isDisabled;
  15370. else
  15371. flags |= isDisabled;
  15372. }
  15373. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15374. {
  15375. if (b)
  15376. flags |= isTicked;
  15377. else
  15378. flags &= ~isTicked;
  15379. }
  15380. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15381. {
  15382. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15383. }
  15384. END_JUCE_NAMESPACE
  15385. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15386. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15387. BEGIN_JUCE_NAMESPACE
  15388. ApplicationCommandManager::ApplicationCommandManager()
  15389. : firstTarget (0)
  15390. {
  15391. keyMappings = new KeyPressMappingSet (this);
  15392. Desktop::getInstance().addFocusChangeListener (this);
  15393. }
  15394. ApplicationCommandManager::~ApplicationCommandManager()
  15395. {
  15396. Desktop::getInstance().removeFocusChangeListener (this);
  15397. keyMappings = 0;
  15398. }
  15399. void ApplicationCommandManager::clearCommands()
  15400. {
  15401. commands.clear();
  15402. keyMappings->clearAllKeyPresses();
  15403. triggerAsyncUpdate();
  15404. }
  15405. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15406. {
  15407. // zero isn't a valid command ID!
  15408. jassert (newCommand.commandID != 0);
  15409. // the name isn't optional!
  15410. jassert (newCommand.shortName.isNotEmpty());
  15411. if (getCommandForID (newCommand.commandID) == 0)
  15412. {
  15413. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15414. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15415. commands.add (newInfo);
  15416. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15417. triggerAsyncUpdate();
  15418. }
  15419. else
  15420. {
  15421. // trying to re-register the same command with different parameters?
  15422. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15423. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15424. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15425. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15426. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15427. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15428. }
  15429. }
  15430. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15431. {
  15432. if (target != 0)
  15433. {
  15434. Array <CommandID> commandIDs;
  15435. target->getAllCommands (commandIDs);
  15436. for (int i = 0; i < commandIDs.size(); ++i)
  15437. {
  15438. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15439. target->getCommandInfo (info.commandID, info);
  15440. registerCommand (info);
  15441. }
  15442. }
  15443. }
  15444. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15445. {
  15446. for (int i = commands.size(); --i >= 0;)
  15447. {
  15448. if (commands.getUnchecked (i)->commandID == commandID)
  15449. {
  15450. commands.remove (i);
  15451. triggerAsyncUpdate();
  15452. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15453. for (int j = keys.size(); --j >= 0;)
  15454. keyMappings->removeKeyPress (keys.getReference (j));
  15455. }
  15456. }
  15457. }
  15458. void ApplicationCommandManager::commandStatusChanged()
  15459. {
  15460. triggerAsyncUpdate();
  15461. }
  15462. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15463. {
  15464. for (int i = commands.size(); --i >= 0;)
  15465. if (commands.getUnchecked(i)->commandID == commandID)
  15466. return commands.getUnchecked(i);
  15467. return 0;
  15468. }
  15469. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15470. {
  15471. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15472. return (ci != 0) ? ci->shortName : String::empty;
  15473. }
  15474. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15475. {
  15476. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15477. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15478. : String::empty;
  15479. }
  15480. const StringArray ApplicationCommandManager::getCommandCategories() const
  15481. {
  15482. StringArray s;
  15483. for (int i = 0; i < commands.size(); ++i)
  15484. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15485. return s;
  15486. }
  15487. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15488. {
  15489. Array <CommandID> results;
  15490. for (int i = 0; i < commands.size(); ++i)
  15491. if (commands.getUnchecked(i)->categoryName == categoryName)
  15492. results.add (commands.getUnchecked(i)->commandID);
  15493. return results;
  15494. }
  15495. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15496. {
  15497. ApplicationCommandTarget::InvocationInfo info (commandID);
  15498. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15499. return invoke (info, asynchronously);
  15500. }
  15501. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15502. {
  15503. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15504. // manager first..
  15505. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15506. ApplicationCommandInfo commandInfo (0);
  15507. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15508. if (target == 0)
  15509. return false;
  15510. ApplicationCommandTarget::InvocationInfo info (info_);
  15511. info.commandFlags = commandInfo.flags;
  15512. sendListenerInvokeCallback (info);
  15513. const bool ok = target->invoke (info, asynchronously);
  15514. commandStatusChanged();
  15515. return ok;
  15516. }
  15517. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15518. {
  15519. return firstTarget != 0 ? firstTarget
  15520. : findDefaultComponentTarget();
  15521. }
  15522. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15523. {
  15524. firstTarget = newTarget;
  15525. }
  15526. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15527. ApplicationCommandInfo& upToDateInfo)
  15528. {
  15529. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15530. if (target == 0)
  15531. target = JUCEApplication::getInstance();
  15532. if (target != 0)
  15533. target = target->getTargetForCommand (commandID);
  15534. if (target != 0)
  15535. target->getCommandInfo (commandID, upToDateInfo);
  15536. return target;
  15537. }
  15538. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15539. {
  15540. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15541. if (target == 0 && c != 0)
  15542. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15543. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15544. return target;
  15545. }
  15546. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15547. {
  15548. Component* c = Component::getCurrentlyFocusedComponent();
  15549. if (c == 0)
  15550. {
  15551. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15552. if (activeWindow != 0)
  15553. {
  15554. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15555. if (c == 0)
  15556. c = activeWindow;
  15557. }
  15558. }
  15559. if (c == 0 && Process::isForegroundProcess())
  15560. {
  15561. // getting a bit desperate now - try all desktop comps..
  15562. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15563. {
  15564. ApplicationCommandTarget* const target
  15565. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15566. ->getPeer()->getLastFocusedSubcomponent());
  15567. if (target != 0)
  15568. return target;
  15569. }
  15570. }
  15571. if (c != 0)
  15572. {
  15573. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15574. // if we're focused on a ResizableWindow, chances are that it's the content
  15575. // component that really should get the event. And if not, the event will
  15576. // still be passed up to the top level window anyway, so let's send it to the
  15577. // content comp.
  15578. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15579. c = resizableWindow->getContentComponent();
  15580. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15581. if (target != 0)
  15582. return target;
  15583. }
  15584. return JUCEApplication::getInstance();
  15585. }
  15586. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15587. {
  15588. listeners.add (listener);
  15589. }
  15590. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15591. {
  15592. listeners.remove (listener);
  15593. }
  15594. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15595. {
  15596. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15597. }
  15598. void ApplicationCommandManager::handleAsyncUpdate()
  15599. {
  15600. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15601. }
  15602. void ApplicationCommandManager::globalFocusChanged (Component*)
  15603. {
  15604. commandStatusChanged();
  15605. }
  15606. END_JUCE_NAMESPACE
  15607. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15608. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15609. BEGIN_JUCE_NAMESPACE
  15610. ApplicationCommandTarget::ApplicationCommandTarget()
  15611. {
  15612. }
  15613. ApplicationCommandTarget::~ApplicationCommandTarget()
  15614. {
  15615. messageInvoker = 0;
  15616. }
  15617. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15618. {
  15619. if (isCommandActive (info.commandID))
  15620. {
  15621. if (async)
  15622. {
  15623. if (messageInvoker == 0)
  15624. messageInvoker = new CommandTargetMessageInvoker (this);
  15625. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15626. return true;
  15627. }
  15628. else
  15629. {
  15630. const bool success = perform (info);
  15631. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15632. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15633. // returns the command's info.
  15634. return success;
  15635. }
  15636. }
  15637. return false;
  15638. }
  15639. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15640. {
  15641. Component* c = dynamic_cast <Component*> (this);
  15642. if (c != 0)
  15643. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15644. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15645. return 0;
  15646. }
  15647. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15648. {
  15649. ApplicationCommandTarget* target = this;
  15650. int depth = 0;
  15651. while (target != 0)
  15652. {
  15653. Array <CommandID> commandIDs;
  15654. target->getAllCommands (commandIDs);
  15655. if (commandIDs.contains (commandID))
  15656. return target;
  15657. target = target->getNextCommandTarget();
  15658. ++depth;
  15659. jassert (depth < 100); // could be a recursive command chain??
  15660. jassert (target != this); // definitely a recursive command chain!
  15661. if (depth > 100 || target == this)
  15662. break;
  15663. }
  15664. if (target == 0)
  15665. {
  15666. target = JUCEApplication::getInstance();
  15667. if (target != 0)
  15668. {
  15669. Array <CommandID> commandIDs;
  15670. target->getAllCommands (commandIDs);
  15671. if (commandIDs.contains (commandID))
  15672. return target;
  15673. }
  15674. }
  15675. return 0;
  15676. }
  15677. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15678. {
  15679. ApplicationCommandInfo info (commandID);
  15680. info.flags = ApplicationCommandInfo::isDisabled;
  15681. getCommandInfo (commandID, info);
  15682. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15683. }
  15684. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15685. {
  15686. ApplicationCommandTarget* target = this;
  15687. int depth = 0;
  15688. while (target != 0)
  15689. {
  15690. if (target->tryToInvoke (info, async))
  15691. return true;
  15692. target = target->getNextCommandTarget();
  15693. ++depth;
  15694. jassert (depth < 100); // could be a recursive command chain??
  15695. jassert (target != this); // definitely a recursive command chain!
  15696. if (depth > 100 || target == this)
  15697. break;
  15698. }
  15699. if (target == 0)
  15700. {
  15701. target = JUCEApplication::getInstance();
  15702. if (target != 0)
  15703. return target->tryToInvoke (info, async);
  15704. }
  15705. return false;
  15706. }
  15707. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15708. {
  15709. ApplicationCommandTarget::InvocationInfo info (commandID);
  15710. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15711. return invoke (info, asynchronously);
  15712. }
  15713. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15714. : commandID (commandID_),
  15715. commandFlags (0),
  15716. invocationMethod (direct),
  15717. originatingComponent (0),
  15718. isKeyDown (false),
  15719. millisecsSinceKeyPressed (0)
  15720. {
  15721. }
  15722. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15723. : owner (owner_)
  15724. {
  15725. }
  15726. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15727. {
  15728. }
  15729. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15730. {
  15731. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15732. owner->tryToInvoke (*info, false);
  15733. }
  15734. END_JUCE_NAMESPACE
  15735. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15736. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15737. BEGIN_JUCE_NAMESPACE
  15738. juce_ImplementSingleton (ApplicationProperties)
  15739. ApplicationProperties::ApplicationProperties()
  15740. : msBeforeSaving (3000),
  15741. options (PropertiesFile::storeAsBinary),
  15742. commonSettingsAreReadOnly (0),
  15743. processLock (0)
  15744. {
  15745. }
  15746. ApplicationProperties::~ApplicationProperties()
  15747. {
  15748. closeFiles();
  15749. clearSingletonInstance();
  15750. }
  15751. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15752. const String& fileNameSuffix,
  15753. const String& folderName_,
  15754. const int millisecondsBeforeSaving,
  15755. const int propertiesFileOptions,
  15756. InterProcessLock* processLock_)
  15757. {
  15758. appName = applicationName;
  15759. fileSuffix = fileNameSuffix;
  15760. folderName = folderName_;
  15761. msBeforeSaving = millisecondsBeforeSaving;
  15762. options = propertiesFileOptions;
  15763. processLock = processLock_;
  15764. }
  15765. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15766. const bool testCommonSettings,
  15767. const bool showWarningDialogOnFailure)
  15768. {
  15769. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15770. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15771. if (! (userOk && commonOk))
  15772. {
  15773. if (showWarningDialogOnFailure)
  15774. {
  15775. String filenames;
  15776. if (userProps != 0 && ! userOk)
  15777. filenames << '\n' << userProps->getFile().getFullPathName();
  15778. if (commonProps != 0 && ! commonOk)
  15779. filenames << '\n' << commonProps->getFile().getFullPathName();
  15780. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15781. appName + TRANS(" - Unable to save settings"),
  15782. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15783. + appName + TRANS(" needs to be able to write to the following files:\n")
  15784. + filenames
  15785. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15786. }
  15787. return false;
  15788. }
  15789. return true;
  15790. }
  15791. void ApplicationProperties::openFiles()
  15792. {
  15793. // You need to call setStorageParameters() before trying to get hold of the
  15794. // properties!
  15795. jassert (appName.isNotEmpty());
  15796. if (appName.isNotEmpty())
  15797. {
  15798. if (userProps == 0)
  15799. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15800. false, msBeforeSaving, options, processLock);
  15801. if (commonProps == 0)
  15802. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15803. true, msBeforeSaving, options, processLock);
  15804. userProps->setFallbackPropertySet (commonProps);
  15805. }
  15806. }
  15807. PropertiesFile* ApplicationProperties::getUserSettings()
  15808. {
  15809. if (userProps == 0)
  15810. openFiles();
  15811. return userProps;
  15812. }
  15813. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15814. {
  15815. if (commonProps == 0)
  15816. openFiles();
  15817. if (returnUserPropsIfReadOnly)
  15818. {
  15819. if (commonSettingsAreReadOnly == 0)
  15820. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15821. if (commonSettingsAreReadOnly > 0)
  15822. return userProps;
  15823. }
  15824. return commonProps;
  15825. }
  15826. bool ApplicationProperties::saveIfNeeded()
  15827. {
  15828. return (userProps == 0 || userProps->saveIfNeeded())
  15829. && (commonProps == 0 || commonProps->saveIfNeeded());
  15830. }
  15831. void ApplicationProperties::closeFiles()
  15832. {
  15833. userProps = 0;
  15834. commonProps = 0;
  15835. }
  15836. END_JUCE_NAMESPACE
  15837. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15838. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15839. BEGIN_JUCE_NAMESPACE
  15840. namespace PropertyFileConstants
  15841. {
  15842. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15843. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15844. static const char* const fileTag = "PROPERTIES";
  15845. static const char* const valueTag = "VALUE";
  15846. static const char* const nameAttribute = "name";
  15847. static const char* const valueAttribute = "val";
  15848. }
  15849. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15850. const int options_, InterProcessLock* const processLock_)
  15851. : PropertySet (ignoreCaseOfKeyNames),
  15852. file (f),
  15853. timerInterval (millisecondsBeforeSaving),
  15854. options (options_),
  15855. loadedOk (false),
  15856. needsWriting (false),
  15857. processLock (processLock_)
  15858. {
  15859. // You need to correctly specify just one storage format for the file
  15860. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15861. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15862. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15863. ProcessScopedLock pl (createProcessLock());
  15864. if (pl != 0 && ! pl->isLocked())
  15865. return; // locking failure..
  15866. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15867. if (fileStream != 0)
  15868. {
  15869. int magicNumber = fileStream->readInt();
  15870. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15871. {
  15872. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15873. magicNumber = PropertyFileConstants::magicNumber;
  15874. }
  15875. if (magicNumber == PropertyFileConstants::magicNumber)
  15876. {
  15877. loadedOk = true;
  15878. BufferedInputStream in (fileStream.release(), 2048, true);
  15879. int numValues = in.readInt();
  15880. while (--numValues >= 0 && ! in.isExhausted())
  15881. {
  15882. const String key (in.readString());
  15883. const String value (in.readString());
  15884. jassert (key.isNotEmpty());
  15885. if (key.isNotEmpty())
  15886. getAllProperties().set (key, value);
  15887. }
  15888. }
  15889. else
  15890. {
  15891. // Not a binary props file - let's see if it's XML..
  15892. fileStream = 0;
  15893. XmlDocument parser (f);
  15894. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15895. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15896. {
  15897. doc = parser.getDocumentElement();
  15898. if (doc != 0)
  15899. {
  15900. loadedOk = true;
  15901. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15902. {
  15903. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15904. if (name.isNotEmpty())
  15905. {
  15906. getAllProperties().set (name,
  15907. e->getFirstChildElement() != 0
  15908. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15909. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15910. }
  15911. }
  15912. }
  15913. else
  15914. {
  15915. // must be a pretty broken XML file we're trying to parse here,
  15916. // or a sign that this object needs an InterProcessLock,
  15917. // or just a failure reading the file. This last reason is why
  15918. // we don't jassertfalse here.
  15919. }
  15920. }
  15921. }
  15922. }
  15923. else
  15924. {
  15925. loadedOk = ! f.exists();
  15926. }
  15927. }
  15928. PropertiesFile::~PropertiesFile()
  15929. {
  15930. if (! saveIfNeeded())
  15931. jassertfalse;
  15932. }
  15933. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15934. {
  15935. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15936. }
  15937. bool PropertiesFile::saveIfNeeded()
  15938. {
  15939. const ScopedLock sl (getLock());
  15940. return (! needsWriting) || save();
  15941. }
  15942. bool PropertiesFile::needsToBeSaved() const
  15943. {
  15944. const ScopedLock sl (getLock());
  15945. return needsWriting;
  15946. }
  15947. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15948. {
  15949. const ScopedLock sl (getLock());
  15950. needsWriting = needsToBeSaved_;
  15951. }
  15952. bool PropertiesFile::save()
  15953. {
  15954. const ScopedLock sl (getLock());
  15955. stopTimer();
  15956. if (file == File::nonexistent
  15957. || file.isDirectory()
  15958. || ! file.getParentDirectory().createDirectory())
  15959. return false;
  15960. if ((options & storeAsXML) != 0)
  15961. {
  15962. XmlElement doc (PropertyFileConstants::fileTag);
  15963. for (int i = 0; i < getAllProperties().size(); ++i)
  15964. {
  15965. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15966. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15967. // if the value seems to contain xml, store it as such..
  15968. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15969. if (childElement != 0)
  15970. e->addChildElement (childElement);
  15971. else
  15972. e->setAttribute (PropertyFileConstants::valueAttribute,
  15973. getAllProperties().getAllValues() [i]);
  15974. }
  15975. ProcessScopedLock pl (createProcessLock());
  15976. if (pl != 0 && ! pl->isLocked())
  15977. return false; // locking failure..
  15978. if (doc.writeToFile (file, String::empty))
  15979. {
  15980. needsWriting = false;
  15981. return true;
  15982. }
  15983. }
  15984. else
  15985. {
  15986. ProcessScopedLock pl (createProcessLock());
  15987. if (pl != 0 && ! pl->isLocked())
  15988. return false; // locking failure..
  15989. TemporaryFile tempFile (file);
  15990. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15991. if (out != 0)
  15992. {
  15993. if ((options & storeAsCompressedBinary) != 0)
  15994. {
  15995. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15996. out->flush();
  15997. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15998. }
  15999. else
  16000. {
  16001. // have you set up the storage option flags correctly?
  16002. jassert ((options & storeAsBinary) != 0);
  16003. out->writeInt (PropertyFileConstants::magicNumber);
  16004. }
  16005. const int numProperties = getAllProperties().size();
  16006. out->writeInt (numProperties);
  16007. for (int i = 0; i < numProperties; ++i)
  16008. {
  16009. out->writeString (getAllProperties().getAllKeys() [i]);
  16010. out->writeString (getAllProperties().getAllValues() [i]);
  16011. }
  16012. out = 0;
  16013. if (tempFile.overwriteTargetFileWithTemporary())
  16014. {
  16015. needsWriting = false;
  16016. return true;
  16017. }
  16018. }
  16019. }
  16020. return false;
  16021. }
  16022. void PropertiesFile::timerCallback()
  16023. {
  16024. saveIfNeeded();
  16025. }
  16026. void PropertiesFile::propertyChanged()
  16027. {
  16028. sendChangeMessage();
  16029. needsWriting = true;
  16030. if (timerInterval > 0)
  16031. startTimer (timerInterval);
  16032. else if (timerInterval == 0)
  16033. saveIfNeeded();
  16034. }
  16035. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16036. const String& fileNameSuffix,
  16037. const String& folderName,
  16038. const bool commonToAllUsers)
  16039. {
  16040. // mustn't have illegal characters in this name..
  16041. jassert (applicationName == File::createLegalFileName (applicationName));
  16042. #if JUCE_MAC || JUCE_IOS
  16043. File dir (commonToAllUsers ? "/Library/Preferences"
  16044. : "~/Library/Preferences");
  16045. if (folderName.isNotEmpty())
  16046. dir = dir.getChildFile (folderName);
  16047. #endif
  16048. #ifdef JUCE_LINUX
  16049. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16050. + (folderName.isNotEmpty() ? folderName
  16051. : ("." + applicationName)));
  16052. #endif
  16053. #if JUCE_WINDOWS
  16054. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16055. : File::userApplicationDataDirectory));
  16056. if (dir == File::nonexistent)
  16057. return File::nonexistent;
  16058. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16059. : applicationName);
  16060. #endif
  16061. return dir.getChildFile (applicationName)
  16062. .withFileExtension (fileNameSuffix);
  16063. }
  16064. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16065. const String& fileNameSuffix,
  16066. const String& folderName,
  16067. const bool commonToAllUsers,
  16068. const int millisecondsBeforeSaving,
  16069. const int propertiesFileOptions,
  16070. InterProcessLock* processLock_)
  16071. {
  16072. const File file (getDefaultAppSettingsFile (applicationName,
  16073. fileNameSuffix,
  16074. folderName,
  16075. commonToAllUsers));
  16076. jassert (file != File::nonexistent);
  16077. if (file == File::nonexistent)
  16078. return 0;
  16079. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16080. }
  16081. END_JUCE_NAMESPACE
  16082. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16083. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16084. BEGIN_JUCE_NAMESPACE
  16085. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16086. const String& fileWildcard_,
  16087. const String& openFileDialogTitle_,
  16088. const String& saveFileDialogTitle_)
  16089. : changedSinceSave (false),
  16090. fileExtension (fileExtension_),
  16091. fileWildcard (fileWildcard_),
  16092. openFileDialogTitle (openFileDialogTitle_),
  16093. saveFileDialogTitle (saveFileDialogTitle_)
  16094. {
  16095. }
  16096. FileBasedDocument::~FileBasedDocument()
  16097. {
  16098. }
  16099. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16100. {
  16101. if (changedSinceSave != hasChanged)
  16102. {
  16103. changedSinceSave = hasChanged;
  16104. sendChangeMessage();
  16105. }
  16106. }
  16107. void FileBasedDocument::changed()
  16108. {
  16109. changedSinceSave = true;
  16110. sendChangeMessage();
  16111. }
  16112. void FileBasedDocument::setFile (const File& newFile)
  16113. {
  16114. if (documentFile != newFile)
  16115. {
  16116. documentFile = newFile;
  16117. changed();
  16118. }
  16119. }
  16120. bool FileBasedDocument::loadFrom (const File& newFile,
  16121. const bool showMessageOnFailure)
  16122. {
  16123. MouseCursor::showWaitCursor();
  16124. const File oldFile (documentFile);
  16125. documentFile = newFile;
  16126. String error;
  16127. if (newFile.existsAsFile())
  16128. {
  16129. error = loadDocument (newFile);
  16130. if (error.isEmpty())
  16131. {
  16132. setChangedFlag (false);
  16133. MouseCursor::hideWaitCursor();
  16134. setLastDocumentOpened (newFile);
  16135. return true;
  16136. }
  16137. }
  16138. else
  16139. {
  16140. error = "The file doesn't exist";
  16141. }
  16142. documentFile = oldFile;
  16143. MouseCursor::hideWaitCursor();
  16144. if (showMessageOnFailure)
  16145. {
  16146. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16147. TRANS("Failed to open file..."),
  16148. TRANS("There was an error while trying to load the file:\n\n")
  16149. + newFile.getFullPathName()
  16150. + "\n\n"
  16151. + error);
  16152. }
  16153. return false;
  16154. }
  16155. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16156. {
  16157. FileChooser fc (openFileDialogTitle,
  16158. getLastDocumentOpened(),
  16159. fileWildcard);
  16160. if (fc.browseForFileToOpen())
  16161. return loadFrom (fc.getResult(), showMessageOnFailure);
  16162. return false;
  16163. }
  16164. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16165. const bool showMessageOnFailure)
  16166. {
  16167. return saveAs (documentFile,
  16168. false,
  16169. askUserForFileIfNotSpecified,
  16170. showMessageOnFailure);
  16171. }
  16172. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16173. const bool warnAboutOverwritingExistingFiles,
  16174. const bool askUserForFileIfNotSpecified,
  16175. const bool showMessageOnFailure)
  16176. {
  16177. if (newFile == File::nonexistent)
  16178. {
  16179. if (askUserForFileIfNotSpecified)
  16180. {
  16181. return saveAsInteractive (true);
  16182. }
  16183. else
  16184. {
  16185. // can't save to an unspecified file
  16186. jassertfalse;
  16187. return failedToWriteToFile;
  16188. }
  16189. }
  16190. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16191. {
  16192. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16193. TRANS("File already exists"),
  16194. TRANS("There's already a file called:\n\n")
  16195. + newFile.getFullPathName()
  16196. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16197. TRANS("overwrite"),
  16198. TRANS("cancel")))
  16199. {
  16200. return userCancelledSave;
  16201. }
  16202. }
  16203. MouseCursor::showWaitCursor();
  16204. const File oldFile (documentFile);
  16205. documentFile = newFile;
  16206. String error (saveDocument (newFile));
  16207. if (error.isEmpty())
  16208. {
  16209. setChangedFlag (false);
  16210. MouseCursor::hideWaitCursor();
  16211. return savedOk;
  16212. }
  16213. documentFile = oldFile;
  16214. MouseCursor::hideWaitCursor();
  16215. if (showMessageOnFailure)
  16216. {
  16217. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16218. TRANS("Error writing to file..."),
  16219. TRANS("An error occurred while trying to save \"")
  16220. + getDocumentTitle()
  16221. + TRANS("\" to the file:\n\n")
  16222. + newFile.getFullPathName()
  16223. + "\n\n"
  16224. + error);
  16225. }
  16226. return failedToWriteToFile;
  16227. }
  16228. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16229. {
  16230. if (! hasChangedSinceSaved())
  16231. return savedOk;
  16232. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16233. TRANS("Closing document..."),
  16234. TRANS("Do you want to save the changes to \"")
  16235. + getDocumentTitle() + "\"?",
  16236. TRANS("save"),
  16237. TRANS("discard changes"),
  16238. TRANS("cancel"));
  16239. if (r == 1)
  16240. {
  16241. // save changes
  16242. return save (true, true);
  16243. }
  16244. else if (r == 2)
  16245. {
  16246. // discard changes
  16247. return savedOk;
  16248. }
  16249. return userCancelledSave;
  16250. }
  16251. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16252. {
  16253. File f;
  16254. if (documentFile.existsAsFile())
  16255. f = documentFile;
  16256. else
  16257. f = getLastDocumentOpened();
  16258. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16259. if (legalFilename.isEmpty())
  16260. legalFilename = "unnamed";
  16261. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16262. f = f.getSiblingFile (legalFilename);
  16263. else
  16264. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16265. f = f.withFileExtension (fileExtension)
  16266. .getNonexistentSibling (true);
  16267. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16268. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16269. {
  16270. File chosen (fc.getResult());
  16271. if (chosen.getFileExtension().isEmpty())
  16272. {
  16273. chosen = chosen.withFileExtension (fileExtension);
  16274. if (chosen.exists())
  16275. {
  16276. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16277. TRANS("File already exists"),
  16278. TRANS("There's already a file called:")
  16279. + "\n\n" + chosen.getFullPathName()
  16280. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16281. TRANS("overwrite"),
  16282. TRANS("cancel")))
  16283. {
  16284. return userCancelledSave;
  16285. }
  16286. }
  16287. }
  16288. setLastDocumentOpened (chosen);
  16289. return saveAs (chosen, false, false, true);
  16290. }
  16291. return userCancelledSave;
  16292. }
  16293. END_JUCE_NAMESPACE
  16294. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16295. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16296. BEGIN_JUCE_NAMESPACE
  16297. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16298. : maxNumberOfItems (10)
  16299. {
  16300. }
  16301. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16302. {
  16303. }
  16304. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16305. {
  16306. maxNumberOfItems = jmax (1, newMaxNumber);
  16307. while (getNumFiles() > maxNumberOfItems)
  16308. files.remove (getNumFiles() - 1);
  16309. }
  16310. int RecentlyOpenedFilesList::getNumFiles() const
  16311. {
  16312. return files.size();
  16313. }
  16314. const File RecentlyOpenedFilesList::getFile (const int index) const
  16315. {
  16316. return File (files [index]);
  16317. }
  16318. void RecentlyOpenedFilesList::clear()
  16319. {
  16320. files.clear();
  16321. }
  16322. void RecentlyOpenedFilesList::addFile (const File& file)
  16323. {
  16324. const String path (file.getFullPathName());
  16325. files.removeString (path, true);
  16326. files.insert (0, path);
  16327. setMaxNumberOfItems (maxNumberOfItems);
  16328. }
  16329. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16330. {
  16331. for (int i = getNumFiles(); --i >= 0;)
  16332. if (! getFile(i).exists())
  16333. files.remove (i);
  16334. }
  16335. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16336. const int baseItemId,
  16337. const bool showFullPaths,
  16338. const bool dontAddNonExistentFiles,
  16339. const File** filesToAvoid)
  16340. {
  16341. int num = 0;
  16342. for (int i = 0; i < getNumFiles(); ++i)
  16343. {
  16344. const File f (getFile(i));
  16345. if ((! dontAddNonExistentFiles) || f.exists())
  16346. {
  16347. bool needsAvoiding = false;
  16348. if (filesToAvoid != 0)
  16349. {
  16350. const File** avoid = filesToAvoid;
  16351. while (*avoid != 0)
  16352. {
  16353. if (f == **avoid)
  16354. {
  16355. needsAvoiding = true;
  16356. break;
  16357. }
  16358. ++avoid;
  16359. }
  16360. }
  16361. if (! needsAvoiding)
  16362. {
  16363. menuToAddTo.addItem (baseItemId + i,
  16364. showFullPaths ? f.getFullPathName()
  16365. : f.getFileName());
  16366. ++num;
  16367. }
  16368. }
  16369. }
  16370. return num;
  16371. }
  16372. const String RecentlyOpenedFilesList::toString() const
  16373. {
  16374. return files.joinIntoString ("\n");
  16375. }
  16376. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16377. {
  16378. clear();
  16379. files.addLines (stringifiedVersion);
  16380. setMaxNumberOfItems (maxNumberOfItems);
  16381. }
  16382. END_JUCE_NAMESPACE
  16383. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16384. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16385. BEGIN_JUCE_NAMESPACE
  16386. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16387. const int minimumTransactions)
  16388. : totalUnitsStored (0),
  16389. nextIndex (0),
  16390. newTransaction (true),
  16391. reentrancyCheck (false)
  16392. {
  16393. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16394. minimumTransactions);
  16395. }
  16396. UndoManager::~UndoManager()
  16397. {
  16398. clearUndoHistory();
  16399. }
  16400. void UndoManager::clearUndoHistory()
  16401. {
  16402. transactions.clear();
  16403. transactionNames.clear();
  16404. totalUnitsStored = 0;
  16405. nextIndex = 0;
  16406. sendChangeMessage();
  16407. }
  16408. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16409. {
  16410. return totalUnitsStored;
  16411. }
  16412. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16413. const int minimumTransactions)
  16414. {
  16415. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16416. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16417. }
  16418. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16419. {
  16420. if (command_ != 0)
  16421. {
  16422. ScopedPointer<UndoableAction> command (command_);
  16423. if (actionName.isNotEmpty())
  16424. currentTransactionName = actionName;
  16425. if (reentrancyCheck)
  16426. {
  16427. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16428. // undo() methods, or else these actions won't actually get done.
  16429. return false;
  16430. }
  16431. else if (command->perform())
  16432. {
  16433. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16434. if (commandSet != 0 && ! newTransaction)
  16435. {
  16436. UndoableAction* lastAction = commandSet->getLast();
  16437. if (lastAction != 0)
  16438. {
  16439. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16440. if (coalescedAction != 0)
  16441. {
  16442. command = coalescedAction;
  16443. totalUnitsStored -= lastAction->getSizeInUnits();
  16444. commandSet->removeLast();
  16445. }
  16446. }
  16447. }
  16448. else
  16449. {
  16450. commandSet = new OwnedArray<UndoableAction>();
  16451. transactions.insert (nextIndex, commandSet);
  16452. transactionNames.insert (nextIndex, currentTransactionName);
  16453. ++nextIndex;
  16454. }
  16455. totalUnitsStored += command->getSizeInUnits();
  16456. commandSet->add (command.release());
  16457. newTransaction = false;
  16458. while (nextIndex < transactions.size())
  16459. {
  16460. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16461. for (int i = lastSet->size(); --i >= 0;)
  16462. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16463. transactions.removeLast();
  16464. transactionNames.remove (transactionNames.size() - 1);
  16465. }
  16466. while (nextIndex > 0
  16467. && totalUnitsStored > maxNumUnitsToKeep
  16468. && transactions.size() > minimumTransactionsToKeep)
  16469. {
  16470. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16471. for (int i = firstSet->size(); --i >= 0;)
  16472. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16473. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16474. transactions.remove (0);
  16475. transactionNames.remove (0);
  16476. --nextIndex;
  16477. }
  16478. sendChangeMessage();
  16479. return true;
  16480. }
  16481. }
  16482. return false;
  16483. }
  16484. void UndoManager::beginNewTransaction (const String& actionName)
  16485. {
  16486. newTransaction = true;
  16487. currentTransactionName = actionName;
  16488. }
  16489. void UndoManager::setCurrentTransactionName (const String& newName)
  16490. {
  16491. currentTransactionName = newName;
  16492. }
  16493. bool UndoManager::canUndo() const
  16494. {
  16495. return nextIndex > 0;
  16496. }
  16497. bool UndoManager::canRedo() const
  16498. {
  16499. return nextIndex < transactions.size();
  16500. }
  16501. const String UndoManager::getUndoDescription() const
  16502. {
  16503. return transactionNames [nextIndex - 1];
  16504. }
  16505. const String UndoManager::getRedoDescription() const
  16506. {
  16507. return transactionNames [nextIndex];
  16508. }
  16509. bool UndoManager::undo()
  16510. {
  16511. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16512. if (commandSet == 0)
  16513. return false;
  16514. reentrancyCheck = true;
  16515. bool failed = false;
  16516. for (int i = commandSet->size(); --i >= 0;)
  16517. {
  16518. if (! commandSet->getUnchecked(i)->undo())
  16519. {
  16520. jassertfalse;
  16521. failed = true;
  16522. break;
  16523. }
  16524. }
  16525. reentrancyCheck = false;
  16526. if (failed)
  16527. clearUndoHistory();
  16528. else
  16529. --nextIndex;
  16530. beginNewTransaction();
  16531. sendChangeMessage();
  16532. return true;
  16533. }
  16534. bool UndoManager::redo()
  16535. {
  16536. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16537. if (commandSet == 0)
  16538. return false;
  16539. reentrancyCheck = true;
  16540. bool failed = false;
  16541. for (int i = 0; i < commandSet->size(); ++i)
  16542. {
  16543. if (! commandSet->getUnchecked(i)->perform())
  16544. {
  16545. jassertfalse;
  16546. failed = true;
  16547. break;
  16548. }
  16549. }
  16550. reentrancyCheck = false;
  16551. if (failed)
  16552. clearUndoHistory();
  16553. else
  16554. ++nextIndex;
  16555. beginNewTransaction();
  16556. sendChangeMessage();
  16557. return true;
  16558. }
  16559. bool UndoManager::undoCurrentTransactionOnly()
  16560. {
  16561. return newTransaction ? false : undo();
  16562. }
  16563. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16564. {
  16565. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16566. if (commandSet != 0 && ! newTransaction)
  16567. {
  16568. for (int i = 0; i < commandSet->size(); ++i)
  16569. actionsFound.add (commandSet->getUnchecked(i));
  16570. }
  16571. }
  16572. int UndoManager::getNumActionsInCurrentTransaction() const
  16573. {
  16574. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16575. if (commandSet != 0 && ! newTransaction)
  16576. return commandSet->size();
  16577. return 0;
  16578. }
  16579. END_JUCE_NAMESPACE
  16580. /*** End of inlined file: juce_UndoManager.cpp ***/
  16581. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16582. BEGIN_JUCE_NAMESPACE
  16583. static const char* const aiffFormatName = "AIFF file";
  16584. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16585. class AiffAudioFormatReader : public AudioFormatReader
  16586. {
  16587. public:
  16588. int bytesPerFrame;
  16589. int64 dataChunkStart;
  16590. bool littleEndian;
  16591. AiffAudioFormatReader (InputStream* in)
  16592. : AudioFormatReader (in, TRANS (aiffFormatName))
  16593. {
  16594. if (input->readInt() == chunkName ("FORM"))
  16595. {
  16596. const int len = input->readIntBigEndian();
  16597. const int64 end = input->getPosition() + len;
  16598. const int nextType = input->readInt();
  16599. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16600. {
  16601. bool hasGotVer = false;
  16602. bool hasGotData = false;
  16603. bool hasGotType = false;
  16604. while (input->getPosition() < end)
  16605. {
  16606. const int type = input->readInt();
  16607. const uint32 length = (uint32) input->readIntBigEndian();
  16608. const int64 chunkEnd = input->getPosition() + length;
  16609. if (type == chunkName ("FVER"))
  16610. {
  16611. hasGotVer = true;
  16612. const int ver = input->readIntBigEndian();
  16613. if (ver != 0 && ver != (int) 0xa2805140)
  16614. break;
  16615. }
  16616. else if (type == chunkName ("COMM"))
  16617. {
  16618. hasGotType = true;
  16619. numChannels = (unsigned int) input->readShortBigEndian();
  16620. lengthInSamples = input->readIntBigEndian();
  16621. bitsPerSample = input->readShortBigEndian();
  16622. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16623. unsigned char sampleRateBytes[10];
  16624. input->read (sampleRateBytes, 10);
  16625. const int byte0 = sampleRateBytes[0];
  16626. if ((byte0 & 0x80) != 0
  16627. || byte0 <= 0x3F || byte0 > 0x40
  16628. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16629. break;
  16630. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16631. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16632. sampleRate = (int) sampRate;
  16633. if (length <= 18)
  16634. {
  16635. // some types don't have a chunk large enough to include a compression
  16636. // type, so assume it's just big-endian pcm
  16637. littleEndian = false;
  16638. }
  16639. else
  16640. {
  16641. const int compType = input->readInt();
  16642. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16643. {
  16644. littleEndian = false;
  16645. }
  16646. else if (compType == chunkName ("sowt"))
  16647. {
  16648. littleEndian = true;
  16649. }
  16650. else
  16651. {
  16652. sampleRate = 0;
  16653. break;
  16654. }
  16655. }
  16656. }
  16657. else if (type == chunkName ("SSND"))
  16658. {
  16659. hasGotData = true;
  16660. const int offset = input->readIntBigEndian();
  16661. dataChunkStart = input->getPosition() + 4 + offset;
  16662. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16663. }
  16664. else if ((hasGotVer && hasGotData && hasGotType)
  16665. || chunkEnd < input->getPosition()
  16666. || input->isExhausted())
  16667. {
  16668. break;
  16669. }
  16670. input->setPosition (chunkEnd);
  16671. }
  16672. }
  16673. }
  16674. }
  16675. ~AiffAudioFormatReader()
  16676. {
  16677. }
  16678. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16679. int64 startSampleInFile, int numSamples)
  16680. {
  16681. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16682. if (samplesAvailable < numSamples)
  16683. {
  16684. for (int i = numDestChannels; --i >= 0;)
  16685. if (destSamples[i] != 0)
  16686. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16687. numSamples = (int) samplesAvailable;
  16688. }
  16689. if (numSamples <= 0)
  16690. return true;
  16691. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16692. while (numSamples > 0)
  16693. {
  16694. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16695. char tempBuffer [tempBufSize];
  16696. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16697. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16698. if (bytesRead < numThisTime * bytesPerFrame)
  16699. {
  16700. jassert (bytesRead >= 0);
  16701. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16702. }
  16703. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16704. if (littleEndian)
  16705. {
  16706. switch (bitsPerSample)
  16707. {
  16708. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16709. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16710. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16711. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16712. default: jassertfalse; break;
  16713. }
  16714. }
  16715. else
  16716. {
  16717. switch (bitsPerSample)
  16718. {
  16719. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16720. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16721. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16722. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16723. default: jassertfalse; break;
  16724. }
  16725. }
  16726. startOffsetInDestBuffer += numThisTime;
  16727. numSamples -= numThisTime;
  16728. }
  16729. return true;
  16730. }
  16731. private:
  16732. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16733. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16734. };
  16735. class AiffAudioFormatWriter : public AudioFormatWriter
  16736. {
  16737. public:
  16738. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16739. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16740. lengthInSamples (0),
  16741. bytesWritten (0),
  16742. writeFailed (false)
  16743. {
  16744. headerPosition = out->getPosition();
  16745. writeHeader();
  16746. }
  16747. ~AiffAudioFormatWriter()
  16748. {
  16749. if ((bytesWritten & 1) != 0)
  16750. output->writeByte (0);
  16751. writeHeader();
  16752. }
  16753. bool write (const int** data, int numSamples)
  16754. {
  16755. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16756. if (writeFailed)
  16757. return false;
  16758. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16759. tempBlock.ensureSize (bytes, false);
  16760. switch (bitsPerSample)
  16761. {
  16762. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16763. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16764. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16765. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16766. default: jassertfalse; break;
  16767. }
  16768. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16769. || ! output->write (tempBlock.getData(), bytes))
  16770. {
  16771. // failed to write to disk, so let's try writing the header.
  16772. // If it's just run out of disk space, then if it does manage
  16773. // to write the header, we'll still have a useable file..
  16774. writeHeader();
  16775. writeFailed = true;
  16776. return false;
  16777. }
  16778. else
  16779. {
  16780. bytesWritten += bytes;
  16781. lengthInSamples += numSamples;
  16782. return true;
  16783. }
  16784. }
  16785. private:
  16786. MemoryBlock tempBlock;
  16787. uint32 lengthInSamples, bytesWritten;
  16788. int64 headerPosition;
  16789. bool writeFailed;
  16790. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16791. void writeHeader()
  16792. {
  16793. const bool couldSeekOk = output->setPosition (headerPosition);
  16794. (void) couldSeekOk;
  16795. // if this fails, you've given it an output stream that can't seek! It needs
  16796. // to be able to seek back to write the header
  16797. jassert (couldSeekOk);
  16798. const int headerLen = 54;
  16799. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16800. audioBytes += (audioBytes & 1);
  16801. output->writeInt (chunkName ("FORM"));
  16802. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16803. output->writeInt (chunkName ("AIFF"));
  16804. output->writeInt (chunkName ("COMM"));
  16805. output->writeIntBigEndian (18);
  16806. output->writeShortBigEndian ((short) numChannels);
  16807. output->writeIntBigEndian (lengthInSamples);
  16808. output->writeShortBigEndian ((short) bitsPerSample);
  16809. uint8 sampleRateBytes[10];
  16810. zeromem (sampleRateBytes, 10);
  16811. if (sampleRate <= 1)
  16812. {
  16813. sampleRateBytes[0] = 0x3f;
  16814. sampleRateBytes[1] = 0xff;
  16815. sampleRateBytes[2] = 0x80;
  16816. }
  16817. else
  16818. {
  16819. int mask = 0x40000000;
  16820. sampleRateBytes[0] = 0x40;
  16821. if (sampleRate >= mask)
  16822. {
  16823. jassertfalse;
  16824. sampleRateBytes[1] = 0x1d;
  16825. }
  16826. else
  16827. {
  16828. int n = (int) sampleRate;
  16829. int i;
  16830. for (i = 0; i <= 32 ; ++i)
  16831. {
  16832. if ((n & mask) != 0)
  16833. break;
  16834. mask >>= 1;
  16835. }
  16836. n = n << (i + 1);
  16837. sampleRateBytes[1] = (uint8) (29 - i);
  16838. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16839. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16840. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16841. sampleRateBytes[5] = (uint8) (n & 0xff);
  16842. }
  16843. }
  16844. output->write (sampleRateBytes, 10);
  16845. output->writeInt (chunkName ("SSND"));
  16846. output->writeIntBigEndian (audioBytes + 8);
  16847. output->writeInt (0);
  16848. output->writeInt (0);
  16849. jassert (output->getPosition() == headerLen);
  16850. }
  16851. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16852. };
  16853. AiffAudioFormat::AiffAudioFormat()
  16854. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16855. {
  16856. }
  16857. AiffAudioFormat::~AiffAudioFormat()
  16858. {
  16859. }
  16860. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16861. {
  16862. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16863. return Array <int> (rates);
  16864. }
  16865. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16866. {
  16867. const int depths[] = { 8, 16, 24, 0 };
  16868. return Array <int> (depths);
  16869. }
  16870. bool AiffAudioFormat::canDoStereo() { return true; }
  16871. bool AiffAudioFormat::canDoMono() { return true; }
  16872. #if JUCE_MAC
  16873. bool AiffAudioFormat::canHandleFile (const File& f)
  16874. {
  16875. if (AudioFormat::canHandleFile (f))
  16876. return true;
  16877. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16878. return type == 'AIFF' || type == 'AIFC'
  16879. || type == 'aiff' || type == 'aifc';
  16880. }
  16881. #endif
  16882. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16883. {
  16884. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16885. if (w->sampleRate != 0)
  16886. return w.release();
  16887. if (! deleteStreamIfOpeningFails)
  16888. w->input = 0;
  16889. return 0;
  16890. }
  16891. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16892. double sampleRate,
  16893. unsigned int numberOfChannels,
  16894. int bitsPerSample,
  16895. const StringPairArray& /*metadataValues*/,
  16896. int /*qualityOptionIndex*/)
  16897. {
  16898. if (getPossibleBitDepths().contains (bitsPerSample))
  16899. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16900. return 0;
  16901. }
  16902. END_JUCE_NAMESPACE
  16903. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16904. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16905. BEGIN_JUCE_NAMESPACE
  16906. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16907. : formatName (name),
  16908. fileExtensions (extensions)
  16909. {
  16910. }
  16911. AudioFormat::~AudioFormat()
  16912. {
  16913. }
  16914. bool AudioFormat::canHandleFile (const File& f)
  16915. {
  16916. for (int i = 0; i < fileExtensions.size(); ++i)
  16917. if (f.hasFileExtension (fileExtensions[i]))
  16918. return true;
  16919. return false;
  16920. }
  16921. const String& AudioFormat::getFormatName() const { return formatName; }
  16922. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16923. bool AudioFormat::isCompressed() { return false; }
  16924. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16925. END_JUCE_NAMESPACE
  16926. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16927. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16928. BEGIN_JUCE_NAMESPACE
  16929. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16930. const String& formatName_)
  16931. : sampleRate (0),
  16932. bitsPerSample (0),
  16933. lengthInSamples (0),
  16934. numChannels (0),
  16935. usesFloatingPointData (false),
  16936. input (in),
  16937. formatName (formatName_)
  16938. {
  16939. }
  16940. AudioFormatReader::~AudioFormatReader()
  16941. {
  16942. delete input;
  16943. }
  16944. bool AudioFormatReader::read (int* const* destSamples,
  16945. int numDestChannels,
  16946. int64 startSampleInSource,
  16947. int numSamplesToRead,
  16948. const bool fillLeftoverChannelsWithCopies)
  16949. {
  16950. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16951. int startOffsetInDestBuffer = 0;
  16952. if (startSampleInSource < 0)
  16953. {
  16954. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16955. for (int i = numDestChannels; --i >= 0;)
  16956. if (destSamples[i] != 0)
  16957. zeromem (destSamples[i], sizeof (int) * silence);
  16958. startOffsetInDestBuffer += silence;
  16959. numSamplesToRead -= silence;
  16960. startSampleInSource = 0;
  16961. }
  16962. if (numSamplesToRead <= 0)
  16963. return true;
  16964. if (! readSamples (const_cast<int**> (destSamples),
  16965. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16966. startSampleInSource, numSamplesToRead))
  16967. return false;
  16968. if (numDestChannels > (int) numChannels)
  16969. {
  16970. if (fillLeftoverChannelsWithCopies)
  16971. {
  16972. int* lastFullChannel = destSamples[0];
  16973. for (int i = (int) numChannels; --i > 0;)
  16974. {
  16975. if (destSamples[i] != 0)
  16976. {
  16977. lastFullChannel = destSamples[i];
  16978. break;
  16979. }
  16980. }
  16981. if (lastFullChannel != 0)
  16982. for (int i = numChannels; i < numDestChannels; ++i)
  16983. if (destSamples[i] != 0)
  16984. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16985. }
  16986. else
  16987. {
  16988. for (int i = numChannels; i < numDestChannels; ++i)
  16989. if (destSamples[i] != 0)
  16990. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16991. }
  16992. }
  16993. return true;
  16994. }
  16995. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16996. int64 numSamples,
  16997. float& lowestLeft, float& highestLeft,
  16998. float& lowestRight, float& highestRight)
  16999. {
  17000. if (numSamples <= 0)
  17001. {
  17002. lowestLeft = 0;
  17003. lowestRight = 0;
  17004. highestLeft = 0;
  17005. highestRight = 0;
  17006. return;
  17007. }
  17008. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17009. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17010. int* tempBuffer[3];
  17011. tempBuffer[0] = tempSpace.getData();
  17012. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17013. tempBuffer[2] = 0;
  17014. if (usesFloatingPointData)
  17015. {
  17016. float lmin = 1.0e6f;
  17017. float lmax = -lmin;
  17018. float rmin = lmin;
  17019. float rmax = lmax;
  17020. while (numSamples > 0)
  17021. {
  17022. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17023. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17024. numSamples -= numToDo;
  17025. startSampleInFile += numToDo;
  17026. float bufMin, bufMax;
  17027. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  17028. lmin = jmin (lmin, bufMin);
  17029. lmax = jmax (lmax, bufMax);
  17030. if (numChannels > 1)
  17031. {
  17032. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  17033. rmin = jmin (rmin, bufMin);
  17034. rmax = jmax (rmax, bufMax);
  17035. }
  17036. }
  17037. if (numChannels <= 1)
  17038. {
  17039. rmax = lmax;
  17040. rmin = lmin;
  17041. }
  17042. lowestLeft = lmin;
  17043. highestLeft = lmax;
  17044. lowestRight = rmin;
  17045. highestRight = rmax;
  17046. }
  17047. else
  17048. {
  17049. int lmax = std::numeric_limits<int>::min();
  17050. int lmin = std::numeric_limits<int>::max();
  17051. int rmax = std::numeric_limits<int>::min();
  17052. int rmin = std::numeric_limits<int>::max();
  17053. while (numSamples > 0)
  17054. {
  17055. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17056. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  17057. break;
  17058. numSamples -= numToDo;
  17059. startSampleInFile += numToDo;
  17060. for (int j = numChannels; --j >= 0;)
  17061. {
  17062. int bufMin, bufMax;
  17063. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  17064. if (j == 0)
  17065. {
  17066. lmax = jmax (lmax, bufMax);
  17067. lmin = jmin (lmin, bufMin);
  17068. }
  17069. else
  17070. {
  17071. rmax = jmax (rmax, bufMax);
  17072. rmin = jmin (rmin, bufMin);
  17073. }
  17074. }
  17075. }
  17076. if (numChannels <= 1)
  17077. {
  17078. rmax = lmax;
  17079. rmin = lmin;
  17080. }
  17081. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17082. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17083. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17084. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17085. }
  17086. }
  17087. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17088. int64 numSamplesToSearch,
  17089. const double magnitudeRangeMinimum,
  17090. const double magnitudeRangeMaximum,
  17091. const int minimumConsecutiveSamples)
  17092. {
  17093. if (numSamplesToSearch == 0)
  17094. return -1;
  17095. const int bufferSize = 4096;
  17096. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17097. int* tempBuffer[3];
  17098. tempBuffer[0] = tempSpace.getData();
  17099. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17100. tempBuffer[2] = 0;
  17101. int consecutive = 0;
  17102. int64 firstMatchPos = -1;
  17103. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17104. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17105. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17106. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17107. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17108. while (numSamplesToSearch != 0)
  17109. {
  17110. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17111. int64 bufferStart = startSample;
  17112. if (numSamplesToSearch < 0)
  17113. bufferStart -= numThisTime;
  17114. if (bufferStart >= (int) lengthInSamples)
  17115. break;
  17116. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17117. int num = numThisTime;
  17118. while (--num >= 0)
  17119. {
  17120. if (numSamplesToSearch < 0)
  17121. --startSample;
  17122. bool matches = false;
  17123. const int index = (int) (startSample - bufferStart);
  17124. if (usesFloatingPointData)
  17125. {
  17126. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17127. if (sample1 >= magnitudeRangeMinimum
  17128. && sample1 <= magnitudeRangeMaximum)
  17129. {
  17130. matches = true;
  17131. }
  17132. else if (numChannels > 1)
  17133. {
  17134. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17135. matches = (sample2 >= magnitudeRangeMinimum
  17136. && sample2 <= magnitudeRangeMaximum);
  17137. }
  17138. }
  17139. else
  17140. {
  17141. const int sample1 = abs (tempBuffer[0] [index]);
  17142. if (sample1 >= intMagnitudeRangeMinimum
  17143. && sample1 <= intMagnitudeRangeMaximum)
  17144. {
  17145. matches = true;
  17146. }
  17147. else if (numChannels > 1)
  17148. {
  17149. const int sample2 = abs (tempBuffer[1][index]);
  17150. matches = (sample2 >= intMagnitudeRangeMinimum
  17151. && sample2 <= intMagnitudeRangeMaximum);
  17152. }
  17153. }
  17154. if (matches)
  17155. {
  17156. if (firstMatchPos < 0)
  17157. firstMatchPos = startSample;
  17158. if (++consecutive >= minimumConsecutiveSamples)
  17159. {
  17160. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17161. return -1;
  17162. return firstMatchPos;
  17163. }
  17164. }
  17165. else
  17166. {
  17167. consecutive = 0;
  17168. firstMatchPos = -1;
  17169. }
  17170. if (numSamplesToSearch > 0)
  17171. ++startSample;
  17172. }
  17173. if (numSamplesToSearch > 0)
  17174. numSamplesToSearch -= numThisTime;
  17175. else
  17176. numSamplesToSearch += numThisTime;
  17177. }
  17178. return -1;
  17179. }
  17180. END_JUCE_NAMESPACE
  17181. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17182. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17183. BEGIN_JUCE_NAMESPACE
  17184. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17185. const String& formatName_,
  17186. const double rate,
  17187. const unsigned int numChannels_,
  17188. const unsigned int bitsPerSample_)
  17189. : sampleRate (rate),
  17190. numChannels (numChannels_),
  17191. bitsPerSample (bitsPerSample_),
  17192. usesFloatingPointData (false),
  17193. output (out),
  17194. formatName (formatName_)
  17195. {
  17196. }
  17197. AudioFormatWriter::~AudioFormatWriter()
  17198. {
  17199. delete output;
  17200. }
  17201. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17202. int64 startSample,
  17203. int64 numSamplesToRead)
  17204. {
  17205. const int bufferSize = 16384;
  17206. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17207. int* buffers [128];
  17208. zerostruct (buffers);
  17209. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17210. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17211. if (numSamplesToRead < 0)
  17212. numSamplesToRead = reader.lengthInSamples;
  17213. while (numSamplesToRead > 0)
  17214. {
  17215. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17216. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17217. return false;
  17218. if (reader.usesFloatingPointData != isFloatingPoint())
  17219. {
  17220. int** bufferChan = buffers;
  17221. while (*bufferChan != 0)
  17222. {
  17223. int* b = *bufferChan++;
  17224. if (isFloatingPoint())
  17225. {
  17226. // int -> float
  17227. const double factor = 1.0 / std::numeric_limits<int>::max();
  17228. for (int i = 0; i < numToDo; ++i)
  17229. ((float*) b)[i] = (float) (factor * b[i]);
  17230. }
  17231. else
  17232. {
  17233. // float -> int
  17234. for (int i = 0; i < numToDo; ++i)
  17235. {
  17236. const double samp = *(const float*) b;
  17237. if (samp <= -1.0)
  17238. *b++ = std::numeric_limits<int>::min();
  17239. else if (samp >= 1.0)
  17240. *b++ = std::numeric_limits<int>::max();
  17241. else
  17242. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17243. }
  17244. }
  17245. }
  17246. }
  17247. if (! write (const_cast<const int**> (buffers), numToDo))
  17248. return false;
  17249. numSamplesToRead -= numToDo;
  17250. startSample += numToDo;
  17251. }
  17252. return true;
  17253. }
  17254. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17255. {
  17256. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17257. while (numSamplesToRead > 0)
  17258. {
  17259. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17260. AudioSourceChannelInfo info;
  17261. info.buffer = &tempBuffer;
  17262. info.startSample = 0;
  17263. info.numSamples = numToDo;
  17264. info.clearActiveBufferRegion();
  17265. source.getNextAudioBlock (info);
  17266. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17267. return false;
  17268. numSamplesToRead -= numToDo;
  17269. }
  17270. return true;
  17271. }
  17272. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17273. {
  17274. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17275. if (numSamples <= 0)
  17276. return true;
  17277. HeapBlock<int> tempBuffer;
  17278. HeapBlock<int*> chans (numChannels + 1);
  17279. chans [numChannels] = 0;
  17280. if (isFloatingPoint())
  17281. {
  17282. for (int i = numChannels; --i >= 0;)
  17283. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17284. }
  17285. else
  17286. {
  17287. tempBuffer.malloc (numSamples * numChannels);
  17288. for (unsigned int i = 0; i < numChannels; ++i)
  17289. {
  17290. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17291. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17292. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17293. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17294. destData.convertSamples (sourceData, numSamples);
  17295. }
  17296. }
  17297. return write ((const int**) chans.getData(), numSamples);
  17298. }
  17299. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17300. public AbstractFifo
  17301. {
  17302. public:
  17303. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17304. : AbstractFifo (bufferSize),
  17305. buffer (numChannels, bufferSize),
  17306. timeSliceThread (timeSliceThread_),
  17307. writer (writer_),
  17308. thumbnailToUpdate (0),
  17309. samplesWritten (0),
  17310. isRunning (true)
  17311. {
  17312. timeSliceThread.addTimeSliceClient (this);
  17313. }
  17314. ~Buffer()
  17315. {
  17316. isRunning = false;
  17317. timeSliceThread.removeTimeSliceClient (this);
  17318. while (useTimeSlice())
  17319. {}
  17320. }
  17321. bool write (const float** data, int numSamples)
  17322. {
  17323. if (numSamples <= 0 || ! isRunning)
  17324. return true;
  17325. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17326. int start1, size1, start2, size2;
  17327. prepareToWrite (numSamples, start1, size1, start2, size2);
  17328. if (size1 + size2 < numSamples)
  17329. return false;
  17330. for (int i = buffer.getNumChannels(); --i >= 0;)
  17331. {
  17332. buffer.copyFrom (i, start1, data[i], size1);
  17333. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17334. }
  17335. finishedWrite (size1 + size2);
  17336. timeSliceThread.notify();
  17337. return true;
  17338. }
  17339. bool useTimeSlice()
  17340. {
  17341. const int numToDo = getTotalSize() / 4;
  17342. int start1, size1, start2, size2;
  17343. prepareToRead (numToDo, start1, size1, start2, size2);
  17344. if (size1 <= 0)
  17345. return false;
  17346. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17347. const ScopedLock sl (thumbnailLock);
  17348. if (thumbnailToUpdate != 0)
  17349. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  17350. samplesWritten += size1;
  17351. if (size2 > 0)
  17352. {
  17353. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17354. if (thumbnailToUpdate != 0)
  17355. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  17356. samplesWritten += size2;
  17357. }
  17358. finishedRead (size1 + size2);
  17359. return true;
  17360. }
  17361. void setThumbnail (AudioThumbnail* thumb)
  17362. {
  17363. if (thumb != 0)
  17364. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  17365. const ScopedLock sl (thumbnailLock);
  17366. thumbnailToUpdate = thumb;
  17367. samplesWritten = 0;
  17368. }
  17369. private:
  17370. AudioSampleBuffer buffer;
  17371. TimeSliceThread& timeSliceThread;
  17372. ScopedPointer<AudioFormatWriter> writer;
  17373. CriticalSection thumbnailLock;
  17374. AudioThumbnail* thumbnailToUpdate;
  17375. int64 samplesWritten;
  17376. volatile bool isRunning;
  17377. JUCE_DECLARE_NON_COPYABLE (Buffer);
  17378. };
  17379. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17380. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17381. {
  17382. }
  17383. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17384. {
  17385. }
  17386. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17387. {
  17388. return buffer->write (data, numSamples);
  17389. }
  17390. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  17391. {
  17392. buffer->setThumbnail (thumb);
  17393. }
  17394. END_JUCE_NAMESPACE
  17395. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17396. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17397. BEGIN_JUCE_NAMESPACE
  17398. AudioFormatManager::AudioFormatManager()
  17399. : defaultFormatIndex (0)
  17400. {
  17401. }
  17402. AudioFormatManager::~AudioFormatManager()
  17403. {
  17404. }
  17405. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17406. {
  17407. jassert (newFormat != 0);
  17408. if (newFormat != 0)
  17409. {
  17410. #if JUCE_DEBUG
  17411. for (int i = getNumKnownFormats(); --i >= 0;)
  17412. {
  17413. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17414. {
  17415. jassertfalse; // trying to add the same format twice!
  17416. }
  17417. }
  17418. #endif
  17419. if (makeThisTheDefaultFormat)
  17420. defaultFormatIndex = getNumKnownFormats();
  17421. knownFormats.add (newFormat);
  17422. }
  17423. }
  17424. void AudioFormatManager::registerBasicFormats()
  17425. {
  17426. #if JUCE_MAC
  17427. registerFormat (new AiffAudioFormat(), true);
  17428. registerFormat (new WavAudioFormat(), false);
  17429. #else
  17430. registerFormat (new WavAudioFormat(), true);
  17431. registerFormat (new AiffAudioFormat(), false);
  17432. #endif
  17433. #if JUCE_USE_FLAC
  17434. registerFormat (new FlacAudioFormat(), false);
  17435. #endif
  17436. #if JUCE_USE_OGGVORBIS
  17437. registerFormat (new OggVorbisAudioFormat(), false);
  17438. #endif
  17439. }
  17440. void AudioFormatManager::clearFormats()
  17441. {
  17442. knownFormats.clear();
  17443. defaultFormatIndex = 0;
  17444. }
  17445. int AudioFormatManager::getNumKnownFormats() const
  17446. {
  17447. return knownFormats.size();
  17448. }
  17449. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17450. {
  17451. return knownFormats [index];
  17452. }
  17453. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17454. {
  17455. return getKnownFormat (defaultFormatIndex);
  17456. }
  17457. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17458. {
  17459. String e (fileExtension);
  17460. if (! e.startsWithChar ('.'))
  17461. e = "." + e;
  17462. for (int i = 0; i < getNumKnownFormats(); ++i)
  17463. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17464. return getKnownFormat(i);
  17465. return 0;
  17466. }
  17467. const String AudioFormatManager::getWildcardForAllFormats() const
  17468. {
  17469. StringArray allExtensions;
  17470. int i;
  17471. for (i = 0; i < getNumKnownFormats(); ++i)
  17472. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17473. allExtensions.trim();
  17474. allExtensions.removeEmptyStrings();
  17475. String s;
  17476. for (i = 0; i < allExtensions.size(); ++i)
  17477. {
  17478. s << '*';
  17479. if (! allExtensions[i].startsWithChar ('.'))
  17480. s << '.';
  17481. s << allExtensions[i];
  17482. if (i < allExtensions.size() - 1)
  17483. s << ';';
  17484. }
  17485. return s;
  17486. }
  17487. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17488. {
  17489. // you need to actually register some formats before the manager can
  17490. // use them to open a file!
  17491. jassert (getNumKnownFormats() > 0);
  17492. for (int i = 0; i < getNumKnownFormats(); ++i)
  17493. {
  17494. AudioFormat* const af = getKnownFormat(i);
  17495. if (af->canHandleFile (file))
  17496. {
  17497. InputStream* const in = file.createInputStream();
  17498. if (in != 0)
  17499. {
  17500. AudioFormatReader* const r = af->createReaderFor (in, true);
  17501. if (r != 0)
  17502. return r;
  17503. }
  17504. }
  17505. }
  17506. return 0;
  17507. }
  17508. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17509. {
  17510. // you need to actually register some formats before the manager can
  17511. // use them to open a file!
  17512. jassert (getNumKnownFormats() > 0);
  17513. ScopedPointer <InputStream> in (audioFileStream);
  17514. if (in != 0)
  17515. {
  17516. const int64 originalStreamPos = in->getPosition();
  17517. for (int i = 0; i < getNumKnownFormats(); ++i)
  17518. {
  17519. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17520. if (r != 0)
  17521. {
  17522. in.release();
  17523. return r;
  17524. }
  17525. in->setPosition (originalStreamPos);
  17526. // the stream that is passed-in must be capable of being repositioned so
  17527. // that all the formats can have a go at opening it.
  17528. jassert (in->getPosition() == originalStreamPos);
  17529. }
  17530. }
  17531. return 0;
  17532. }
  17533. END_JUCE_NAMESPACE
  17534. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17535. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17536. BEGIN_JUCE_NAMESPACE
  17537. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17538. const int64 startSample_,
  17539. const int64 length_,
  17540. const bool deleteSourceWhenDeleted_)
  17541. : AudioFormatReader (0, source_->getFormatName()),
  17542. source (source_),
  17543. startSample (startSample_),
  17544. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17545. {
  17546. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17547. sampleRate = source->sampleRate;
  17548. bitsPerSample = source->bitsPerSample;
  17549. lengthInSamples = length;
  17550. numChannels = source->numChannels;
  17551. usesFloatingPointData = source->usesFloatingPointData;
  17552. }
  17553. AudioSubsectionReader::~AudioSubsectionReader()
  17554. {
  17555. if (deleteSourceWhenDeleted)
  17556. delete source;
  17557. }
  17558. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17559. int64 startSampleInFile, int numSamples)
  17560. {
  17561. if (startSampleInFile + numSamples > length)
  17562. {
  17563. for (int i = numDestChannels; --i >= 0;)
  17564. if (destSamples[i] != 0)
  17565. zeromem (destSamples[i], sizeof (int) * numSamples);
  17566. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17567. if (numSamples <= 0)
  17568. return true;
  17569. }
  17570. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17571. startSampleInFile + startSample, numSamples);
  17572. }
  17573. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17574. int64 numSamples,
  17575. float& lowestLeft,
  17576. float& highestLeft,
  17577. float& lowestRight,
  17578. float& highestRight)
  17579. {
  17580. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17581. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17582. source->readMaxLevels (startSampleInFile + startSample,
  17583. numSamples,
  17584. lowestLeft,
  17585. highestLeft,
  17586. lowestRight,
  17587. highestRight);
  17588. }
  17589. END_JUCE_NAMESPACE
  17590. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17591. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17592. BEGIN_JUCE_NAMESPACE
  17593. struct AudioThumbnail::MinMaxValue
  17594. {
  17595. char minValue;
  17596. char maxValue;
  17597. MinMaxValue() : minValue (0), maxValue (0)
  17598. {
  17599. }
  17600. inline void set (const char newMin, const char newMax) throw()
  17601. {
  17602. minValue = newMin;
  17603. maxValue = newMax;
  17604. }
  17605. inline void setFloat (const float newMin, const float newMax) throw()
  17606. {
  17607. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17608. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17609. if (maxValue == minValue)
  17610. maxValue = (char) jmin (127, maxValue + 1);
  17611. }
  17612. inline bool isNonZero() const throw()
  17613. {
  17614. return maxValue > minValue;
  17615. }
  17616. inline int getPeak() const throw()
  17617. {
  17618. return jmax (std::abs ((int) minValue),
  17619. std::abs ((int) maxValue));
  17620. }
  17621. inline void read (InputStream& input)
  17622. {
  17623. minValue = input.readByte();
  17624. maxValue = input.readByte();
  17625. }
  17626. inline void write (OutputStream& output)
  17627. {
  17628. output.writeByte (minValue);
  17629. output.writeByte (maxValue);
  17630. }
  17631. };
  17632. class AudioThumbnail::LevelDataSource : public TimeSliceClient,
  17633. public Timer
  17634. {
  17635. public:
  17636. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17637. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17638. hashCode (hash), owner (owner_), reader (newReader)
  17639. {
  17640. }
  17641. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17642. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17643. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17644. {
  17645. }
  17646. ~LevelDataSource()
  17647. {
  17648. owner.cache.removeTimeSliceClient (this);
  17649. }
  17650. enum { timeBeforeDeletingReader = 2000 };
  17651. void initialise (int64 numSamplesFinished_)
  17652. {
  17653. const ScopedLock sl (readerLock);
  17654. numSamplesFinished = numSamplesFinished_;
  17655. createReader();
  17656. if (reader != 0)
  17657. {
  17658. lengthInSamples = reader->lengthInSamples;
  17659. numChannels = reader->numChannels;
  17660. sampleRate = reader->sampleRate;
  17661. if (lengthInSamples <= 0)
  17662. reader = 0;
  17663. else if (! isFullyLoaded())
  17664. owner.cache.addTimeSliceClient (this);
  17665. }
  17666. }
  17667. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17668. {
  17669. const ScopedLock sl (readerLock);
  17670. createReader();
  17671. if (reader != 0)
  17672. {
  17673. float l[4] = { 0 };
  17674. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17675. levels.clearQuick();
  17676. levels.addArray ((const float*) l, 4);
  17677. }
  17678. }
  17679. void releaseResources()
  17680. {
  17681. const ScopedLock sl (readerLock);
  17682. reader = 0;
  17683. }
  17684. bool useTimeSlice()
  17685. {
  17686. if (isFullyLoaded())
  17687. {
  17688. if (reader != 0 && source != 0)
  17689. startTimer (timeBeforeDeletingReader);
  17690. owner.cache.removeTimeSliceClient (this);
  17691. return false;
  17692. }
  17693. stopTimer();
  17694. bool justFinished = false;
  17695. {
  17696. const ScopedLock sl (readerLock);
  17697. createReader();
  17698. if (reader != 0)
  17699. {
  17700. if (! readNextBlock())
  17701. return true;
  17702. justFinished = true;
  17703. }
  17704. }
  17705. if (justFinished)
  17706. owner.cache.storeThumb (owner, hashCode);
  17707. return false;
  17708. }
  17709. void timerCallback()
  17710. {
  17711. stopTimer();
  17712. releaseResources();
  17713. }
  17714. bool isFullyLoaded() const throw()
  17715. {
  17716. return numSamplesFinished >= lengthInSamples;
  17717. }
  17718. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17719. {
  17720. return (int) (originalSample / owner.samplesPerThumbSample);
  17721. }
  17722. int64 lengthInSamples, numSamplesFinished;
  17723. double sampleRate;
  17724. int numChannels;
  17725. int64 hashCode;
  17726. private:
  17727. AudioThumbnail& owner;
  17728. ScopedPointer <InputSource> source;
  17729. ScopedPointer <AudioFormatReader> reader;
  17730. CriticalSection readerLock;
  17731. void createReader()
  17732. {
  17733. if (reader == 0 && source != 0)
  17734. {
  17735. InputStream* audioFileStream = source->createInputStream();
  17736. if (audioFileStream != 0)
  17737. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17738. }
  17739. }
  17740. bool readNextBlock()
  17741. {
  17742. jassert (reader != 0);
  17743. if (! isFullyLoaded())
  17744. {
  17745. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17746. if (numToDo > 0)
  17747. {
  17748. int64 startSample = numSamplesFinished;
  17749. const int firstThumbIndex = sampleToThumbSample (startSample);
  17750. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17751. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17752. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17753. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17754. for (int i = 0; i < numThumbSamps; ++i)
  17755. {
  17756. float lowestLeft, highestLeft, lowestRight, highestRight;
  17757. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17758. lowestLeft, highestLeft, lowestRight, highestRight);
  17759. levels[0][i].setFloat (lowestLeft, highestLeft);
  17760. levels[1][i].setFloat (lowestRight, highestRight);
  17761. }
  17762. {
  17763. const ScopedUnlock su (readerLock);
  17764. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17765. }
  17766. numSamplesFinished += numToDo;
  17767. }
  17768. }
  17769. return isFullyLoaded();
  17770. }
  17771. };
  17772. class AudioThumbnail::ThumbData
  17773. {
  17774. public:
  17775. ThumbData (const int numThumbSamples)
  17776. : peakLevel (-1)
  17777. {
  17778. ensureSize (numThumbSamples);
  17779. }
  17780. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17781. {
  17782. jassert (thumbSampleIndex < data.size());
  17783. return data.getRawDataPointer() + thumbSampleIndex;
  17784. }
  17785. int getSize() const throw()
  17786. {
  17787. return data.size();
  17788. }
  17789. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17790. {
  17791. if (startSample >= 0)
  17792. {
  17793. endSample = jmin (endSample, data.size() - 1);
  17794. char mx = -128;
  17795. char mn = 127;
  17796. while (startSample <= endSample)
  17797. {
  17798. const MinMaxValue& v = data.getReference (startSample);
  17799. if (v.minValue < mn) mn = v.minValue;
  17800. if (v.maxValue > mx) mx = v.maxValue;
  17801. ++startSample;
  17802. }
  17803. if (mn <= mx)
  17804. {
  17805. result.set (mn, mx);
  17806. return;
  17807. }
  17808. }
  17809. result.set (1, 0);
  17810. }
  17811. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17812. {
  17813. resetPeak();
  17814. if (startIndex + numValues > data.size())
  17815. ensureSize (startIndex + numValues);
  17816. MinMaxValue* const dest = getData (startIndex);
  17817. for (int i = 0; i < numValues; ++i)
  17818. dest[i] = source[i];
  17819. }
  17820. void resetPeak()
  17821. {
  17822. peakLevel = -1;
  17823. }
  17824. int getPeak()
  17825. {
  17826. if (peakLevel < 0)
  17827. {
  17828. for (int i = 0; i < data.size(); ++i)
  17829. {
  17830. const int peak = data[i].getPeak();
  17831. if (peak > peakLevel)
  17832. peakLevel = peak;
  17833. }
  17834. }
  17835. return peakLevel;
  17836. }
  17837. private:
  17838. Array <MinMaxValue> data;
  17839. int peakLevel;
  17840. void ensureSize (const int thumbSamples)
  17841. {
  17842. const int extraNeeded = thumbSamples - data.size();
  17843. if (extraNeeded > 0)
  17844. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17845. }
  17846. };
  17847. class AudioThumbnail::CachedWindow
  17848. {
  17849. public:
  17850. CachedWindow()
  17851. : cachedStart (0), cachedTimePerPixel (0),
  17852. numChannelsCached (0), numSamplesCached (0),
  17853. cacheNeedsRefilling (true)
  17854. {
  17855. }
  17856. void invalidate()
  17857. {
  17858. cacheNeedsRefilling = true;
  17859. }
  17860. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17861. const double startTime, const double endTime,
  17862. const int channelNum, const float verticalZoomFactor,
  17863. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17864. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17865. {
  17866. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17867. numChannels, samplesPerThumbSample, levelData, channels);
  17868. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17869. {
  17870. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17871. if (! clip.isEmpty())
  17872. {
  17873. const float topY = (float) area.getY();
  17874. const float bottomY = (float) area.getBottom();
  17875. const float midY = (topY + bottomY) * 0.5f;
  17876. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17877. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17878. int x = clip.getX();
  17879. for (int w = clip.getWidth(); --w >= 0;)
  17880. {
  17881. if (cacheData->isNonZero())
  17882. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17883. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17884. ++x;
  17885. ++cacheData;
  17886. }
  17887. }
  17888. }
  17889. }
  17890. private:
  17891. Array <MinMaxValue> data;
  17892. double cachedStart, cachedTimePerPixel;
  17893. int numChannelsCached, numSamplesCached;
  17894. bool cacheNeedsRefilling;
  17895. void refillCache (const int numSamples, double startTime, const double endTime,
  17896. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17897. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17898. {
  17899. const double timePerPixel = (endTime - startTime) / numSamples;
  17900. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17901. {
  17902. invalidate();
  17903. return;
  17904. }
  17905. if (numSamples == numSamplesCached
  17906. && numChannelsCached == numChannels
  17907. && startTime == cachedStart
  17908. && timePerPixel == cachedTimePerPixel
  17909. && ! cacheNeedsRefilling)
  17910. {
  17911. return;
  17912. }
  17913. numSamplesCached = numSamples;
  17914. numChannelsCached = numChannels;
  17915. cachedStart = startTime;
  17916. cachedTimePerPixel = timePerPixel;
  17917. cacheNeedsRefilling = false;
  17918. ensureSize (numSamples);
  17919. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17920. {
  17921. int sample = roundToInt (startTime * sampleRate);
  17922. Array<float> levels;
  17923. int i;
  17924. for (i = 0; i < numSamples; ++i)
  17925. {
  17926. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17927. if (sample >= 0)
  17928. {
  17929. if (sample >= levelData->lengthInSamples)
  17930. break;
  17931. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17932. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17933. for (int chan = 0; chan < numChans; ++chan)
  17934. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17935. levels.getUnchecked (chan * 2 + 1));
  17936. }
  17937. startTime += timePerPixel;
  17938. sample = nextSample;
  17939. }
  17940. numSamplesCached = i;
  17941. }
  17942. else
  17943. {
  17944. jassert (channels.size() == numChannelsCached);
  17945. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17946. {
  17947. ThumbData* channelData = channels.getUnchecked (channelNum);
  17948. MinMaxValue* cacheData = getData (channelNum, 0);
  17949. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17950. startTime = cachedStart;
  17951. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17952. for (int i = numSamples; --i >= 0;)
  17953. {
  17954. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17955. channelData->getMinMax (sample, nextSample, *cacheData);
  17956. ++cacheData;
  17957. startTime += timePerPixel;
  17958. sample = nextSample;
  17959. }
  17960. }
  17961. }
  17962. }
  17963. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17964. {
  17965. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17966. return data.getRawDataPointer() + channelNum * numSamplesCached
  17967. + cacheIndex;
  17968. }
  17969. void ensureSize (const int numSamples)
  17970. {
  17971. const int itemsRequired = numSamples * numChannelsCached;
  17972. if (data.size() < itemsRequired)
  17973. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17974. }
  17975. };
  17976. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17977. AudioFormatManager& formatManagerToUse_,
  17978. AudioThumbnailCache& cacheToUse)
  17979. : formatManagerToUse (formatManagerToUse_),
  17980. cache (cacheToUse),
  17981. window (new CachedWindow()),
  17982. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17983. totalSamples (0),
  17984. numChannels (0),
  17985. sampleRate (0)
  17986. {
  17987. }
  17988. AudioThumbnail::~AudioThumbnail()
  17989. {
  17990. clear();
  17991. }
  17992. void AudioThumbnail::clear()
  17993. {
  17994. source = 0;
  17995. const ScopedLock sl (lock);
  17996. window->invalidate();
  17997. channels.clear();
  17998. totalSamples = numSamplesFinished = 0;
  17999. numChannels = 0;
  18000. sampleRate = 0;
  18001. sendChangeMessage();
  18002. }
  18003. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  18004. {
  18005. clear();
  18006. numChannels = newNumChannels;
  18007. sampleRate = newSampleRate;
  18008. totalSamples = totalSamplesInSource;
  18009. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  18010. }
  18011. void AudioThumbnail::createChannels (const int length)
  18012. {
  18013. while (channels.size() < numChannels)
  18014. channels.add (new ThumbData (length));
  18015. }
  18016. void AudioThumbnail::loadFrom (InputStream& input)
  18017. {
  18018. clear();
  18019. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  18020. return;
  18021. samplesPerThumbSample = input.readInt();
  18022. totalSamples = input.readInt64(); // Total number of source samples.
  18023. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  18024. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  18025. numChannels = input.readInt(); // Number of audio channels.
  18026. sampleRate = input.readInt(); // Source sample rate.
  18027. input.skipNextBytes (16); // reserved area
  18028. createChannels (numThumbnailSamples);
  18029. for (int i = 0; i < numThumbnailSamples; ++i)
  18030. for (int chan = 0; chan < numChannels; ++chan)
  18031. channels.getUnchecked(chan)->getData(i)->read (input);
  18032. }
  18033. void AudioThumbnail::saveTo (OutputStream& output) const
  18034. {
  18035. const ScopedLock sl (lock);
  18036. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  18037. output.write ("jatm", 4);
  18038. output.writeInt (samplesPerThumbSample);
  18039. output.writeInt64 (totalSamples);
  18040. output.writeInt64 (numSamplesFinished);
  18041. output.writeInt (numThumbnailSamples);
  18042. output.writeInt (numChannels);
  18043. output.writeInt ((int) sampleRate);
  18044. output.writeInt64 (0);
  18045. output.writeInt64 (0);
  18046. for (int i = 0; i < numThumbnailSamples; ++i)
  18047. for (int chan = 0; chan < numChannels; ++chan)
  18048. channels.getUnchecked(chan)->getData(i)->write (output);
  18049. }
  18050. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  18051. {
  18052. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  18053. numSamplesFinished = 0;
  18054. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  18055. {
  18056. source = newSource; // (make sure this isn't done before loadThumb is called)
  18057. source->lengthInSamples = totalSamples;
  18058. source->sampleRate = sampleRate;
  18059. source->numChannels = numChannels;
  18060. source->numSamplesFinished = numSamplesFinished;
  18061. }
  18062. else
  18063. {
  18064. source = newSource; // (make sure this isn't done before loadThumb is called)
  18065. const ScopedLock sl (lock);
  18066. source->initialise (numSamplesFinished);
  18067. totalSamples = source->lengthInSamples;
  18068. sampleRate = source->sampleRate;
  18069. numChannels = source->numChannels;
  18070. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  18071. }
  18072. return sampleRate > 0 && totalSamples > 0;
  18073. }
  18074. bool AudioThumbnail::setSource (InputSource* const newSource)
  18075. {
  18076. clear();
  18077. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  18078. }
  18079. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  18080. {
  18081. clear();
  18082. if (newReader != 0)
  18083. setDataSource (new LevelDataSource (*this, newReader, hash));
  18084. }
  18085. int64 AudioThumbnail::getHashCode() const
  18086. {
  18087. return source == 0 ? 0 : source->hashCode;
  18088. }
  18089. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  18090. int startOffsetInBuffer, int numSamples)
  18091. {
  18092. jassert (startSample >= 0);
  18093. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  18094. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  18095. const int numToDo = lastThumbIndex - firstThumbIndex;
  18096. if (numToDo > 0)
  18097. {
  18098. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  18099. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  18100. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  18101. for (int chan = 0; chan < numChans; ++chan)
  18102. {
  18103. const float* const source = incoming.getSampleData (chan, startOffsetInBuffer);
  18104. MinMaxValue* const dest = thumbData + numToDo * chan;
  18105. thumbChannels [chan] = dest;
  18106. for (int i = 0; i < numToDo; ++i)
  18107. {
  18108. float low, high;
  18109. const int start = i * samplesPerThumbSample;
  18110. findMinAndMax (source + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  18111. dest[i].setFloat (low, high);
  18112. }
  18113. }
  18114. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  18115. }
  18116. }
  18117. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  18118. {
  18119. const ScopedLock sl (lock);
  18120. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  18121. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  18122. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  18123. totalSamples = jmax (numSamplesFinished, totalSamples);
  18124. window->invalidate();
  18125. sendChangeMessage();
  18126. }
  18127. int AudioThumbnail::getNumChannels() const throw()
  18128. {
  18129. return numChannels;
  18130. }
  18131. double AudioThumbnail::getTotalLength() const throw()
  18132. {
  18133. return totalSamples / sampleRate;
  18134. }
  18135. bool AudioThumbnail::isFullyLoaded() const throw()
  18136. {
  18137. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  18138. }
  18139. float AudioThumbnail::getApproximatePeak() const
  18140. {
  18141. int peak = 0;
  18142. for (int i = channels.size(); --i >= 0;)
  18143. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  18144. return jlimit (0, 127, peak) / 127.0f;
  18145. }
  18146. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  18147. double endTime, int channelNum, float verticalZoomFactor)
  18148. {
  18149. const ScopedLock sl (lock);
  18150. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  18151. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  18152. }
  18153. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  18154. double endTimeSeconds, float verticalZoomFactor)
  18155. {
  18156. for (int i = 0; i < numChannels; ++i)
  18157. {
  18158. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  18159. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  18160. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  18161. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  18162. }
  18163. }
  18164. END_JUCE_NAMESPACE
  18165. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18166. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18167. BEGIN_JUCE_NAMESPACE
  18168. struct ThumbnailCacheEntry
  18169. {
  18170. int64 hash;
  18171. uint32 lastUsed;
  18172. MemoryBlock data;
  18173. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  18174. };
  18175. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18176. : TimeSliceThread ("thumb cache"),
  18177. maxNumThumbsToStore (maxNumThumbsToStore_)
  18178. {
  18179. startThread (2);
  18180. }
  18181. AudioThumbnailCache::~AudioThumbnailCache()
  18182. {
  18183. }
  18184. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  18185. {
  18186. for (int i = thumbs.size(); --i >= 0;)
  18187. if (thumbs.getUnchecked(i)->hash == hash)
  18188. return thumbs.getUnchecked(i);
  18189. return 0;
  18190. }
  18191. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18192. {
  18193. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18194. if (te != 0)
  18195. {
  18196. te->lastUsed = Time::getMillisecondCounter();
  18197. MemoryInputStream in (te->data, false);
  18198. thumb.loadFrom (in);
  18199. return true;
  18200. }
  18201. return false;
  18202. }
  18203. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18204. const int64 hashCode)
  18205. {
  18206. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18207. if (te == 0)
  18208. {
  18209. te = new ThumbnailCacheEntry();
  18210. te->hash = hashCode;
  18211. if (thumbs.size() < maxNumThumbsToStore)
  18212. {
  18213. thumbs.add (te);
  18214. }
  18215. else
  18216. {
  18217. int oldest = 0;
  18218. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  18219. for (int i = thumbs.size(); --i >= 0;)
  18220. {
  18221. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  18222. {
  18223. oldest = i;
  18224. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  18225. }
  18226. }
  18227. thumbs.set (oldest, te);
  18228. }
  18229. }
  18230. te->lastUsed = Time::getMillisecondCounter();
  18231. MemoryOutputStream out (te->data, false);
  18232. thumb.saveTo (out);
  18233. }
  18234. void AudioThumbnailCache::clear()
  18235. {
  18236. thumbs.clear();
  18237. }
  18238. END_JUCE_NAMESPACE
  18239. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18240. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18241. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18242. #if ! JUCE_WINDOWS
  18243. #include <QuickTime/Movies.h>
  18244. #include <QuickTime/QTML.h>
  18245. #include <QuickTime/QuickTimeComponents.h>
  18246. #include <QuickTime/MediaHandlers.h>
  18247. #include <QuickTime/ImageCodec.h>
  18248. #else
  18249. #if JUCE_MSVC
  18250. #pragma warning (push)
  18251. #pragma warning (disable : 4100)
  18252. #endif
  18253. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18254. add its header directory to your include path.
  18255. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18256. flag in juce_Config.h
  18257. */
  18258. #include <Movies.h>
  18259. #include <QTML.h>
  18260. #include <QuickTimeComponents.h>
  18261. #include <MediaHandlers.h>
  18262. #include <ImageCodec.h>
  18263. #if JUCE_MSVC
  18264. #pragma warning (pop)
  18265. #endif
  18266. #endif
  18267. BEGIN_JUCE_NAMESPACE
  18268. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18269. static const char* const quickTimeFormatName = "QuickTime file";
  18270. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18271. class QTAudioReader : public AudioFormatReader
  18272. {
  18273. public:
  18274. QTAudioReader (InputStream* const input_, const int trackNum_)
  18275. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18276. ok (false),
  18277. movie (0),
  18278. trackNum (trackNum_),
  18279. lastSampleRead (0),
  18280. lastThreadId (0),
  18281. extractor (0),
  18282. dataHandle (0)
  18283. {
  18284. JUCE_AUTORELEASEPOOL
  18285. bufferList.calloc (256, 1);
  18286. #if JUCE_WINDOWS
  18287. if (InitializeQTML (0) != noErr)
  18288. return;
  18289. #endif
  18290. if (EnterMovies() != noErr)
  18291. return;
  18292. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18293. if (! opened)
  18294. return;
  18295. {
  18296. const int numTracks = GetMovieTrackCount (movie);
  18297. int trackCount = 0;
  18298. for (int i = 1; i <= numTracks; ++i)
  18299. {
  18300. track = GetMovieIndTrack (movie, i);
  18301. media = GetTrackMedia (track);
  18302. OSType mediaType;
  18303. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18304. if (mediaType == SoundMediaType
  18305. && trackCount++ == trackNum_)
  18306. {
  18307. ok = true;
  18308. break;
  18309. }
  18310. }
  18311. }
  18312. if (! ok)
  18313. return;
  18314. ok = false;
  18315. lengthInSamples = GetMediaDecodeDuration (media);
  18316. usesFloatingPointData = false;
  18317. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18318. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18319. / GetMediaTimeScale (media);
  18320. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18321. unsigned long output_layout_size;
  18322. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18323. kQTPropertyClass_MovieAudioExtraction_Audio,
  18324. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18325. 0, &output_layout_size, 0);
  18326. if (err != noErr)
  18327. return;
  18328. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18329. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18330. err = MovieAudioExtractionGetProperty (extractor,
  18331. kQTPropertyClass_MovieAudioExtraction_Audio,
  18332. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18333. output_layout_size, qt_audio_channel_layout, 0);
  18334. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18335. err = MovieAudioExtractionSetProperty (extractor,
  18336. kQTPropertyClass_MovieAudioExtraction_Audio,
  18337. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18338. output_layout_size,
  18339. qt_audio_channel_layout);
  18340. err = MovieAudioExtractionGetProperty (extractor,
  18341. kQTPropertyClass_MovieAudioExtraction_Audio,
  18342. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18343. sizeof (inputStreamDesc),
  18344. &inputStreamDesc, 0);
  18345. if (err != noErr)
  18346. return;
  18347. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18348. | kAudioFormatFlagIsPacked
  18349. | kAudioFormatFlagsNativeEndian;
  18350. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18351. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18352. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18353. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18354. err = MovieAudioExtractionSetProperty (extractor,
  18355. kQTPropertyClass_MovieAudioExtraction_Audio,
  18356. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18357. sizeof (inputStreamDesc),
  18358. &inputStreamDesc);
  18359. if (err != noErr)
  18360. return;
  18361. Boolean allChannelsDiscrete = false;
  18362. err = MovieAudioExtractionSetProperty (extractor,
  18363. kQTPropertyClass_MovieAudioExtraction_Movie,
  18364. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18365. sizeof (allChannelsDiscrete),
  18366. &allChannelsDiscrete);
  18367. if (err != noErr)
  18368. return;
  18369. bufferList->mNumberBuffers = 1;
  18370. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18371. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18372. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18373. bufferList->mBuffers[0].mData = dataBuffer;
  18374. sampleRate = inputStreamDesc.mSampleRate;
  18375. bitsPerSample = 16;
  18376. numChannels = inputStreamDesc.mChannelsPerFrame;
  18377. detachThread();
  18378. ok = true;
  18379. }
  18380. ~QTAudioReader()
  18381. {
  18382. JUCE_AUTORELEASEPOOL
  18383. checkThreadIsAttached();
  18384. if (dataHandle != 0)
  18385. DisposeHandle (dataHandle);
  18386. if (extractor != 0)
  18387. {
  18388. MovieAudioExtractionEnd (extractor);
  18389. extractor = 0;
  18390. }
  18391. DisposeMovie (movie);
  18392. #if JUCE_MAC
  18393. ExitMoviesOnThread ();
  18394. #endif
  18395. }
  18396. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18397. int64 startSampleInFile, int numSamples)
  18398. {
  18399. JUCE_AUTORELEASEPOOL
  18400. checkThreadIsAttached();
  18401. bool ok = true;
  18402. while (numSamples > 0)
  18403. {
  18404. if (lastSampleRead != startSampleInFile)
  18405. {
  18406. TimeRecord time;
  18407. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18408. time.base = 0;
  18409. time.value.hi = 0;
  18410. time.value.lo = (UInt32) startSampleInFile;
  18411. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18412. kQTPropertyClass_MovieAudioExtraction_Movie,
  18413. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18414. sizeof (time), &time);
  18415. if (err != noErr)
  18416. {
  18417. ok = false;
  18418. break;
  18419. }
  18420. }
  18421. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18422. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18423. UInt32 outFlags = 0;
  18424. UInt32 actualNumFrames = framesToDo;
  18425. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18426. if (err != noErr)
  18427. {
  18428. ok = false;
  18429. break;
  18430. }
  18431. lastSampleRead = startSampleInFile + actualNumFrames;
  18432. const int samplesReceived = actualNumFrames;
  18433. for (int j = numDestChannels; --j >= 0;)
  18434. {
  18435. if (destSamples[j] != 0)
  18436. {
  18437. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18438. for (int i = 0; i < samplesReceived; ++i)
  18439. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18440. }
  18441. }
  18442. startOffsetInDestBuffer += samplesReceived;
  18443. startSampleInFile += samplesReceived;
  18444. numSamples -= samplesReceived;
  18445. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18446. {
  18447. for (int j = numDestChannels; --j >= 0;)
  18448. if (destSamples[j] != 0)
  18449. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18450. break;
  18451. }
  18452. }
  18453. detachThread();
  18454. return ok;
  18455. }
  18456. bool ok;
  18457. private:
  18458. Movie movie;
  18459. Media media;
  18460. Track track;
  18461. const int trackNum;
  18462. double trackUnitsPerFrame;
  18463. int samplesPerFrame;
  18464. int64 lastSampleRead;
  18465. Thread::ThreadID lastThreadId;
  18466. MovieAudioExtractionRef extractor;
  18467. AudioStreamBasicDescription inputStreamDesc;
  18468. HeapBlock <AudioBufferList> bufferList;
  18469. HeapBlock <char> dataBuffer;
  18470. Handle dataHandle;
  18471. void checkThreadIsAttached()
  18472. {
  18473. #if JUCE_MAC
  18474. if (Thread::getCurrentThreadId() != lastThreadId)
  18475. EnterMoviesOnThread (0);
  18476. AttachMovieToCurrentThread (movie);
  18477. #endif
  18478. }
  18479. void detachThread()
  18480. {
  18481. #if JUCE_MAC
  18482. DetachMovieFromCurrentThread (movie);
  18483. #endif
  18484. }
  18485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18486. };
  18487. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18488. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18489. {
  18490. }
  18491. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18492. {
  18493. }
  18494. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18495. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18496. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18497. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18498. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18499. const bool deleteStreamIfOpeningFails)
  18500. {
  18501. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18502. if (r->ok)
  18503. return r.release();
  18504. if (! deleteStreamIfOpeningFails)
  18505. r->input = 0;
  18506. return 0;
  18507. }
  18508. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18509. double /*sampleRateToUse*/,
  18510. unsigned int /*numberOfChannels*/,
  18511. int /*bitsPerSample*/,
  18512. const StringPairArray& /*metadataValues*/,
  18513. int /*qualityOptionIndex*/)
  18514. {
  18515. jassertfalse; // not yet implemented!
  18516. return 0;
  18517. }
  18518. END_JUCE_NAMESPACE
  18519. #endif
  18520. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18521. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18522. BEGIN_JUCE_NAMESPACE
  18523. static const char* const wavFormatName = "WAV file";
  18524. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18525. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18526. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18527. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18528. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18529. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18530. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18531. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18532. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18533. const String& originator,
  18534. const String& originatorRef,
  18535. const Time& date,
  18536. const int64 timeReferenceSamples,
  18537. const String& codingHistory)
  18538. {
  18539. StringPairArray m;
  18540. m.set (bwavDescription, description);
  18541. m.set (bwavOriginator, originator);
  18542. m.set (bwavOriginatorRef, originatorRef);
  18543. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18544. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18545. m.set (bwavTimeReference, String (timeReferenceSamples));
  18546. m.set (bwavCodingHistory, codingHistory);
  18547. return m;
  18548. }
  18549. #if JUCE_MSVC
  18550. #pragma pack (push, 1)
  18551. #define PACKED
  18552. #elif JUCE_GCC
  18553. #define PACKED __attribute__((packed))
  18554. #else
  18555. #define PACKED
  18556. #endif
  18557. struct BWAVChunk
  18558. {
  18559. char description [256];
  18560. char originator [32];
  18561. char originatorRef [32];
  18562. char originationDate [10];
  18563. char originationTime [8];
  18564. uint32 timeRefLow;
  18565. uint32 timeRefHigh;
  18566. uint16 version;
  18567. uint8 umid[64];
  18568. uint8 reserved[190];
  18569. char codingHistory[1];
  18570. void copyTo (StringPairArray& values) const
  18571. {
  18572. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18573. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18574. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18575. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18576. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18577. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18578. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18579. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18580. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18581. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18582. }
  18583. static MemoryBlock createFrom (const StringPairArray& values)
  18584. {
  18585. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18586. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18587. data.fillWith (0);
  18588. BWAVChunk* b = (BWAVChunk*) data.getData();
  18589. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18590. // as they get called in the right order..
  18591. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18592. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18593. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18594. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18595. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18596. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18597. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18598. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18599. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18600. if (b->description[0] != 0
  18601. || b->originator[0] != 0
  18602. || b->originationDate[0] != 0
  18603. || b->originationTime[0] != 0
  18604. || b->codingHistory[0] != 0
  18605. || time != 0)
  18606. {
  18607. return data;
  18608. }
  18609. return MemoryBlock();
  18610. }
  18611. } PACKED;
  18612. struct SMPLChunk
  18613. {
  18614. struct SampleLoop
  18615. {
  18616. uint32 identifier;
  18617. uint32 type;
  18618. uint32 start;
  18619. uint32 end;
  18620. uint32 fraction;
  18621. uint32 playCount;
  18622. } PACKED;
  18623. uint32 manufacturer;
  18624. uint32 product;
  18625. uint32 samplePeriod;
  18626. uint32 midiUnityNote;
  18627. uint32 midiPitchFraction;
  18628. uint32 smpteFormat;
  18629. uint32 smpteOffset;
  18630. uint32 numSampleLoops;
  18631. uint32 samplerData;
  18632. SampleLoop loops[1];
  18633. void copyTo (StringPairArray& values, const int totalSize) const
  18634. {
  18635. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18636. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18637. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18638. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18639. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18640. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18641. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18642. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18643. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18644. for (uint32 i = 0; i < numSampleLoops; ++i)
  18645. {
  18646. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18647. break;
  18648. const String prefix ("Loop" + String(i));
  18649. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18650. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18651. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18652. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18653. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18654. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18655. }
  18656. }
  18657. static MemoryBlock createFrom (const StringPairArray& values)
  18658. {
  18659. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18660. if (numLoops <= 0)
  18661. return MemoryBlock();
  18662. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18663. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18664. data.fillWith (0);
  18665. SMPLChunk* s = (SMPLChunk*) data.getData();
  18666. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18667. // as they get called in the right order..
  18668. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18669. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18670. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18671. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18672. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18673. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18674. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18675. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18676. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18677. for (int i = 0; i < numLoops; ++i)
  18678. {
  18679. const String prefix ("Loop" + String(i));
  18680. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18681. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18682. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18683. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18684. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18685. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18686. }
  18687. return data;
  18688. }
  18689. } PACKED;
  18690. struct ExtensibleWavSubFormat
  18691. {
  18692. uint32 data1;
  18693. uint16 data2;
  18694. uint16 data3;
  18695. uint8 data4[8];
  18696. } PACKED;
  18697. #if JUCE_MSVC
  18698. #pragma pack (pop)
  18699. #endif
  18700. #undef PACKED
  18701. class WavAudioFormatReader : public AudioFormatReader
  18702. {
  18703. public:
  18704. WavAudioFormatReader (InputStream* const in)
  18705. : AudioFormatReader (in, TRANS (wavFormatName)),
  18706. bwavChunkStart (0),
  18707. bwavSize (0),
  18708. dataLength (0)
  18709. {
  18710. if (input->readInt() == chunkName ("RIFF"))
  18711. {
  18712. const uint32 len = (uint32) input->readInt();
  18713. const int64 end = input->getPosition() + len;
  18714. bool hasGotType = false;
  18715. bool hasGotData = false;
  18716. if (input->readInt() == chunkName ("WAVE"))
  18717. {
  18718. while (input->getPosition() < end
  18719. && ! input->isExhausted())
  18720. {
  18721. const int chunkType = input->readInt();
  18722. uint32 length = (uint32) input->readInt();
  18723. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18724. if (chunkType == chunkName ("fmt "))
  18725. {
  18726. // read the format chunk
  18727. const unsigned short format = input->readShort();
  18728. const short numChans = input->readShort();
  18729. sampleRate = input->readInt();
  18730. const int bytesPerSec = input->readInt();
  18731. numChannels = numChans;
  18732. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18733. bitsPerSample = 8 * bytesPerFrame / numChans;
  18734. if (format == 3)
  18735. {
  18736. usesFloatingPointData = true;
  18737. }
  18738. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18739. {
  18740. if (length < 40) // too short
  18741. {
  18742. bytesPerFrame = 0;
  18743. }
  18744. else
  18745. {
  18746. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18747. ExtensibleWavSubFormat subFormat;
  18748. subFormat.data1 = input->readInt();
  18749. subFormat.data2 = input->readShort();
  18750. subFormat.data3 = input->readShort();
  18751. input->read (subFormat.data4, sizeof (subFormat.data4));
  18752. const ExtensibleWavSubFormat pcmFormat
  18753. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18754. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18755. {
  18756. const ExtensibleWavSubFormat ambisonicFormat
  18757. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18758. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18759. bytesPerFrame = 0;
  18760. }
  18761. }
  18762. }
  18763. else if (format != 1)
  18764. {
  18765. bytesPerFrame = 0;
  18766. }
  18767. hasGotType = true;
  18768. }
  18769. else if (chunkType == chunkName ("data"))
  18770. {
  18771. // get the data chunk's position
  18772. dataLength = length;
  18773. dataChunkStart = input->getPosition();
  18774. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18775. hasGotData = true;
  18776. }
  18777. else if (chunkType == chunkName ("bext"))
  18778. {
  18779. bwavChunkStart = input->getPosition();
  18780. bwavSize = length;
  18781. // Broadcast-wav extension chunk..
  18782. HeapBlock <BWAVChunk> bwav;
  18783. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18784. input->read (bwav, length);
  18785. bwav->copyTo (metadataValues);
  18786. }
  18787. else if (chunkType == chunkName ("smpl"))
  18788. {
  18789. HeapBlock <SMPLChunk> smpl;
  18790. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18791. input->read (smpl, length);
  18792. smpl->copyTo (metadataValues, length);
  18793. }
  18794. else if (chunkEnd <= input->getPosition())
  18795. {
  18796. break;
  18797. }
  18798. input->setPosition (chunkEnd);
  18799. }
  18800. }
  18801. }
  18802. }
  18803. ~WavAudioFormatReader()
  18804. {
  18805. }
  18806. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18807. int64 startSampleInFile, int numSamples)
  18808. {
  18809. jassert (destSamples != 0);
  18810. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18811. if (samplesAvailable < numSamples)
  18812. {
  18813. for (int i = numDestChannels; --i >= 0;)
  18814. if (destSamples[i] != 0)
  18815. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18816. numSamples = (int) samplesAvailable;
  18817. }
  18818. if (numSamples <= 0)
  18819. return true;
  18820. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18821. while (numSamples > 0)
  18822. {
  18823. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18824. char tempBuffer [tempBufSize];
  18825. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18826. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18827. if (bytesRead < numThisTime * bytesPerFrame)
  18828. {
  18829. jassert (bytesRead >= 0);
  18830. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18831. }
  18832. switch (bitsPerSample)
  18833. {
  18834. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18835. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18836. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18837. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18838. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18839. default: jassertfalse; break;
  18840. }
  18841. startOffsetInDestBuffer += numThisTime;
  18842. numSamples -= numThisTime;
  18843. }
  18844. return true;
  18845. }
  18846. int64 bwavChunkStart, bwavSize;
  18847. private:
  18848. ScopedPointer<AudioData::Converter> converter;
  18849. int bytesPerFrame;
  18850. int64 dataChunkStart, dataLength;
  18851. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18852. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18853. };
  18854. class WavAudioFormatWriter : public AudioFormatWriter
  18855. {
  18856. public:
  18857. WavAudioFormatWriter (OutputStream* const out,
  18858. const double sampleRate_,
  18859. const unsigned int numChannels_,
  18860. const int bits,
  18861. const StringPairArray& metadataValues)
  18862. : AudioFormatWriter (out,
  18863. TRANS (wavFormatName),
  18864. sampleRate_,
  18865. numChannels_,
  18866. bits),
  18867. lengthInSamples (0),
  18868. bytesWritten (0),
  18869. writeFailed (false)
  18870. {
  18871. if (metadataValues.size() > 0)
  18872. {
  18873. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18874. smplChunk = SMPLChunk::createFrom (metadataValues);
  18875. }
  18876. headerPosition = out->getPosition();
  18877. writeHeader();
  18878. }
  18879. ~WavAudioFormatWriter()
  18880. {
  18881. writeHeader();
  18882. }
  18883. bool write (const int** data, int numSamples)
  18884. {
  18885. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18886. if (writeFailed)
  18887. return false;
  18888. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18889. tempBlock.ensureSize (bytes, false);
  18890. switch (bitsPerSample)
  18891. {
  18892. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18893. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18894. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18895. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18896. default: jassertfalse; break;
  18897. }
  18898. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18899. || ! output->write (tempBlock.getData(), bytes))
  18900. {
  18901. // failed to write to disk, so let's try writing the header.
  18902. // If it's just run out of disk space, then if it does manage
  18903. // to write the header, we'll still have a useable file..
  18904. writeHeader();
  18905. writeFailed = true;
  18906. return false;
  18907. }
  18908. else
  18909. {
  18910. bytesWritten += bytes;
  18911. lengthInSamples += numSamples;
  18912. return true;
  18913. }
  18914. }
  18915. private:
  18916. ScopedPointer<AudioData::Converter> converter;
  18917. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18918. uint32 lengthInSamples, bytesWritten;
  18919. int64 headerPosition;
  18920. bool writeFailed;
  18921. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18922. void writeHeader()
  18923. {
  18924. const bool seekedOk = output->setPosition (headerPosition);
  18925. (void) seekedOk;
  18926. // if this fails, you've given it an output stream that can't seek! It needs
  18927. // to be able to seek back to write the header
  18928. jassert (seekedOk);
  18929. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18930. output->writeInt (chunkName ("RIFF"));
  18931. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18932. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18933. output->writeInt (chunkName ("WAVE"));
  18934. output->writeInt (chunkName ("fmt "));
  18935. output->writeInt (16);
  18936. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18937. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18938. output->writeShort ((short) numChannels);
  18939. output->writeInt ((int) sampleRate);
  18940. output->writeInt (bytesPerFrame * (int) sampleRate);
  18941. output->writeShort ((short) bytesPerFrame);
  18942. output->writeShort ((short) bitsPerSample);
  18943. if (bwavChunk.getSize() > 0)
  18944. {
  18945. output->writeInt (chunkName ("bext"));
  18946. output->writeInt ((int) bwavChunk.getSize());
  18947. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18948. }
  18949. if (smplChunk.getSize() > 0)
  18950. {
  18951. output->writeInt (chunkName ("smpl"));
  18952. output->writeInt ((int) smplChunk.getSize());
  18953. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18954. }
  18955. output->writeInt (chunkName ("data"));
  18956. output->writeInt (lengthInSamples * bytesPerFrame);
  18957. usesFloatingPointData = (bitsPerSample == 32);
  18958. }
  18959. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18960. };
  18961. WavAudioFormat::WavAudioFormat()
  18962. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18963. {
  18964. }
  18965. WavAudioFormat::~WavAudioFormat()
  18966. {
  18967. }
  18968. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18969. {
  18970. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18971. return Array <int> (rates);
  18972. }
  18973. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18974. {
  18975. const int depths[] = { 8, 16, 24, 32, 0 };
  18976. return Array <int> (depths);
  18977. }
  18978. bool WavAudioFormat::canDoStereo() { return true; }
  18979. bool WavAudioFormat::canDoMono() { return true; }
  18980. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18981. const bool deleteStreamIfOpeningFails)
  18982. {
  18983. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18984. if (r->sampleRate != 0)
  18985. return r.release();
  18986. if (! deleteStreamIfOpeningFails)
  18987. r->input = 0;
  18988. return 0;
  18989. }
  18990. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18991. double sampleRate,
  18992. unsigned int numChannels,
  18993. int bitsPerSample,
  18994. const StringPairArray& metadataValues,
  18995. int /*qualityOptionIndex*/)
  18996. {
  18997. if (getPossibleBitDepths().contains (bitsPerSample))
  18998. {
  18999. return new WavAudioFormatWriter (out,
  19000. sampleRate,
  19001. numChannels,
  19002. bitsPerSample,
  19003. metadataValues);
  19004. }
  19005. return 0;
  19006. }
  19007. namespace
  19008. {
  19009. bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  19010. {
  19011. TemporaryFile tempFile (file);
  19012. WavAudioFormat wav;
  19013. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  19014. if (reader != 0)
  19015. {
  19016. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  19017. if (outStream != 0)
  19018. {
  19019. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  19020. reader->numChannels, reader->bitsPerSample,
  19021. metadata, 0));
  19022. if (writer != 0)
  19023. {
  19024. outStream.release();
  19025. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  19026. writer = 0;
  19027. reader = 0;
  19028. return ok && tempFile.overwriteTargetFileWithTemporary();
  19029. }
  19030. }
  19031. }
  19032. return false;
  19033. }
  19034. }
  19035. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  19036. {
  19037. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  19038. if (reader != 0)
  19039. {
  19040. const int64 bwavPos = reader->bwavChunkStart;
  19041. const int64 bwavSize = reader->bwavSize;
  19042. reader = 0;
  19043. if (bwavSize > 0)
  19044. {
  19045. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  19046. if (chunk.getSize() <= (size_t) bwavSize)
  19047. {
  19048. // the new one will fit in the space available, so write it directly..
  19049. const int64 oldSize = wavFile.getSize();
  19050. {
  19051. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  19052. out->setPosition (bwavPos);
  19053. out->write (chunk.getData(), (int) chunk.getSize());
  19054. out->setPosition (oldSize);
  19055. }
  19056. jassert (wavFile.getSize() == oldSize);
  19057. return true;
  19058. }
  19059. }
  19060. }
  19061. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  19062. }
  19063. END_JUCE_NAMESPACE
  19064. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  19065. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  19066. #if JUCE_USE_CDREADER
  19067. BEGIN_JUCE_NAMESPACE
  19068. int AudioCDReader::getNumTracks() const
  19069. {
  19070. return trackStartSamples.size() - 1;
  19071. }
  19072. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  19073. {
  19074. return trackStartSamples [trackNum];
  19075. }
  19076. const Array<int>& AudioCDReader::getTrackOffsets() const
  19077. {
  19078. return trackStartSamples;
  19079. }
  19080. int AudioCDReader::getCDDBId()
  19081. {
  19082. int checksum = 0;
  19083. const int numTracks = getNumTracks();
  19084. for (int i = 0; i < numTracks; ++i)
  19085. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  19086. checksum += offset % 10;
  19087. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  19088. // CCLLLLTT: checksum, length, tracks
  19089. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  19090. }
  19091. END_JUCE_NAMESPACE
  19092. #endif
  19093. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  19094. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19095. BEGIN_JUCE_NAMESPACE
  19096. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  19097. const bool deleteReaderWhenThisIsDeleted)
  19098. : reader (reader_),
  19099. deleteReader (deleteReaderWhenThisIsDeleted),
  19100. nextPlayPos (0),
  19101. looping (false)
  19102. {
  19103. jassert (reader != 0);
  19104. }
  19105. AudioFormatReaderSource::~AudioFormatReaderSource()
  19106. {
  19107. releaseResources();
  19108. if (deleteReader)
  19109. delete reader;
  19110. }
  19111. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19112. {
  19113. nextPlayPos = newPosition;
  19114. }
  19115. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19116. {
  19117. looping = shouldLoop;
  19118. }
  19119. int AudioFormatReaderSource::getNextReadPosition() const
  19120. {
  19121. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19122. : nextPlayPos;
  19123. }
  19124. int AudioFormatReaderSource::getTotalLength() const
  19125. {
  19126. return (int) reader->lengthInSamples;
  19127. }
  19128. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19129. double /*sampleRate*/)
  19130. {
  19131. }
  19132. void AudioFormatReaderSource::releaseResources()
  19133. {
  19134. }
  19135. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19136. {
  19137. if (info.numSamples > 0)
  19138. {
  19139. const int start = nextPlayPos;
  19140. if (looping)
  19141. {
  19142. const int newStart = start % (int) reader->lengthInSamples;
  19143. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19144. if (newEnd > newStart)
  19145. {
  19146. info.buffer->readFromAudioReader (reader,
  19147. info.startSample,
  19148. newEnd - newStart,
  19149. newStart,
  19150. true, true);
  19151. }
  19152. else
  19153. {
  19154. const int endSamps = (int) reader->lengthInSamples - newStart;
  19155. info.buffer->readFromAudioReader (reader,
  19156. info.startSample,
  19157. endSamps,
  19158. newStart,
  19159. true, true);
  19160. info.buffer->readFromAudioReader (reader,
  19161. info.startSample + endSamps,
  19162. newEnd,
  19163. 0,
  19164. true, true);
  19165. }
  19166. nextPlayPos = newEnd;
  19167. }
  19168. else
  19169. {
  19170. info.buffer->readFromAudioReader (reader,
  19171. info.startSample,
  19172. info.numSamples,
  19173. start,
  19174. true, true);
  19175. nextPlayPos += info.numSamples;
  19176. }
  19177. }
  19178. }
  19179. END_JUCE_NAMESPACE
  19180. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19181. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19182. BEGIN_JUCE_NAMESPACE
  19183. AudioSourcePlayer::AudioSourcePlayer()
  19184. : source (0),
  19185. sampleRate (0),
  19186. bufferSize (0),
  19187. tempBuffer (2, 8),
  19188. lastGain (1.0f),
  19189. gain (1.0f)
  19190. {
  19191. }
  19192. AudioSourcePlayer::~AudioSourcePlayer()
  19193. {
  19194. setSource (0);
  19195. }
  19196. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19197. {
  19198. if (source != newSource)
  19199. {
  19200. AudioSource* const oldSource = source;
  19201. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19202. newSource->prepareToPlay (bufferSize, sampleRate);
  19203. {
  19204. const ScopedLock sl (readLock);
  19205. source = newSource;
  19206. }
  19207. if (oldSource != 0)
  19208. oldSource->releaseResources();
  19209. }
  19210. }
  19211. void AudioSourcePlayer::setGain (const float newGain) throw()
  19212. {
  19213. gain = newGain;
  19214. }
  19215. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19216. int totalNumInputChannels,
  19217. float** outputChannelData,
  19218. int totalNumOutputChannels,
  19219. int numSamples)
  19220. {
  19221. // these should have been prepared by audioDeviceAboutToStart()...
  19222. jassert (sampleRate > 0 && bufferSize > 0);
  19223. const ScopedLock sl (readLock);
  19224. if (source != 0)
  19225. {
  19226. AudioSourceChannelInfo info;
  19227. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19228. // messy stuff needed to compact the channels down into an array
  19229. // of non-zero pointers..
  19230. for (i = 0; i < totalNumInputChannels; ++i)
  19231. {
  19232. if (inputChannelData[i] != 0)
  19233. {
  19234. inputChans [numInputs++] = inputChannelData[i];
  19235. if (numInputs >= numElementsInArray (inputChans))
  19236. break;
  19237. }
  19238. }
  19239. for (i = 0; i < totalNumOutputChannels; ++i)
  19240. {
  19241. if (outputChannelData[i] != 0)
  19242. {
  19243. outputChans [numOutputs++] = outputChannelData[i];
  19244. if (numOutputs >= numElementsInArray (outputChans))
  19245. break;
  19246. }
  19247. }
  19248. if (numInputs > numOutputs)
  19249. {
  19250. // if there aren't enough output channels for the number of
  19251. // inputs, we need to create some temporary extra ones (can't
  19252. // use the input data in case it gets written to)
  19253. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19254. false, false, true);
  19255. for (i = 0; i < numOutputs; ++i)
  19256. {
  19257. channels[numActiveChans] = outputChans[i];
  19258. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19259. ++numActiveChans;
  19260. }
  19261. for (i = numOutputs; i < numInputs; ++i)
  19262. {
  19263. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19264. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19265. ++numActiveChans;
  19266. }
  19267. }
  19268. else
  19269. {
  19270. for (i = 0; i < numInputs; ++i)
  19271. {
  19272. channels[numActiveChans] = outputChans[i];
  19273. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19274. ++numActiveChans;
  19275. }
  19276. for (i = numInputs; i < numOutputs; ++i)
  19277. {
  19278. channels[numActiveChans] = outputChans[i];
  19279. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19280. ++numActiveChans;
  19281. }
  19282. }
  19283. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19284. info.buffer = &buffer;
  19285. info.startSample = 0;
  19286. info.numSamples = numSamples;
  19287. source->getNextAudioBlock (info);
  19288. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19289. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19290. lastGain = gain;
  19291. }
  19292. else
  19293. {
  19294. for (int i = 0; i < totalNumOutputChannels; ++i)
  19295. if (outputChannelData[i] != 0)
  19296. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19297. }
  19298. }
  19299. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19300. {
  19301. sampleRate = device->getCurrentSampleRate();
  19302. bufferSize = device->getCurrentBufferSizeSamples();
  19303. zeromem (channels, sizeof (channels));
  19304. if (source != 0)
  19305. source->prepareToPlay (bufferSize, sampleRate);
  19306. }
  19307. void AudioSourcePlayer::audioDeviceStopped()
  19308. {
  19309. if (source != 0)
  19310. source->releaseResources();
  19311. sampleRate = 0.0;
  19312. bufferSize = 0;
  19313. tempBuffer.setSize (2, 8);
  19314. }
  19315. END_JUCE_NAMESPACE
  19316. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19317. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19318. BEGIN_JUCE_NAMESPACE
  19319. AudioTransportSource::AudioTransportSource()
  19320. : source (0),
  19321. resamplerSource (0),
  19322. bufferingSource (0),
  19323. positionableSource (0),
  19324. masterSource (0),
  19325. gain (1.0f),
  19326. lastGain (1.0f),
  19327. playing (false),
  19328. stopped (true),
  19329. sampleRate (44100.0),
  19330. sourceSampleRate (0.0),
  19331. blockSize (128),
  19332. readAheadBufferSize (0),
  19333. isPrepared (false),
  19334. inputStreamEOF (false)
  19335. {
  19336. }
  19337. AudioTransportSource::~AudioTransportSource()
  19338. {
  19339. setSource (0);
  19340. releaseResources();
  19341. }
  19342. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19343. int readAheadBufferSize_,
  19344. double sourceSampleRateToCorrectFor)
  19345. {
  19346. if (source == newSource)
  19347. {
  19348. if (source == 0)
  19349. return;
  19350. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19351. }
  19352. readAheadBufferSize = readAheadBufferSize_;
  19353. sourceSampleRate = sourceSampleRateToCorrectFor;
  19354. ResamplingAudioSource* newResamplerSource = 0;
  19355. BufferingAudioSource* newBufferingSource = 0;
  19356. PositionableAudioSource* newPositionableSource = 0;
  19357. AudioSource* newMasterSource = 0;
  19358. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19359. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19360. AudioSource* oldMasterSource = masterSource;
  19361. if (newSource != 0)
  19362. {
  19363. newPositionableSource = newSource;
  19364. if (readAheadBufferSize_ > 0)
  19365. newPositionableSource = newBufferingSource
  19366. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19367. newPositionableSource->setNextReadPosition (0);
  19368. if (sourceSampleRateToCorrectFor != 0)
  19369. newMasterSource = newResamplerSource
  19370. = new ResamplingAudioSource (newPositionableSource, false);
  19371. else
  19372. newMasterSource = newPositionableSource;
  19373. if (isPrepared)
  19374. {
  19375. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19376. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19377. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19378. }
  19379. }
  19380. {
  19381. const ScopedLock sl (callbackLock);
  19382. source = newSource;
  19383. resamplerSource = newResamplerSource;
  19384. bufferingSource = newBufferingSource;
  19385. masterSource = newMasterSource;
  19386. positionableSource = newPositionableSource;
  19387. playing = false;
  19388. }
  19389. if (oldMasterSource != 0)
  19390. oldMasterSource->releaseResources();
  19391. }
  19392. void AudioTransportSource::start()
  19393. {
  19394. if ((! playing) && masterSource != 0)
  19395. {
  19396. {
  19397. const ScopedLock sl (callbackLock);
  19398. playing = true;
  19399. stopped = false;
  19400. inputStreamEOF = false;
  19401. }
  19402. sendChangeMessage();
  19403. }
  19404. }
  19405. void AudioTransportSource::stop()
  19406. {
  19407. if (playing)
  19408. {
  19409. {
  19410. const ScopedLock sl (callbackLock);
  19411. playing = false;
  19412. }
  19413. int n = 500;
  19414. while (--n >= 0 && ! stopped)
  19415. Thread::sleep (2);
  19416. sendChangeMessage();
  19417. }
  19418. }
  19419. void AudioTransportSource::setPosition (double newPosition)
  19420. {
  19421. if (sampleRate > 0.0)
  19422. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19423. }
  19424. double AudioTransportSource::getCurrentPosition() const
  19425. {
  19426. if (sampleRate > 0.0)
  19427. return getNextReadPosition() / sampleRate;
  19428. else
  19429. return 0.0;
  19430. }
  19431. double AudioTransportSource::getLengthInSeconds() const
  19432. {
  19433. return getTotalLength() / sampleRate;
  19434. }
  19435. void AudioTransportSource::setNextReadPosition (int newPosition)
  19436. {
  19437. if (positionableSource != 0)
  19438. {
  19439. if (sampleRate > 0 && sourceSampleRate > 0)
  19440. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19441. positionableSource->setNextReadPosition (newPosition);
  19442. }
  19443. }
  19444. int AudioTransportSource::getNextReadPosition() const
  19445. {
  19446. if (positionableSource != 0)
  19447. {
  19448. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19449. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19450. }
  19451. return 0;
  19452. }
  19453. int AudioTransportSource::getTotalLength() const
  19454. {
  19455. const ScopedLock sl (callbackLock);
  19456. if (positionableSource != 0)
  19457. {
  19458. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19459. return roundToInt (positionableSource->getTotalLength() * ratio);
  19460. }
  19461. return 0;
  19462. }
  19463. bool AudioTransportSource::isLooping() const
  19464. {
  19465. const ScopedLock sl (callbackLock);
  19466. return positionableSource != 0
  19467. && positionableSource->isLooping();
  19468. }
  19469. void AudioTransportSource::setGain (const float newGain) throw()
  19470. {
  19471. gain = newGain;
  19472. }
  19473. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19474. double sampleRate_)
  19475. {
  19476. const ScopedLock sl (callbackLock);
  19477. sampleRate = sampleRate_;
  19478. blockSize = samplesPerBlockExpected;
  19479. if (masterSource != 0)
  19480. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19481. if (resamplerSource != 0 && sourceSampleRate != 0)
  19482. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19483. isPrepared = true;
  19484. }
  19485. void AudioTransportSource::releaseResources()
  19486. {
  19487. const ScopedLock sl (callbackLock);
  19488. if (masterSource != 0)
  19489. masterSource->releaseResources();
  19490. isPrepared = false;
  19491. }
  19492. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19493. {
  19494. const ScopedLock sl (callbackLock);
  19495. inputStreamEOF = false;
  19496. if (masterSource != 0 && ! stopped)
  19497. {
  19498. masterSource->getNextAudioBlock (info);
  19499. if (! playing)
  19500. {
  19501. // just stopped playing, so fade out the last block..
  19502. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19503. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19504. if (info.numSamples > 256)
  19505. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19506. }
  19507. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19508. && ! positionableSource->isLooping())
  19509. {
  19510. playing = false;
  19511. inputStreamEOF = true;
  19512. sendChangeMessage();
  19513. }
  19514. stopped = ! playing;
  19515. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19516. {
  19517. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19518. lastGain, gain);
  19519. }
  19520. }
  19521. else
  19522. {
  19523. info.clearActiveBufferRegion();
  19524. stopped = true;
  19525. }
  19526. lastGain = gain;
  19527. }
  19528. END_JUCE_NAMESPACE
  19529. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19530. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19531. BEGIN_JUCE_NAMESPACE
  19532. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19533. public Thread,
  19534. private Timer
  19535. {
  19536. public:
  19537. SharedBufferingAudioSourceThread()
  19538. : Thread ("Audio Buffer")
  19539. {
  19540. }
  19541. ~SharedBufferingAudioSourceThread()
  19542. {
  19543. stopThread (10000);
  19544. clearSingletonInstance();
  19545. }
  19546. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19547. void addSource (BufferingAudioSource* source)
  19548. {
  19549. const ScopedLock sl (lock);
  19550. if (! sources.contains (source))
  19551. {
  19552. sources.add (source);
  19553. startThread();
  19554. stopTimer();
  19555. }
  19556. notify();
  19557. }
  19558. void removeSource (BufferingAudioSource* source)
  19559. {
  19560. const ScopedLock sl (lock);
  19561. sources.removeValue (source);
  19562. if (sources.size() == 0)
  19563. startTimer (5000);
  19564. }
  19565. private:
  19566. Array <BufferingAudioSource*> sources;
  19567. CriticalSection lock;
  19568. void run()
  19569. {
  19570. while (! threadShouldExit())
  19571. {
  19572. bool busy = false;
  19573. for (int i = sources.size(); --i >= 0;)
  19574. {
  19575. if (threadShouldExit())
  19576. return;
  19577. const ScopedLock sl (lock);
  19578. BufferingAudioSource* const b = sources[i];
  19579. if (b != 0 && b->readNextBufferChunk())
  19580. busy = true;
  19581. }
  19582. if (! busy)
  19583. wait (500);
  19584. }
  19585. }
  19586. void timerCallback()
  19587. {
  19588. stopTimer();
  19589. if (sources.size() == 0)
  19590. deleteInstance();
  19591. }
  19592. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19593. };
  19594. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19595. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19596. const bool deleteSourceWhenDeleted_,
  19597. int numberOfSamplesToBuffer_)
  19598. : source (source_),
  19599. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19600. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19601. buffer (2, 0),
  19602. bufferValidStart (0),
  19603. bufferValidEnd (0),
  19604. nextPlayPos (0),
  19605. wasSourceLooping (false)
  19606. {
  19607. jassert (source_ != 0);
  19608. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19609. // not using a larger buffer..
  19610. }
  19611. BufferingAudioSource::~BufferingAudioSource()
  19612. {
  19613. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19614. if (thread != 0)
  19615. thread->removeSource (this);
  19616. if (deleteSourceWhenDeleted)
  19617. delete source;
  19618. }
  19619. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19620. {
  19621. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19622. sampleRate = sampleRate_;
  19623. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19624. buffer.clear();
  19625. bufferValidStart = 0;
  19626. bufferValidEnd = 0;
  19627. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19628. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19629. buffer.getNumSamples() / 2))
  19630. {
  19631. SharedBufferingAudioSourceThread::getInstance()->notify();
  19632. Thread::sleep (5);
  19633. }
  19634. }
  19635. void BufferingAudioSource::releaseResources()
  19636. {
  19637. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19638. if (thread != 0)
  19639. thread->removeSource (this);
  19640. buffer.setSize (2, 0);
  19641. source->releaseResources();
  19642. }
  19643. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19644. {
  19645. const ScopedLock sl (bufferStartPosLock);
  19646. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19647. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19648. if (validStart == validEnd)
  19649. {
  19650. // total cache miss
  19651. info.clearActiveBufferRegion();
  19652. }
  19653. else
  19654. {
  19655. if (validStart > 0)
  19656. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19657. if (validEnd < info.numSamples)
  19658. info.buffer->clear (info.startSample + validEnd,
  19659. info.numSamples - validEnd); // partial cache miss at end
  19660. if (validStart < validEnd)
  19661. {
  19662. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19663. {
  19664. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19665. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19666. if (startBufferIndex < endBufferIndex)
  19667. {
  19668. info.buffer->copyFrom (chan, info.startSample + validStart,
  19669. buffer,
  19670. chan, startBufferIndex,
  19671. validEnd - validStart);
  19672. }
  19673. else
  19674. {
  19675. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19676. info.buffer->copyFrom (chan, info.startSample + validStart,
  19677. buffer,
  19678. chan, startBufferIndex,
  19679. initialSize);
  19680. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19681. buffer,
  19682. chan, 0,
  19683. (validEnd - validStart) - initialSize);
  19684. }
  19685. }
  19686. }
  19687. nextPlayPos += info.numSamples;
  19688. if (source->isLooping() && nextPlayPos > 0)
  19689. nextPlayPos %= source->getTotalLength();
  19690. }
  19691. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19692. if (thread != 0)
  19693. thread->notify();
  19694. }
  19695. int BufferingAudioSource::getNextReadPosition() const
  19696. {
  19697. return (source->isLooping() && nextPlayPos > 0)
  19698. ? nextPlayPos % source->getTotalLength()
  19699. : nextPlayPos;
  19700. }
  19701. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19702. {
  19703. const ScopedLock sl (bufferStartPosLock);
  19704. nextPlayPos = newPosition;
  19705. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19706. if (thread != 0)
  19707. thread->notify();
  19708. }
  19709. bool BufferingAudioSource::readNextBufferChunk()
  19710. {
  19711. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19712. {
  19713. const ScopedLock sl (bufferStartPosLock);
  19714. if (wasSourceLooping != isLooping())
  19715. {
  19716. wasSourceLooping = isLooping();
  19717. bufferValidStart = 0;
  19718. bufferValidEnd = 0;
  19719. }
  19720. newBVS = jmax (0, nextPlayPos);
  19721. newBVE = newBVS + buffer.getNumSamples() - 4;
  19722. sectionToReadStart = 0;
  19723. sectionToReadEnd = 0;
  19724. const int maxChunkSize = 2048;
  19725. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19726. {
  19727. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19728. sectionToReadStart = newBVS;
  19729. sectionToReadEnd = newBVE;
  19730. bufferValidStart = 0;
  19731. bufferValidEnd = 0;
  19732. }
  19733. else if (abs (newBVS - bufferValidStart) > 512
  19734. || abs (newBVE - bufferValidEnd) > 512)
  19735. {
  19736. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19737. sectionToReadStart = bufferValidEnd;
  19738. sectionToReadEnd = newBVE;
  19739. bufferValidStart = newBVS;
  19740. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19741. }
  19742. }
  19743. if (sectionToReadStart != sectionToReadEnd)
  19744. {
  19745. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19746. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19747. if (bufferIndexStart < bufferIndexEnd)
  19748. {
  19749. readBufferSection (sectionToReadStart,
  19750. sectionToReadEnd - sectionToReadStart,
  19751. bufferIndexStart);
  19752. }
  19753. else
  19754. {
  19755. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19756. readBufferSection (sectionToReadStart,
  19757. initialSize,
  19758. bufferIndexStart);
  19759. readBufferSection (sectionToReadStart + initialSize,
  19760. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19761. 0);
  19762. }
  19763. const ScopedLock sl2 (bufferStartPosLock);
  19764. bufferValidStart = newBVS;
  19765. bufferValidEnd = newBVE;
  19766. return true;
  19767. }
  19768. else
  19769. {
  19770. return false;
  19771. }
  19772. }
  19773. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19774. {
  19775. if (source->getNextReadPosition() != start)
  19776. source->setNextReadPosition (start);
  19777. AudioSourceChannelInfo info;
  19778. info.buffer = &buffer;
  19779. info.startSample = bufferOffset;
  19780. info.numSamples = length;
  19781. source->getNextAudioBlock (info);
  19782. }
  19783. END_JUCE_NAMESPACE
  19784. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19785. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19786. BEGIN_JUCE_NAMESPACE
  19787. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19788. const bool deleteSourceWhenDeleted_)
  19789. : requiredNumberOfChannels (2),
  19790. source (source_),
  19791. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19792. buffer (2, 16)
  19793. {
  19794. remappedInfo.buffer = &buffer;
  19795. remappedInfo.startSample = 0;
  19796. }
  19797. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19798. {
  19799. if (deleteSourceWhenDeleted)
  19800. delete source;
  19801. }
  19802. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19803. {
  19804. const ScopedLock sl (lock);
  19805. requiredNumberOfChannels = requiredNumberOfChannels_;
  19806. }
  19807. void ChannelRemappingAudioSource::clearAllMappings()
  19808. {
  19809. const ScopedLock sl (lock);
  19810. remappedInputs.clear();
  19811. remappedOutputs.clear();
  19812. }
  19813. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19814. {
  19815. const ScopedLock sl (lock);
  19816. while (remappedInputs.size() < destIndex)
  19817. remappedInputs.add (-1);
  19818. remappedInputs.set (destIndex, sourceIndex);
  19819. }
  19820. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19821. {
  19822. const ScopedLock sl (lock);
  19823. while (remappedOutputs.size() < sourceIndex)
  19824. remappedOutputs.add (-1);
  19825. remappedOutputs.set (sourceIndex, destIndex);
  19826. }
  19827. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19828. {
  19829. const ScopedLock sl (lock);
  19830. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19831. return remappedInputs.getUnchecked (inputChannelIndex);
  19832. return -1;
  19833. }
  19834. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19835. {
  19836. const ScopedLock sl (lock);
  19837. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19838. return remappedOutputs .getUnchecked (outputChannelIndex);
  19839. return -1;
  19840. }
  19841. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19842. {
  19843. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19844. }
  19845. void ChannelRemappingAudioSource::releaseResources()
  19846. {
  19847. source->releaseResources();
  19848. }
  19849. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19850. {
  19851. const ScopedLock sl (lock);
  19852. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19853. const int numChans = bufferToFill.buffer->getNumChannels();
  19854. int i;
  19855. for (i = 0; i < buffer.getNumChannels(); ++i)
  19856. {
  19857. const int remappedChan = getRemappedInputChannel (i);
  19858. if (remappedChan >= 0 && remappedChan < numChans)
  19859. {
  19860. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19861. remappedChan,
  19862. bufferToFill.startSample,
  19863. bufferToFill.numSamples);
  19864. }
  19865. else
  19866. {
  19867. buffer.clear (i, 0, bufferToFill.numSamples);
  19868. }
  19869. }
  19870. remappedInfo.numSamples = bufferToFill.numSamples;
  19871. source->getNextAudioBlock (remappedInfo);
  19872. bufferToFill.clearActiveBufferRegion();
  19873. for (i = 0; i < requiredNumberOfChannels; ++i)
  19874. {
  19875. const int remappedChan = getRemappedOutputChannel (i);
  19876. if (remappedChan >= 0 && remappedChan < numChans)
  19877. {
  19878. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19879. buffer, i, 0, bufferToFill.numSamples);
  19880. }
  19881. }
  19882. }
  19883. XmlElement* ChannelRemappingAudioSource::createXml() const
  19884. {
  19885. XmlElement* e = new XmlElement ("MAPPINGS");
  19886. String ins, outs;
  19887. int i;
  19888. const ScopedLock sl (lock);
  19889. for (i = 0; i < remappedInputs.size(); ++i)
  19890. ins << remappedInputs.getUnchecked(i) << ' ';
  19891. for (i = 0; i < remappedOutputs.size(); ++i)
  19892. outs << remappedOutputs.getUnchecked(i) << ' ';
  19893. e->setAttribute ("inputs", ins.trimEnd());
  19894. e->setAttribute ("outputs", outs.trimEnd());
  19895. return e;
  19896. }
  19897. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19898. {
  19899. if (e.hasTagName ("MAPPINGS"))
  19900. {
  19901. const ScopedLock sl (lock);
  19902. clearAllMappings();
  19903. StringArray ins, outs;
  19904. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19905. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19906. int i;
  19907. for (i = 0; i < ins.size(); ++i)
  19908. remappedInputs.add (ins[i].getIntValue());
  19909. for (i = 0; i < outs.size(); ++i)
  19910. remappedOutputs.add (outs[i].getIntValue());
  19911. }
  19912. }
  19913. END_JUCE_NAMESPACE
  19914. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19915. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19916. BEGIN_JUCE_NAMESPACE
  19917. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19918. const bool deleteInputWhenDeleted_)
  19919. : input (inputSource),
  19920. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19921. {
  19922. jassert (inputSource != 0);
  19923. for (int i = 2; --i >= 0;)
  19924. iirFilters.add (new IIRFilter());
  19925. }
  19926. IIRFilterAudioSource::~IIRFilterAudioSource()
  19927. {
  19928. if (deleteInputWhenDeleted)
  19929. delete input;
  19930. }
  19931. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19932. {
  19933. for (int i = iirFilters.size(); --i >= 0;)
  19934. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19935. }
  19936. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19937. {
  19938. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19939. for (int i = iirFilters.size(); --i >= 0;)
  19940. iirFilters.getUnchecked(i)->reset();
  19941. }
  19942. void IIRFilterAudioSource::releaseResources()
  19943. {
  19944. input->releaseResources();
  19945. }
  19946. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19947. {
  19948. input->getNextAudioBlock (bufferToFill);
  19949. const int numChannels = bufferToFill.buffer->getNumChannels();
  19950. while (numChannels > iirFilters.size())
  19951. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19952. for (int i = 0; i < numChannels; ++i)
  19953. iirFilters.getUnchecked(i)
  19954. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19955. bufferToFill.numSamples);
  19956. }
  19957. END_JUCE_NAMESPACE
  19958. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19959. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19960. BEGIN_JUCE_NAMESPACE
  19961. MixerAudioSource::MixerAudioSource()
  19962. : tempBuffer (2, 0),
  19963. currentSampleRate (0.0),
  19964. bufferSizeExpected (0)
  19965. {
  19966. }
  19967. MixerAudioSource::~MixerAudioSource()
  19968. {
  19969. removeAllInputs();
  19970. }
  19971. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19972. {
  19973. if (input != 0 && ! inputs.contains (input))
  19974. {
  19975. double localRate;
  19976. int localBufferSize;
  19977. {
  19978. const ScopedLock sl (lock);
  19979. localRate = currentSampleRate;
  19980. localBufferSize = bufferSizeExpected;
  19981. }
  19982. if (localRate != 0.0)
  19983. input->prepareToPlay (localBufferSize, localRate);
  19984. const ScopedLock sl (lock);
  19985. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19986. inputs.add (input);
  19987. }
  19988. }
  19989. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19990. {
  19991. if (input != 0)
  19992. {
  19993. int index;
  19994. {
  19995. const ScopedLock sl (lock);
  19996. index = inputs.indexOf (input);
  19997. if (index >= 0)
  19998. {
  19999. inputsToDelete.shiftBits (index, 1);
  20000. inputs.remove (index);
  20001. }
  20002. }
  20003. if (index >= 0)
  20004. {
  20005. input->releaseResources();
  20006. if (deleteInput)
  20007. delete input;
  20008. }
  20009. }
  20010. }
  20011. void MixerAudioSource::removeAllInputs()
  20012. {
  20013. OwnedArray<AudioSource> toDelete;
  20014. {
  20015. const ScopedLock sl (lock);
  20016. for (int i = inputs.size(); --i >= 0;)
  20017. if (inputsToDelete[i])
  20018. toDelete.add (inputs.getUnchecked(i));
  20019. }
  20020. }
  20021. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  20022. {
  20023. tempBuffer.setSize (2, samplesPerBlockExpected);
  20024. const ScopedLock sl (lock);
  20025. currentSampleRate = sampleRate;
  20026. bufferSizeExpected = samplesPerBlockExpected;
  20027. for (int i = inputs.size(); --i >= 0;)
  20028. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20029. }
  20030. void MixerAudioSource::releaseResources()
  20031. {
  20032. const ScopedLock sl (lock);
  20033. for (int i = inputs.size(); --i >= 0;)
  20034. inputs.getUnchecked(i)->releaseResources();
  20035. tempBuffer.setSize (2, 0);
  20036. currentSampleRate = 0;
  20037. bufferSizeExpected = 0;
  20038. }
  20039. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20040. {
  20041. const ScopedLock sl (lock);
  20042. if (inputs.size() > 0)
  20043. {
  20044. inputs.getUnchecked(0)->getNextAudioBlock (info);
  20045. if (inputs.size() > 1)
  20046. {
  20047. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  20048. info.buffer->getNumSamples());
  20049. AudioSourceChannelInfo info2;
  20050. info2.buffer = &tempBuffer;
  20051. info2.numSamples = info.numSamples;
  20052. info2.startSample = 0;
  20053. for (int i = 1; i < inputs.size(); ++i)
  20054. {
  20055. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  20056. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  20057. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  20058. }
  20059. }
  20060. }
  20061. else
  20062. {
  20063. info.clearActiveBufferRegion();
  20064. }
  20065. }
  20066. END_JUCE_NAMESPACE
  20067. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  20068. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  20069. BEGIN_JUCE_NAMESPACE
  20070. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  20071. const bool deleteInputWhenDeleted_,
  20072. const int numChannels_)
  20073. : input (inputSource),
  20074. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  20075. ratio (1.0),
  20076. lastRatio (1.0),
  20077. buffer (numChannels_, 0),
  20078. sampsInBuffer (0),
  20079. numChannels (numChannels_)
  20080. {
  20081. jassert (input != 0);
  20082. }
  20083. ResamplingAudioSource::~ResamplingAudioSource()
  20084. {
  20085. if (deleteInputWhenDeleted)
  20086. delete input;
  20087. }
  20088. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  20089. {
  20090. jassert (samplesInPerOutputSample > 0);
  20091. const ScopedLock sl (ratioLock);
  20092. ratio = jmax (0.0, samplesInPerOutputSample);
  20093. }
  20094. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  20095. double sampleRate)
  20096. {
  20097. const ScopedLock sl (ratioLock);
  20098. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20099. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  20100. buffer.clear();
  20101. sampsInBuffer = 0;
  20102. bufferPos = 0;
  20103. subSampleOffset = 0.0;
  20104. filterStates.calloc (numChannels);
  20105. srcBuffers.calloc (numChannels);
  20106. destBuffers.calloc (numChannels);
  20107. createLowPass (ratio);
  20108. resetFilters();
  20109. }
  20110. void ResamplingAudioSource::releaseResources()
  20111. {
  20112. input->releaseResources();
  20113. buffer.setSize (numChannels, 0);
  20114. }
  20115. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20116. {
  20117. const ScopedLock sl (ratioLock);
  20118. if (lastRatio != ratio)
  20119. {
  20120. createLowPass (ratio);
  20121. lastRatio = ratio;
  20122. }
  20123. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20124. int bufferSize = buffer.getNumSamples();
  20125. if (bufferSize < sampsNeeded + 8)
  20126. {
  20127. bufferPos %= bufferSize;
  20128. bufferSize = sampsNeeded + 32;
  20129. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20130. }
  20131. bufferPos %= bufferSize;
  20132. int endOfBufferPos = bufferPos + sampsInBuffer;
  20133. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20134. while (sampsNeeded > sampsInBuffer)
  20135. {
  20136. endOfBufferPos %= bufferSize;
  20137. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20138. bufferSize - endOfBufferPos);
  20139. AudioSourceChannelInfo readInfo;
  20140. readInfo.buffer = &buffer;
  20141. readInfo.numSamples = numToDo;
  20142. readInfo.startSample = endOfBufferPos;
  20143. input->getNextAudioBlock (readInfo);
  20144. if (ratio > 1.0001)
  20145. {
  20146. // for down-sampling, pre-apply the filter..
  20147. for (int i = channelsToProcess; --i >= 0;)
  20148. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20149. }
  20150. sampsInBuffer += numToDo;
  20151. endOfBufferPos += numToDo;
  20152. }
  20153. for (int channel = 0; channel < channelsToProcess; ++channel)
  20154. {
  20155. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20156. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20157. }
  20158. int nextPos = (bufferPos + 1) % bufferSize;
  20159. for (int m = info.numSamples; --m >= 0;)
  20160. {
  20161. const float alpha = (float) subSampleOffset;
  20162. const float invAlpha = 1.0f - alpha;
  20163. for (int channel = 0; channel < channelsToProcess; ++channel)
  20164. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20165. subSampleOffset += ratio;
  20166. jassert (sampsInBuffer > 0);
  20167. while (subSampleOffset >= 1.0)
  20168. {
  20169. if (++bufferPos >= bufferSize)
  20170. bufferPos = 0;
  20171. --sampsInBuffer;
  20172. nextPos = (bufferPos + 1) % bufferSize;
  20173. subSampleOffset -= 1.0;
  20174. }
  20175. }
  20176. if (ratio < 0.9999)
  20177. {
  20178. // for up-sampling, apply the filter after transposing..
  20179. for (int i = channelsToProcess; --i >= 0;)
  20180. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20181. }
  20182. else if (ratio <= 1.0001)
  20183. {
  20184. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20185. for (int i = channelsToProcess; --i >= 0;)
  20186. {
  20187. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20188. FilterState& fs = filterStates[i];
  20189. if (info.numSamples > 1)
  20190. {
  20191. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20192. }
  20193. else
  20194. {
  20195. fs.y2 = fs.y1;
  20196. fs.x2 = fs.x1;
  20197. }
  20198. fs.y1 = fs.x1 = *endOfBuffer;
  20199. }
  20200. }
  20201. jassert (sampsInBuffer >= 0);
  20202. }
  20203. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20204. {
  20205. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20206. : 0.5 * frequencyRatio;
  20207. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  20208. const double nSquared = n * n;
  20209. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20210. setFilterCoefficients (c1,
  20211. c1 * 2.0f,
  20212. c1,
  20213. 1.0,
  20214. c1 * 2.0 * (1.0 - nSquared),
  20215. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20216. }
  20217. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20218. {
  20219. const double a = 1.0 / c4;
  20220. c1 *= a;
  20221. c2 *= a;
  20222. c3 *= a;
  20223. c5 *= a;
  20224. c6 *= a;
  20225. coefficients[0] = c1;
  20226. coefficients[1] = c2;
  20227. coefficients[2] = c3;
  20228. coefficients[3] = c4;
  20229. coefficients[4] = c5;
  20230. coefficients[5] = c6;
  20231. }
  20232. void ResamplingAudioSource::resetFilters()
  20233. {
  20234. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20235. }
  20236. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20237. {
  20238. while (--num >= 0)
  20239. {
  20240. const double in = *samples;
  20241. double out = coefficients[0] * in
  20242. + coefficients[1] * fs.x1
  20243. + coefficients[2] * fs.x2
  20244. - coefficients[4] * fs.y1
  20245. - coefficients[5] * fs.y2;
  20246. #if JUCE_INTEL
  20247. if (! (out < -1.0e-8 || out > 1.0e-8))
  20248. out = 0;
  20249. #endif
  20250. fs.x2 = fs.x1;
  20251. fs.x1 = in;
  20252. fs.y2 = fs.y1;
  20253. fs.y1 = out;
  20254. *samples++ = (float) out;
  20255. }
  20256. }
  20257. END_JUCE_NAMESPACE
  20258. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20259. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20260. BEGIN_JUCE_NAMESPACE
  20261. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20262. : frequency (1000.0),
  20263. sampleRate (44100.0),
  20264. currentPhase (0.0),
  20265. phasePerSample (0.0),
  20266. amplitude (0.5f)
  20267. {
  20268. }
  20269. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20270. {
  20271. }
  20272. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20273. {
  20274. amplitude = newAmplitude;
  20275. }
  20276. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20277. {
  20278. frequency = newFrequencyHz;
  20279. phasePerSample = 0.0;
  20280. }
  20281. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20282. double sampleRate_)
  20283. {
  20284. currentPhase = 0.0;
  20285. phasePerSample = 0.0;
  20286. sampleRate = sampleRate_;
  20287. }
  20288. void ToneGeneratorAudioSource::releaseResources()
  20289. {
  20290. }
  20291. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20292. {
  20293. if (phasePerSample == 0.0)
  20294. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20295. for (int i = 0; i < info.numSamples; ++i)
  20296. {
  20297. const float sample = amplitude * (float) std::sin (currentPhase);
  20298. currentPhase += phasePerSample;
  20299. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20300. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20301. }
  20302. }
  20303. END_JUCE_NAMESPACE
  20304. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20305. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20306. BEGIN_JUCE_NAMESPACE
  20307. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20308. : sampleRate (0),
  20309. bufferSize (0),
  20310. useDefaultInputChannels (true),
  20311. useDefaultOutputChannels (true)
  20312. {
  20313. }
  20314. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20315. {
  20316. return outputDeviceName == other.outputDeviceName
  20317. && inputDeviceName == other.inputDeviceName
  20318. && sampleRate == other.sampleRate
  20319. && bufferSize == other.bufferSize
  20320. && inputChannels == other.inputChannels
  20321. && useDefaultInputChannels == other.useDefaultInputChannels
  20322. && outputChannels == other.outputChannels
  20323. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20324. }
  20325. AudioDeviceManager::AudioDeviceManager()
  20326. : currentAudioDevice (0),
  20327. numInputChansNeeded (0),
  20328. numOutputChansNeeded (2),
  20329. listNeedsScanning (true),
  20330. useInputNames (false),
  20331. inputLevelMeasurementEnabledCount (0),
  20332. inputLevel (0),
  20333. tempBuffer (2, 2),
  20334. defaultMidiOutput (0),
  20335. cpuUsageMs (0),
  20336. timeToCpuScale (0)
  20337. {
  20338. callbackHandler.owner = this;
  20339. }
  20340. AudioDeviceManager::~AudioDeviceManager()
  20341. {
  20342. currentAudioDevice = 0;
  20343. defaultMidiOutput = 0;
  20344. }
  20345. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20346. {
  20347. if (availableDeviceTypes.size() == 0)
  20348. {
  20349. createAudioDeviceTypes (availableDeviceTypes);
  20350. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20351. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20352. if (availableDeviceTypes.size() > 0)
  20353. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20354. }
  20355. }
  20356. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20357. {
  20358. scanDevicesIfNeeded();
  20359. return availableDeviceTypes;
  20360. }
  20361. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20362. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20363. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20364. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20365. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20366. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20367. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20368. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20369. {
  20370. (void) list; // (to avoid 'unused param' warnings)
  20371. #if JUCE_WINDOWS
  20372. #if JUCE_WASAPI
  20373. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20374. list.add (juce_createAudioIODeviceType_WASAPI());
  20375. #endif
  20376. #if JUCE_DIRECTSOUND
  20377. list.add (juce_createAudioIODeviceType_DirectSound());
  20378. #endif
  20379. #if JUCE_ASIO
  20380. list.add (juce_createAudioIODeviceType_ASIO());
  20381. #endif
  20382. #endif
  20383. #if JUCE_MAC
  20384. list.add (juce_createAudioIODeviceType_CoreAudio());
  20385. #endif
  20386. #if JUCE_IOS
  20387. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20388. #endif
  20389. #if JUCE_LINUX && JUCE_ALSA
  20390. list.add (juce_createAudioIODeviceType_ALSA());
  20391. #endif
  20392. #if JUCE_LINUX && JUCE_JACK
  20393. list.add (juce_createAudioIODeviceType_JACK());
  20394. #endif
  20395. }
  20396. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20397. const int numOutputChannelsNeeded,
  20398. const XmlElement* const e,
  20399. const bool selectDefaultDeviceOnFailure,
  20400. const String& preferredDefaultDeviceName,
  20401. const AudioDeviceSetup* preferredSetupOptions)
  20402. {
  20403. scanDevicesIfNeeded();
  20404. numInputChansNeeded = numInputChannelsNeeded;
  20405. numOutputChansNeeded = numOutputChannelsNeeded;
  20406. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20407. {
  20408. lastExplicitSettings = new XmlElement (*e);
  20409. String error;
  20410. AudioDeviceSetup setup;
  20411. if (preferredSetupOptions != 0)
  20412. setup = *preferredSetupOptions;
  20413. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20414. {
  20415. setup.inputDeviceName = setup.outputDeviceName
  20416. = e->getStringAttribute ("audioDeviceName");
  20417. }
  20418. else
  20419. {
  20420. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20421. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20422. }
  20423. currentDeviceType = e->getStringAttribute ("deviceType");
  20424. if (currentDeviceType.isEmpty())
  20425. {
  20426. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20427. if (type != 0)
  20428. currentDeviceType = type->getTypeName();
  20429. else if (availableDeviceTypes.size() > 0)
  20430. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20431. }
  20432. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20433. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20434. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20435. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20436. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20437. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20438. error = setAudioDeviceSetup (setup, true);
  20439. midiInsFromXml.clear();
  20440. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20441. midiInsFromXml.add (c->getStringAttribute ("name"));
  20442. const StringArray allMidiIns (MidiInput::getDevices());
  20443. for (int i = allMidiIns.size(); --i >= 0;)
  20444. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20445. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20446. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20447. false, preferredDefaultDeviceName);
  20448. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20449. return error;
  20450. }
  20451. else
  20452. {
  20453. AudioDeviceSetup setup;
  20454. if (preferredSetupOptions != 0)
  20455. {
  20456. setup = *preferredSetupOptions;
  20457. }
  20458. else if (preferredDefaultDeviceName.isNotEmpty())
  20459. {
  20460. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20461. {
  20462. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20463. StringArray outs (type->getDeviceNames (false));
  20464. int i;
  20465. for (i = 0; i < outs.size(); ++i)
  20466. {
  20467. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20468. {
  20469. setup.outputDeviceName = outs[i];
  20470. break;
  20471. }
  20472. }
  20473. StringArray ins (type->getDeviceNames (true));
  20474. for (i = 0; i < ins.size(); ++i)
  20475. {
  20476. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20477. {
  20478. setup.inputDeviceName = ins[i];
  20479. break;
  20480. }
  20481. }
  20482. }
  20483. }
  20484. insertDefaultDeviceNames (setup);
  20485. return setAudioDeviceSetup (setup, false);
  20486. }
  20487. }
  20488. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20489. {
  20490. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20491. if (type != 0)
  20492. {
  20493. if (setup.outputDeviceName.isEmpty())
  20494. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20495. if (setup.inputDeviceName.isEmpty())
  20496. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20497. }
  20498. }
  20499. XmlElement* AudioDeviceManager::createStateXml() const
  20500. {
  20501. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20502. }
  20503. void AudioDeviceManager::scanDevicesIfNeeded()
  20504. {
  20505. if (listNeedsScanning)
  20506. {
  20507. listNeedsScanning = false;
  20508. createDeviceTypesIfNeeded();
  20509. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20510. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20511. }
  20512. }
  20513. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20514. {
  20515. scanDevicesIfNeeded();
  20516. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20517. {
  20518. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20519. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20520. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20521. {
  20522. return type;
  20523. }
  20524. }
  20525. return 0;
  20526. }
  20527. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20528. {
  20529. setup = currentSetup;
  20530. }
  20531. void AudioDeviceManager::deleteCurrentDevice()
  20532. {
  20533. currentAudioDevice = 0;
  20534. currentSetup.inputDeviceName = String::empty;
  20535. currentSetup.outputDeviceName = String::empty;
  20536. }
  20537. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20538. const bool treatAsChosenDevice)
  20539. {
  20540. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20541. {
  20542. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20543. && currentDeviceType != type)
  20544. {
  20545. currentDeviceType = type;
  20546. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20547. insertDefaultDeviceNames (s);
  20548. setAudioDeviceSetup (s, treatAsChosenDevice);
  20549. sendChangeMessage();
  20550. break;
  20551. }
  20552. }
  20553. }
  20554. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20555. {
  20556. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20557. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20558. return availableDeviceTypes[i];
  20559. return availableDeviceTypes[0];
  20560. }
  20561. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20562. const bool treatAsChosenDevice)
  20563. {
  20564. jassert (&newSetup != &currentSetup); // this will have no effect
  20565. if (newSetup == currentSetup && currentAudioDevice != 0)
  20566. return String::empty;
  20567. if (! (newSetup == currentSetup))
  20568. sendChangeMessage();
  20569. stopDevice();
  20570. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20571. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20572. String error;
  20573. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20574. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20575. {
  20576. deleteCurrentDevice();
  20577. if (treatAsChosenDevice)
  20578. updateXml();
  20579. return String::empty;
  20580. }
  20581. if (currentSetup.inputDeviceName != newInputDeviceName
  20582. || currentSetup.outputDeviceName != newOutputDeviceName
  20583. || currentAudioDevice == 0)
  20584. {
  20585. deleteCurrentDevice();
  20586. scanDevicesIfNeeded();
  20587. if (newOutputDeviceName.isNotEmpty()
  20588. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20589. {
  20590. return "No such device: " + newOutputDeviceName;
  20591. }
  20592. if (newInputDeviceName.isNotEmpty()
  20593. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20594. {
  20595. return "No such device: " + newInputDeviceName;
  20596. }
  20597. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20598. if (currentAudioDevice == 0)
  20599. 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!";
  20600. else
  20601. error = currentAudioDevice->getLastError();
  20602. if (error.isNotEmpty())
  20603. {
  20604. deleteCurrentDevice();
  20605. return error;
  20606. }
  20607. if (newSetup.useDefaultInputChannels)
  20608. {
  20609. inputChannels.clear();
  20610. inputChannels.setRange (0, numInputChansNeeded, true);
  20611. }
  20612. if (newSetup.useDefaultOutputChannels)
  20613. {
  20614. outputChannels.clear();
  20615. outputChannels.setRange (0, numOutputChansNeeded, true);
  20616. }
  20617. if (newInputDeviceName.isEmpty())
  20618. inputChannels.clear();
  20619. if (newOutputDeviceName.isEmpty())
  20620. outputChannels.clear();
  20621. }
  20622. if (! newSetup.useDefaultInputChannels)
  20623. inputChannels = newSetup.inputChannels;
  20624. if (! newSetup.useDefaultOutputChannels)
  20625. outputChannels = newSetup.outputChannels;
  20626. currentSetup = newSetup;
  20627. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20628. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20629. error = currentAudioDevice->open (inputChannels,
  20630. outputChannels,
  20631. currentSetup.sampleRate,
  20632. currentSetup.bufferSize);
  20633. if (error.isEmpty())
  20634. {
  20635. currentDeviceType = currentAudioDevice->getTypeName();
  20636. currentAudioDevice->start (&callbackHandler);
  20637. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20638. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20639. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20640. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20641. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20642. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20643. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20644. if (treatAsChosenDevice)
  20645. updateXml();
  20646. }
  20647. else
  20648. {
  20649. deleteCurrentDevice();
  20650. }
  20651. return error;
  20652. }
  20653. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20654. {
  20655. jassert (currentAudioDevice != 0);
  20656. if (rate > 0)
  20657. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20658. if (currentAudioDevice->getSampleRate (i) == rate)
  20659. return rate;
  20660. double lowestAbove44 = 0.0;
  20661. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20662. {
  20663. const double sr = currentAudioDevice->getSampleRate (i);
  20664. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20665. lowestAbove44 = sr;
  20666. }
  20667. if (lowestAbove44 > 0.0)
  20668. return lowestAbove44;
  20669. return currentAudioDevice->getSampleRate (0);
  20670. }
  20671. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20672. {
  20673. jassert (currentAudioDevice != 0);
  20674. if (bufferSize > 0)
  20675. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20676. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20677. return bufferSize;
  20678. return currentAudioDevice->getDefaultBufferSize();
  20679. }
  20680. void AudioDeviceManager::stopDevice()
  20681. {
  20682. if (currentAudioDevice != 0)
  20683. currentAudioDevice->stop();
  20684. testSound = 0;
  20685. }
  20686. void AudioDeviceManager::closeAudioDevice()
  20687. {
  20688. stopDevice();
  20689. currentAudioDevice = 0;
  20690. }
  20691. void AudioDeviceManager::restartLastAudioDevice()
  20692. {
  20693. if (currentAudioDevice == 0)
  20694. {
  20695. if (currentSetup.inputDeviceName.isEmpty()
  20696. && currentSetup.outputDeviceName.isEmpty())
  20697. {
  20698. // This method will only reload the last device that was running
  20699. // before closeAudioDevice() was called - you need to actually open
  20700. // one first, with setAudioDevice().
  20701. jassertfalse;
  20702. return;
  20703. }
  20704. AudioDeviceSetup s (currentSetup);
  20705. setAudioDeviceSetup (s, false);
  20706. }
  20707. }
  20708. void AudioDeviceManager::updateXml()
  20709. {
  20710. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20711. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20712. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20713. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20714. if (currentAudioDevice != 0)
  20715. {
  20716. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20717. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20718. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20719. if (! currentSetup.useDefaultInputChannels)
  20720. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20721. if (! currentSetup.useDefaultOutputChannels)
  20722. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20723. }
  20724. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20725. {
  20726. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20727. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20728. }
  20729. if (midiInsFromXml.size() > 0)
  20730. {
  20731. // Add any midi devices that have been enabled before, but which aren't currently
  20732. // open because the device has been disconnected.
  20733. const StringArray availableMidiDevices (MidiInput::getDevices());
  20734. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20735. {
  20736. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20737. {
  20738. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20739. m->setAttribute ("name", midiInsFromXml[i]);
  20740. }
  20741. }
  20742. }
  20743. if (defaultMidiOutputName.isNotEmpty())
  20744. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20745. }
  20746. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20747. {
  20748. {
  20749. const ScopedLock sl (audioCallbackLock);
  20750. if (callbacks.contains (newCallback))
  20751. return;
  20752. }
  20753. if (currentAudioDevice != 0 && newCallback != 0)
  20754. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20755. const ScopedLock sl (audioCallbackLock);
  20756. callbacks.add (newCallback);
  20757. }
  20758. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20759. {
  20760. if (callback != 0)
  20761. {
  20762. bool needsDeinitialising = currentAudioDevice != 0;
  20763. {
  20764. const ScopedLock sl (audioCallbackLock);
  20765. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20766. callbacks.removeValue (callback);
  20767. }
  20768. if (needsDeinitialising)
  20769. callback->audioDeviceStopped();
  20770. }
  20771. }
  20772. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20773. int numInputChannels,
  20774. float** outputChannelData,
  20775. int numOutputChannels,
  20776. int numSamples)
  20777. {
  20778. const ScopedLock sl (audioCallbackLock);
  20779. if (inputLevelMeasurementEnabledCount > 0)
  20780. {
  20781. for (int j = 0; j < numSamples; ++j)
  20782. {
  20783. float s = 0;
  20784. for (int i = 0; i < numInputChannels; ++i)
  20785. s += std::abs (inputChannelData[i][j]);
  20786. s /= numInputChannels;
  20787. const double decayFactor = 0.99992;
  20788. if (s > inputLevel)
  20789. inputLevel = s;
  20790. else if (inputLevel > 0.001f)
  20791. inputLevel *= decayFactor;
  20792. else
  20793. inputLevel = 0;
  20794. }
  20795. }
  20796. if (callbacks.size() > 0)
  20797. {
  20798. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20799. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20800. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20801. outputChannelData, numOutputChannels, numSamples);
  20802. float** const tempChans = tempBuffer.getArrayOfChannels();
  20803. for (int i = callbacks.size(); --i > 0;)
  20804. {
  20805. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20806. tempChans, numOutputChannels, numSamples);
  20807. for (int chan = 0; chan < numOutputChannels; ++chan)
  20808. {
  20809. const float* const src = tempChans [chan];
  20810. float* const dst = outputChannelData [chan];
  20811. if (src != 0 && dst != 0)
  20812. for (int j = 0; j < numSamples; ++j)
  20813. dst[j] += src[j];
  20814. }
  20815. }
  20816. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20817. const double filterAmount = 0.2;
  20818. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20819. }
  20820. else
  20821. {
  20822. for (int i = 0; i < numOutputChannels; ++i)
  20823. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20824. }
  20825. if (testSound != 0)
  20826. {
  20827. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20828. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20829. for (int i = 0; i < numOutputChannels; ++i)
  20830. for (int j = 0; j < numSamps; ++j)
  20831. outputChannelData [i][j] += src[j];
  20832. testSoundPosition += numSamps;
  20833. if (testSoundPosition >= testSound->getNumSamples())
  20834. testSound = 0;
  20835. }
  20836. }
  20837. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20838. {
  20839. cpuUsageMs = 0;
  20840. const double sampleRate = device->getCurrentSampleRate();
  20841. const int blockSize = device->getCurrentBufferSizeSamples();
  20842. if (sampleRate > 0.0 && blockSize > 0)
  20843. {
  20844. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20845. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20846. }
  20847. {
  20848. const ScopedLock sl (audioCallbackLock);
  20849. for (int i = callbacks.size(); --i >= 0;)
  20850. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20851. }
  20852. sendChangeMessage();
  20853. }
  20854. void AudioDeviceManager::audioDeviceStoppedInt()
  20855. {
  20856. cpuUsageMs = 0;
  20857. timeToCpuScale = 0;
  20858. sendChangeMessage();
  20859. const ScopedLock sl (audioCallbackLock);
  20860. for (int i = callbacks.size(); --i >= 0;)
  20861. callbacks.getUnchecked(i)->audioDeviceStopped();
  20862. }
  20863. double AudioDeviceManager::getCpuUsage() const
  20864. {
  20865. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20866. }
  20867. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20868. const bool enabled)
  20869. {
  20870. if (enabled != isMidiInputEnabled (name))
  20871. {
  20872. if (enabled)
  20873. {
  20874. const int index = MidiInput::getDevices().indexOf (name);
  20875. if (index >= 0)
  20876. {
  20877. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20878. if (min != 0)
  20879. {
  20880. enabledMidiInputs.add (min);
  20881. min->start();
  20882. }
  20883. }
  20884. }
  20885. else
  20886. {
  20887. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20888. if (enabledMidiInputs[i]->getName() == name)
  20889. enabledMidiInputs.remove (i);
  20890. }
  20891. updateXml();
  20892. sendChangeMessage();
  20893. }
  20894. }
  20895. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20896. {
  20897. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20898. if (enabledMidiInputs[i]->getName() == name)
  20899. return true;
  20900. return false;
  20901. }
  20902. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20903. MidiInputCallback* callback)
  20904. {
  20905. removeMidiInputCallback (name, callback);
  20906. if (name.isEmpty())
  20907. {
  20908. midiCallbacks.add (callback);
  20909. midiCallbackDevices.add (0);
  20910. }
  20911. else
  20912. {
  20913. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20914. {
  20915. if (enabledMidiInputs[i]->getName() == name)
  20916. {
  20917. const ScopedLock sl (midiCallbackLock);
  20918. midiCallbacks.add (callback);
  20919. midiCallbackDevices.add (enabledMidiInputs[i]);
  20920. break;
  20921. }
  20922. }
  20923. }
  20924. }
  20925. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20926. MidiInputCallback* /*callback*/)
  20927. {
  20928. const ScopedLock sl (midiCallbackLock);
  20929. for (int i = midiCallbacks.size(); --i >= 0;)
  20930. {
  20931. String devName;
  20932. if (midiCallbackDevices.getUnchecked(i) != 0)
  20933. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20934. if (devName == name)
  20935. {
  20936. midiCallbacks.remove (i);
  20937. midiCallbackDevices.remove (i);
  20938. }
  20939. }
  20940. }
  20941. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20942. const MidiMessage& message)
  20943. {
  20944. if (! message.isActiveSense())
  20945. {
  20946. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20947. const ScopedLock sl (midiCallbackLock);
  20948. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20949. {
  20950. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20951. if (md == source || (md == 0 && isDefaultSource))
  20952. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20953. }
  20954. }
  20955. }
  20956. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20957. {
  20958. if (defaultMidiOutputName != deviceName)
  20959. {
  20960. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20961. {
  20962. const ScopedLock sl (audioCallbackLock);
  20963. oldCallbacks = callbacks;
  20964. callbacks.clear();
  20965. }
  20966. if (currentAudioDevice != 0)
  20967. for (int i = oldCallbacks.size(); --i >= 0;)
  20968. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20969. defaultMidiOutput = 0;
  20970. defaultMidiOutputName = deviceName;
  20971. if (deviceName.isNotEmpty())
  20972. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20973. if (currentAudioDevice != 0)
  20974. for (int i = oldCallbacks.size(); --i >= 0;)
  20975. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20976. {
  20977. const ScopedLock sl (audioCallbackLock);
  20978. callbacks = oldCallbacks;
  20979. }
  20980. updateXml();
  20981. sendChangeMessage();
  20982. }
  20983. }
  20984. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20985. int numInputChannels,
  20986. float** outputChannelData,
  20987. int numOutputChannels,
  20988. int numSamples)
  20989. {
  20990. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20991. }
  20992. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20993. {
  20994. owner->audioDeviceAboutToStartInt (device);
  20995. }
  20996. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20997. {
  20998. owner->audioDeviceStoppedInt();
  20999. }
  21000. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  21001. {
  21002. owner->handleIncomingMidiMessageInt (source, message);
  21003. }
  21004. void AudioDeviceManager::playTestSound()
  21005. {
  21006. { // cunningly nested to swap, unlock and delete in that order.
  21007. ScopedPointer <AudioSampleBuffer> oldSound;
  21008. {
  21009. const ScopedLock sl (audioCallbackLock);
  21010. oldSound = testSound;
  21011. }
  21012. }
  21013. testSoundPosition = 0;
  21014. if (currentAudioDevice != 0)
  21015. {
  21016. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  21017. const int soundLength = (int) sampleRate;
  21018. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  21019. float* samples = newSound->getSampleData (0);
  21020. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  21021. const float amplitude = 0.5f;
  21022. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  21023. for (int i = 0; i < soundLength; ++i)
  21024. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  21025. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  21026. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  21027. const ScopedLock sl (audioCallbackLock);
  21028. testSound = newSound;
  21029. }
  21030. }
  21031. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  21032. {
  21033. const ScopedLock sl (audioCallbackLock);
  21034. if (enableMeasurement)
  21035. ++inputLevelMeasurementEnabledCount;
  21036. else
  21037. --inputLevelMeasurementEnabledCount;
  21038. inputLevel = 0;
  21039. }
  21040. double AudioDeviceManager::getCurrentInputLevel() const
  21041. {
  21042. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  21043. return inputLevel;
  21044. }
  21045. END_JUCE_NAMESPACE
  21046. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  21047. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  21048. BEGIN_JUCE_NAMESPACE
  21049. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  21050. : name (deviceName),
  21051. typeName (typeName_)
  21052. {
  21053. }
  21054. AudioIODevice::~AudioIODevice()
  21055. {
  21056. }
  21057. bool AudioIODevice::hasControlPanel() const
  21058. {
  21059. return false;
  21060. }
  21061. bool AudioIODevice::showControlPanel()
  21062. {
  21063. jassertfalse; // this should only be called for devices which return true from
  21064. // their hasControlPanel() method.
  21065. return false;
  21066. }
  21067. END_JUCE_NAMESPACE
  21068. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  21069. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  21070. BEGIN_JUCE_NAMESPACE
  21071. AudioIODeviceType::AudioIODeviceType (const String& name)
  21072. : typeName (name)
  21073. {
  21074. }
  21075. AudioIODeviceType::~AudioIODeviceType()
  21076. {
  21077. }
  21078. END_JUCE_NAMESPACE
  21079. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  21080. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  21081. BEGIN_JUCE_NAMESPACE
  21082. MidiOutput::MidiOutput()
  21083. : Thread ("midi out"),
  21084. internal (0),
  21085. firstMessage (0)
  21086. {
  21087. }
  21088. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  21089. const double sampleNumber)
  21090. : message (data, len, sampleNumber)
  21091. {
  21092. }
  21093. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  21094. const double millisecondCounterToStartAt,
  21095. double samplesPerSecondForBuffer)
  21096. {
  21097. // You've got to call startBackgroundThread() for this to actually work..
  21098. jassert (isThreadRunning());
  21099. // this needs to be a value in the future - RTFM for this method!
  21100. jassert (millisecondCounterToStartAt > 0);
  21101. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  21102. MidiBuffer::Iterator i (buffer);
  21103. const uint8* data;
  21104. int len, time;
  21105. while (i.getNextEvent (data, len, time))
  21106. {
  21107. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  21108. PendingMessage* const m
  21109. = new PendingMessage (data, len, eventTime);
  21110. const ScopedLock sl (lock);
  21111. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21112. {
  21113. m->next = firstMessage;
  21114. firstMessage = m;
  21115. }
  21116. else
  21117. {
  21118. PendingMessage* mm = firstMessage;
  21119. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21120. mm = mm->next;
  21121. m->next = mm->next;
  21122. mm->next = m;
  21123. }
  21124. }
  21125. notify();
  21126. }
  21127. void MidiOutput::clearAllPendingMessages()
  21128. {
  21129. const ScopedLock sl (lock);
  21130. while (firstMessage != 0)
  21131. {
  21132. PendingMessage* const m = firstMessage;
  21133. firstMessage = firstMessage->next;
  21134. delete m;
  21135. }
  21136. }
  21137. void MidiOutput::startBackgroundThread()
  21138. {
  21139. startThread (9);
  21140. }
  21141. void MidiOutput::stopBackgroundThread()
  21142. {
  21143. stopThread (5000);
  21144. }
  21145. void MidiOutput::run()
  21146. {
  21147. while (! threadShouldExit())
  21148. {
  21149. uint32 now = Time::getMillisecondCounter();
  21150. uint32 eventTime = 0;
  21151. uint32 timeToWait = 500;
  21152. PendingMessage* message;
  21153. {
  21154. const ScopedLock sl (lock);
  21155. message = firstMessage;
  21156. if (message != 0)
  21157. {
  21158. eventTime = roundToInt (message->message.getTimeStamp());
  21159. if (eventTime > now + 20)
  21160. {
  21161. timeToWait = eventTime - (now + 20);
  21162. message = 0;
  21163. }
  21164. else
  21165. {
  21166. firstMessage = message->next;
  21167. }
  21168. }
  21169. }
  21170. if (message != 0)
  21171. {
  21172. if (eventTime > now)
  21173. {
  21174. Time::waitForMillisecondCounter (eventTime);
  21175. if (threadShouldExit())
  21176. break;
  21177. }
  21178. if (eventTime > now - 200)
  21179. sendMessageNow (message->message);
  21180. delete message;
  21181. }
  21182. else
  21183. {
  21184. jassert (timeToWait < 1000 * 30);
  21185. wait (timeToWait);
  21186. }
  21187. }
  21188. clearAllPendingMessages();
  21189. }
  21190. END_JUCE_NAMESPACE
  21191. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21192. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21193. BEGIN_JUCE_NAMESPACE
  21194. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21195. {
  21196. const double maxVal = (double) 0x7fff;
  21197. char* intData = static_cast <char*> (dest);
  21198. if (dest != (void*) source || destBytesPerSample <= 4)
  21199. {
  21200. for (int i = 0; i < numSamples; ++i)
  21201. {
  21202. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21203. intData += destBytesPerSample;
  21204. }
  21205. }
  21206. else
  21207. {
  21208. intData += destBytesPerSample * numSamples;
  21209. for (int i = numSamples; --i >= 0;)
  21210. {
  21211. intData -= destBytesPerSample;
  21212. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21213. }
  21214. }
  21215. }
  21216. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21217. {
  21218. const double maxVal = (double) 0x7fff;
  21219. char* intData = static_cast <char*> (dest);
  21220. if (dest != (void*) source || destBytesPerSample <= 4)
  21221. {
  21222. for (int i = 0; i < numSamples; ++i)
  21223. {
  21224. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21225. intData += destBytesPerSample;
  21226. }
  21227. }
  21228. else
  21229. {
  21230. intData += destBytesPerSample * numSamples;
  21231. for (int i = numSamples; --i >= 0;)
  21232. {
  21233. intData -= destBytesPerSample;
  21234. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21235. }
  21236. }
  21237. }
  21238. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21239. {
  21240. const double maxVal = (double) 0x7fffff;
  21241. char* intData = static_cast <char*> (dest);
  21242. if (dest != (void*) source || destBytesPerSample <= 4)
  21243. {
  21244. for (int i = 0; i < numSamples; ++i)
  21245. {
  21246. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21247. intData += destBytesPerSample;
  21248. }
  21249. }
  21250. else
  21251. {
  21252. intData += destBytesPerSample * numSamples;
  21253. for (int i = numSamples; --i >= 0;)
  21254. {
  21255. intData -= destBytesPerSample;
  21256. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21257. }
  21258. }
  21259. }
  21260. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21261. {
  21262. const double maxVal = (double) 0x7fffff;
  21263. char* intData = static_cast <char*> (dest);
  21264. if (dest != (void*) source || destBytesPerSample <= 4)
  21265. {
  21266. for (int i = 0; i < numSamples; ++i)
  21267. {
  21268. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21269. intData += destBytesPerSample;
  21270. }
  21271. }
  21272. else
  21273. {
  21274. intData += destBytesPerSample * numSamples;
  21275. for (int i = numSamples; --i >= 0;)
  21276. {
  21277. intData -= destBytesPerSample;
  21278. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21279. }
  21280. }
  21281. }
  21282. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21283. {
  21284. const double maxVal = (double) 0x7fffffff;
  21285. char* intData = static_cast <char*> (dest);
  21286. if (dest != (void*) source || destBytesPerSample <= 4)
  21287. {
  21288. for (int i = 0; i < numSamples; ++i)
  21289. {
  21290. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21291. intData += destBytesPerSample;
  21292. }
  21293. }
  21294. else
  21295. {
  21296. intData += destBytesPerSample * numSamples;
  21297. for (int i = numSamples; --i >= 0;)
  21298. {
  21299. intData -= destBytesPerSample;
  21300. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21301. }
  21302. }
  21303. }
  21304. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21305. {
  21306. const double maxVal = (double) 0x7fffffff;
  21307. char* intData = static_cast <char*> (dest);
  21308. if (dest != (void*) source || destBytesPerSample <= 4)
  21309. {
  21310. for (int i = 0; i < numSamples; ++i)
  21311. {
  21312. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21313. intData += destBytesPerSample;
  21314. }
  21315. }
  21316. else
  21317. {
  21318. intData += destBytesPerSample * numSamples;
  21319. for (int i = numSamples; --i >= 0;)
  21320. {
  21321. intData -= destBytesPerSample;
  21322. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21323. }
  21324. }
  21325. }
  21326. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21327. {
  21328. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21329. char* d = static_cast <char*> (dest);
  21330. for (int i = 0; i < numSamples; ++i)
  21331. {
  21332. *(float*) d = source[i];
  21333. #if JUCE_BIG_ENDIAN
  21334. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21335. #endif
  21336. d += destBytesPerSample;
  21337. }
  21338. }
  21339. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21340. {
  21341. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21342. char* d = static_cast <char*> (dest);
  21343. for (int i = 0; i < numSamples; ++i)
  21344. {
  21345. *(float*) d = source[i];
  21346. #if JUCE_LITTLE_ENDIAN
  21347. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21348. #endif
  21349. d += destBytesPerSample;
  21350. }
  21351. }
  21352. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21353. {
  21354. const float scale = 1.0f / 0x7fff;
  21355. const char* intData = static_cast <const char*> (source);
  21356. if (source != (void*) dest || srcBytesPerSample >= 4)
  21357. {
  21358. for (int i = 0; i < numSamples; ++i)
  21359. {
  21360. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21361. intData += srcBytesPerSample;
  21362. }
  21363. }
  21364. else
  21365. {
  21366. intData += srcBytesPerSample * numSamples;
  21367. for (int i = numSamples; --i >= 0;)
  21368. {
  21369. intData -= srcBytesPerSample;
  21370. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21371. }
  21372. }
  21373. }
  21374. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21375. {
  21376. const float scale = 1.0f / 0x7fff;
  21377. const char* intData = static_cast <const char*> (source);
  21378. if (source != (void*) dest || srcBytesPerSample >= 4)
  21379. {
  21380. for (int i = 0; i < numSamples; ++i)
  21381. {
  21382. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21383. intData += srcBytesPerSample;
  21384. }
  21385. }
  21386. else
  21387. {
  21388. intData += srcBytesPerSample * numSamples;
  21389. for (int i = numSamples; --i >= 0;)
  21390. {
  21391. intData -= srcBytesPerSample;
  21392. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21393. }
  21394. }
  21395. }
  21396. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21397. {
  21398. const float scale = 1.0f / 0x7fffff;
  21399. const char* intData = static_cast <const char*> (source);
  21400. if (source != (void*) dest || srcBytesPerSample >= 4)
  21401. {
  21402. for (int i = 0; i < numSamples; ++i)
  21403. {
  21404. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21405. intData += srcBytesPerSample;
  21406. }
  21407. }
  21408. else
  21409. {
  21410. intData += srcBytesPerSample * numSamples;
  21411. for (int i = numSamples; --i >= 0;)
  21412. {
  21413. intData -= srcBytesPerSample;
  21414. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21415. }
  21416. }
  21417. }
  21418. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21419. {
  21420. const float scale = 1.0f / 0x7fffff;
  21421. const char* intData = static_cast <const char*> (source);
  21422. if (source != (void*) dest || srcBytesPerSample >= 4)
  21423. {
  21424. for (int i = 0; i < numSamples; ++i)
  21425. {
  21426. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21427. intData += srcBytesPerSample;
  21428. }
  21429. }
  21430. else
  21431. {
  21432. intData += srcBytesPerSample * numSamples;
  21433. for (int i = numSamples; --i >= 0;)
  21434. {
  21435. intData -= srcBytesPerSample;
  21436. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21437. }
  21438. }
  21439. }
  21440. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21441. {
  21442. const float scale = 1.0f / 0x7fffffff;
  21443. const char* intData = static_cast <const char*> (source);
  21444. if (source != (void*) dest || srcBytesPerSample >= 4)
  21445. {
  21446. for (int i = 0; i < numSamples; ++i)
  21447. {
  21448. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21449. intData += srcBytesPerSample;
  21450. }
  21451. }
  21452. else
  21453. {
  21454. intData += srcBytesPerSample * numSamples;
  21455. for (int i = numSamples; --i >= 0;)
  21456. {
  21457. intData -= srcBytesPerSample;
  21458. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21459. }
  21460. }
  21461. }
  21462. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21463. {
  21464. const float scale = 1.0f / 0x7fffffff;
  21465. const char* intData = static_cast <const char*> (source);
  21466. if (source != (void*) dest || srcBytesPerSample >= 4)
  21467. {
  21468. for (int i = 0; i < numSamples; ++i)
  21469. {
  21470. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21471. intData += srcBytesPerSample;
  21472. }
  21473. }
  21474. else
  21475. {
  21476. intData += srcBytesPerSample * numSamples;
  21477. for (int i = numSamples; --i >= 0;)
  21478. {
  21479. intData -= srcBytesPerSample;
  21480. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21481. }
  21482. }
  21483. }
  21484. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21485. {
  21486. const char* s = static_cast <const char*> (source);
  21487. for (int i = 0; i < numSamples; ++i)
  21488. {
  21489. dest[i] = *(float*)s;
  21490. #if JUCE_BIG_ENDIAN
  21491. uint32* const d = (uint32*) (dest + i);
  21492. *d = ByteOrder::swap (*d);
  21493. #endif
  21494. s += srcBytesPerSample;
  21495. }
  21496. }
  21497. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21498. {
  21499. const char* s = static_cast <const char*> (source);
  21500. for (int i = 0; i < numSamples; ++i)
  21501. {
  21502. dest[i] = *(float*)s;
  21503. #if JUCE_LITTLE_ENDIAN
  21504. uint32* const d = (uint32*) (dest + i);
  21505. *d = ByteOrder::swap (*d);
  21506. #endif
  21507. s += srcBytesPerSample;
  21508. }
  21509. }
  21510. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21511. const float* const source,
  21512. void* const dest,
  21513. const int numSamples)
  21514. {
  21515. switch (destFormat)
  21516. {
  21517. case int16LE:
  21518. convertFloatToInt16LE (source, dest, numSamples);
  21519. break;
  21520. case int16BE:
  21521. convertFloatToInt16BE (source, dest, numSamples);
  21522. break;
  21523. case int24LE:
  21524. convertFloatToInt24LE (source, dest, numSamples);
  21525. break;
  21526. case int24BE:
  21527. convertFloatToInt24BE (source, dest, numSamples);
  21528. break;
  21529. case int32LE:
  21530. convertFloatToInt32LE (source, dest, numSamples);
  21531. break;
  21532. case int32BE:
  21533. convertFloatToInt32BE (source, dest, numSamples);
  21534. break;
  21535. case float32LE:
  21536. convertFloatToFloat32LE (source, dest, numSamples);
  21537. break;
  21538. case float32BE:
  21539. convertFloatToFloat32BE (source, dest, numSamples);
  21540. break;
  21541. default:
  21542. jassertfalse;
  21543. break;
  21544. }
  21545. }
  21546. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21547. const void* const source,
  21548. float* const dest,
  21549. const int numSamples)
  21550. {
  21551. switch (sourceFormat)
  21552. {
  21553. case int16LE:
  21554. convertInt16LEToFloat (source, dest, numSamples);
  21555. break;
  21556. case int16BE:
  21557. convertInt16BEToFloat (source, dest, numSamples);
  21558. break;
  21559. case int24LE:
  21560. convertInt24LEToFloat (source, dest, numSamples);
  21561. break;
  21562. case int24BE:
  21563. convertInt24BEToFloat (source, dest, numSamples);
  21564. break;
  21565. case int32LE:
  21566. convertInt32LEToFloat (source, dest, numSamples);
  21567. break;
  21568. case int32BE:
  21569. convertInt32BEToFloat (source, dest, numSamples);
  21570. break;
  21571. case float32LE:
  21572. convertFloat32LEToFloat (source, dest, numSamples);
  21573. break;
  21574. case float32BE:
  21575. convertFloat32BEToFloat (source, dest, numSamples);
  21576. break;
  21577. default:
  21578. jassertfalse;
  21579. break;
  21580. }
  21581. }
  21582. void AudioDataConverters::interleaveSamples (const float** const source,
  21583. float* const dest,
  21584. const int numSamples,
  21585. const int numChannels)
  21586. {
  21587. for (int chan = 0; chan < numChannels; ++chan)
  21588. {
  21589. int i = chan;
  21590. const float* src = source [chan];
  21591. for (int j = 0; j < numSamples; ++j)
  21592. {
  21593. dest [i] = src [j];
  21594. i += numChannels;
  21595. }
  21596. }
  21597. }
  21598. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21599. float** const dest,
  21600. const int numSamples,
  21601. const int numChannels)
  21602. {
  21603. for (int chan = 0; chan < numChannels; ++chan)
  21604. {
  21605. int i = chan;
  21606. float* dst = dest [chan];
  21607. for (int j = 0; j < numSamples; ++j)
  21608. {
  21609. dst [j] = source [i];
  21610. i += numChannels;
  21611. }
  21612. }
  21613. }
  21614. #if JUCE_UNIT_TESTS
  21615. class AudioConversionTests : public UnitTest
  21616. {
  21617. public:
  21618. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21619. template <class F1, class E1, class F2, class E2>
  21620. struct Test5
  21621. {
  21622. static void test (UnitTest& unitTest)
  21623. {
  21624. test (unitTest, false);
  21625. test (unitTest, true);
  21626. }
  21627. static void test (UnitTest& unitTest, bool inPlace)
  21628. {
  21629. const int numSamples = 2048;
  21630. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21631. {
  21632. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21633. bool clippingFailed = false;
  21634. for (int i = 0; i < numSamples / 2; ++i)
  21635. {
  21636. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21637. if (! d.isFloatingPoint())
  21638. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21639. ++d;
  21640. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21641. ++d;
  21642. }
  21643. unitTest.expect (! clippingFailed);
  21644. }
  21645. // convert data from the source to dest format..
  21646. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21647. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21648. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21649. // ..and back again..
  21650. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21651. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21652. if (! inPlace)
  21653. zerostruct (reversed);
  21654. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21655. {
  21656. int biggestDiff = 0;
  21657. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21658. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21659. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21660. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21661. for (int i = 0; i < numSamples; ++i)
  21662. {
  21663. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21664. ++d1;
  21665. ++d2;
  21666. }
  21667. unitTest.expect (biggestDiff <= errorMargin);
  21668. }
  21669. }
  21670. };
  21671. template <class F1, class E1, class FormatType>
  21672. struct Test3
  21673. {
  21674. static void test (UnitTest& unitTest)
  21675. {
  21676. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21677. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21678. }
  21679. };
  21680. template <class FormatType, class Endianness>
  21681. struct Test2
  21682. {
  21683. static void test (UnitTest& unitTest)
  21684. {
  21685. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21686. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21687. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21688. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21689. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21690. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21691. }
  21692. };
  21693. template <class FormatType>
  21694. struct Test1
  21695. {
  21696. static void test (UnitTest& unitTest)
  21697. {
  21698. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21699. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21700. }
  21701. };
  21702. void runTest()
  21703. {
  21704. beginTest ("Round-trip conversion");
  21705. Test1 <AudioData::Int8>::test (*this);
  21706. Test1 <AudioData::Int16>::test (*this);
  21707. Test1 <AudioData::Int24>::test (*this);
  21708. Test1 <AudioData::Int32>::test (*this);
  21709. Test1 <AudioData::Float32>::test (*this);
  21710. }
  21711. };
  21712. static AudioConversionTests audioConversionUnitTests;
  21713. #endif
  21714. END_JUCE_NAMESPACE
  21715. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21716. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21717. BEGIN_JUCE_NAMESPACE
  21718. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21719. const int numSamples) throw()
  21720. : numChannels (numChannels_),
  21721. size (numSamples)
  21722. {
  21723. jassert (numSamples >= 0);
  21724. jassert (numChannels_ > 0);
  21725. allocateData();
  21726. }
  21727. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21728. : numChannels (other.numChannels),
  21729. size (other.size)
  21730. {
  21731. allocateData();
  21732. const size_t numBytes = size * sizeof (float);
  21733. for (int i = 0; i < numChannels; ++i)
  21734. memcpy (channels[i], other.channels[i], numBytes);
  21735. }
  21736. void AudioSampleBuffer::allocateData()
  21737. {
  21738. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21739. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21740. allocatedData.malloc (allocatedBytes);
  21741. channels = reinterpret_cast <float**> (allocatedData.getData());
  21742. float* chan = (float*) (allocatedData + channelListSize);
  21743. for (int i = 0; i < numChannels; ++i)
  21744. {
  21745. channels[i] = chan;
  21746. chan += size;
  21747. }
  21748. channels [numChannels] = 0;
  21749. }
  21750. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21751. const int numChannels_,
  21752. const int numSamples) throw()
  21753. : numChannels (numChannels_),
  21754. size (numSamples),
  21755. allocatedBytes (0)
  21756. {
  21757. jassert (numChannels_ > 0);
  21758. allocateChannels (dataToReferTo);
  21759. }
  21760. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21761. const int newNumChannels,
  21762. const int newNumSamples) throw()
  21763. {
  21764. jassert (newNumChannels > 0);
  21765. allocatedBytes = 0;
  21766. allocatedData.free();
  21767. numChannels = newNumChannels;
  21768. size = newNumSamples;
  21769. allocateChannels (dataToReferTo);
  21770. }
  21771. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21772. {
  21773. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21774. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21775. {
  21776. channels = static_cast <float**> (preallocatedChannelSpace);
  21777. }
  21778. else
  21779. {
  21780. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21781. channels = reinterpret_cast <float**> (allocatedData.getData());
  21782. }
  21783. for (int i = 0; i < numChannels; ++i)
  21784. {
  21785. // you have to pass in the same number of valid pointers as numChannels
  21786. jassert (dataToReferTo[i] != 0);
  21787. channels[i] = dataToReferTo[i];
  21788. }
  21789. channels [numChannels] = 0;
  21790. }
  21791. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21792. {
  21793. if (this != &other)
  21794. {
  21795. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21796. const size_t numBytes = size * sizeof (float);
  21797. for (int i = 0; i < numChannels; ++i)
  21798. memcpy (channels[i], other.channels[i], numBytes);
  21799. }
  21800. return *this;
  21801. }
  21802. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21803. {
  21804. }
  21805. void AudioSampleBuffer::setSize (const int newNumChannels,
  21806. const int newNumSamples,
  21807. const bool keepExistingContent,
  21808. const bool clearExtraSpace,
  21809. const bool avoidReallocating) throw()
  21810. {
  21811. jassert (newNumChannels > 0);
  21812. if (newNumSamples != size || newNumChannels != numChannels)
  21813. {
  21814. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21815. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21816. if (keepExistingContent)
  21817. {
  21818. HeapBlock <char> newData;
  21819. newData.allocate (newTotalBytes, clearExtraSpace);
  21820. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21821. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21822. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21823. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21824. for (int i = 0; i < numChansToCopy; ++i)
  21825. {
  21826. memcpy (newChan, channels[i], numBytesToCopy);
  21827. newChannels[i] = newChan;
  21828. newChan += newNumSamples;
  21829. }
  21830. allocatedData.swapWith (newData);
  21831. allocatedBytes = (int) newTotalBytes;
  21832. channels = newChannels;
  21833. }
  21834. else
  21835. {
  21836. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21837. {
  21838. if (clearExtraSpace)
  21839. zeromem (allocatedData, newTotalBytes);
  21840. }
  21841. else
  21842. {
  21843. allocatedBytes = newTotalBytes;
  21844. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21845. channels = reinterpret_cast <float**> (allocatedData.getData());
  21846. }
  21847. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21848. for (int i = 0; i < newNumChannels; ++i)
  21849. {
  21850. channels[i] = chan;
  21851. chan += newNumSamples;
  21852. }
  21853. }
  21854. channels [newNumChannels] = 0;
  21855. size = newNumSamples;
  21856. numChannels = newNumChannels;
  21857. }
  21858. }
  21859. void AudioSampleBuffer::clear() throw()
  21860. {
  21861. for (int i = 0; i < numChannels; ++i)
  21862. zeromem (channels[i], size * sizeof (float));
  21863. }
  21864. void AudioSampleBuffer::clear (const int startSample,
  21865. const int numSamples) throw()
  21866. {
  21867. jassert (startSample >= 0 && startSample + numSamples <= size);
  21868. for (int i = 0; i < numChannels; ++i)
  21869. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21870. }
  21871. void AudioSampleBuffer::clear (const int channel,
  21872. const int startSample,
  21873. const int numSamples) throw()
  21874. {
  21875. jassert (isPositiveAndBelow (channel, numChannels));
  21876. jassert (startSample >= 0 && startSample + numSamples <= size);
  21877. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21878. }
  21879. void AudioSampleBuffer::applyGain (const int channel,
  21880. const int startSample,
  21881. int numSamples,
  21882. const float gain) throw()
  21883. {
  21884. jassert (isPositiveAndBelow (channel, numChannels));
  21885. jassert (startSample >= 0 && startSample + numSamples <= size);
  21886. if (gain != 1.0f)
  21887. {
  21888. float* d = channels [channel] + startSample;
  21889. if (gain == 0.0f)
  21890. {
  21891. zeromem (d, sizeof (float) * numSamples);
  21892. }
  21893. else
  21894. {
  21895. while (--numSamples >= 0)
  21896. *d++ *= gain;
  21897. }
  21898. }
  21899. }
  21900. void AudioSampleBuffer::applyGainRamp (const int channel,
  21901. const int startSample,
  21902. int numSamples,
  21903. float startGain,
  21904. float endGain) throw()
  21905. {
  21906. if (startGain == endGain)
  21907. {
  21908. applyGain (channel, startSample, numSamples, startGain);
  21909. }
  21910. else
  21911. {
  21912. jassert (isPositiveAndBelow (channel, numChannels));
  21913. jassert (startSample >= 0 && startSample + numSamples <= size);
  21914. const float increment = (endGain - startGain) / numSamples;
  21915. float* d = channels [channel] + startSample;
  21916. while (--numSamples >= 0)
  21917. {
  21918. *d++ *= startGain;
  21919. startGain += increment;
  21920. }
  21921. }
  21922. }
  21923. void AudioSampleBuffer::applyGain (const int startSample,
  21924. const int numSamples,
  21925. const float gain) throw()
  21926. {
  21927. for (int i = 0; i < numChannels; ++i)
  21928. applyGain (i, startSample, numSamples, gain);
  21929. }
  21930. void AudioSampleBuffer::addFrom (const int destChannel,
  21931. const int destStartSample,
  21932. const AudioSampleBuffer& source,
  21933. const int sourceChannel,
  21934. const int sourceStartSample,
  21935. int numSamples,
  21936. const float gain) throw()
  21937. {
  21938. jassert (&source != this || sourceChannel != destChannel);
  21939. jassert (isPositiveAndBelow (destChannel, numChannels));
  21940. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21941. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21942. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21943. if (gain != 0.0f && numSamples > 0)
  21944. {
  21945. float* d = channels [destChannel] + destStartSample;
  21946. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21947. if (gain != 1.0f)
  21948. {
  21949. while (--numSamples >= 0)
  21950. *d++ += gain * *s++;
  21951. }
  21952. else
  21953. {
  21954. while (--numSamples >= 0)
  21955. *d++ += *s++;
  21956. }
  21957. }
  21958. }
  21959. void AudioSampleBuffer::addFrom (const int destChannel,
  21960. const int destStartSample,
  21961. const float* source,
  21962. int numSamples,
  21963. const float gain) throw()
  21964. {
  21965. jassert (isPositiveAndBelow (destChannel, numChannels));
  21966. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21967. jassert (source != 0);
  21968. if (gain != 0.0f && numSamples > 0)
  21969. {
  21970. float* d = channels [destChannel] + destStartSample;
  21971. if (gain != 1.0f)
  21972. {
  21973. while (--numSamples >= 0)
  21974. *d++ += gain * *source++;
  21975. }
  21976. else
  21977. {
  21978. while (--numSamples >= 0)
  21979. *d++ += *source++;
  21980. }
  21981. }
  21982. }
  21983. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21984. const int destStartSample,
  21985. const float* source,
  21986. int numSamples,
  21987. float startGain,
  21988. const float endGain) throw()
  21989. {
  21990. jassert (isPositiveAndBelow (destChannel, numChannels));
  21991. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21992. jassert (source != 0);
  21993. if (startGain == endGain)
  21994. {
  21995. addFrom (destChannel,
  21996. destStartSample,
  21997. source,
  21998. numSamples,
  21999. startGain);
  22000. }
  22001. else
  22002. {
  22003. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22004. {
  22005. const float increment = (endGain - startGain) / numSamples;
  22006. float* d = channels [destChannel] + destStartSample;
  22007. while (--numSamples >= 0)
  22008. {
  22009. *d++ += startGain * *source++;
  22010. startGain += increment;
  22011. }
  22012. }
  22013. }
  22014. }
  22015. void AudioSampleBuffer::copyFrom (const int destChannel,
  22016. const int destStartSample,
  22017. const AudioSampleBuffer& source,
  22018. const int sourceChannel,
  22019. const int sourceStartSample,
  22020. int numSamples) throw()
  22021. {
  22022. jassert (&source != this || sourceChannel != destChannel);
  22023. jassert (isPositiveAndBelow (destChannel, numChannels));
  22024. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22025. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  22026. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  22027. if (numSamples > 0)
  22028. {
  22029. memcpy (channels [destChannel] + destStartSample,
  22030. source.channels [sourceChannel] + sourceStartSample,
  22031. sizeof (float) * numSamples);
  22032. }
  22033. }
  22034. void AudioSampleBuffer::copyFrom (const int destChannel,
  22035. const int destStartSample,
  22036. const float* source,
  22037. int numSamples) throw()
  22038. {
  22039. jassert (isPositiveAndBelow (destChannel, numChannels));
  22040. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22041. jassert (source != 0);
  22042. if (numSamples > 0)
  22043. {
  22044. memcpy (channels [destChannel] + destStartSample,
  22045. source,
  22046. sizeof (float) * numSamples);
  22047. }
  22048. }
  22049. void AudioSampleBuffer::copyFrom (const int destChannel,
  22050. const int destStartSample,
  22051. const float* source,
  22052. int numSamples,
  22053. const float gain) throw()
  22054. {
  22055. jassert (isPositiveAndBelow (destChannel, numChannels));
  22056. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22057. jassert (source != 0);
  22058. if (numSamples > 0)
  22059. {
  22060. float* d = channels [destChannel] + destStartSample;
  22061. if (gain != 1.0f)
  22062. {
  22063. if (gain == 0)
  22064. {
  22065. zeromem (d, sizeof (float) * numSamples);
  22066. }
  22067. else
  22068. {
  22069. while (--numSamples >= 0)
  22070. *d++ = gain * *source++;
  22071. }
  22072. }
  22073. else
  22074. {
  22075. memcpy (d, source, sizeof (float) * numSamples);
  22076. }
  22077. }
  22078. }
  22079. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  22080. const int destStartSample,
  22081. const float* source,
  22082. int numSamples,
  22083. float startGain,
  22084. float endGain) throw()
  22085. {
  22086. jassert (isPositiveAndBelow (destChannel, numChannels));
  22087. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22088. jassert (source != 0);
  22089. if (startGain == endGain)
  22090. {
  22091. copyFrom (destChannel,
  22092. destStartSample,
  22093. source,
  22094. numSamples,
  22095. startGain);
  22096. }
  22097. else
  22098. {
  22099. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22100. {
  22101. const float increment = (endGain - startGain) / numSamples;
  22102. float* d = channels [destChannel] + destStartSample;
  22103. while (--numSamples >= 0)
  22104. {
  22105. *d++ = startGain * *source++;
  22106. startGain += increment;
  22107. }
  22108. }
  22109. }
  22110. }
  22111. void AudioSampleBuffer::findMinMax (const int channel,
  22112. const int startSample,
  22113. int numSamples,
  22114. float& minVal,
  22115. float& maxVal) const throw()
  22116. {
  22117. jassert (isPositiveAndBelow (channel, numChannels));
  22118. jassert (startSample >= 0 && startSample + numSamples <= size);
  22119. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  22120. }
  22121. float AudioSampleBuffer::getMagnitude (const int channel,
  22122. const int startSample,
  22123. const int numSamples) const throw()
  22124. {
  22125. jassert (isPositiveAndBelow (channel, numChannels));
  22126. jassert (startSample >= 0 && startSample + numSamples <= size);
  22127. float mn, mx;
  22128. findMinMax (channel, startSample, numSamples, mn, mx);
  22129. return jmax (mn, -mn, mx, -mx);
  22130. }
  22131. float AudioSampleBuffer::getMagnitude (const int startSample,
  22132. const int numSamples) const throw()
  22133. {
  22134. float mag = 0.0f;
  22135. for (int i = 0; i < numChannels; ++i)
  22136. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22137. return mag;
  22138. }
  22139. float AudioSampleBuffer::getRMSLevel (const int channel,
  22140. const int startSample,
  22141. const int numSamples) const throw()
  22142. {
  22143. jassert (isPositiveAndBelow (channel, numChannels));
  22144. jassert (startSample >= 0 && startSample + numSamples <= size);
  22145. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22146. return 0.0f;
  22147. const float* const data = channels [channel] + startSample;
  22148. double sum = 0.0;
  22149. for (int i = 0; i < numSamples; ++i)
  22150. {
  22151. const float sample = data [i];
  22152. sum += sample * sample;
  22153. }
  22154. return (float) std::sqrt (sum / numSamples);
  22155. }
  22156. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22157. const int startSample,
  22158. const int numSamples,
  22159. const int readerStartSample,
  22160. const bool useLeftChan,
  22161. const bool useRightChan)
  22162. {
  22163. jassert (reader != 0);
  22164. jassert (startSample >= 0 && startSample + numSamples <= size);
  22165. if (numSamples > 0)
  22166. {
  22167. int* chans[3];
  22168. if (useLeftChan == useRightChan)
  22169. {
  22170. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22171. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22172. }
  22173. else if (useLeftChan || (reader->numChannels == 1))
  22174. {
  22175. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22176. chans[1] = 0;
  22177. }
  22178. else if (useRightChan)
  22179. {
  22180. chans[0] = 0;
  22181. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22182. }
  22183. chans[2] = 0;
  22184. reader->read (chans, 2, readerStartSample, numSamples, true);
  22185. if (! reader->usesFloatingPointData)
  22186. {
  22187. for (int j = 0; j < 2; ++j)
  22188. {
  22189. float* const d = reinterpret_cast <float*> (chans[j]);
  22190. if (d != 0)
  22191. {
  22192. const float multiplier = 1.0f / 0x7fffffff;
  22193. for (int i = 0; i < numSamples; ++i)
  22194. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22195. }
  22196. }
  22197. }
  22198. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22199. {
  22200. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22201. memcpy (getSampleData (1, startSample),
  22202. getSampleData (0, startSample),
  22203. sizeof (float) * numSamples);
  22204. }
  22205. }
  22206. }
  22207. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22208. const int startSample,
  22209. const int numSamples) const
  22210. {
  22211. jassert (writer != 0);
  22212. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22213. }
  22214. END_JUCE_NAMESPACE
  22215. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22216. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22217. BEGIN_JUCE_NAMESPACE
  22218. IIRFilter::IIRFilter()
  22219. : active (false)
  22220. {
  22221. reset();
  22222. }
  22223. IIRFilter::IIRFilter (const IIRFilter& other)
  22224. : active (other.active)
  22225. {
  22226. const ScopedLock sl (other.processLock);
  22227. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22228. reset();
  22229. }
  22230. IIRFilter::~IIRFilter()
  22231. {
  22232. }
  22233. void IIRFilter::reset() throw()
  22234. {
  22235. const ScopedLock sl (processLock);
  22236. x1 = 0;
  22237. x2 = 0;
  22238. y1 = 0;
  22239. y2 = 0;
  22240. }
  22241. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22242. {
  22243. float out = coefficients[0] * in
  22244. + coefficients[1] * x1
  22245. + coefficients[2] * x2
  22246. - coefficients[4] * y1
  22247. - coefficients[5] * y2;
  22248. #if JUCE_INTEL
  22249. if (! (out < -1.0e-8 || out > 1.0e-8))
  22250. out = 0;
  22251. #endif
  22252. x2 = x1;
  22253. x1 = in;
  22254. y2 = y1;
  22255. y1 = out;
  22256. return out;
  22257. }
  22258. void IIRFilter::processSamples (float* const samples,
  22259. const int numSamples) throw()
  22260. {
  22261. const ScopedLock sl (processLock);
  22262. if (active)
  22263. {
  22264. for (int i = 0; i < numSamples; ++i)
  22265. {
  22266. const float in = samples[i];
  22267. float out = coefficients[0] * in
  22268. + coefficients[1] * x1
  22269. + coefficients[2] * x2
  22270. - coefficients[4] * y1
  22271. - coefficients[5] * y2;
  22272. #if JUCE_INTEL
  22273. if (! (out < -1.0e-8 || out > 1.0e-8))
  22274. out = 0;
  22275. #endif
  22276. x2 = x1;
  22277. x1 = in;
  22278. y2 = y1;
  22279. y1 = out;
  22280. samples[i] = out;
  22281. }
  22282. }
  22283. }
  22284. void IIRFilter::makeLowPass (const double sampleRate,
  22285. const double frequency) throw()
  22286. {
  22287. jassert (sampleRate > 0);
  22288. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22289. const double nSquared = n * n;
  22290. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22291. setCoefficients (c1,
  22292. c1 * 2.0f,
  22293. c1,
  22294. 1.0,
  22295. c1 * 2.0 * (1.0 - nSquared),
  22296. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22297. }
  22298. void IIRFilter::makeHighPass (const double sampleRate,
  22299. const double frequency) throw()
  22300. {
  22301. const double n = tan (double_Pi * frequency / sampleRate);
  22302. const double nSquared = n * n;
  22303. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22304. setCoefficients (c1,
  22305. c1 * -2.0f,
  22306. c1,
  22307. 1.0,
  22308. c1 * 2.0 * (nSquared - 1.0),
  22309. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22310. }
  22311. void IIRFilter::makeLowShelf (const double sampleRate,
  22312. const double cutOffFrequency,
  22313. const double Q,
  22314. const float gainFactor) throw()
  22315. {
  22316. jassert (sampleRate > 0);
  22317. jassert (Q > 0);
  22318. const double A = jmax (0.0f, gainFactor);
  22319. const double aminus1 = A - 1.0;
  22320. const double aplus1 = A + 1.0;
  22321. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22322. const double coso = std::cos (omega);
  22323. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22324. const double aminus1TimesCoso = aminus1 * coso;
  22325. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22326. A * 2.0 * (aminus1 - aplus1 * coso),
  22327. A * (aplus1 - aminus1TimesCoso - beta),
  22328. aplus1 + aminus1TimesCoso + beta,
  22329. -2.0 * (aminus1 + aplus1 * coso),
  22330. aplus1 + aminus1TimesCoso - beta);
  22331. }
  22332. void IIRFilter::makeHighShelf (const double sampleRate,
  22333. const double cutOffFrequency,
  22334. const double Q,
  22335. const float gainFactor) throw()
  22336. {
  22337. jassert (sampleRate > 0);
  22338. jassert (Q > 0);
  22339. const double A = jmax (0.0f, gainFactor);
  22340. const double aminus1 = A - 1.0;
  22341. const double aplus1 = A + 1.0;
  22342. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22343. const double coso = std::cos (omega);
  22344. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22345. const double aminus1TimesCoso = aminus1 * coso;
  22346. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22347. A * -2.0 * (aminus1 + aplus1 * coso),
  22348. A * (aplus1 + aminus1TimesCoso - beta),
  22349. aplus1 - aminus1TimesCoso + beta,
  22350. 2.0 * (aminus1 - aplus1 * coso),
  22351. aplus1 - aminus1TimesCoso - beta);
  22352. }
  22353. void IIRFilter::makeBandPass (const double sampleRate,
  22354. const double centreFrequency,
  22355. const double Q,
  22356. const float gainFactor) throw()
  22357. {
  22358. jassert (sampleRate > 0);
  22359. jassert (Q > 0);
  22360. const double A = jmax (0.0f, gainFactor);
  22361. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22362. const double alpha = 0.5 * std::sin (omega) / Q;
  22363. const double c2 = -2.0 * std::cos (omega);
  22364. const double alphaTimesA = alpha * A;
  22365. const double alphaOverA = alpha / A;
  22366. setCoefficients (1.0 + alphaTimesA,
  22367. c2,
  22368. 1.0 - alphaTimesA,
  22369. 1.0 + alphaOverA,
  22370. c2,
  22371. 1.0 - alphaOverA);
  22372. }
  22373. void IIRFilter::makeInactive() throw()
  22374. {
  22375. const ScopedLock sl (processLock);
  22376. active = false;
  22377. }
  22378. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22379. {
  22380. const ScopedLock sl (processLock);
  22381. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22382. active = other.active;
  22383. }
  22384. void IIRFilter::setCoefficients (double c1,
  22385. double c2,
  22386. double c3,
  22387. double c4,
  22388. double c5,
  22389. double c6) throw()
  22390. {
  22391. const double a = 1.0 / c4;
  22392. c1 *= a;
  22393. c2 *= a;
  22394. c3 *= a;
  22395. c5 *= a;
  22396. c6 *= a;
  22397. const ScopedLock sl (processLock);
  22398. coefficients[0] = (float) c1;
  22399. coefficients[1] = (float) c2;
  22400. coefficients[2] = (float) c3;
  22401. coefficients[3] = (float) c4;
  22402. coefficients[4] = (float) c5;
  22403. coefficients[5] = (float) c6;
  22404. active = true;
  22405. }
  22406. END_JUCE_NAMESPACE
  22407. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22408. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22409. BEGIN_JUCE_NAMESPACE
  22410. MidiBuffer::MidiBuffer() throw()
  22411. : bytesUsed (0)
  22412. {
  22413. }
  22414. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22415. : bytesUsed (0)
  22416. {
  22417. addEvent (message, 0);
  22418. }
  22419. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22420. : data (other.data),
  22421. bytesUsed (other.bytesUsed)
  22422. {
  22423. }
  22424. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22425. {
  22426. bytesUsed = other.bytesUsed;
  22427. data = other.data;
  22428. return *this;
  22429. }
  22430. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22431. {
  22432. data.swapWith (other.data);
  22433. swapVariables <int> (bytesUsed, other.bytesUsed);
  22434. }
  22435. MidiBuffer::~MidiBuffer()
  22436. {
  22437. }
  22438. inline uint8* MidiBuffer::getData() const throw()
  22439. {
  22440. return static_cast <uint8*> (data.getData());
  22441. }
  22442. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22443. {
  22444. return *static_cast <const int*> (d);
  22445. }
  22446. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22447. {
  22448. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22449. }
  22450. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22451. {
  22452. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22453. }
  22454. void MidiBuffer::clear() throw()
  22455. {
  22456. bytesUsed = 0;
  22457. }
  22458. void MidiBuffer::clear (const int startSample, const int numSamples)
  22459. {
  22460. uint8* const start = findEventAfter (getData(), startSample - 1);
  22461. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22462. if (end > start)
  22463. {
  22464. const int bytesToMove = bytesUsed - (int) (end - getData());
  22465. if (bytesToMove > 0)
  22466. memmove (start, end, bytesToMove);
  22467. bytesUsed -= (int) (end - start);
  22468. }
  22469. }
  22470. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22471. {
  22472. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22473. }
  22474. namespace MidiBufferHelpers
  22475. {
  22476. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22477. {
  22478. unsigned int byte = (unsigned int) *data;
  22479. int size = 0;
  22480. if (byte == 0xf0 || byte == 0xf7)
  22481. {
  22482. const uint8* d = data + 1;
  22483. while (d < data + maxBytes)
  22484. if (*d++ == 0xf7)
  22485. break;
  22486. size = (int) (d - data);
  22487. }
  22488. else if (byte == 0xff)
  22489. {
  22490. int n;
  22491. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22492. size = jmin (maxBytes, n + 2 + bytesLeft);
  22493. }
  22494. else if (byte >= 0x80)
  22495. {
  22496. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22497. }
  22498. return size;
  22499. }
  22500. }
  22501. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22502. {
  22503. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22504. if (numBytes > 0)
  22505. {
  22506. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22507. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22508. uint8* d = findEventAfter (getData(), sampleNumber);
  22509. const int bytesToMove = bytesUsed - (int) (d - getData());
  22510. if (bytesToMove > 0)
  22511. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22512. *reinterpret_cast <int*> (d) = sampleNumber;
  22513. d += sizeof (int);
  22514. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22515. d += sizeof (uint16);
  22516. memcpy (d, newData, numBytes);
  22517. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22518. }
  22519. }
  22520. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22521. const int startSample,
  22522. const int numSamples,
  22523. const int sampleDeltaToAdd)
  22524. {
  22525. Iterator i (otherBuffer);
  22526. i.setNextSamplePosition (startSample);
  22527. const uint8* eventData;
  22528. int eventSize, position;
  22529. while (i.getNextEvent (eventData, eventSize, position)
  22530. && (position < startSample + numSamples || numSamples < 0))
  22531. {
  22532. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22533. }
  22534. }
  22535. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22536. {
  22537. data.ensureSize (minimumNumBytes);
  22538. }
  22539. bool MidiBuffer::isEmpty() const throw()
  22540. {
  22541. return bytesUsed == 0;
  22542. }
  22543. int MidiBuffer::getNumEvents() const throw()
  22544. {
  22545. int n = 0;
  22546. const uint8* d = getData();
  22547. const uint8* const end = d + bytesUsed;
  22548. while (d < end)
  22549. {
  22550. d += getEventTotalSize (d);
  22551. ++n;
  22552. }
  22553. return n;
  22554. }
  22555. int MidiBuffer::getFirstEventTime() const throw()
  22556. {
  22557. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22558. }
  22559. int MidiBuffer::getLastEventTime() const throw()
  22560. {
  22561. if (bytesUsed == 0)
  22562. return 0;
  22563. const uint8* d = getData();
  22564. const uint8* const endData = d + bytesUsed;
  22565. for (;;)
  22566. {
  22567. const uint8* const nextOne = d + getEventTotalSize (d);
  22568. if (nextOne >= endData)
  22569. return getEventTime (d);
  22570. d = nextOne;
  22571. }
  22572. }
  22573. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22574. {
  22575. const uint8* const endData = getData() + bytesUsed;
  22576. while (d < endData && getEventTime (d) <= samplePosition)
  22577. d += getEventTotalSize (d);
  22578. return d;
  22579. }
  22580. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22581. : buffer (buffer_),
  22582. data (buffer_.getData())
  22583. {
  22584. }
  22585. MidiBuffer::Iterator::~Iterator() throw()
  22586. {
  22587. }
  22588. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22589. {
  22590. data = buffer.getData();
  22591. const uint8* dataEnd = data + buffer.bytesUsed;
  22592. while (data < dataEnd && getEventTime (data) < samplePosition)
  22593. data += getEventTotalSize (data);
  22594. }
  22595. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22596. {
  22597. if (data >= buffer.getData() + buffer.bytesUsed)
  22598. return false;
  22599. samplePosition = getEventTime (data);
  22600. numBytes = getEventDataSize (data);
  22601. data += sizeof (int) + sizeof (uint16);
  22602. midiData = data;
  22603. data += numBytes;
  22604. return true;
  22605. }
  22606. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22607. {
  22608. if (data >= buffer.getData() + buffer.bytesUsed)
  22609. return false;
  22610. samplePosition = getEventTime (data);
  22611. const int numBytes = getEventDataSize (data);
  22612. data += sizeof (int) + sizeof (uint16);
  22613. result = MidiMessage (data, numBytes, samplePosition);
  22614. data += numBytes;
  22615. return true;
  22616. }
  22617. END_JUCE_NAMESPACE
  22618. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22619. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22620. BEGIN_JUCE_NAMESPACE
  22621. namespace MidiFileHelpers
  22622. {
  22623. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22624. {
  22625. unsigned int buffer = v & 0x7F;
  22626. while ((v >>= 7) != 0)
  22627. {
  22628. buffer <<= 8;
  22629. buffer |= ((v & 0x7F) | 0x80);
  22630. }
  22631. for (;;)
  22632. {
  22633. out.writeByte ((char) buffer);
  22634. if (buffer & 0x80)
  22635. buffer >>= 8;
  22636. else
  22637. break;
  22638. }
  22639. }
  22640. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22641. {
  22642. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22643. data += 4;
  22644. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22645. {
  22646. bool ok = false;
  22647. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22648. {
  22649. for (int i = 0; i < 8; ++i)
  22650. {
  22651. ch = ByteOrder::bigEndianInt (data);
  22652. data += 4;
  22653. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22654. {
  22655. ok = true;
  22656. break;
  22657. }
  22658. }
  22659. }
  22660. if (! ok)
  22661. return false;
  22662. }
  22663. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22664. data += 4;
  22665. fileType = (short) ByteOrder::bigEndianShort (data);
  22666. data += 2;
  22667. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22668. data += 2;
  22669. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22670. data += 2;
  22671. bytesRemaining -= 6;
  22672. data += bytesRemaining;
  22673. return true;
  22674. }
  22675. double convertTicksToSeconds (const double time,
  22676. const MidiMessageSequence& tempoEvents,
  22677. const int timeFormat)
  22678. {
  22679. if (timeFormat > 0)
  22680. {
  22681. int numer = 4, denom = 4;
  22682. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22683. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22684. double secsPerTick = 0.5 * tickLen;
  22685. const int numEvents = tempoEvents.getNumEvents();
  22686. for (int i = 0; i < numEvents; ++i)
  22687. {
  22688. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22689. if (time <= m.getTimeStamp())
  22690. break;
  22691. if (timeFormat > 0)
  22692. {
  22693. correctedTempoTime = correctedTempoTime
  22694. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22695. }
  22696. else
  22697. {
  22698. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22699. }
  22700. tempoTime = m.getTimeStamp();
  22701. if (m.isTempoMetaEvent())
  22702. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22703. else if (m.isTimeSignatureMetaEvent())
  22704. m.getTimeSignatureInfo (numer, denom);
  22705. while (i + 1 < numEvents)
  22706. {
  22707. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22708. if (m2.getTimeStamp() == tempoTime)
  22709. {
  22710. ++i;
  22711. if (m2.isTempoMetaEvent())
  22712. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22713. else if (m2.isTimeSignatureMetaEvent())
  22714. m2.getTimeSignatureInfo (numer, denom);
  22715. }
  22716. else
  22717. {
  22718. break;
  22719. }
  22720. }
  22721. }
  22722. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22723. }
  22724. else
  22725. {
  22726. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22727. }
  22728. }
  22729. // a comparator that puts all the note-offs before note-ons that have the same time
  22730. struct Sorter
  22731. {
  22732. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22733. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22734. {
  22735. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22736. if (diff == 0)
  22737. {
  22738. if (first->message.isNoteOff() && second->message.isNoteOn())
  22739. return -1;
  22740. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22741. return 1;
  22742. else
  22743. return 0;
  22744. }
  22745. else
  22746. {
  22747. return (diff > 0) ? 1 : -1;
  22748. }
  22749. }
  22750. };
  22751. }
  22752. MidiFile::MidiFile()
  22753. : timeFormat ((short) (unsigned short) 0xe728)
  22754. {
  22755. }
  22756. MidiFile::~MidiFile()
  22757. {
  22758. clear();
  22759. }
  22760. void MidiFile::clear()
  22761. {
  22762. tracks.clear();
  22763. }
  22764. int MidiFile::getNumTracks() const throw()
  22765. {
  22766. return tracks.size();
  22767. }
  22768. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22769. {
  22770. return tracks [index];
  22771. }
  22772. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22773. {
  22774. tracks.add (new MidiMessageSequence (trackSequence));
  22775. }
  22776. short MidiFile::getTimeFormat() const throw()
  22777. {
  22778. return timeFormat;
  22779. }
  22780. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22781. {
  22782. timeFormat = (short) ticks;
  22783. }
  22784. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22785. const int subframeResolution) throw()
  22786. {
  22787. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22788. }
  22789. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22790. {
  22791. for (int i = tracks.size(); --i >= 0;)
  22792. {
  22793. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22794. for (int j = 0; j < numEvents; ++j)
  22795. {
  22796. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22797. if (m.isTempoMetaEvent())
  22798. tempoChangeEvents.addEvent (m);
  22799. }
  22800. }
  22801. }
  22802. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22803. {
  22804. for (int i = tracks.size(); --i >= 0;)
  22805. {
  22806. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22807. for (int j = 0; j < numEvents; ++j)
  22808. {
  22809. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22810. if (m.isTimeSignatureMetaEvent())
  22811. timeSigEvents.addEvent (m);
  22812. }
  22813. }
  22814. }
  22815. double MidiFile::getLastTimestamp() const
  22816. {
  22817. double t = 0.0;
  22818. for (int i = tracks.size(); --i >= 0;)
  22819. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22820. return t;
  22821. }
  22822. bool MidiFile::readFrom (InputStream& sourceStream)
  22823. {
  22824. clear();
  22825. MemoryBlock data;
  22826. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22827. // (put a sanity-check on the file size, as midi files are generally small)
  22828. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22829. {
  22830. size_t size = data.getSize();
  22831. const uint8* d = static_cast <const uint8*> (data.getData());
  22832. short fileType, expectedTracks;
  22833. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22834. {
  22835. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22836. int track = 0;
  22837. while (size > 0 && track < expectedTracks)
  22838. {
  22839. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22840. d += 4;
  22841. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22842. d += 4;
  22843. if (chunkSize <= 0)
  22844. break;
  22845. if (size < 0)
  22846. return false;
  22847. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22848. {
  22849. readNextTrack (d, chunkSize);
  22850. }
  22851. size -= chunkSize + 8;
  22852. d += chunkSize;
  22853. ++track;
  22854. }
  22855. return true;
  22856. }
  22857. }
  22858. return false;
  22859. }
  22860. void MidiFile::readNextTrack (const uint8* data, int size)
  22861. {
  22862. double time = 0;
  22863. char lastStatusByte = 0;
  22864. MidiMessageSequence result;
  22865. while (size > 0)
  22866. {
  22867. int bytesUsed;
  22868. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22869. data += bytesUsed;
  22870. size -= bytesUsed;
  22871. time += delay;
  22872. int messSize = 0;
  22873. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22874. if (messSize <= 0)
  22875. break;
  22876. size -= messSize;
  22877. data += messSize;
  22878. result.addEvent (mm);
  22879. const char firstByte = *(mm.getRawData());
  22880. if ((firstByte & 0xf0) != 0xf0)
  22881. lastStatusByte = firstByte;
  22882. }
  22883. // use a sort that puts all the note-offs before note-ons that have the same time
  22884. MidiFileHelpers::Sorter sorter;
  22885. result.list.sort (sorter, true);
  22886. result.updateMatchedPairs();
  22887. addTrack (result);
  22888. }
  22889. void MidiFile::convertTimestampTicksToSeconds()
  22890. {
  22891. MidiMessageSequence tempoEvents;
  22892. findAllTempoEvents (tempoEvents);
  22893. findAllTimeSigEvents (tempoEvents);
  22894. for (int i = 0; i < tracks.size(); ++i)
  22895. {
  22896. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22897. for (int j = ms.getNumEvents(); --j >= 0;)
  22898. {
  22899. MidiMessage& m = ms.getEventPointer(j)->message;
  22900. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22901. tempoEvents,
  22902. timeFormat));
  22903. }
  22904. }
  22905. }
  22906. bool MidiFile::writeTo (OutputStream& out)
  22907. {
  22908. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22909. out.writeIntBigEndian (6);
  22910. out.writeShortBigEndian (1); // type
  22911. out.writeShortBigEndian ((short) tracks.size());
  22912. out.writeShortBigEndian (timeFormat);
  22913. for (int i = 0; i < tracks.size(); ++i)
  22914. writeTrack (out, i);
  22915. out.flush();
  22916. return true;
  22917. }
  22918. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22919. {
  22920. MemoryOutputStream out;
  22921. const MidiMessageSequence& ms = *tracks[trackNum];
  22922. int lastTick = 0;
  22923. char lastStatusByte = 0;
  22924. for (int i = 0; i < ms.getNumEvents(); ++i)
  22925. {
  22926. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22927. const int tick = roundToInt (mm.getTimeStamp());
  22928. const int delta = jmax (0, tick - lastTick);
  22929. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22930. lastTick = tick;
  22931. const char statusByte = *(mm.getRawData());
  22932. if ((statusByte == lastStatusByte)
  22933. && ((statusByte & 0xf0) != 0xf0)
  22934. && i > 0
  22935. && mm.getRawDataSize() > 1)
  22936. {
  22937. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22938. }
  22939. else
  22940. {
  22941. out.write (mm.getRawData(), mm.getRawDataSize());
  22942. }
  22943. lastStatusByte = statusByte;
  22944. }
  22945. out.writeByte (0);
  22946. const MidiMessage m (MidiMessage::endOfTrack());
  22947. out.write (m.getRawData(),
  22948. m.getRawDataSize());
  22949. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22950. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22951. mainOut.write (out.getData(), (int) out.getDataSize());
  22952. }
  22953. END_JUCE_NAMESPACE
  22954. /*** End of inlined file: juce_MidiFile.cpp ***/
  22955. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22956. BEGIN_JUCE_NAMESPACE
  22957. MidiKeyboardState::MidiKeyboardState()
  22958. {
  22959. zerostruct (noteStates);
  22960. }
  22961. MidiKeyboardState::~MidiKeyboardState()
  22962. {
  22963. }
  22964. void MidiKeyboardState::reset()
  22965. {
  22966. const ScopedLock sl (lock);
  22967. zerostruct (noteStates);
  22968. eventsToAdd.clear();
  22969. }
  22970. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22971. {
  22972. jassert (midiChannel >= 0 && midiChannel <= 16);
  22973. return isPositiveAndBelow (n, (int) 128)
  22974. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22975. }
  22976. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22977. {
  22978. return isPositiveAndBelow (n, (int) 128)
  22979. && (noteStates[n] & midiChannelMask) != 0;
  22980. }
  22981. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22982. {
  22983. jassert (midiChannel >= 0 && midiChannel <= 16);
  22984. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22985. const ScopedLock sl (lock);
  22986. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22987. {
  22988. const int timeNow = (int) Time::getMillisecondCounter();
  22989. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22990. eventsToAdd.clear (0, timeNow - 500);
  22991. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22992. }
  22993. }
  22994. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22995. {
  22996. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22997. {
  22998. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22999. for (int i = listeners.size(); --i >= 0;)
  23000. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  23001. }
  23002. }
  23003. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  23004. {
  23005. const ScopedLock sl (lock);
  23006. if (isNoteOn (midiChannel, midiNoteNumber))
  23007. {
  23008. const int timeNow = (int) Time::getMillisecondCounter();
  23009. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  23010. eventsToAdd.clear (0, timeNow - 500);
  23011. noteOffInternal (midiChannel, midiNoteNumber);
  23012. }
  23013. }
  23014. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  23015. {
  23016. if (isNoteOn (midiChannel, midiNoteNumber))
  23017. {
  23018. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  23019. for (int i = listeners.size(); --i >= 0;)
  23020. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  23021. }
  23022. }
  23023. void MidiKeyboardState::allNotesOff (const int midiChannel)
  23024. {
  23025. const ScopedLock sl (lock);
  23026. if (midiChannel <= 0)
  23027. {
  23028. for (int i = 1; i <= 16; ++i)
  23029. allNotesOff (i);
  23030. }
  23031. else
  23032. {
  23033. for (int i = 0; i < 128; ++i)
  23034. noteOff (midiChannel, i);
  23035. }
  23036. }
  23037. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  23038. {
  23039. if (message.isNoteOn())
  23040. {
  23041. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  23042. }
  23043. else if (message.isNoteOff())
  23044. {
  23045. noteOffInternal (message.getChannel(), message.getNoteNumber());
  23046. }
  23047. else if (message.isAllNotesOff())
  23048. {
  23049. for (int i = 0; i < 128; ++i)
  23050. noteOffInternal (message.getChannel(), i);
  23051. }
  23052. }
  23053. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  23054. const int startSample,
  23055. const int numSamples,
  23056. const bool injectIndirectEvents)
  23057. {
  23058. MidiBuffer::Iterator i (buffer);
  23059. MidiMessage message (0xf4, 0.0);
  23060. int time;
  23061. const ScopedLock sl (lock);
  23062. while (i.getNextEvent (message, time))
  23063. processNextMidiEvent (message);
  23064. if (injectIndirectEvents)
  23065. {
  23066. MidiBuffer::Iterator i2 (eventsToAdd);
  23067. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  23068. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  23069. while (i2.getNextEvent (message, time))
  23070. {
  23071. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  23072. buffer.addEvent (message, startSample + pos);
  23073. }
  23074. }
  23075. eventsToAdd.clear();
  23076. }
  23077. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  23078. {
  23079. const ScopedLock sl (lock);
  23080. listeners.addIfNotAlreadyThere (listener);
  23081. }
  23082. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  23083. {
  23084. const ScopedLock sl (lock);
  23085. listeners.removeValue (listener);
  23086. }
  23087. END_JUCE_NAMESPACE
  23088. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  23089. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  23090. BEGIN_JUCE_NAMESPACE
  23091. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  23092. {
  23093. numBytesUsed = 0;
  23094. int v = 0;
  23095. int i;
  23096. do
  23097. {
  23098. i = (int) *data++;
  23099. if (++numBytesUsed > 6)
  23100. break;
  23101. v = (v << 7) + (i & 0x7f);
  23102. } while (i & 0x80);
  23103. return v;
  23104. }
  23105. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23106. {
  23107. // this method only works for valid starting bytes of a short midi message
  23108. jassert (firstByte >= 0x80
  23109. && firstByte != 0xf0
  23110. && firstByte != 0xf7);
  23111. static const char messageLengths[] =
  23112. {
  23113. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23114. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23115. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23116. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23117. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23118. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23119. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23120. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23121. };
  23122. return messageLengths [firstByte & 0x7f];
  23123. }
  23124. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23125. : timeStamp (t),
  23126. size (dataSize)
  23127. {
  23128. jassert (dataSize > 0);
  23129. if (dataSize <= 4)
  23130. data = static_cast<uint8*> (preallocatedData.asBytes);
  23131. else
  23132. data = new uint8 [dataSize];
  23133. memcpy (data, d, dataSize);
  23134. // check that the length matches the data..
  23135. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23136. }
  23137. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23138. : timeStamp (t),
  23139. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23140. size (1)
  23141. {
  23142. data[0] = (uint8) byte1;
  23143. // check that the length matches the data..
  23144. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23145. }
  23146. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23147. : timeStamp (t),
  23148. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23149. size (2)
  23150. {
  23151. data[0] = (uint8) byte1;
  23152. data[1] = (uint8) byte2;
  23153. // check that the length matches the data..
  23154. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23155. }
  23156. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23157. : timeStamp (t),
  23158. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23159. size (3)
  23160. {
  23161. data[0] = (uint8) byte1;
  23162. data[1] = (uint8) byte2;
  23163. data[2] = (uint8) byte3;
  23164. // check that the length matches the data..
  23165. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23166. }
  23167. MidiMessage::MidiMessage (const MidiMessage& other)
  23168. : timeStamp (other.timeStamp),
  23169. size (other.size)
  23170. {
  23171. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23172. {
  23173. data = new uint8 [size];
  23174. memcpy (data, other.data, size);
  23175. }
  23176. else
  23177. {
  23178. data = static_cast<uint8*> (preallocatedData.asBytes);
  23179. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23180. }
  23181. }
  23182. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23183. : timeStamp (newTimeStamp),
  23184. size (other.size)
  23185. {
  23186. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23187. {
  23188. data = new uint8 [size];
  23189. memcpy (data, other.data, size);
  23190. }
  23191. else
  23192. {
  23193. data = static_cast<uint8*> (preallocatedData.asBytes);
  23194. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23195. }
  23196. }
  23197. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23198. : timeStamp (t),
  23199. data (static_cast<uint8*> (preallocatedData.asBytes))
  23200. {
  23201. const uint8* src = static_cast <const uint8*> (src_);
  23202. unsigned int byte = (unsigned int) *src;
  23203. if (byte < 0x80)
  23204. {
  23205. byte = (unsigned int) (uint8) lastStatusByte;
  23206. numBytesUsed = -1;
  23207. }
  23208. else
  23209. {
  23210. numBytesUsed = 0;
  23211. --sz;
  23212. ++src;
  23213. }
  23214. if (byte >= 0x80)
  23215. {
  23216. if (byte == 0xf0)
  23217. {
  23218. const uint8* d = src;
  23219. bool haveReadAllLengthBytes = false;
  23220. while (d < src + sz)
  23221. {
  23222. if (*d >= 0x80)
  23223. {
  23224. if (*d == 0xf7)
  23225. {
  23226. ++d; // include the trailing 0xf7 when we hit it
  23227. break;
  23228. }
  23229. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  23230. break; // bytes, assume it's the end of the sysex
  23231. ++d;
  23232. continue;
  23233. }
  23234. haveReadAllLengthBytes = true;
  23235. ++d;
  23236. }
  23237. size = 1 + (int) (d - src);
  23238. data = new uint8 [size];
  23239. *data = (uint8) byte;
  23240. memcpy (data + 1, src, size - 1);
  23241. }
  23242. else if (byte == 0xff)
  23243. {
  23244. int n;
  23245. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23246. size = jmin (sz + 1, n + 2 + bytesLeft);
  23247. data = new uint8 [size];
  23248. *data = (uint8) byte;
  23249. memcpy (data + 1, src, size - 1);
  23250. }
  23251. else
  23252. {
  23253. preallocatedData.asInt32 = 0;
  23254. size = getMessageLengthFromFirstByte ((uint8) byte);
  23255. data[0] = (uint8) byte;
  23256. if (size > 1)
  23257. {
  23258. data[1] = src[0];
  23259. if (size > 2)
  23260. data[2] = src[1];
  23261. }
  23262. }
  23263. numBytesUsed += size;
  23264. }
  23265. else
  23266. {
  23267. preallocatedData.asInt32 = 0;
  23268. size = 0;
  23269. }
  23270. }
  23271. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23272. {
  23273. if (this != &other)
  23274. {
  23275. timeStamp = other.timeStamp;
  23276. size = other.size;
  23277. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23278. delete[] data;
  23279. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23280. {
  23281. data = new uint8 [size];
  23282. memcpy (data, other.data, size);
  23283. }
  23284. else
  23285. {
  23286. data = static_cast<uint8*> (preallocatedData.asBytes);
  23287. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23288. }
  23289. }
  23290. return *this;
  23291. }
  23292. MidiMessage::~MidiMessage()
  23293. {
  23294. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23295. delete[] data;
  23296. }
  23297. int MidiMessage::getChannel() const throw()
  23298. {
  23299. if ((data[0] & 0xf0) != 0xf0)
  23300. return (data[0] & 0xf) + 1;
  23301. else
  23302. return 0;
  23303. }
  23304. bool MidiMessage::isForChannel (const int channel) const throw()
  23305. {
  23306. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23307. return ((data[0] & 0xf) == channel - 1)
  23308. && ((data[0] & 0xf0) != 0xf0);
  23309. }
  23310. void MidiMessage::setChannel (const int channel) throw()
  23311. {
  23312. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23313. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23314. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23315. | (uint8)(channel - 1));
  23316. }
  23317. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23318. {
  23319. return ((data[0] & 0xf0) == 0x90)
  23320. && (returnTrueForVelocity0 || data[2] != 0);
  23321. }
  23322. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23323. {
  23324. return ((data[0] & 0xf0) == 0x80)
  23325. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23326. }
  23327. bool MidiMessage::isNoteOnOrOff() const throw()
  23328. {
  23329. const int d = data[0] & 0xf0;
  23330. return (d == 0x90) || (d == 0x80);
  23331. }
  23332. int MidiMessage::getNoteNumber() const throw()
  23333. {
  23334. return data[1];
  23335. }
  23336. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23337. {
  23338. if (isNoteOnOrOff())
  23339. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23340. }
  23341. uint8 MidiMessage::getVelocity() const throw()
  23342. {
  23343. if (isNoteOnOrOff())
  23344. return data[2];
  23345. else
  23346. return 0;
  23347. }
  23348. float MidiMessage::getFloatVelocity() const throw()
  23349. {
  23350. return getVelocity() * (1.0f / 127.0f);
  23351. }
  23352. void MidiMessage::setVelocity (const float newVelocity) throw()
  23353. {
  23354. if (isNoteOnOrOff())
  23355. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23356. }
  23357. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23358. {
  23359. if (isNoteOnOrOff())
  23360. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23361. }
  23362. bool MidiMessage::isAftertouch() const throw()
  23363. {
  23364. return (data[0] & 0xf0) == 0xa0;
  23365. }
  23366. int MidiMessage::getAfterTouchValue() const throw()
  23367. {
  23368. return data[2];
  23369. }
  23370. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23371. const int noteNum,
  23372. const int aftertouchValue) throw()
  23373. {
  23374. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23375. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23376. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23377. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23378. noteNum & 0x7f,
  23379. aftertouchValue & 0x7f);
  23380. }
  23381. bool MidiMessage::isChannelPressure() const throw()
  23382. {
  23383. return (data[0] & 0xf0) == 0xd0;
  23384. }
  23385. int MidiMessage::getChannelPressureValue() const throw()
  23386. {
  23387. jassert (isChannelPressure());
  23388. return data[1];
  23389. }
  23390. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23391. const int pressure) throw()
  23392. {
  23393. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23394. jassert (isPositiveAndBelow (pressure, (int) 128));
  23395. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23396. pressure & 0x7f);
  23397. }
  23398. bool MidiMessage::isProgramChange() const throw()
  23399. {
  23400. return (data[0] & 0xf0) == 0xc0;
  23401. }
  23402. int MidiMessage::getProgramChangeNumber() const throw()
  23403. {
  23404. return data[1];
  23405. }
  23406. const MidiMessage MidiMessage::programChange (const int channel,
  23407. const int programNumber) throw()
  23408. {
  23409. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23410. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23411. programNumber & 0x7f);
  23412. }
  23413. bool MidiMessage::isPitchWheel() const throw()
  23414. {
  23415. return (data[0] & 0xf0) == 0xe0;
  23416. }
  23417. int MidiMessage::getPitchWheelValue() const throw()
  23418. {
  23419. return data[1] | (data[2] << 7);
  23420. }
  23421. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23422. const int position) throw()
  23423. {
  23424. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23425. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23426. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23427. position & 127,
  23428. (position >> 7) & 127);
  23429. }
  23430. bool MidiMessage::isController() const throw()
  23431. {
  23432. return (data[0] & 0xf0) == 0xb0;
  23433. }
  23434. int MidiMessage::getControllerNumber() const throw()
  23435. {
  23436. jassert (isController());
  23437. return data[1];
  23438. }
  23439. int MidiMessage::getControllerValue() const throw()
  23440. {
  23441. jassert (isController());
  23442. return data[2];
  23443. }
  23444. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23445. const int controllerType,
  23446. const int value) throw()
  23447. {
  23448. // the channel must be between 1 and 16 inclusive
  23449. jassert (channel > 0 && channel <= 16);
  23450. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23451. controllerType & 127,
  23452. value & 127);
  23453. }
  23454. const MidiMessage MidiMessage::noteOn (const int channel,
  23455. const int noteNumber,
  23456. const float velocity) throw()
  23457. {
  23458. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23459. }
  23460. const MidiMessage MidiMessage::noteOn (const int channel,
  23461. const int noteNumber,
  23462. const uint8 velocity) throw()
  23463. {
  23464. jassert (channel > 0 && channel <= 16);
  23465. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23466. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23467. noteNumber & 127,
  23468. jlimit (0, 127, roundToInt (velocity)));
  23469. }
  23470. const MidiMessage MidiMessage::noteOff (const int channel,
  23471. const int noteNumber) throw()
  23472. {
  23473. jassert (channel > 0 && channel <= 16);
  23474. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23475. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23476. }
  23477. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23478. {
  23479. return controllerEvent (channel, 123, 0);
  23480. }
  23481. bool MidiMessage::isAllNotesOff() const throw()
  23482. {
  23483. return (data[0] & 0xf0) == 0xb0
  23484. && data[1] == 123;
  23485. }
  23486. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23487. {
  23488. return controllerEvent (channel, 120, 0);
  23489. }
  23490. bool MidiMessage::isAllSoundOff() const throw()
  23491. {
  23492. return (data[0] & 0xf0) == 0xb0
  23493. && data[1] == 120;
  23494. }
  23495. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23496. {
  23497. return controllerEvent (channel, 121, 0);
  23498. }
  23499. const MidiMessage MidiMessage::masterVolume (const float volume)
  23500. {
  23501. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23502. uint8 buf[8];
  23503. buf[0] = 0xf0;
  23504. buf[1] = 0x7f;
  23505. buf[2] = 0x7f;
  23506. buf[3] = 0x04;
  23507. buf[4] = 0x01;
  23508. buf[5] = (uint8) (vol & 0x7f);
  23509. buf[6] = (uint8) (vol >> 7);
  23510. buf[7] = 0xf7;
  23511. return MidiMessage (buf, 8);
  23512. }
  23513. bool MidiMessage::isSysEx() const throw()
  23514. {
  23515. return *data == 0xf0;
  23516. }
  23517. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23518. {
  23519. MemoryBlock mm (dataSize + 2);
  23520. uint8* const m = static_cast <uint8*> (mm.getData());
  23521. m[0] = 0xf0;
  23522. memcpy (m + 1, sysexData, dataSize);
  23523. m[dataSize + 1] = 0xf7;
  23524. return MidiMessage (m, dataSize + 2);
  23525. }
  23526. const uint8* MidiMessage::getSysExData() const throw()
  23527. {
  23528. return (isSysEx()) ? getRawData() + 1 : 0;
  23529. }
  23530. int MidiMessage::getSysExDataSize() const throw()
  23531. {
  23532. return (isSysEx()) ? size - 2 : 0;
  23533. }
  23534. bool MidiMessage::isMetaEvent() const throw()
  23535. {
  23536. return *data == 0xff;
  23537. }
  23538. bool MidiMessage::isActiveSense() const throw()
  23539. {
  23540. return *data == 0xfe;
  23541. }
  23542. int MidiMessage::getMetaEventType() const throw()
  23543. {
  23544. if (*data != 0xff)
  23545. return -1;
  23546. else
  23547. return data[1];
  23548. }
  23549. int MidiMessage::getMetaEventLength() const throw()
  23550. {
  23551. if (*data == 0xff)
  23552. {
  23553. int n;
  23554. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23555. }
  23556. return 0;
  23557. }
  23558. const uint8* MidiMessage::getMetaEventData() const throw()
  23559. {
  23560. int n;
  23561. const uint8* d = data + 2;
  23562. readVariableLengthVal (d, n);
  23563. return d + n;
  23564. }
  23565. bool MidiMessage::isTrackMetaEvent() const throw()
  23566. {
  23567. return getMetaEventType() == 0;
  23568. }
  23569. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23570. {
  23571. return getMetaEventType() == 47;
  23572. }
  23573. bool MidiMessage::isTextMetaEvent() const throw()
  23574. {
  23575. const int t = getMetaEventType();
  23576. return t > 0 && t < 16;
  23577. }
  23578. const String MidiMessage::getTextFromTextMetaEvent() const
  23579. {
  23580. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23581. }
  23582. bool MidiMessage::isTrackNameEvent() const throw()
  23583. {
  23584. return (data[1] == 3)
  23585. && (*data == 0xff);
  23586. }
  23587. bool MidiMessage::isTempoMetaEvent() const throw()
  23588. {
  23589. return (data[1] == 81)
  23590. && (*data == 0xff);
  23591. }
  23592. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23593. {
  23594. return (data[1] == 0x20)
  23595. && (*data == 0xff)
  23596. && (data[2] == 1);
  23597. }
  23598. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23599. {
  23600. return data[3] + 1;
  23601. }
  23602. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23603. {
  23604. if (! isTempoMetaEvent())
  23605. return 0.0;
  23606. const uint8* const d = getMetaEventData();
  23607. return (((unsigned int) d[0] << 16)
  23608. | ((unsigned int) d[1] << 8)
  23609. | d[2])
  23610. / 1000000.0;
  23611. }
  23612. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23613. {
  23614. if (timeFormat > 0)
  23615. {
  23616. if (! isTempoMetaEvent())
  23617. return 0.5 / timeFormat;
  23618. return getTempoSecondsPerQuarterNote() / timeFormat;
  23619. }
  23620. else
  23621. {
  23622. const int frameCode = (-timeFormat) >> 8;
  23623. double framesPerSecond;
  23624. switch (frameCode)
  23625. {
  23626. case 24: framesPerSecond = 24.0; break;
  23627. case 25: framesPerSecond = 25.0; break;
  23628. case 29: framesPerSecond = 29.97; break;
  23629. case 30: framesPerSecond = 30.0; break;
  23630. default: framesPerSecond = 30.0; break;
  23631. }
  23632. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23633. }
  23634. }
  23635. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23636. {
  23637. uint8 d[8];
  23638. d[0] = 0xff;
  23639. d[1] = 81;
  23640. d[2] = 3;
  23641. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23642. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23643. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23644. return MidiMessage (d, 6, 0.0);
  23645. }
  23646. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23647. {
  23648. return (data[1] == 0x58)
  23649. && (*data == (uint8) 0xff);
  23650. }
  23651. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23652. {
  23653. if (isTimeSignatureMetaEvent())
  23654. {
  23655. const uint8* const d = getMetaEventData();
  23656. numerator = d[0];
  23657. denominator = 1 << d[1];
  23658. }
  23659. else
  23660. {
  23661. numerator = 4;
  23662. denominator = 4;
  23663. }
  23664. }
  23665. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23666. {
  23667. uint8 d[8];
  23668. d[0] = 0xff;
  23669. d[1] = 0x58;
  23670. d[2] = 0x04;
  23671. d[3] = (uint8) numerator;
  23672. int n = 1;
  23673. int powerOfTwo = 0;
  23674. while (n < denominator)
  23675. {
  23676. n <<= 1;
  23677. ++powerOfTwo;
  23678. }
  23679. d[4] = (uint8) powerOfTwo;
  23680. d[5] = 0x01;
  23681. d[6] = 96;
  23682. return MidiMessage (d, 7, 0.0);
  23683. }
  23684. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23685. {
  23686. uint8 d[8];
  23687. d[0] = 0xff;
  23688. d[1] = 0x20;
  23689. d[2] = 0x01;
  23690. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23691. return MidiMessage (d, 4, 0.0);
  23692. }
  23693. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23694. {
  23695. return getMetaEventType() == 89;
  23696. }
  23697. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23698. {
  23699. return (int) *getMetaEventData();
  23700. }
  23701. const MidiMessage MidiMessage::endOfTrack() throw()
  23702. {
  23703. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23704. }
  23705. bool MidiMessage::isSongPositionPointer() const throw()
  23706. {
  23707. return *data == 0xf2;
  23708. }
  23709. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23710. {
  23711. return data[1] | (data[2] << 7);
  23712. }
  23713. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23714. {
  23715. return MidiMessage (0xf2,
  23716. positionInMidiBeats & 127,
  23717. (positionInMidiBeats >> 7) & 127);
  23718. }
  23719. bool MidiMessage::isMidiStart() const throw()
  23720. {
  23721. return *data == 0xfa;
  23722. }
  23723. const MidiMessage MidiMessage::midiStart() throw()
  23724. {
  23725. return MidiMessage (0xfa);
  23726. }
  23727. bool MidiMessage::isMidiContinue() const throw()
  23728. {
  23729. return *data == 0xfb;
  23730. }
  23731. const MidiMessage MidiMessage::midiContinue() throw()
  23732. {
  23733. return MidiMessage (0xfb);
  23734. }
  23735. bool MidiMessage::isMidiStop() const throw()
  23736. {
  23737. return *data == 0xfc;
  23738. }
  23739. const MidiMessage MidiMessage::midiStop() throw()
  23740. {
  23741. return MidiMessage (0xfc);
  23742. }
  23743. bool MidiMessage::isMidiClock() const throw()
  23744. {
  23745. return *data == 0xf8;
  23746. }
  23747. const MidiMessage MidiMessage::midiClock() throw()
  23748. {
  23749. return MidiMessage (0xf8);
  23750. }
  23751. bool MidiMessage::isQuarterFrame() const throw()
  23752. {
  23753. return *data == 0xf1;
  23754. }
  23755. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23756. {
  23757. return ((int) data[1]) >> 4;
  23758. }
  23759. int MidiMessage::getQuarterFrameValue() const throw()
  23760. {
  23761. return ((int) data[1]) & 0x0f;
  23762. }
  23763. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23764. const int value) throw()
  23765. {
  23766. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23767. }
  23768. bool MidiMessage::isFullFrame() const throw()
  23769. {
  23770. return data[0] == 0xf0
  23771. && data[1] == 0x7f
  23772. && size >= 10
  23773. && data[3] == 0x01
  23774. && data[4] == 0x01;
  23775. }
  23776. void MidiMessage::getFullFrameParameters (int& hours,
  23777. int& minutes,
  23778. int& seconds,
  23779. int& frames,
  23780. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23781. {
  23782. jassert (isFullFrame());
  23783. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23784. hours = data[5] & 0x1f;
  23785. minutes = data[6];
  23786. seconds = data[7];
  23787. frames = data[8];
  23788. }
  23789. const MidiMessage MidiMessage::fullFrame (const int hours,
  23790. const int minutes,
  23791. const int seconds,
  23792. const int frames,
  23793. MidiMessage::SmpteTimecodeType timecodeType)
  23794. {
  23795. uint8 d[10];
  23796. d[0] = 0xf0;
  23797. d[1] = 0x7f;
  23798. d[2] = 0x7f;
  23799. d[3] = 0x01;
  23800. d[4] = 0x01;
  23801. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23802. d[6] = (uint8) minutes;
  23803. d[7] = (uint8) seconds;
  23804. d[8] = (uint8) frames;
  23805. d[9] = 0xf7;
  23806. return MidiMessage (d, 10, 0.0);
  23807. }
  23808. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23809. {
  23810. return data[0] == 0xf0
  23811. && data[1] == 0x7f
  23812. && data[3] == 0x06
  23813. && size > 5;
  23814. }
  23815. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23816. {
  23817. jassert (isMidiMachineControlMessage());
  23818. return (MidiMachineControlCommand) data[4];
  23819. }
  23820. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23821. {
  23822. uint8 d[6];
  23823. d[0] = 0xf0;
  23824. d[1] = 0x7f;
  23825. d[2] = 0x00;
  23826. d[3] = 0x06;
  23827. d[4] = (uint8) command;
  23828. d[5] = 0xf7;
  23829. return MidiMessage (d, 6, 0.0);
  23830. }
  23831. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23832. int& minutes,
  23833. int& seconds,
  23834. int& frames) const throw()
  23835. {
  23836. if (size >= 12
  23837. && data[0] == 0xf0
  23838. && data[1] == 0x7f
  23839. && data[3] == 0x06
  23840. && data[4] == 0x44
  23841. && data[5] == 0x06
  23842. && data[6] == 0x01)
  23843. {
  23844. hours = data[7] % 24; // (that some machines send out hours > 24)
  23845. minutes = data[8];
  23846. seconds = data[9];
  23847. frames = data[10];
  23848. return true;
  23849. }
  23850. return false;
  23851. }
  23852. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23853. int minutes,
  23854. int seconds,
  23855. int frames)
  23856. {
  23857. uint8 d[12];
  23858. d[0] = 0xf0;
  23859. d[1] = 0x7f;
  23860. d[2] = 0x00;
  23861. d[3] = 0x06;
  23862. d[4] = 0x44;
  23863. d[5] = 0x06;
  23864. d[6] = 0x01;
  23865. d[7] = (uint8) hours;
  23866. d[8] = (uint8) minutes;
  23867. d[9] = (uint8) seconds;
  23868. d[10] = (uint8) frames;
  23869. d[11] = 0xf7;
  23870. return MidiMessage (d, 12, 0.0);
  23871. }
  23872. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23873. {
  23874. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23875. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23876. if (isPositiveAndBelow (note, (int) 128))
  23877. {
  23878. String s (useSharps ? sharpNoteNames [note % 12]
  23879. : flatNoteNames [note % 12]);
  23880. if (includeOctaveNumber)
  23881. s << (note / 12 + (octaveNumForMiddleC - 5));
  23882. return s;
  23883. }
  23884. return String::empty;
  23885. }
  23886. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23887. {
  23888. noteNumber -= 12 * 6 + 9; // now 0 = A
  23889. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23890. }
  23891. const String MidiMessage::getGMInstrumentName (const int n)
  23892. {
  23893. const char* names[] =
  23894. {
  23895. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23896. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23897. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23898. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23899. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23900. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23901. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23902. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23903. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23904. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23905. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23906. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23907. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23908. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23909. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23910. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23911. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23912. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23913. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23914. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23915. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23916. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23917. "Applause", "Gunshot"
  23918. };
  23919. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23920. }
  23921. const String MidiMessage::getGMInstrumentBankName (const int n)
  23922. {
  23923. const char* names[] =
  23924. {
  23925. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23926. "Bass", "Strings", "Ensemble", "Brass",
  23927. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23928. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23929. };
  23930. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23931. }
  23932. const String MidiMessage::getRhythmInstrumentName (const int n)
  23933. {
  23934. const char* names[] =
  23935. {
  23936. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23937. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23938. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23939. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23940. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23941. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23942. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23943. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23944. "Mute Triangle", "Open Triangle"
  23945. };
  23946. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23947. }
  23948. const String MidiMessage::getControllerName (const int n)
  23949. {
  23950. const char* names[] =
  23951. {
  23952. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23953. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23954. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23955. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23956. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23957. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23958. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23959. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23960. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23961. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23962. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23963. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23964. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23965. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23966. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23967. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23968. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23969. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23970. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23972. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23973. "Poly Operation"
  23974. };
  23975. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23976. }
  23977. END_JUCE_NAMESPACE
  23978. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23979. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23980. BEGIN_JUCE_NAMESPACE
  23981. MidiMessageCollector::MidiMessageCollector()
  23982. : lastCallbackTime (0),
  23983. sampleRate (44100.0001)
  23984. {
  23985. }
  23986. MidiMessageCollector::~MidiMessageCollector()
  23987. {
  23988. }
  23989. void MidiMessageCollector::reset (const double sampleRate_)
  23990. {
  23991. jassert (sampleRate_ > 0);
  23992. const ScopedLock sl (midiCallbackLock);
  23993. sampleRate = sampleRate_;
  23994. incomingMessages.clear();
  23995. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23996. }
  23997. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23998. {
  23999. // you need to call reset() to set the correct sample rate before using this object
  24000. jassert (sampleRate != 44100.0001);
  24001. // the messages that come in here need to be time-stamped correctly - see MidiInput
  24002. // for details of what the number should be.
  24003. jassert (message.getTimeStamp() != 0);
  24004. const ScopedLock sl (midiCallbackLock);
  24005. const int sampleNumber
  24006. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  24007. incomingMessages.addEvent (message, sampleNumber);
  24008. // if the messages don't get used for over a second, we'd better
  24009. // get rid of any old ones to avoid the queue getting too big
  24010. if (sampleNumber > sampleRate)
  24011. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  24012. }
  24013. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  24014. const int numSamples)
  24015. {
  24016. // you need to call reset() to set the correct sample rate before using this object
  24017. jassert (sampleRate != 44100.0001);
  24018. const double timeNow = Time::getMillisecondCounterHiRes();
  24019. const double msElapsed = timeNow - lastCallbackTime;
  24020. const ScopedLock sl (midiCallbackLock);
  24021. lastCallbackTime = timeNow;
  24022. if (! incomingMessages.isEmpty())
  24023. {
  24024. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  24025. int startSample = 0;
  24026. int scale = 1 << 16;
  24027. const uint8* midiData;
  24028. int numBytes, samplePosition;
  24029. MidiBuffer::Iterator iter (incomingMessages);
  24030. if (numSourceSamples > numSamples)
  24031. {
  24032. // if our list of events is longer than the buffer we're being
  24033. // asked for, scale them down to squeeze them all in..
  24034. const int maxBlockLengthToUse = numSamples << 5;
  24035. if (numSourceSamples > maxBlockLengthToUse)
  24036. {
  24037. startSample = numSourceSamples - maxBlockLengthToUse;
  24038. numSourceSamples = maxBlockLengthToUse;
  24039. iter.setNextSamplePosition (startSample);
  24040. }
  24041. scale = (numSamples << 10) / numSourceSamples;
  24042. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24043. {
  24044. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  24045. destBuffer.addEvent (midiData, numBytes,
  24046. jlimit (0, numSamples - 1, samplePosition));
  24047. }
  24048. }
  24049. else
  24050. {
  24051. // if our event list is shorter than the number we need, put them
  24052. // towards the end of the buffer
  24053. startSample = numSamples - numSourceSamples;
  24054. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24055. {
  24056. destBuffer.addEvent (midiData, numBytes,
  24057. jlimit (0, numSamples - 1, samplePosition + startSample));
  24058. }
  24059. }
  24060. incomingMessages.clear();
  24061. }
  24062. }
  24063. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  24064. {
  24065. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  24066. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24067. addMessageToQueue (m);
  24068. }
  24069. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  24070. {
  24071. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  24072. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24073. addMessageToQueue (m);
  24074. }
  24075. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  24076. {
  24077. addMessageToQueue (message);
  24078. }
  24079. END_JUCE_NAMESPACE
  24080. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  24081. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  24082. BEGIN_JUCE_NAMESPACE
  24083. MidiMessageSequence::MidiMessageSequence()
  24084. {
  24085. }
  24086. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  24087. {
  24088. list.ensureStorageAllocated (other.list.size());
  24089. for (int i = 0; i < other.list.size(); ++i)
  24090. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  24091. }
  24092. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  24093. {
  24094. MidiMessageSequence otherCopy (other);
  24095. swapWith (otherCopy);
  24096. return *this;
  24097. }
  24098. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  24099. {
  24100. list.swapWithArray (other.list);
  24101. }
  24102. MidiMessageSequence::~MidiMessageSequence()
  24103. {
  24104. }
  24105. void MidiMessageSequence::clear()
  24106. {
  24107. list.clear();
  24108. }
  24109. int MidiMessageSequence::getNumEvents() const
  24110. {
  24111. return list.size();
  24112. }
  24113. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24114. {
  24115. return list [index];
  24116. }
  24117. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24118. {
  24119. const MidiEventHolder* const meh = list [index];
  24120. if (meh != 0 && meh->noteOffObject != 0)
  24121. return meh->noteOffObject->message.getTimeStamp();
  24122. else
  24123. return 0.0;
  24124. }
  24125. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24126. {
  24127. const MidiEventHolder* const meh = list [index];
  24128. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24129. }
  24130. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24131. {
  24132. return list.indexOf (event);
  24133. }
  24134. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24135. {
  24136. const int numEvents = list.size();
  24137. int i;
  24138. for (i = 0; i < numEvents; ++i)
  24139. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24140. break;
  24141. return i;
  24142. }
  24143. double MidiMessageSequence::getStartTime() const
  24144. {
  24145. if (list.size() > 0)
  24146. return list.getUnchecked(0)->message.getTimeStamp();
  24147. else
  24148. return 0;
  24149. }
  24150. double MidiMessageSequence::getEndTime() const
  24151. {
  24152. if (list.size() > 0)
  24153. return list.getLast()->message.getTimeStamp();
  24154. else
  24155. return 0;
  24156. }
  24157. double MidiMessageSequence::getEventTime (const int index) const
  24158. {
  24159. if (isPositiveAndBelow (index, list.size()))
  24160. return list.getUnchecked (index)->message.getTimeStamp();
  24161. return 0.0;
  24162. }
  24163. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24164. double timeAdjustment)
  24165. {
  24166. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24167. timeAdjustment += newMessage.getTimeStamp();
  24168. newOne->message.setTimeStamp (timeAdjustment);
  24169. int i;
  24170. for (i = list.size(); --i >= 0;)
  24171. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24172. break;
  24173. list.insert (i + 1, newOne);
  24174. }
  24175. void MidiMessageSequence::deleteEvent (const int index,
  24176. const bool deleteMatchingNoteUp)
  24177. {
  24178. if (isPositiveAndBelow (index, list.size()))
  24179. {
  24180. if (deleteMatchingNoteUp)
  24181. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24182. list.remove (index);
  24183. }
  24184. }
  24185. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24186. double timeAdjustment,
  24187. double firstAllowableTime,
  24188. double endOfAllowableDestTimes)
  24189. {
  24190. firstAllowableTime -= timeAdjustment;
  24191. endOfAllowableDestTimes -= timeAdjustment;
  24192. for (int i = 0; i < other.list.size(); ++i)
  24193. {
  24194. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24195. const double t = m.getTimeStamp();
  24196. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24197. {
  24198. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24199. newOne->message.setTimeStamp (timeAdjustment + t);
  24200. list.add (newOne);
  24201. }
  24202. }
  24203. sort();
  24204. }
  24205. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24206. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24207. {
  24208. const double diff = first->message.getTimeStamp()
  24209. - second->message.getTimeStamp();
  24210. return (diff > 0) - (diff < 0);
  24211. }
  24212. void MidiMessageSequence::sort()
  24213. {
  24214. list.sort (*this, true);
  24215. }
  24216. void MidiMessageSequence::updateMatchedPairs()
  24217. {
  24218. for (int i = 0; i < list.size(); ++i)
  24219. {
  24220. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24221. if (m1.isNoteOn())
  24222. {
  24223. list.getUnchecked(i)->noteOffObject = 0;
  24224. const int note = m1.getNoteNumber();
  24225. const int chan = m1.getChannel();
  24226. const int len = list.size();
  24227. for (int j = i + 1; j < len; ++j)
  24228. {
  24229. const MidiMessage& m = list.getUnchecked(j)->message;
  24230. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24231. {
  24232. if (m.isNoteOff())
  24233. {
  24234. list.getUnchecked(i)->noteOffObject = list[j];
  24235. break;
  24236. }
  24237. else if (m.isNoteOn())
  24238. {
  24239. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24240. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24241. list.getUnchecked(i)->noteOffObject = list[j];
  24242. break;
  24243. }
  24244. }
  24245. }
  24246. }
  24247. }
  24248. }
  24249. void MidiMessageSequence::addTimeToMessages (const double delta)
  24250. {
  24251. for (int i = list.size(); --i >= 0;)
  24252. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24253. + delta);
  24254. }
  24255. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24256. MidiMessageSequence& destSequence,
  24257. const bool alsoIncludeMetaEvents) const
  24258. {
  24259. for (int i = 0; i < list.size(); ++i)
  24260. {
  24261. const MidiMessage& mm = list.getUnchecked(i)->message;
  24262. if (mm.isForChannel (channelNumberToExtract)
  24263. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24264. {
  24265. destSequence.addEvent (mm);
  24266. }
  24267. }
  24268. }
  24269. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24270. {
  24271. for (int i = 0; i < list.size(); ++i)
  24272. {
  24273. const MidiMessage& mm = list.getUnchecked(i)->message;
  24274. if (mm.isSysEx())
  24275. destSequence.addEvent (mm);
  24276. }
  24277. }
  24278. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24279. {
  24280. for (int i = list.size(); --i >= 0;)
  24281. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24282. list.remove(i);
  24283. }
  24284. void MidiMessageSequence::deleteSysExMessages()
  24285. {
  24286. for (int i = list.size(); --i >= 0;)
  24287. if (list.getUnchecked(i)->message.isSysEx())
  24288. list.remove(i);
  24289. }
  24290. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24291. const double time,
  24292. OwnedArray<MidiMessage>& dest)
  24293. {
  24294. bool doneProg = false;
  24295. bool donePitchWheel = false;
  24296. Array <int> doneControllers;
  24297. doneControllers.ensureStorageAllocated (32);
  24298. for (int i = list.size(); --i >= 0;)
  24299. {
  24300. const MidiMessage& mm = list.getUnchecked(i)->message;
  24301. if (mm.isForChannel (channelNumber)
  24302. && mm.getTimeStamp() <= time)
  24303. {
  24304. if (mm.isProgramChange())
  24305. {
  24306. if (! doneProg)
  24307. {
  24308. dest.add (new MidiMessage (mm, 0.0));
  24309. doneProg = true;
  24310. }
  24311. }
  24312. else if (mm.isController())
  24313. {
  24314. if (! doneControllers.contains (mm.getControllerNumber()))
  24315. {
  24316. dest.add (new MidiMessage (mm, 0.0));
  24317. doneControllers.add (mm.getControllerNumber());
  24318. }
  24319. }
  24320. else if (mm.isPitchWheel())
  24321. {
  24322. if (! donePitchWheel)
  24323. {
  24324. dest.add (new MidiMessage (mm, 0.0));
  24325. donePitchWheel = true;
  24326. }
  24327. }
  24328. }
  24329. }
  24330. }
  24331. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24332. : message (message_),
  24333. noteOffObject (0)
  24334. {
  24335. }
  24336. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24337. {
  24338. }
  24339. END_JUCE_NAMESPACE
  24340. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24341. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24342. BEGIN_JUCE_NAMESPACE
  24343. AudioPluginFormat::AudioPluginFormat() throw()
  24344. {
  24345. }
  24346. AudioPluginFormat::~AudioPluginFormat()
  24347. {
  24348. }
  24349. END_JUCE_NAMESPACE
  24350. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24351. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24352. BEGIN_JUCE_NAMESPACE
  24353. AudioPluginFormatManager::AudioPluginFormatManager()
  24354. {
  24355. }
  24356. AudioPluginFormatManager::~AudioPluginFormatManager()
  24357. {
  24358. clearSingletonInstance();
  24359. }
  24360. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24361. void AudioPluginFormatManager::addDefaultFormats()
  24362. {
  24363. #if JUCE_DEBUG
  24364. // you should only call this method once!
  24365. for (int i = formats.size(); --i >= 0;)
  24366. {
  24367. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24368. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24369. #endif
  24370. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24371. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24372. #endif
  24373. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24374. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24375. #endif
  24376. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24377. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24378. #endif
  24379. }
  24380. #endif
  24381. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24382. formats.add (new AudioUnitPluginFormat());
  24383. #endif
  24384. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24385. formats.add (new VSTPluginFormat());
  24386. #endif
  24387. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24388. formats.add (new DirectXPluginFormat());
  24389. #endif
  24390. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24391. formats.add (new LADSPAPluginFormat());
  24392. #endif
  24393. }
  24394. int AudioPluginFormatManager::getNumFormats()
  24395. {
  24396. return formats.size();
  24397. }
  24398. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24399. {
  24400. return formats [index];
  24401. }
  24402. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24403. {
  24404. formats.add (format);
  24405. }
  24406. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24407. String& errorMessage) const
  24408. {
  24409. AudioPluginInstance* result = 0;
  24410. for (int i = 0; i < formats.size(); ++i)
  24411. {
  24412. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24413. if (result != 0)
  24414. break;
  24415. }
  24416. if (result == 0)
  24417. {
  24418. if (! doesPluginStillExist (description))
  24419. errorMessage = TRANS ("This plug-in file no longer exists");
  24420. else
  24421. errorMessage = TRANS ("This plug-in failed to load correctly");
  24422. }
  24423. return result;
  24424. }
  24425. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24426. {
  24427. for (int i = 0; i < formats.size(); ++i)
  24428. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24429. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24430. return false;
  24431. }
  24432. END_JUCE_NAMESPACE
  24433. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24434. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24435. #define JUCE_PLUGIN_HOST 1
  24436. BEGIN_JUCE_NAMESPACE
  24437. AudioPluginInstance::AudioPluginInstance()
  24438. {
  24439. }
  24440. AudioPluginInstance::~AudioPluginInstance()
  24441. {
  24442. }
  24443. void* AudioPluginInstance::getPlatformSpecificData()
  24444. {
  24445. return 0;
  24446. }
  24447. END_JUCE_NAMESPACE
  24448. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24449. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24450. BEGIN_JUCE_NAMESPACE
  24451. KnownPluginList::KnownPluginList()
  24452. {
  24453. }
  24454. KnownPluginList::~KnownPluginList()
  24455. {
  24456. }
  24457. void KnownPluginList::clear()
  24458. {
  24459. if (types.size() > 0)
  24460. {
  24461. types.clear();
  24462. sendChangeMessage();
  24463. }
  24464. }
  24465. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24466. {
  24467. for (int i = 0; i < types.size(); ++i)
  24468. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24469. return types.getUnchecked(i);
  24470. return 0;
  24471. }
  24472. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24473. {
  24474. for (int i = 0; i < types.size(); ++i)
  24475. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24476. return types.getUnchecked(i);
  24477. return 0;
  24478. }
  24479. bool KnownPluginList::addType (const PluginDescription& type)
  24480. {
  24481. for (int i = types.size(); --i >= 0;)
  24482. {
  24483. if (types.getUnchecked(i)->isDuplicateOf (type))
  24484. {
  24485. // strange - found a duplicate plugin with different info..
  24486. jassert (types.getUnchecked(i)->name == type.name);
  24487. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24488. *types.getUnchecked(i) = type;
  24489. return false;
  24490. }
  24491. }
  24492. types.add (new PluginDescription (type));
  24493. sendChangeMessage();
  24494. return true;
  24495. }
  24496. void KnownPluginList::removeType (const int index)
  24497. {
  24498. types.remove (index);
  24499. sendChangeMessage();
  24500. }
  24501. namespace
  24502. {
  24503. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24504. {
  24505. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24506. return File (fileOrIdentifier).getLastModificationTime();
  24507. return Time();
  24508. }
  24509. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24510. {
  24511. return t1 != t2 || t1 == Time();
  24512. }
  24513. }
  24514. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24515. {
  24516. if (getTypeForFile (fileOrIdentifier) == 0)
  24517. return false;
  24518. for (int i = types.size(); --i >= 0;)
  24519. {
  24520. const PluginDescription* const d = types.getUnchecked(i);
  24521. if (d->fileOrIdentifier == fileOrIdentifier
  24522. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24523. {
  24524. return false;
  24525. }
  24526. }
  24527. return true;
  24528. }
  24529. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24530. const bool dontRescanIfAlreadyInList,
  24531. OwnedArray <PluginDescription>& typesFound,
  24532. AudioPluginFormat& format)
  24533. {
  24534. bool addedOne = false;
  24535. if (dontRescanIfAlreadyInList
  24536. && getTypeForFile (fileOrIdentifier) != 0)
  24537. {
  24538. bool needsRescanning = false;
  24539. for (int i = types.size(); --i >= 0;)
  24540. {
  24541. const PluginDescription* const d = types.getUnchecked(i);
  24542. if (d->fileOrIdentifier == fileOrIdentifier)
  24543. {
  24544. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24545. needsRescanning = true;
  24546. else
  24547. typesFound.add (new PluginDescription (*d));
  24548. }
  24549. }
  24550. if (! needsRescanning)
  24551. return false;
  24552. }
  24553. OwnedArray <PluginDescription> found;
  24554. format.findAllTypesForFile (found, fileOrIdentifier);
  24555. for (int i = 0; i < found.size(); ++i)
  24556. {
  24557. PluginDescription* const desc = found.getUnchecked(i);
  24558. jassert (desc != 0);
  24559. if (addType (*desc))
  24560. addedOne = true;
  24561. typesFound.add (new PluginDescription (*desc));
  24562. }
  24563. return addedOne;
  24564. }
  24565. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24566. OwnedArray <PluginDescription>& typesFound)
  24567. {
  24568. for (int i = 0; i < files.size(); ++i)
  24569. {
  24570. bool loaded = false;
  24571. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24572. {
  24573. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24574. if (scanAndAddFile (files[i], true, typesFound, *format))
  24575. loaded = true;
  24576. }
  24577. if (! loaded)
  24578. {
  24579. const File f (files[i]);
  24580. if (f.isDirectory())
  24581. {
  24582. StringArray s;
  24583. {
  24584. Array<File> subFiles;
  24585. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24586. for (int j = 0; j < subFiles.size(); ++j)
  24587. s.add (subFiles.getReference(j).getFullPathName());
  24588. }
  24589. scanAndAddDragAndDroppedFiles (s, typesFound);
  24590. }
  24591. }
  24592. }
  24593. }
  24594. class PluginSorter
  24595. {
  24596. public:
  24597. KnownPluginList::SortMethod method;
  24598. PluginSorter() throw() {}
  24599. int compareElements (const PluginDescription* const first,
  24600. const PluginDescription* const second) const
  24601. {
  24602. int diff = 0;
  24603. if (method == KnownPluginList::sortByCategory)
  24604. diff = first->category.compareLexicographically (second->category);
  24605. else if (method == KnownPluginList::sortByManufacturer)
  24606. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24607. else if (method == KnownPluginList::sortByFileSystemLocation)
  24608. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24609. .upToLastOccurrenceOf ("/", false, false)
  24610. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24611. .upToLastOccurrenceOf ("/", false, false));
  24612. if (diff == 0)
  24613. diff = first->name.compareLexicographically (second->name);
  24614. return diff;
  24615. }
  24616. };
  24617. void KnownPluginList::sort (const SortMethod method)
  24618. {
  24619. if (method != defaultOrder)
  24620. {
  24621. PluginSorter sorter;
  24622. sorter.method = method;
  24623. types.sort (sorter, true);
  24624. sendChangeMessage();
  24625. }
  24626. }
  24627. XmlElement* KnownPluginList::createXml() const
  24628. {
  24629. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24630. for (int i = 0; i < types.size(); ++i)
  24631. e->addChildElement (types.getUnchecked(i)->createXml());
  24632. return e;
  24633. }
  24634. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24635. {
  24636. clear();
  24637. if (xml.hasTagName ("KNOWNPLUGINS"))
  24638. {
  24639. forEachXmlChildElement (xml, e)
  24640. {
  24641. PluginDescription info;
  24642. if (info.loadFromXml (*e))
  24643. addType (info);
  24644. }
  24645. }
  24646. }
  24647. const int menuIdBase = 0x324503f4;
  24648. // This is used to turn a bunch of paths into a nested menu structure.
  24649. struct PluginFilesystemTree
  24650. {
  24651. private:
  24652. String folder;
  24653. OwnedArray <PluginFilesystemTree> subFolders;
  24654. Array <PluginDescription*> plugins;
  24655. void addPlugin (PluginDescription* const pd, const String& path)
  24656. {
  24657. if (path.isEmpty())
  24658. {
  24659. plugins.add (pd);
  24660. }
  24661. else
  24662. {
  24663. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24664. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24665. for (int i = subFolders.size(); --i >= 0;)
  24666. {
  24667. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24668. {
  24669. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24670. return;
  24671. }
  24672. }
  24673. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24674. newFolder->folder = firstSubFolder;
  24675. subFolders.add (newFolder);
  24676. newFolder->addPlugin (pd, remainingPath);
  24677. }
  24678. }
  24679. // removes any deeply nested folders that don't contain any actual plugins
  24680. void optimise()
  24681. {
  24682. for (int i = subFolders.size(); --i >= 0;)
  24683. {
  24684. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24685. sub->optimise();
  24686. if (sub->plugins.size() == 0)
  24687. {
  24688. for (int j = 0; j < sub->subFolders.size(); ++j)
  24689. subFolders.add (sub->subFolders.getUnchecked(j));
  24690. sub->subFolders.clear (false);
  24691. subFolders.remove (i);
  24692. }
  24693. }
  24694. }
  24695. public:
  24696. void buildTree (const Array <PluginDescription*>& allPlugins)
  24697. {
  24698. for (int i = 0; i < allPlugins.size(); ++i)
  24699. {
  24700. String path (allPlugins.getUnchecked(i)
  24701. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24702. .upToLastOccurrenceOf ("/", false, false));
  24703. if (path.substring (1, 2) == ":")
  24704. path = path.substring (2);
  24705. addPlugin (allPlugins.getUnchecked(i), path);
  24706. }
  24707. optimise();
  24708. }
  24709. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24710. {
  24711. int i;
  24712. for (i = 0; i < subFolders.size(); ++i)
  24713. {
  24714. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24715. PopupMenu subMenu;
  24716. sub->addToMenu (subMenu, allPlugins);
  24717. #if JUCE_MAC
  24718. // avoid the special AU formatting nonsense on Mac..
  24719. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24720. #else
  24721. m.addSubMenu (sub->folder, subMenu);
  24722. #endif
  24723. }
  24724. for (i = 0; i < plugins.size(); ++i)
  24725. {
  24726. PluginDescription* const plugin = plugins.getUnchecked(i);
  24727. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24728. plugin->name, true, false);
  24729. }
  24730. }
  24731. };
  24732. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24733. {
  24734. Array <PluginDescription*> sorted;
  24735. {
  24736. PluginSorter sorter;
  24737. sorter.method = sortMethod;
  24738. for (int i = 0; i < types.size(); ++i)
  24739. sorted.addSorted (sorter, types.getUnchecked(i));
  24740. }
  24741. if (sortMethod == sortByCategory
  24742. || sortMethod == sortByManufacturer)
  24743. {
  24744. String lastSubMenuName;
  24745. PopupMenu sub;
  24746. for (int i = 0; i < sorted.size(); ++i)
  24747. {
  24748. const PluginDescription* const pd = sorted.getUnchecked(i);
  24749. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24750. : pd->manufacturerName);
  24751. if (! thisSubMenuName.containsNonWhitespaceChars())
  24752. thisSubMenuName = "Other";
  24753. if (thisSubMenuName != lastSubMenuName)
  24754. {
  24755. if (sub.getNumItems() > 0)
  24756. {
  24757. menu.addSubMenu (lastSubMenuName, sub);
  24758. sub.clear();
  24759. }
  24760. lastSubMenuName = thisSubMenuName;
  24761. }
  24762. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24763. }
  24764. if (sub.getNumItems() > 0)
  24765. menu.addSubMenu (lastSubMenuName, sub);
  24766. }
  24767. else if (sortMethod == sortByFileSystemLocation)
  24768. {
  24769. PluginFilesystemTree root;
  24770. root.buildTree (sorted);
  24771. root.addToMenu (menu, types);
  24772. }
  24773. else
  24774. {
  24775. for (int i = 0; i < sorted.size(); ++i)
  24776. {
  24777. const PluginDescription* const pd = sorted.getUnchecked(i);
  24778. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24779. }
  24780. }
  24781. }
  24782. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24783. {
  24784. const int i = menuResultCode - menuIdBase;
  24785. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24786. }
  24787. END_JUCE_NAMESPACE
  24788. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24789. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24790. BEGIN_JUCE_NAMESPACE
  24791. PluginDescription::PluginDescription()
  24792. : uid (0),
  24793. isInstrument (false),
  24794. numInputChannels (0),
  24795. numOutputChannels (0)
  24796. {
  24797. }
  24798. PluginDescription::~PluginDescription()
  24799. {
  24800. }
  24801. PluginDescription::PluginDescription (const PluginDescription& other)
  24802. : name (other.name),
  24803. descriptiveName (other.descriptiveName),
  24804. pluginFormatName (other.pluginFormatName),
  24805. category (other.category),
  24806. manufacturerName (other.manufacturerName),
  24807. version (other.version),
  24808. fileOrIdentifier (other.fileOrIdentifier),
  24809. lastFileModTime (other.lastFileModTime),
  24810. uid (other.uid),
  24811. isInstrument (other.isInstrument),
  24812. numInputChannels (other.numInputChannels),
  24813. numOutputChannels (other.numOutputChannels)
  24814. {
  24815. }
  24816. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24817. {
  24818. name = other.name;
  24819. descriptiveName = other.descriptiveName;
  24820. pluginFormatName = other.pluginFormatName;
  24821. category = other.category;
  24822. manufacturerName = other.manufacturerName;
  24823. version = other.version;
  24824. fileOrIdentifier = other.fileOrIdentifier;
  24825. uid = other.uid;
  24826. isInstrument = other.isInstrument;
  24827. lastFileModTime = other.lastFileModTime;
  24828. numInputChannels = other.numInputChannels;
  24829. numOutputChannels = other.numOutputChannels;
  24830. return *this;
  24831. }
  24832. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24833. {
  24834. return fileOrIdentifier == other.fileOrIdentifier
  24835. && uid == other.uid;
  24836. }
  24837. const String PluginDescription::createIdentifierString() const
  24838. {
  24839. return pluginFormatName
  24840. + "-" + name
  24841. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24842. + "-" + String::toHexString (uid);
  24843. }
  24844. XmlElement* PluginDescription::createXml() const
  24845. {
  24846. XmlElement* const e = new XmlElement ("PLUGIN");
  24847. e->setAttribute ("name", name);
  24848. if (descriptiveName != name)
  24849. e->setAttribute ("descriptiveName", descriptiveName);
  24850. e->setAttribute ("format", pluginFormatName);
  24851. e->setAttribute ("category", category);
  24852. e->setAttribute ("manufacturer", manufacturerName);
  24853. e->setAttribute ("version", version);
  24854. e->setAttribute ("file", fileOrIdentifier);
  24855. e->setAttribute ("uid", String::toHexString (uid));
  24856. e->setAttribute ("isInstrument", isInstrument);
  24857. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24858. e->setAttribute ("numInputs", numInputChannels);
  24859. e->setAttribute ("numOutputs", numOutputChannels);
  24860. return e;
  24861. }
  24862. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24863. {
  24864. if (xml.hasTagName ("PLUGIN"))
  24865. {
  24866. name = xml.getStringAttribute ("name");
  24867. descriptiveName = xml.getStringAttribute ("name", name);
  24868. pluginFormatName = xml.getStringAttribute ("format");
  24869. category = xml.getStringAttribute ("category");
  24870. manufacturerName = xml.getStringAttribute ("manufacturer");
  24871. version = xml.getStringAttribute ("version");
  24872. fileOrIdentifier = xml.getStringAttribute ("file");
  24873. uid = xml.getStringAttribute ("uid").getHexValue32();
  24874. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24875. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24876. numInputChannels = xml.getIntAttribute ("numInputs");
  24877. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24878. return true;
  24879. }
  24880. return false;
  24881. }
  24882. END_JUCE_NAMESPACE
  24883. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24884. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24885. BEGIN_JUCE_NAMESPACE
  24886. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24887. AudioPluginFormat& formatToLookFor,
  24888. FileSearchPath directoriesToSearch,
  24889. const bool recursive,
  24890. const File& deadMansPedalFile_)
  24891. : list (listToAddTo),
  24892. format (formatToLookFor),
  24893. deadMansPedalFile (deadMansPedalFile_),
  24894. nextIndex (0),
  24895. progress (0)
  24896. {
  24897. directoriesToSearch.removeRedundantPaths();
  24898. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24899. // If any plugins have crashed recently when being loaded, move them to the
  24900. // end of the list to give the others a chance to load correctly..
  24901. const StringArray crashedPlugins (getDeadMansPedalFile());
  24902. for (int i = 0; i < crashedPlugins.size(); ++i)
  24903. {
  24904. const String f = crashedPlugins[i];
  24905. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24906. if (f == filesOrIdentifiersToScan[j])
  24907. filesOrIdentifiersToScan.move (j, -1);
  24908. }
  24909. }
  24910. PluginDirectoryScanner::~PluginDirectoryScanner()
  24911. {
  24912. }
  24913. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24914. {
  24915. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24916. }
  24917. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24918. {
  24919. String file (filesOrIdentifiersToScan [nextIndex]);
  24920. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24921. {
  24922. OwnedArray <PluginDescription> typesFound;
  24923. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24924. StringArray crashedPlugins (getDeadMansPedalFile());
  24925. crashedPlugins.removeString (file);
  24926. crashedPlugins.add (file);
  24927. setDeadMansPedalFile (crashedPlugins);
  24928. list.scanAndAddFile (file,
  24929. dontRescanIfAlreadyInList,
  24930. typesFound,
  24931. format);
  24932. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24933. crashedPlugins.removeString (file);
  24934. setDeadMansPedalFile (crashedPlugins);
  24935. if (typesFound.size() == 0)
  24936. failedFiles.add (file);
  24937. }
  24938. return skipNextFile();
  24939. }
  24940. bool PluginDirectoryScanner::skipNextFile()
  24941. {
  24942. if (nextIndex >= filesOrIdentifiersToScan.size())
  24943. return false;
  24944. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24945. return nextIndex < filesOrIdentifiersToScan.size();
  24946. }
  24947. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24948. {
  24949. StringArray lines;
  24950. if (deadMansPedalFile != File::nonexistent)
  24951. {
  24952. lines.addLines (deadMansPedalFile.loadFileAsString());
  24953. lines.removeEmptyStrings();
  24954. }
  24955. return lines;
  24956. }
  24957. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24958. {
  24959. if (deadMansPedalFile != File::nonexistent)
  24960. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24961. }
  24962. END_JUCE_NAMESPACE
  24963. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24964. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24965. BEGIN_JUCE_NAMESPACE
  24966. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24967. const File& deadMansPedalFile_,
  24968. PropertiesFile* const propertiesToUse_)
  24969. : list (listToEdit),
  24970. deadMansPedalFile (deadMansPedalFile_),
  24971. optionsButton ("Options..."),
  24972. propertiesToUse (propertiesToUse_)
  24973. {
  24974. listBox.setModel (this);
  24975. addAndMakeVisible (&listBox);
  24976. addAndMakeVisible (&optionsButton);
  24977. optionsButton.addListener (this);
  24978. optionsButton.setTriggeredOnMouseDown (true);
  24979. setSize (400, 600);
  24980. list.addChangeListener (this);
  24981. changeListenerCallback (0);
  24982. }
  24983. PluginListComponent::~PluginListComponent()
  24984. {
  24985. list.removeChangeListener (this);
  24986. }
  24987. void PluginListComponent::resized()
  24988. {
  24989. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24990. optionsButton.changeWidthToFitText (24);
  24991. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24992. }
  24993. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24994. {
  24995. listBox.updateContent();
  24996. listBox.repaint();
  24997. }
  24998. int PluginListComponent::getNumRows()
  24999. {
  25000. return list.getNumTypes();
  25001. }
  25002. void PluginListComponent::paintListBoxItem (int row,
  25003. Graphics& g,
  25004. int width, int height,
  25005. bool rowIsSelected)
  25006. {
  25007. if (rowIsSelected)
  25008. g.fillAll (findColour (TextEditor::highlightColourId));
  25009. const PluginDescription* const pd = list.getType (row);
  25010. if (pd != 0)
  25011. {
  25012. GlyphArrangement ga;
  25013. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  25014. g.setColour (Colours::black);
  25015. ga.draw (g);
  25016. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  25017. String desc;
  25018. desc << pd->pluginFormatName
  25019. << (pd->isInstrument ? " instrument" : " effect")
  25020. << " - "
  25021. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  25022. << " / "
  25023. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  25024. if (pd->manufacturerName.isNotEmpty())
  25025. desc << " - " << pd->manufacturerName;
  25026. if (pd->version.isNotEmpty())
  25027. desc << " - " << pd->version;
  25028. if (pd->category.isNotEmpty())
  25029. desc << " - category: '" << pd->category << '\'';
  25030. g.setColour (Colours::grey);
  25031. ga.clear();
  25032. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  25033. ga.draw (g);
  25034. }
  25035. }
  25036. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  25037. {
  25038. list.removeType (lastRowSelected);
  25039. }
  25040. void PluginListComponent::buttonClicked (Button* button)
  25041. {
  25042. if (button == &optionsButton)
  25043. {
  25044. PopupMenu menu;
  25045. menu.addItem (1, TRANS("Clear list"));
  25046. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  25047. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  25048. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  25049. menu.addSeparator();
  25050. menu.addItem (2, TRANS("Sort alphabetically"));
  25051. menu.addItem (3, TRANS("Sort by category"));
  25052. menu.addItem (4, TRANS("Sort by manufacturer"));
  25053. menu.addSeparator();
  25054. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  25055. {
  25056. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  25057. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  25058. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  25059. }
  25060. const int r = menu.showAt (&optionsButton);
  25061. if (r == 1)
  25062. {
  25063. list.clear();
  25064. }
  25065. else if (r == 2)
  25066. {
  25067. list.sort (KnownPluginList::sortAlphabetically);
  25068. }
  25069. else if (r == 3)
  25070. {
  25071. list.sort (KnownPluginList::sortByCategory);
  25072. }
  25073. else if (r == 4)
  25074. {
  25075. list.sort (KnownPluginList::sortByManufacturer);
  25076. }
  25077. else if (r == 5)
  25078. {
  25079. const SparseSet <int> selected (listBox.getSelectedRows());
  25080. for (int i = list.getNumTypes(); --i >= 0;)
  25081. if (selected.contains (i))
  25082. list.removeType (i);
  25083. }
  25084. else if (r == 6)
  25085. {
  25086. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  25087. if (desc != 0)
  25088. {
  25089. if (File (desc->fileOrIdentifier).existsAsFile())
  25090. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  25091. }
  25092. }
  25093. else if (r == 7)
  25094. {
  25095. for (int i = list.getNumTypes(); --i >= 0;)
  25096. {
  25097. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  25098. {
  25099. list.removeType (i);
  25100. }
  25101. }
  25102. }
  25103. else if (r != 0)
  25104. {
  25105. typeToScan = r - 10;
  25106. startTimer (1);
  25107. }
  25108. }
  25109. }
  25110. void PluginListComponent::timerCallback()
  25111. {
  25112. stopTimer();
  25113. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  25114. }
  25115. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25116. {
  25117. return true;
  25118. }
  25119. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25120. {
  25121. OwnedArray <PluginDescription> typesFound;
  25122. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25123. }
  25124. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25125. {
  25126. if (format == 0)
  25127. return;
  25128. FileSearchPath path (format->getDefaultLocationsToSearch());
  25129. if (propertiesToUse != 0)
  25130. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25131. {
  25132. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25133. FileSearchPathListComponent pathList;
  25134. pathList.setSize (500, 300);
  25135. pathList.setPath (path);
  25136. aw.addCustomComponent (&pathList);
  25137. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25138. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  25139. if (aw.runModalLoop() == 0)
  25140. return;
  25141. path = pathList.getPath();
  25142. }
  25143. if (propertiesToUse != 0)
  25144. {
  25145. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25146. propertiesToUse->saveIfNeeded();
  25147. }
  25148. double progress = 0.0;
  25149. AlertWindow aw (TRANS("Scanning for plugins..."),
  25150. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25151. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  25152. aw.addProgressBarComponent (progress);
  25153. aw.enterModalState();
  25154. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25155. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25156. for (;;)
  25157. {
  25158. aw.setMessage (TRANS("Testing:\n\n")
  25159. + scanner.getNextPluginFileThatWillBeScanned());
  25160. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25161. if (! scanner.scanNextFile (true))
  25162. break;
  25163. if (! aw.isCurrentlyModal())
  25164. break;
  25165. progress = scanner.getProgress();
  25166. }
  25167. if (scanner.getFailedFiles().size() > 0)
  25168. {
  25169. StringArray shortNames;
  25170. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25171. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25172. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25173. TRANS("Scan complete"),
  25174. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25175. + shortNames.joinIntoString (", "));
  25176. }
  25177. }
  25178. END_JUCE_NAMESPACE
  25179. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25180. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25181. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25182. #include <AudioUnit/AudioUnit.h>
  25183. #include <AudioUnit/AUCocoaUIView.h>
  25184. #include <CoreAudioKit/AUGenericView.h>
  25185. #if JUCE_SUPPORT_CARBON
  25186. #include <AudioToolbox/AudioUnitUtilities.h>
  25187. #include <AudioUnit/AudioUnitCarbonView.h>
  25188. #endif
  25189. BEGIN_JUCE_NAMESPACE
  25190. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25191. #endif
  25192. #if JUCE_MAC
  25193. // Change this to disable logging of various activities
  25194. #ifndef AU_LOGGING
  25195. #define AU_LOGGING 1
  25196. #endif
  25197. #if AU_LOGGING
  25198. #define log(a) Logger::writeToLog(a);
  25199. #else
  25200. #define log(a)
  25201. #endif
  25202. namespace AudioUnitFormatHelpers
  25203. {
  25204. static int insideCallback = 0;
  25205. const String osTypeToString (OSType type)
  25206. {
  25207. char s[4];
  25208. s[0] = (char) (((uint32) type) >> 24);
  25209. s[1] = (char) (((uint32) type) >> 16);
  25210. s[2] = (char) (((uint32) type) >> 8);
  25211. s[3] = (char) ((uint32) type);
  25212. return String (s, 4);
  25213. }
  25214. OSType stringToOSType (const String& s1)
  25215. {
  25216. const String s (s1 + " ");
  25217. return (((OSType) (unsigned char) s[0]) << 24)
  25218. | (((OSType) (unsigned char) s[1]) << 16)
  25219. | (((OSType) (unsigned char) s[2]) << 8)
  25220. | ((OSType) (unsigned char) s[3]);
  25221. }
  25222. static const char* auIdentifierPrefix = "AudioUnit:";
  25223. const String createAUPluginIdentifier (const ComponentDescription& desc)
  25224. {
  25225. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25226. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25227. String s (auIdentifierPrefix);
  25228. if (desc.componentType == kAudioUnitType_MusicDevice)
  25229. s << "Synths/";
  25230. else if (desc.componentType == kAudioUnitType_MusicEffect
  25231. || desc.componentType == kAudioUnitType_Effect)
  25232. s << "Effects/";
  25233. else if (desc.componentType == kAudioUnitType_Generator)
  25234. s << "Generators/";
  25235. else if (desc.componentType == kAudioUnitType_Panner)
  25236. s << "Panners/";
  25237. s << osTypeToString (desc.componentType) << ","
  25238. << osTypeToString (desc.componentSubType) << ","
  25239. << osTypeToString (desc.componentManufacturer);
  25240. return s;
  25241. }
  25242. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25243. {
  25244. Handle componentNameHandle = NewHandle (sizeof (void*));
  25245. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25246. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25247. {
  25248. ComponentDescription desc;
  25249. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25250. {
  25251. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25252. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25253. if (nameString != 0 && nameString[0] != 0)
  25254. {
  25255. const String all ((const char*) nameString + 1, nameString[0]);
  25256. DBG ("name: "+ all);
  25257. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25258. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25259. }
  25260. if (infoString != 0 && infoString[0] != 0)
  25261. {
  25262. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25263. }
  25264. if (name.isEmpty())
  25265. name = "<Unknown>";
  25266. }
  25267. DisposeHandle (componentNameHandle);
  25268. DisposeHandle (componentInfoHandle);
  25269. }
  25270. }
  25271. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25272. String& name, String& version, String& manufacturer)
  25273. {
  25274. zerostruct (desc);
  25275. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25276. {
  25277. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25278. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25279. StringArray tokens;
  25280. tokens.addTokens (s, ",", String::empty);
  25281. tokens.trim();
  25282. tokens.removeEmptyStrings();
  25283. if (tokens.size() == 3)
  25284. {
  25285. desc.componentType = stringToOSType (tokens[0]);
  25286. desc.componentSubType = stringToOSType (tokens[1]);
  25287. desc.componentManufacturer = stringToOSType (tokens[2]);
  25288. ComponentRecord* comp = FindNextComponent (0, &desc);
  25289. if (comp != 0)
  25290. {
  25291. getAUDetails (comp, name, manufacturer);
  25292. return true;
  25293. }
  25294. }
  25295. }
  25296. return false;
  25297. }
  25298. }
  25299. class AudioUnitPluginWindowCarbon;
  25300. class AudioUnitPluginWindowCocoa;
  25301. class AudioUnitPluginInstance : public AudioPluginInstance
  25302. {
  25303. public:
  25304. ~AudioUnitPluginInstance();
  25305. void initialise();
  25306. // AudioPluginInstance methods:
  25307. void fillInPluginDescription (PluginDescription& desc) const
  25308. {
  25309. desc.name = pluginName;
  25310. desc.descriptiveName = pluginName;
  25311. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25312. desc.uid = ((int) componentDesc.componentType)
  25313. ^ ((int) componentDesc.componentSubType)
  25314. ^ ((int) componentDesc.componentManufacturer);
  25315. desc.lastFileModTime = Time();
  25316. desc.pluginFormatName = "AudioUnit";
  25317. desc.category = getCategory();
  25318. desc.manufacturerName = manufacturer;
  25319. desc.version = version;
  25320. desc.numInputChannels = getNumInputChannels();
  25321. desc.numOutputChannels = getNumOutputChannels();
  25322. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25323. }
  25324. void* getPlatformSpecificData() { return audioUnit; }
  25325. const String getName() const { return pluginName; }
  25326. bool acceptsMidi() const { return wantsMidiMessages; }
  25327. bool producesMidi() const { return false; }
  25328. // AudioProcessor methods:
  25329. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25330. void releaseResources();
  25331. void processBlock (AudioSampleBuffer& buffer,
  25332. MidiBuffer& midiMessages);
  25333. bool hasEditor() const;
  25334. AudioProcessorEditor* createEditor();
  25335. const String getInputChannelName (int index) const;
  25336. bool isInputChannelStereoPair (int index) const;
  25337. const String getOutputChannelName (int index) const;
  25338. bool isOutputChannelStereoPair (int index) const;
  25339. int getNumParameters();
  25340. float getParameter (int index);
  25341. void setParameter (int index, float newValue);
  25342. const String getParameterName (int index);
  25343. const String getParameterText (int index);
  25344. bool isParameterAutomatable (int index) const;
  25345. int getNumPrograms();
  25346. int getCurrentProgram();
  25347. void setCurrentProgram (int index);
  25348. const String getProgramName (int index);
  25349. void changeProgramName (int index, const String& newName);
  25350. void getStateInformation (MemoryBlock& destData);
  25351. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25352. void setStateInformation (const void* data, int sizeInBytes);
  25353. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25354. private:
  25355. friend class AudioUnitPluginWindowCarbon;
  25356. friend class AudioUnitPluginWindowCocoa;
  25357. friend class AudioUnitPluginFormat;
  25358. ComponentDescription componentDesc;
  25359. String pluginName, manufacturer, version;
  25360. String fileOrIdentifier;
  25361. CriticalSection lock;
  25362. bool wantsMidiMessages, wasPlaying, prepared;
  25363. HeapBlock <AudioBufferList> outputBufferList;
  25364. AudioTimeStamp timeStamp;
  25365. AudioSampleBuffer* currentBuffer;
  25366. AudioUnit audioUnit;
  25367. Array <int> parameterIds;
  25368. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25369. void setPluginCallbacks();
  25370. void getParameterListFromPlugin();
  25371. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25372. const AudioTimeStamp* inTimeStamp,
  25373. UInt32 inBusNumber,
  25374. UInt32 inNumberFrames,
  25375. AudioBufferList* ioData) const;
  25376. static OSStatus renderGetInputCallback (void* inRefCon,
  25377. AudioUnitRenderActionFlags* ioActionFlags,
  25378. const AudioTimeStamp* inTimeStamp,
  25379. UInt32 inBusNumber,
  25380. UInt32 inNumberFrames,
  25381. AudioBufferList* ioData)
  25382. {
  25383. return ((AudioUnitPluginInstance*) inRefCon)
  25384. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25385. }
  25386. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25387. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25388. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25389. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25390. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25391. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25392. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25393. {
  25394. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25395. }
  25396. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25397. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25398. Float64* outCurrentMeasureDownBeat)
  25399. {
  25400. return ((AudioUnitPluginInstance*) inHostUserData)
  25401. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25402. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25403. }
  25404. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25405. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25406. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25407. {
  25408. return ((AudioUnitPluginInstance*) inHostUserData)
  25409. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25410. outCurrentSampleInTimeLine, outIsCycling,
  25411. outCycleStartBeat, outCycleEndBeat);
  25412. }
  25413. void getNumChannels (int& numIns, int& numOuts)
  25414. {
  25415. numIns = 0;
  25416. numOuts = 0;
  25417. AUChannelInfo supportedChannels [128];
  25418. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25419. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25420. 0, supportedChannels, &supportedChannelsSize) == noErr
  25421. && supportedChannelsSize > 0)
  25422. {
  25423. int explicitNumIns = 0;
  25424. int explicitNumOuts = 0;
  25425. int maximumNumIns = 0;
  25426. int maximumNumOuts = 0;
  25427. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25428. {
  25429. const int inChannels = (int) supportedChannels[i].inChannels;
  25430. const int outChannels = (int) supportedChannels[i].outChannels;
  25431. if (inChannels < 0)
  25432. maximumNumIns = jmin (maximumNumIns, inChannels);
  25433. else
  25434. explicitNumIns = jmax (explicitNumIns, inChannels);
  25435. if (outChannels < 0)
  25436. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25437. else
  25438. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25439. }
  25440. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25441. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25442. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25443. {
  25444. numIns = numOuts = 2;
  25445. }
  25446. else
  25447. {
  25448. numIns = explicitNumIns;
  25449. numOuts = explicitNumOuts;
  25450. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25451. numIns = 2;
  25452. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25453. numOuts = 2;
  25454. }
  25455. }
  25456. else
  25457. {
  25458. // (this really means the plugin will take any number of ins/outs as long
  25459. // as they are the same)
  25460. numIns = numOuts = 2;
  25461. }
  25462. }
  25463. const String getCategory() const;
  25464. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25465. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25466. };
  25467. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25468. : fileOrIdentifier (fileOrIdentifier),
  25469. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25470. currentBuffer (0),
  25471. audioUnit (0)
  25472. {
  25473. using namespace AudioUnitFormatHelpers;
  25474. try
  25475. {
  25476. ++insideCallback;
  25477. log ("Opening AU: " + fileOrIdentifier);
  25478. if (getComponentDescFromFile (fileOrIdentifier))
  25479. {
  25480. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25481. if (comp != 0)
  25482. {
  25483. audioUnit = (AudioUnit) OpenComponent (comp);
  25484. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25485. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25486. }
  25487. }
  25488. --insideCallback;
  25489. }
  25490. catch (...)
  25491. {
  25492. --insideCallback;
  25493. }
  25494. }
  25495. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25496. {
  25497. const ScopedLock sl (lock);
  25498. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25499. if (audioUnit != 0)
  25500. {
  25501. AudioUnitUninitialize (audioUnit);
  25502. CloseComponent (audioUnit);
  25503. audioUnit = 0;
  25504. }
  25505. }
  25506. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25507. {
  25508. zerostruct (componentDesc);
  25509. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25510. return true;
  25511. const File file (fileOrIdentifier);
  25512. if (! file.hasFileExtension (".component"))
  25513. return false;
  25514. const char* const utf8 = fileOrIdentifier.toUTF8();
  25515. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25516. strlen (utf8), file.isDirectory());
  25517. if (url != 0)
  25518. {
  25519. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25520. CFRelease (url);
  25521. if (bundleRef != 0)
  25522. {
  25523. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25524. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25525. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25526. if (pluginName.isEmpty())
  25527. pluginName = file.getFileNameWithoutExtension();
  25528. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25529. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25530. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25531. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25532. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25533. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25534. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25535. UseResFile (resFileId);
  25536. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25537. {
  25538. Handle h = Get1IndResource ('thng', i);
  25539. if (h != 0)
  25540. {
  25541. HLock (h);
  25542. const uint32* const types = (const uint32*) *h;
  25543. if (types[0] == kAudioUnitType_MusicDevice
  25544. || types[0] == kAudioUnitType_MusicEffect
  25545. || types[0] == kAudioUnitType_Effect
  25546. || types[0] == kAudioUnitType_Generator
  25547. || types[0] == kAudioUnitType_Panner)
  25548. {
  25549. componentDesc.componentType = types[0];
  25550. componentDesc.componentSubType = types[1];
  25551. componentDesc.componentManufacturer = types[2];
  25552. break;
  25553. }
  25554. HUnlock (h);
  25555. ReleaseResource (h);
  25556. }
  25557. }
  25558. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25559. CFRelease (bundleRef);
  25560. }
  25561. }
  25562. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25563. }
  25564. void AudioUnitPluginInstance::initialise()
  25565. {
  25566. getParameterListFromPlugin();
  25567. setPluginCallbacks();
  25568. int numIns, numOuts;
  25569. getNumChannels (numIns, numOuts);
  25570. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25571. setLatencySamples (0);
  25572. }
  25573. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25574. {
  25575. parameterIds.clear();
  25576. if (audioUnit != 0)
  25577. {
  25578. UInt32 paramListSize = 0;
  25579. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25580. 0, 0, &paramListSize);
  25581. if (paramListSize > 0)
  25582. {
  25583. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25584. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25585. 0, &parameterIds.getReference(0), &paramListSize);
  25586. }
  25587. }
  25588. }
  25589. void AudioUnitPluginInstance::setPluginCallbacks()
  25590. {
  25591. if (audioUnit != 0)
  25592. {
  25593. {
  25594. AURenderCallbackStruct info;
  25595. zerostruct (info);
  25596. info.inputProcRefCon = this;
  25597. info.inputProc = renderGetInputCallback;
  25598. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25599. 0, &info, sizeof (info));
  25600. }
  25601. {
  25602. HostCallbackInfo info;
  25603. zerostruct (info);
  25604. info.hostUserData = this;
  25605. info.beatAndTempoProc = getBeatAndTempoCallback;
  25606. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25607. info.transportStateProc = getTransportStateCallback;
  25608. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25609. 0, &info, sizeof (info));
  25610. }
  25611. }
  25612. }
  25613. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25614. int samplesPerBlockExpected)
  25615. {
  25616. if (audioUnit != 0)
  25617. {
  25618. releaseResources();
  25619. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25620. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25621. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25622. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25623. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25624. {
  25625. Float64 sr = sampleRate_;
  25626. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25627. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25628. }
  25629. int numIns, numOuts;
  25630. getNumChannels (numIns, numOuts);
  25631. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25632. Float64 latencySecs = 0.0;
  25633. UInt32 latencySize = sizeof (latencySecs);
  25634. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25635. 0, &latencySecs, &latencySize);
  25636. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25637. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25638. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25639. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25640. {
  25641. AudioStreamBasicDescription stream;
  25642. zerostruct (stream);
  25643. stream.mSampleRate = sampleRate_;
  25644. stream.mFormatID = kAudioFormatLinearPCM;
  25645. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25646. stream.mFramesPerPacket = 1;
  25647. stream.mBytesPerPacket = 4;
  25648. stream.mBytesPerFrame = 4;
  25649. stream.mBitsPerChannel = 32;
  25650. stream.mChannelsPerFrame = numIns;
  25651. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25652. 0, &stream, sizeof (stream));
  25653. stream.mChannelsPerFrame = numOuts;
  25654. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25655. 0, &stream, sizeof (stream));
  25656. }
  25657. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25658. outputBufferList->mNumberBuffers = numOuts;
  25659. for (int i = numOuts; --i >= 0;)
  25660. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25661. zerostruct (timeStamp);
  25662. timeStamp.mSampleTime = 0;
  25663. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25664. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25665. currentBuffer = 0;
  25666. wasPlaying = false;
  25667. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25668. }
  25669. }
  25670. void AudioUnitPluginInstance::releaseResources()
  25671. {
  25672. if (prepared)
  25673. {
  25674. AudioUnitUninitialize (audioUnit);
  25675. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25676. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25677. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25678. outputBufferList.free();
  25679. currentBuffer = 0;
  25680. prepared = false;
  25681. }
  25682. }
  25683. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25684. const AudioTimeStamp* inTimeStamp,
  25685. UInt32 inBusNumber,
  25686. UInt32 inNumberFrames,
  25687. AudioBufferList* ioData) const
  25688. {
  25689. if (inBusNumber == 0
  25690. && currentBuffer != 0)
  25691. {
  25692. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25693. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25694. {
  25695. if (i < currentBuffer->getNumChannels())
  25696. {
  25697. memcpy (ioData->mBuffers[i].mData,
  25698. currentBuffer->getSampleData (i, 0),
  25699. sizeof (float) * inNumberFrames);
  25700. }
  25701. else
  25702. {
  25703. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25704. }
  25705. }
  25706. }
  25707. return noErr;
  25708. }
  25709. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25710. MidiBuffer& midiMessages)
  25711. {
  25712. const int numSamples = buffer.getNumSamples();
  25713. if (prepared)
  25714. {
  25715. AudioUnitRenderActionFlags flags = 0;
  25716. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25717. for (int i = getNumOutputChannels(); --i >= 0;)
  25718. {
  25719. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25720. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25721. }
  25722. currentBuffer = &buffer;
  25723. if (wantsMidiMessages)
  25724. {
  25725. const uint8* midiEventData;
  25726. int midiEventSize, midiEventPosition;
  25727. MidiBuffer::Iterator i (midiMessages);
  25728. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25729. {
  25730. if (midiEventSize <= 3)
  25731. MusicDeviceMIDIEvent (audioUnit,
  25732. midiEventData[0], midiEventData[1], midiEventData[2],
  25733. midiEventPosition);
  25734. else
  25735. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25736. }
  25737. midiMessages.clear();
  25738. }
  25739. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25740. 0, numSamples, outputBufferList);
  25741. timeStamp.mSampleTime += numSamples;
  25742. }
  25743. else
  25744. {
  25745. // Plugin not working correctly, so just bypass..
  25746. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25747. buffer.clear (i, 0, buffer.getNumSamples());
  25748. }
  25749. }
  25750. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25751. {
  25752. AudioPlayHead* const ph = getPlayHead();
  25753. AudioPlayHead::CurrentPositionInfo result;
  25754. if (ph != 0 && ph->getCurrentPosition (result))
  25755. {
  25756. if (outCurrentBeat != 0)
  25757. *outCurrentBeat = result.ppqPosition;
  25758. if (outCurrentTempo != 0)
  25759. *outCurrentTempo = result.bpm;
  25760. }
  25761. else
  25762. {
  25763. if (outCurrentBeat != 0)
  25764. *outCurrentBeat = 0;
  25765. if (outCurrentTempo != 0)
  25766. *outCurrentTempo = 120.0;
  25767. }
  25768. return noErr;
  25769. }
  25770. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25771. Float32* outTimeSig_Numerator,
  25772. UInt32* outTimeSig_Denominator,
  25773. Float64* outCurrentMeasureDownBeat) const
  25774. {
  25775. AudioPlayHead* const ph = getPlayHead();
  25776. AudioPlayHead::CurrentPositionInfo result;
  25777. if (ph != 0 && ph->getCurrentPosition (result))
  25778. {
  25779. if (outTimeSig_Numerator != 0)
  25780. *outTimeSig_Numerator = result.timeSigNumerator;
  25781. if (outTimeSig_Denominator != 0)
  25782. *outTimeSig_Denominator = result.timeSigDenominator;
  25783. if (outDeltaSampleOffsetToNextBeat != 0)
  25784. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25785. if (outCurrentMeasureDownBeat != 0)
  25786. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25787. }
  25788. else
  25789. {
  25790. if (outDeltaSampleOffsetToNextBeat != 0)
  25791. *outDeltaSampleOffsetToNextBeat = 0;
  25792. if (outTimeSig_Numerator != 0)
  25793. *outTimeSig_Numerator = 4;
  25794. if (outTimeSig_Denominator != 0)
  25795. *outTimeSig_Denominator = 4;
  25796. if (outCurrentMeasureDownBeat != 0)
  25797. *outCurrentMeasureDownBeat = 0;
  25798. }
  25799. return noErr;
  25800. }
  25801. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25802. Boolean* outTransportStateChanged,
  25803. Float64* outCurrentSampleInTimeLine,
  25804. Boolean* outIsCycling,
  25805. Float64* outCycleStartBeat,
  25806. Float64* outCycleEndBeat)
  25807. {
  25808. AudioPlayHead* const ph = getPlayHead();
  25809. AudioPlayHead::CurrentPositionInfo result;
  25810. if (ph != 0 && ph->getCurrentPosition (result))
  25811. {
  25812. if (outIsPlaying != 0)
  25813. *outIsPlaying = result.isPlaying;
  25814. if (outTransportStateChanged != 0)
  25815. {
  25816. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25817. wasPlaying = result.isPlaying;
  25818. }
  25819. if (outCurrentSampleInTimeLine != 0)
  25820. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25821. if (outIsCycling != 0)
  25822. *outIsCycling = false;
  25823. if (outCycleStartBeat != 0)
  25824. *outCycleStartBeat = 0;
  25825. if (outCycleEndBeat != 0)
  25826. *outCycleEndBeat = 0;
  25827. }
  25828. else
  25829. {
  25830. if (outIsPlaying != 0)
  25831. *outIsPlaying = false;
  25832. if (outTransportStateChanged != 0)
  25833. *outTransportStateChanged = false;
  25834. if (outCurrentSampleInTimeLine != 0)
  25835. *outCurrentSampleInTimeLine = 0;
  25836. if (outIsCycling != 0)
  25837. *outIsCycling = false;
  25838. if (outCycleStartBeat != 0)
  25839. *outCycleStartBeat = 0;
  25840. if (outCycleEndBeat != 0)
  25841. *outCycleEndBeat = 0;
  25842. }
  25843. return noErr;
  25844. }
  25845. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25846. public Timer
  25847. {
  25848. public:
  25849. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25850. : AudioProcessorEditor (&plugin_),
  25851. plugin (plugin_)
  25852. {
  25853. addAndMakeVisible (&wrapper);
  25854. setOpaque (true);
  25855. setVisible (true);
  25856. setSize (100, 100);
  25857. createView (createGenericViewIfNeeded);
  25858. }
  25859. ~AudioUnitPluginWindowCocoa()
  25860. {
  25861. const bool wasValid = isValid();
  25862. wrapper.setView (0);
  25863. if (wasValid)
  25864. plugin.editorBeingDeleted (this);
  25865. }
  25866. bool isValid() const { return wrapper.getView() != 0; }
  25867. void paint (Graphics& g)
  25868. {
  25869. g.fillAll (Colours::white);
  25870. }
  25871. void resized()
  25872. {
  25873. wrapper.setSize (getWidth(), getHeight());
  25874. }
  25875. void timerCallback()
  25876. {
  25877. wrapper.resizeToFitView();
  25878. startTimer (jmin (713, getTimerInterval() + 51));
  25879. }
  25880. void childBoundsChanged (Component* child)
  25881. {
  25882. setSize (wrapper.getWidth(), wrapper.getHeight());
  25883. startTimer (70);
  25884. }
  25885. private:
  25886. AudioUnitPluginInstance& plugin;
  25887. NSViewComponent wrapper;
  25888. bool createView (const bool createGenericViewIfNeeded)
  25889. {
  25890. NSView* pluginView = 0;
  25891. UInt32 dataSize = 0;
  25892. Boolean isWritable = false;
  25893. AudioUnitInitialize (plugin.audioUnit);
  25894. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25895. 0, &dataSize, &isWritable) == noErr
  25896. && dataSize != 0
  25897. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25898. 0, &dataSize, &isWritable) == noErr)
  25899. {
  25900. HeapBlock <AudioUnitCocoaViewInfo> info;
  25901. info.calloc (dataSize, 1);
  25902. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25903. 0, info, &dataSize) == noErr)
  25904. {
  25905. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25906. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25907. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25908. Class viewClass = [viewBundle classNamed: viewClassName];
  25909. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25910. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25911. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25912. {
  25913. id factory = [[[viewClass alloc] init] autorelease];
  25914. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25915. withSize: NSMakeSize (getWidth(), getHeight())];
  25916. }
  25917. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25918. CFRelease (info->mCocoaAUViewClass[i]);
  25919. CFRelease (info->mCocoaAUViewBundleLocation);
  25920. }
  25921. }
  25922. if (createGenericViewIfNeeded && (pluginView == 0))
  25923. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25924. wrapper.setView (pluginView);
  25925. if (pluginView != 0)
  25926. {
  25927. timerCallback();
  25928. startTimer (70);
  25929. }
  25930. return pluginView != 0;
  25931. }
  25932. };
  25933. #if JUCE_SUPPORT_CARBON
  25934. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25935. {
  25936. public:
  25937. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25938. : AudioProcessorEditor (&plugin_),
  25939. plugin (plugin_),
  25940. viewComponent (0)
  25941. {
  25942. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25943. setOpaque (true);
  25944. setVisible (true);
  25945. setSize (400, 300);
  25946. ComponentDescription viewList [16];
  25947. UInt32 viewListSize = sizeof (viewList);
  25948. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25949. 0, &viewList, &viewListSize);
  25950. componentRecord = FindNextComponent (0, &viewList[0]);
  25951. }
  25952. ~AudioUnitPluginWindowCarbon()
  25953. {
  25954. innerWrapper = 0;
  25955. if (isValid())
  25956. plugin.editorBeingDeleted (this);
  25957. }
  25958. bool isValid() const throw() { return componentRecord != 0; }
  25959. void paint (Graphics& g)
  25960. {
  25961. g.fillAll (Colours::black);
  25962. }
  25963. void resized()
  25964. {
  25965. innerWrapper->setSize (getWidth(), getHeight());
  25966. }
  25967. bool keyStateChanged (bool)
  25968. {
  25969. return false;
  25970. }
  25971. bool keyPressed (const KeyPress&)
  25972. {
  25973. return false;
  25974. }
  25975. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25976. AudioUnitCarbonView getViewComponent()
  25977. {
  25978. if (viewComponent == 0 && componentRecord != 0)
  25979. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25980. return viewComponent;
  25981. }
  25982. void closeViewComponent()
  25983. {
  25984. if (viewComponent != 0)
  25985. {
  25986. log ("Closing AU GUI: " + plugin.getName());
  25987. CloseComponent (viewComponent);
  25988. viewComponent = 0;
  25989. }
  25990. }
  25991. private:
  25992. AudioUnitPluginInstance& plugin;
  25993. ComponentRecord* componentRecord;
  25994. AudioUnitCarbonView viewComponent;
  25995. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25996. {
  25997. public:
  25998. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25999. : owner (owner_)
  26000. {
  26001. }
  26002. ~InnerWrapperComponent()
  26003. {
  26004. deleteWindow();
  26005. }
  26006. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26007. {
  26008. log ("Opening AU GUI: " + owner->plugin.getName());
  26009. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  26010. if (viewComponent == 0)
  26011. return 0;
  26012. Float32Point pos = { 0, 0 };
  26013. Float32Point size = { 250, 200 };
  26014. HIViewRef pluginView = 0;
  26015. AudioUnitCarbonViewCreate (viewComponent,
  26016. owner->getAudioUnit(),
  26017. windowRef,
  26018. rootView,
  26019. &pos,
  26020. &size,
  26021. (ControlRef*) &pluginView);
  26022. return pluginView;
  26023. }
  26024. void removeView (HIViewRef)
  26025. {
  26026. owner->closeViewComponent();
  26027. }
  26028. private:
  26029. AudioUnitPluginWindowCarbon* const owner;
  26030. };
  26031. friend class InnerWrapperComponent;
  26032. ScopedPointer<InnerWrapperComponent> innerWrapper;
  26033. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  26034. };
  26035. #endif
  26036. bool AudioUnitPluginInstance::hasEditor() const
  26037. {
  26038. return true;
  26039. }
  26040. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  26041. {
  26042. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  26043. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26044. w = 0;
  26045. #if JUCE_SUPPORT_CARBON
  26046. if (w == 0)
  26047. {
  26048. w = new AudioUnitPluginWindowCarbon (*this);
  26049. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26050. w = 0;
  26051. }
  26052. #endif
  26053. if (w == 0)
  26054. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  26055. return w.release();
  26056. }
  26057. const String AudioUnitPluginInstance::getCategory() const
  26058. {
  26059. const char* result = 0;
  26060. switch (componentDesc.componentType)
  26061. {
  26062. case kAudioUnitType_Effect:
  26063. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  26064. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  26065. case kAudioUnitType_Generator: result = "Generator"; break;
  26066. case kAudioUnitType_Panner: result = "Panner"; break;
  26067. default: break;
  26068. }
  26069. return result;
  26070. }
  26071. int AudioUnitPluginInstance::getNumParameters()
  26072. {
  26073. return parameterIds.size();
  26074. }
  26075. float AudioUnitPluginInstance::getParameter (int index)
  26076. {
  26077. const ScopedLock sl (lock);
  26078. Float32 value = 0.0f;
  26079. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  26080. {
  26081. AudioUnitGetParameter (audioUnit,
  26082. (UInt32) parameterIds.getUnchecked (index),
  26083. kAudioUnitScope_Global, 0,
  26084. &value);
  26085. }
  26086. return value;
  26087. }
  26088. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  26089. {
  26090. const ScopedLock sl (lock);
  26091. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  26092. {
  26093. AudioUnitSetParameter (audioUnit,
  26094. (UInt32) parameterIds.getUnchecked (index),
  26095. kAudioUnitScope_Global, 0,
  26096. newValue, 0);
  26097. }
  26098. }
  26099. const String AudioUnitPluginInstance::getParameterName (int index)
  26100. {
  26101. AudioUnitParameterInfo info;
  26102. zerostruct (info);
  26103. UInt32 sz = sizeof (info);
  26104. String name;
  26105. if (AudioUnitGetProperty (audioUnit,
  26106. kAudioUnitProperty_ParameterInfo,
  26107. kAudioUnitScope_Global,
  26108. parameterIds [index], &info, &sz) == noErr)
  26109. {
  26110. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26111. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26112. else
  26113. name = String (info.name, sizeof (info.name));
  26114. }
  26115. return name;
  26116. }
  26117. const String AudioUnitPluginInstance::getParameterText (int index)
  26118. {
  26119. return String (getParameter (index));
  26120. }
  26121. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26122. {
  26123. AudioUnitParameterInfo info;
  26124. UInt32 sz = sizeof (info);
  26125. if (AudioUnitGetProperty (audioUnit,
  26126. kAudioUnitProperty_ParameterInfo,
  26127. kAudioUnitScope_Global,
  26128. parameterIds [index], &info, &sz) == noErr)
  26129. {
  26130. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26131. }
  26132. return true;
  26133. }
  26134. int AudioUnitPluginInstance::getNumPrograms()
  26135. {
  26136. CFArrayRef presets;
  26137. UInt32 sz = sizeof (CFArrayRef);
  26138. int num = 0;
  26139. if (AudioUnitGetProperty (audioUnit,
  26140. kAudioUnitProperty_FactoryPresets,
  26141. kAudioUnitScope_Global,
  26142. 0, &presets, &sz) == noErr)
  26143. {
  26144. num = (int) CFArrayGetCount (presets);
  26145. CFRelease (presets);
  26146. }
  26147. return num;
  26148. }
  26149. int AudioUnitPluginInstance::getCurrentProgram()
  26150. {
  26151. AUPreset current;
  26152. current.presetNumber = 0;
  26153. UInt32 sz = sizeof (AUPreset);
  26154. AudioUnitGetProperty (audioUnit,
  26155. kAudioUnitProperty_FactoryPresets,
  26156. kAudioUnitScope_Global,
  26157. 0, &current, &sz);
  26158. return current.presetNumber;
  26159. }
  26160. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26161. {
  26162. AUPreset current;
  26163. current.presetNumber = newIndex;
  26164. current.presetName = 0;
  26165. AudioUnitSetProperty (audioUnit,
  26166. kAudioUnitProperty_FactoryPresets,
  26167. kAudioUnitScope_Global,
  26168. 0, &current, sizeof (AUPreset));
  26169. }
  26170. const String AudioUnitPluginInstance::getProgramName (int index)
  26171. {
  26172. String s;
  26173. CFArrayRef presets;
  26174. UInt32 sz = sizeof (CFArrayRef);
  26175. if (AudioUnitGetProperty (audioUnit,
  26176. kAudioUnitProperty_FactoryPresets,
  26177. kAudioUnitScope_Global,
  26178. 0, &presets, &sz) == noErr)
  26179. {
  26180. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26181. {
  26182. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26183. if (p != 0 && p->presetNumber == index)
  26184. {
  26185. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26186. break;
  26187. }
  26188. }
  26189. CFRelease (presets);
  26190. }
  26191. return s;
  26192. }
  26193. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26194. {
  26195. jassertfalse; // xxx not implemented!
  26196. }
  26197. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26198. {
  26199. if (isPositiveAndBelow (index, getNumInputChannels()))
  26200. return "Input " + String (index + 1);
  26201. return String::empty;
  26202. }
  26203. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26204. {
  26205. if (! isPositiveAndBelow (index, getNumInputChannels()))
  26206. return false;
  26207. return true;
  26208. }
  26209. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26210. {
  26211. if (isPositiveAndBelow (index, getNumOutputChannels()))
  26212. return "Output " + String (index + 1);
  26213. return String::empty;
  26214. }
  26215. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26216. {
  26217. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  26218. return false;
  26219. return true;
  26220. }
  26221. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26222. {
  26223. getCurrentProgramStateInformation (destData);
  26224. }
  26225. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26226. {
  26227. CFPropertyListRef propertyList = 0;
  26228. UInt32 sz = sizeof (CFPropertyListRef);
  26229. if (AudioUnitGetProperty (audioUnit,
  26230. kAudioUnitProperty_ClassInfo,
  26231. kAudioUnitScope_Global,
  26232. 0, &propertyList, &sz) == noErr)
  26233. {
  26234. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26235. CFWriteStreamOpen (stream);
  26236. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26237. CFWriteStreamClose (stream);
  26238. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26239. destData.setSize (bytesWritten);
  26240. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26241. CFRelease (data);
  26242. CFRelease (stream);
  26243. CFRelease (propertyList);
  26244. }
  26245. }
  26246. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26247. {
  26248. setCurrentProgramStateInformation (data, sizeInBytes);
  26249. }
  26250. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26251. {
  26252. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26253. (const UInt8*) data,
  26254. sizeInBytes,
  26255. kCFAllocatorNull);
  26256. CFReadStreamOpen (stream);
  26257. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26258. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26259. stream,
  26260. 0,
  26261. kCFPropertyListImmutable,
  26262. &format,
  26263. 0);
  26264. CFRelease (stream);
  26265. if (propertyList != 0)
  26266. AudioUnitSetProperty (audioUnit,
  26267. kAudioUnitProperty_ClassInfo,
  26268. kAudioUnitScope_Global,
  26269. 0, &propertyList, sizeof (propertyList));
  26270. }
  26271. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26272. {
  26273. }
  26274. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26275. {
  26276. }
  26277. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26278. const String& fileOrIdentifier)
  26279. {
  26280. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26281. return;
  26282. PluginDescription desc;
  26283. desc.fileOrIdentifier = fileOrIdentifier;
  26284. desc.uid = 0;
  26285. try
  26286. {
  26287. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26288. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26289. if (auInstance != 0)
  26290. {
  26291. auInstance->fillInPluginDescription (desc);
  26292. results.add (new PluginDescription (desc));
  26293. }
  26294. }
  26295. catch (...)
  26296. {
  26297. // crashed while loading...
  26298. }
  26299. }
  26300. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26301. {
  26302. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26303. {
  26304. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26305. if (result->audioUnit != 0)
  26306. {
  26307. result->initialise();
  26308. return result.release();
  26309. }
  26310. }
  26311. return 0;
  26312. }
  26313. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26314. const bool /*recursive*/)
  26315. {
  26316. StringArray result;
  26317. ComponentRecord* comp = 0;
  26318. ComponentDescription desc;
  26319. zerostruct (desc);
  26320. for (;;)
  26321. {
  26322. zerostruct (desc);
  26323. comp = FindNextComponent (comp, &desc);
  26324. if (comp == 0)
  26325. break;
  26326. GetComponentInfo (comp, &desc, 0, 0, 0);
  26327. if (desc.componentType == kAudioUnitType_MusicDevice
  26328. || desc.componentType == kAudioUnitType_MusicEffect
  26329. || desc.componentType == kAudioUnitType_Effect
  26330. || desc.componentType == kAudioUnitType_Generator
  26331. || desc.componentType == kAudioUnitType_Panner)
  26332. {
  26333. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26334. DBG (s);
  26335. result.add (s);
  26336. }
  26337. }
  26338. return result;
  26339. }
  26340. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26341. {
  26342. ComponentDescription desc;
  26343. String name, version, manufacturer;
  26344. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26345. return FindNextComponent (0, &desc) != 0;
  26346. const File f (fileOrIdentifier);
  26347. return f.hasFileExtension (".component")
  26348. && f.isDirectory();
  26349. }
  26350. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26351. {
  26352. ComponentDescription desc;
  26353. String name, version, manufacturer;
  26354. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26355. if (name.isEmpty())
  26356. name = fileOrIdentifier;
  26357. return name;
  26358. }
  26359. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26360. {
  26361. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26362. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26363. else
  26364. return File (desc.fileOrIdentifier).exists();
  26365. }
  26366. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26367. {
  26368. return FileSearchPath ("/(Default AudioUnit locations)");
  26369. }
  26370. #endif
  26371. END_JUCE_NAMESPACE
  26372. #undef log
  26373. #endif
  26374. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26375. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26376. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26377. #define JUCE_MAC_VST_INCLUDED 1
  26378. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26379. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26380. #if JUCE_WINDOWS
  26381. #undef _WIN32_WINNT
  26382. #define _WIN32_WINNT 0x500
  26383. #undef STRICT
  26384. #define STRICT
  26385. #include <windows.h>
  26386. #include <float.h>
  26387. #pragma warning (disable : 4312 4355)
  26388. #elif JUCE_LINUX
  26389. #include <float.h>
  26390. #include <sys/time.h>
  26391. #include <X11/Xlib.h>
  26392. #include <X11/Xutil.h>
  26393. #include <X11/Xatom.h>
  26394. #undef Font
  26395. #undef KeyPress
  26396. #undef Drawable
  26397. #undef Time
  26398. #else
  26399. #include <Cocoa/Cocoa.h>
  26400. #include <Carbon/Carbon.h>
  26401. #endif
  26402. #if ! (JUCE_MAC && JUCE_64BIT)
  26403. BEGIN_JUCE_NAMESPACE
  26404. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26405. #endif
  26406. #undef PRAGMA_ALIGN_SUPPORTED
  26407. #define VST_FORCE_DEPRECATED 0
  26408. #if JUCE_MSVC
  26409. #pragma warning (push)
  26410. #pragma warning (disable: 4996)
  26411. #endif
  26412. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26413. your include path if you want to add VST support.
  26414. If you're not interested in VSTs, you can disable them by changing the
  26415. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26416. */
  26417. #include <pluginterfaces/vst2.x/aeffectx.h>
  26418. #if JUCE_MSVC
  26419. #pragma warning (pop)
  26420. #endif
  26421. #if JUCE_LINUX
  26422. #define Font JUCE_NAMESPACE::Font
  26423. #define KeyPress JUCE_NAMESPACE::KeyPress
  26424. #define Drawable JUCE_NAMESPACE::Drawable
  26425. #define Time JUCE_NAMESPACE::Time
  26426. #endif
  26427. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26428. #ifdef __aeffect__
  26429. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26430. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26431. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26432. events to the list.
  26433. This is used by both the VST hosting code and the plugin wrapper.
  26434. */
  26435. class VSTMidiEventList
  26436. {
  26437. public:
  26438. VSTMidiEventList()
  26439. : numEventsUsed (0), numEventsAllocated (0)
  26440. {
  26441. }
  26442. ~VSTMidiEventList()
  26443. {
  26444. freeEvents();
  26445. }
  26446. void clear()
  26447. {
  26448. numEventsUsed = 0;
  26449. if (events != 0)
  26450. events->numEvents = 0;
  26451. }
  26452. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26453. {
  26454. ensureSize (numEventsUsed + 1);
  26455. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26456. events->numEvents = ++numEventsUsed;
  26457. if (numBytes <= 4)
  26458. {
  26459. if (e->type == kVstSysExType)
  26460. {
  26461. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26462. e->type = kVstMidiType;
  26463. e->byteSize = sizeof (VstMidiEvent);
  26464. e->noteLength = 0;
  26465. e->noteOffset = 0;
  26466. e->detune = 0;
  26467. e->noteOffVelocity = 0;
  26468. }
  26469. e->deltaFrames = frameOffset;
  26470. memcpy (e->midiData, midiData, numBytes);
  26471. }
  26472. else
  26473. {
  26474. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26475. if (se->type == kVstSysExType)
  26476. delete[] se->sysexDump;
  26477. se->sysexDump = new char [numBytes];
  26478. memcpy (se->sysexDump, midiData, numBytes);
  26479. se->type = kVstSysExType;
  26480. se->byteSize = sizeof (VstMidiSysexEvent);
  26481. se->deltaFrames = frameOffset;
  26482. se->flags = 0;
  26483. se->dumpBytes = numBytes;
  26484. se->resvd1 = 0;
  26485. se->resvd2 = 0;
  26486. }
  26487. }
  26488. // Handy method to pull the events out of an event buffer supplied by the host
  26489. // or plugin.
  26490. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26491. {
  26492. for (int i = 0; i < events->numEvents; ++i)
  26493. {
  26494. const VstEvent* const e = events->events[i];
  26495. if (e != 0)
  26496. {
  26497. if (e->type == kVstMidiType)
  26498. {
  26499. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26500. 4, e->deltaFrames);
  26501. }
  26502. else if (e->type == kVstSysExType)
  26503. {
  26504. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26505. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26506. e->deltaFrames);
  26507. }
  26508. }
  26509. }
  26510. }
  26511. void ensureSize (int numEventsNeeded)
  26512. {
  26513. if (numEventsNeeded > numEventsAllocated)
  26514. {
  26515. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26516. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26517. if (events == 0)
  26518. events.calloc (size, 1);
  26519. else
  26520. events.realloc (size, 1);
  26521. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26522. {
  26523. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26524. (int) sizeof (VstMidiSysexEvent)));
  26525. e->type = kVstMidiType;
  26526. e->byteSize = sizeof (VstMidiEvent);
  26527. events->events[i] = (VstEvent*) e;
  26528. }
  26529. numEventsAllocated = numEventsNeeded;
  26530. }
  26531. }
  26532. void freeEvents()
  26533. {
  26534. if (events != 0)
  26535. {
  26536. for (int i = numEventsAllocated; --i >= 0;)
  26537. {
  26538. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26539. if (e->type == kVstSysExType)
  26540. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26541. juce_free (e);
  26542. }
  26543. events.free();
  26544. numEventsUsed = 0;
  26545. numEventsAllocated = 0;
  26546. }
  26547. }
  26548. HeapBlock <VstEvents> events;
  26549. private:
  26550. int numEventsUsed, numEventsAllocated;
  26551. };
  26552. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26553. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26554. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26555. #if ! JUCE_WINDOWS
  26556. static void _fpreset() {}
  26557. static void _clearfp() {}
  26558. #endif
  26559. extern void juce_callAnyTimersSynchronously();
  26560. const int fxbVersionNum = 1;
  26561. struct fxProgram
  26562. {
  26563. long chunkMagic; // 'CcnK'
  26564. long byteSize; // of this chunk, excl. magic + byteSize
  26565. long fxMagic; // 'FxCk'
  26566. long version;
  26567. long fxID; // fx unique id
  26568. long fxVersion;
  26569. long numParams;
  26570. char prgName[28];
  26571. float params[1]; // variable no. of parameters
  26572. };
  26573. struct fxSet
  26574. {
  26575. long chunkMagic; // 'CcnK'
  26576. long byteSize; // of this chunk, excl. magic + byteSize
  26577. long fxMagic; // 'FxBk'
  26578. long version;
  26579. long fxID; // fx unique id
  26580. long fxVersion;
  26581. long numPrograms;
  26582. char future[128];
  26583. fxProgram programs[1]; // variable no. of programs
  26584. };
  26585. struct fxChunkSet
  26586. {
  26587. long chunkMagic; // 'CcnK'
  26588. long byteSize; // of this chunk, excl. magic + byteSize
  26589. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26590. long version;
  26591. long fxID; // fx unique id
  26592. long fxVersion;
  26593. long numPrograms;
  26594. char future[128];
  26595. long chunkSize;
  26596. char chunk[8]; // variable
  26597. };
  26598. struct fxProgramSet
  26599. {
  26600. long chunkMagic; // 'CcnK'
  26601. long byteSize; // of this chunk, excl. magic + byteSize
  26602. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26603. long version;
  26604. long fxID; // fx unique id
  26605. long fxVersion;
  26606. long numPrograms;
  26607. char name[28];
  26608. long chunkSize;
  26609. char chunk[8]; // variable
  26610. };
  26611. namespace
  26612. {
  26613. long vst_swap (const long x) throw()
  26614. {
  26615. #ifdef JUCE_LITTLE_ENDIAN
  26616. return (long) ByteOrder::swap ((uint32) x);
  26617. #else
  26618. return x;
  26619. #endif
  26620. }
  26621. float vst_swapFloat (const float x) throw()
  26622. {
  26623. #ifdef JUCE_LITTLE_ENDIAN
  26624. union { uint32 asInt; float asFloat; } n;
  26625. n.asFloat = x;
  26626. n.asInt = ByteOrder::swap (n.asInt);
  26627. return n.asFloat;
  26628. #else
  26629. return x;
  26630. #endif
  26631. }
  26632. double getVSTHostTimeNanoseconds()
  26633. {
  26634. #if JUCE_WINDOWS
  26635. return timeGetTime() * 1000000.0;
  26636. #elif JUCE_LINUX
  26637. timeval micro;
  26638. gettimeofday (&micro, 0);
  26639. return micro.tv_usec * 1000.0;
  26640. #elif JUCE_MAC
  26641. UnsignedWide micro;
  26642. Microseconds (&micro);
  26643. return micro.lo * 1000.0;
  26644. #endif
  26645. }
  26646. }
  26647. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26648. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26649. static int shellUIDToCreate = 0;
  26650. static int insideVSTCallback = 0;
  26651. class VSTPluginWindow;
  26652. // Change this to disable logging of various VST activities
  26653. #ifndef VST_LOGGING
  26654. #define VST_LOGGING 1
  26655. #endif
  26656. #if VST_LOGGING
  26657. #define log(a) Logger::writeToLog(a);
  26658. #else
  26659. #define log(a)
  26660. #endif
  26661. #if JUCE_MAC && JUCE_PPC
  26662. static void* NewCFMFromMachO (void* const machofp) throw()
  26663. {
  26664. void* result = (void*) new char[8];
  26665. ((void**) result)[0] = machofp;
  26666. ((void**) result)[1] = result;
  26667. return result;
  26668. }
  26669. #endif
  26670. #if JUCE_LINUX
  26671. extern Display* display;
  26672. extern XContext windowHandleXContext;
  26673. typedef void (*EventProcPtr) (XEvent* ev);
  26674. static bool xErrorTriggered;
  26675. namespace
  26676. {
  26677. int temporaryErrorHandler (Display*, XErrorEvent*)
  26678. {
  26679. xErrorTriggered = true;
  26680. return 0;
  26681. }
  26682. int getPropertyFromXWindow (Window handle, Atom atom)
  26683. {
  26684. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26685. xErrorTriggered = false;
  26686. int userSize;
  26687. unsigned long bytes, userCount;
  26688. unsigned char* data;
  26689. Atom userType;
  26690. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26691. &userType, &userSize, &userCount, &bytes, &data);
  26692. XSetErrorHandler (oldErrorHandler);
  26693. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26694. : 0;
  26695. }
  26696. Window getChildWindow (Window windowToCheck)
  26697. {
  26698. Window rootWindow, parentWindow;
  26699. Window* childWindows;
  26700. unsigned int numChildren;
  26701. XQueryTree (display,
  26702. windowToCheck,
  26703. &rootWindow,
  26704. &parentWindow,
  26705. &childWindows,
  26706. &numChildren);
  26707. if (numChildren > 0)
  26708. return childWindows [0];
  26709. return 0;
  26710. }
  26711. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26712. {
  26713. if (e.mods.isLeftButtonDown())
  26714. {
  26715. ev.xbutton.button = Button1;
  26716. ev.xbutton.state |= Button1Mask;
  26717. }
  26718. else if (e.mods.isRightButtonDown())
  26719. {
  26720. ev.xbutton.button = Button3;
  26721. ev.xbutton.state |= Button3Mask;
  26722. }
  26723. else if (e.mods.isMiddleButtonDown())
  26724. {
  26725. ev.xbutton.button = Button2;
  26726. ev.xbutton.state |= Button2Mask;
  26727. }
  26728. }
  26729. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26730. {
  26731. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26732. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26733. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26734. }
  26735. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26736. {
  26737. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26738. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26739. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26740. }
  26741. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26742. {
  26743. if (increment < 0)
  26744. {
  26745. ev.xbutton.button = Button5;
  26746. ev.xbutton.state |= Button5Mask;
  26747. }
  26748. else if (increment > 0)
  26749. {
  26750. ev.xbutton.button = Button4;
  26751. ev.xbutton.state |= Button4Mask;
  26752. }
  26753. }
  26754. }
  26755. #endif
  26756. class ModuleHandle : public ReferenceCountedObject
  26757. {
  26758. public:
  26759. File file;
  26760. MainCall moduleMain;
  26761. String pluginName;
  26762. static Array <ModuleHandle*>& getActiveModules()
  26763. {
  26764. static Array <ModuleHandle*> activeModules;
  26765. return activeModules;
  26766. }
  26767. static ModuleHandle* findOrCreateModule (const File& file)
  26768. {
  26769. for (int i = getActiveModules().size(); --i >= 0;)
  26770. {
  26771. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26772. if (module->file == file)
  26773. return module;
  26774. }
  26775. _fpreset(); // (doesn't do any harm)
  26776. ++insideVSTCallback;
  26777. shellUIDToCreate = 0;
  26778. log ("Attempting to load VST: " + file.getFullPathName());
  26779. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26780. if (! m->open())
  26781. m = 0;
  26782. --insideVSTCallback;
  26783. _fpreset(); // (doesn't do any harm)
  26784. return m.release();
  26785. }
  26786. ModuleHandle (const File& file_)
  26787. : file (file_),
  26788. moduleMain (0),
  26789. #if JUCE_WINDOWS || JUCE_LINUX
  26790. hModule (0)
  26791. #elif JUCE_MAC
  26792. fragId (0),
  26793. resHandle (0),
  26794. bundleRef (0),
  26795. resFileId (0)
  26796. #endif
  26797. {
  26798. getActiveModules().add (this);
  26799. #if JUCE_WINDOWS || JUCE_LINUX
  26800. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26801. #elif JUCE_MAC
  26802. FSRef ref;
  26803. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26804. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26805. #endif
  26806. }
  26807. ~ModuleHandle()
  26808. {
  26809. getActiveModules().removeValue (this);
  26810. close();
  26811. }
  26812. #if JUCE_WINDOWS || JUCE_LINUX
  26813. void* hModule;
  26814. String fullParentDirectoryPathName;
  26815. bool open()
  26816. {
  26817. #if JUCE_WINDOWS
  26818. static bool timePeriodSet = false;
  26819. if (! timePeriodSet)
  26820. {
  26821. timePeriodSet = true;
  26822. timeBeginPeriod (2);
  26823. }
  26824. #endif
  26825. pluginName = file.getFileNameWithoutExtension();
  26826. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26827. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26828. if (moduleMain == 0)
  26829. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26830. return moduleMain != 0;
  26831. }
  26832. void close()
  26833. {
  26834. _fpreset(); // (doesn't do any harm)
  26835. PlatformUtilities::freeDynamicLibrary (hModule);
  26836. }
  26837. void closeEffect (AEffect* eff)
  26838. {
  26839. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26840. }
  26841. #else
  26842. CFragConnectionID fragId;
  26843. Handle resHandle;
  26844. CFBundleRef bundleRef;
  26845. FSSpec parentDirFSSpec;
  26846. short resFileId;
  26847. bool open()
  26848. {
  26849. bool ok = false;
  26850. const String filename (file.getFullPathName());
  26851. if (file.hasFileExtension (".vst"))
  26852. {
  26853. const char* const utf8 = filename.toUTF8();
  26854. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26855. strlen (utf8), file.isDirectory());
  26856. if (url != 0)
  26857. {
  26858. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26859. CFRelease (url);
  26860. if (bundleRef != 0)
  26861. {
  26862. if (CFBundleLoadExecutable (bundleRef))
  26863. {
  26864. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26865. if (moduleMain == 0)
  26866. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26867. if (moduleMain != 0)
  26868. {
  26869. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26870. if (name != 0)
  26871. {
  26872. if (CFGetTypeID (name) == CFStringGetTypeID())
  26873. {
  26874. char buffer[1024];
  26875. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26876. pluginName = buffer;
  26877. }
  26878. }
  26879. if (pluginName.isEmpty())
  26880. pluginName = file.getFileNameWithoutExtension();
  26881. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26882. ok = true;
  26883. }
  26884. }
  26885. if (! ok)
  26886. {
  26887. CFBundleUnloadExecutable (bundleRef);
  26888. CFRelease (bundleRef);
  26889. bundleRef = 0;
  26890. }
  26891. }
  26892. }
  26893. }
  26894. #if JUCE_PPC
  26895. else
  26896. {
  26897. FSRef fn;
  26898. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26899. {
  26900. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26901. if (resFileId != -1)
  26902. {
  26903. const int numEffs = Count1Resources ('aEff');
  26904. for (int i = 0; i < numEffs; ++i)
  26905. {
  26906. resHandle = Get1IndResource ('aEff', i + 1);
  26907. if (resHandle != 0)
  26908. {
  26909. OSType type;
  26910. Str255 name;
  26911. SInt16 id;
  26912. GetResInfo (resHandle, &id, &type, name);
  26913. pluginName = String ((const char*) name + 1, name[0]);
  26914. DetachResource (resHandle);
  26915. HLock (resHandle);
  26916. Ptr ptr;
  26917. Str255 errorText;
  26918. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26919. name, kPrivateCFragCopy,
  26920. &fragId, &ptr, errorText);
  26921. if (err == noErr)
  26922. {
  26923. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26924. ok = true;
  26925. }
  26926. else
  26927. {
  26928. HUnlock (resHandle);
  26929. }
  26930. break;
  26931. }
  26932. }
  26933. if (! ok)
  26934. CloseResFile (resFileId);
  26935. }
  26936. }
  26937. }
  26938. #endif
  26939. return ok;
  26940. }
  26941. void close()
  26942. {
  26943. #if JUCE_PPC
  26944. if (fragId != 0)
  26945. {
  26946. if (moduleMain != 0)
  26947. disposeMachOFromCFM ((void*) moduleMain);
  26948. CloseConnection (&fragId);
  26949. HUnlock (resHandle);
  26950. if (resFileId != 0)
  26951. CloseResFile (resFileId);
  26952. }
  26953. else
  26954. #endif
  26955. if (bundleRef != 0)
  26956. {
  26957. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26958. if (CFGetRetainCount (bundleRef) == 1)
  26959. CFBundleUnloadExecutable (bundleRef);
  26960. if (CFGetRetainCount (bundleRef) > 0)
  26961. CFRelease (bundleRef);
  26962. }
  26963. }
  26964. void closeEffect (AEffect* eff)
  26965. {
  26966. #if JUCE_PPC
  26967. if (fragId != 0)
  26968. {
  26969. Array<void*> thingsToDelete;
  26970. thingsToDelete.add ((void*) eff->dispatcher);
  26971. thingsToDelete.add ((void*) eff->process);
  26972. thingsToDelete.add ((void*) eff->setParameter);
  26973. thingsToDelete.add ((void*) eff->getParameter);
  26974. thingsToDelete.add ((void*) eff->processReplacing);
  26975. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26976. for (int i = thingsToDelete.size(); --i >= 0;)
  26977. disposeMachOFromCFM (thingsToDelete[i]);
  26978. }
  26979. else
  26980. #endif
  26981. {
  26982. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26983. }
  26984. }
  26985. #if JUCE_PPC
  26986. static void* newMachOFromCFM (void* cfmfp)
  26987. {
  26988. if (cfmfp == 0)
  26989. return 0;
  26990. UInt32* const mfp = new UInt32[6];
  26991. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26992. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26993. mfp[2] = 0x800c0000;
  26994. mfp[3] = 0x804c0004;
  26995. mfp[4] = 0x7c0903a6;
  26996. mfp[5] = 0x4e800420;
  26997. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26998. return mfp;
  26999. }
  27000. static void disposeMachOFromCFM (void* ptr)
  27001. {
  27002. delete[] static_cast <UInt32*> (ptr);
  27003. }
  27004. void coerceAEffectFunctionCalls (AEffect* eff)
  27005. {
  27006. if (fragId != 0)
  27007. {
  27008. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  27009. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  27010. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  27011. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  27012. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  27013. }
  27014. }
  27015. #endif
  27016. #endif
  27017. private:
  27018. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  27019. };
  27020. /**
  27021. An instance of a plugin, created by a VSTPluginFormat.
  27022. */
  27023. class VSTPluginInstance : public AudioPluginInstance,
  27024. private Timer,
  27025. private AsyncUpdater
  27026. {
  27027. public:
  27028. ~VSTPluginInstance();
  27029. // AudioPluginInstance methods:
  27030. void fillInPluginDescription (PluginDescription& desc) const
  27031. {
  27032. desc.name = name;
  27033. {
  27034. char buffer [512];
  27035. zerostruct (buffer);
  27036. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27037. desc.descriptiveName = String (buffer).trim();
  27038. if (desc.descriptiveName.isEmpty())
  27039. desc.descriptiveName = name;
  27040. }
  27041. desc.fileOrIdentifier = module->file.getFullPathName();
  27042. desc.uid = getUID();
  27043. desc.lastFileModTime = module->file.getLastModificationTime();
  27044. desc.pluginFormatName = "VST";
  27045. desc.category = getCategory();
  27046. {
  27047. char buffer [kVstMaxVendorStrLen + 8];
  27048. zerostruct (buffer);
  27049. dispatch (effGetVendorString, 0, 0, buffer, 0);
  27050. desc.manufacturerName = buffer;
  27051. }
  27052. desc.version = getVersion();
  27053. desc.numInputChannels = getNumInputChannels();
  27054. desc.numOutputChannels = getNumOutputChannels();
  27055. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  27056. }
  27057. void* getPlatformSpecificData() { return effect; }
  27058. const String getName() const { return name; }
  27059. int getUID() const;
  27060. bool acceptsMidi() const { return wantsMidiMessages; }
  27061. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  27062. // AudioProcessor methods:
  27063. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  27064. void releaseResources();
  27065. void processBlock (AudioSampleBuffer& buffer,
  27066. MidiBuffer& midiMessages);
  27067. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  27068. AudioProcessorEditor* createEditor();
  27069. const String getInputChannelName (int index) const;
  27070. bool isInputChannelStereoPair (int index) const;
  27071. const String getOutputChannelName (int index) const;
  27072. bool isOutputChannelStereoPair (int index) const;
  27073. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  27074. float getParameter (int index);
  27075. void setParameter (int index, float newValue);
  27076. const String getParameterName (int index);
  27077. const String getParameterText (int index);
  27078. bool isParameterAutomatable (int index) const;
  27079. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  27080. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  27081. void setCurrentProgram (int index);
  27082. const String getProgramName (int index);
  27083. void changeProgramName (int index, const String& newName);
  27084. void getStateInformation (MemoryBlock& destData);
  27085. void getCurrentProgramStateInformation (MemoryBlock& destData);
  27086. void setStateInformation (const void* data, int sizeInBytes);
  27087. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27088. void timerCallback();
  27089. void handleAsyncUpdate();
  27090. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  27091. private:
  27092. friend class VSTPluginWindow;
  27093. friend class VSTPluginFormat;
  27094. AEffect* effect;
  27095. String name;
  27096. CriticalSection lock;
  27097. bool wantsMidiMessages, initialised, isPowerOn;
  27098. mutable StringArray programNames;
  27099. AudioSampleBuffer tempBuffer;
  27100. CriticalSection midiInLock;
  27101. MidiBuffer incomingMidi;
  27102. VSTMidiEventList midiEventsToSend;
  27103. VstTimeInfo vstHostTime;
  27104. ReferenceCountedObjectPtr <ModuleHandle> module;
  27105. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  27106. bool restoreProgramSettings (const fxProgram* const prog);
  27107. const String getCurrentProgramName();
  27108. void setParamsInProgramBlock (fxProgram* const prog);
  27109. void updateStoredProgramNames();
  27110. void initialise();
  27111. void handleMidiFromPlugin (const VstEvents* const events);
  27112. void createTempParameterStore (MemoryBlock& dest);
  27113. void restoreFromTempParameterStore (const MemoryBlock& mb);
  27114. const String getParameterLabel (int index) const;
  27115. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  27116. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  27117. void setChunkData (const char* data, int size, bool isPreset);
  27118. bool loadFromFXBFile (const void* data, int numBytes);
  27119. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  27120. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  27121. const String getVersion() const;
  27122. const String getCategory() const;
  27123. void setPower (const bool on);
  27124. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27125. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  27126. };
  27127. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27128. : effect (0),
  27129. wantsMidiMessages (false),
  27130. initialised (false),
  27131. isPowerOn (false),
  27132. tempBuffer (1, 1),
  27133. module (module_)
  27134. {
  27135. try
  27136. {
  27137. _fpreset();
  27138. ++insideVSTCallback;
  27139. name = module->pluginName;
  27140. log ("Creating VST instance: " + name);
  27141. #if JUCE_MAC
  27142. if (module->resFileId != 0)
  27143. UseResFile (module->resFileId);
  27144. #if JUCE_PPC
  27145. if (module->fragId != 0)
  27146. {
  27147. static void* audioMasterCoerced = 0;
  27148. if (audioMasterCoerced == 0)
  27149. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27150. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27151. }
  27152. else
  27153. #endif
  27154. #endif
  27155. {
  27156. effect = module->moduleMain (&audioMaster);
  27157. }
  27158. --insideVSTCallback;
  27159. if (effect != 0 && effect->magic == kEffectMagic)
  27160. {
  27161. #if JUCE_PPC
  27162. module->coerceAEffectFunctionCalls (effect);
  27163. #endif
  27164. jassert (effect->resvd2 == 0);
  27165. jassert (effect->object != 0);
  27166. _fpreset(); // some dodgy plugs fuck around with this
  27167. }
  27168. else
  27169. {
  27170. effect = 0;
  27171. }
  27172. }
  27173. catch (...)
  27174. {
  27175. --insideVSTCallback;
  27176. }
  27177. }
  27178. VSTPluginInstance::~VSTPluginInstance()
  27179. {
  27180. const ScopedLock sl (lock);
  27181. jassert (insideVSTCallback == 0);
  27182. if (effect != 0 && effect->magic == kEffectMagic)
  27183. {
  27184. try
  27185. {
  27186. #if JUCE_MAC
  27187. if (module->resFileId != 0)
  27188. UseResFile (module->resFileId);
  27189. #endif
  27190. // Must delete any editors before deleting the plugin instance!
  27191. jassert (getActiveEditor() == 0);
  27192. _fpreset(); // some dodgy plugs fuck around with this
  27193. module->closeEffect (effect);
  27194. }
  27195. catch (...)
  27196. {}
  27197. }
  27198. module = 0;
  27199. effect = 0;
  27200. }
  27201. void VSTPluginInstance::initialise()
  27202. {
  27203. if (initialised || effect == 0)
  27204. return;
  27205. log ("Initialising VST: " + module->pluginName);
  27206. initialised = true;
  27207. dispatch (effIdentify, 0, 0, 0, 0);
  27208. if (getSampleRate() > 0)
  27209. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27210. if (getBlockSize() > 0)
  27211. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27212. dispatch (effOpen, 0, 0, 0, 0);
  27213. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27214. getSampleRate(), getBlockSize());
  27215. if (getNumPrograms() > 1)
  27216. setCurrentProgram (0);
  27217. else
  27218. dispatch (effSetProgram, 0, 0, 0, 0);
  27219. int i;
  27220. for (i = effect->numInputs; --i >= 0;)
  27221. dispatch (effConnectInput, i, 1, 0, 0);
  27222. for (i = effect->numOutputs; --i >= 0;)
  27223. dispatch (effConnectOutput, i, 1, 0, 0);
  27224. updateStoredProgramNames();
  27225. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27226. setLatencySamples (effect->initialDelay);
  27227. }
  27228. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27229. int samplesPerBlockExpected)
  27230. {
  27231. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27232. sampleRate_, samplesPerBlockExpected);
  27233. setLatencySamples (effect->initialDelay);
  27234. vstHostTime.tempo = 120.0;
  27235. vstHostTime.timeSigNumerator = 4;
  27236. vstHostTime.timeSigDenominator = 4;
  27237. vstHostTime.sampleRate = sampleRate_;
  27238. vstHostTime.samplePos = 0;
  27239. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27240. initialise();
  27241. if (initialised)
  27242. {
  27243. wantsMidiMessages = wantsMidiMessages
  27244. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27245. if (wantsMidiMessages)
  27246. midiEventsToSend.ensureSize (256);
  27247. else
  27248. midiEventsToSend.freeEvents();
  27249. incomingMidi.clear();
  27250. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27251. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27252. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27253. if (! isPowerOn)
  27254. setPower (true);
  27255. // dodgy hack to force some plugins to initialise the sample rate..
  27256. if ((! hasEditor()) && getNumParameters() > 0)
  27257. {
  27258. const float old = getParameter (0);
  27259. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27260. setParameter (0, old);
  27261. }
  27262. dispatch (effStartProcess, 0, 0, 0, 0);
  27263. }
  27264. }
  27265. void VSTPluginInstance::releaseResources()
  27266. {
  27267. if (initialised)
  27268. {
  27269. dispatch (effStopProcess, 0, 0, 0, 0);
  27270. setPower (false);
  27271. }
  27272. tempBuffer.setSize (1, 1);
  27273. incomingMidi.clear();
  27274. midiEventsToSend.freeEvents();
  27275. }
  27276. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27277. MidiBuffer& midiMessages)
  27278. {
  27279. const int numSamples = buffer.getNumSamples();
  27280. if (initialised)
  27281. {
  27282. AudioPlayHead* playHead = getPlayHead();
  27283. if (playHead != 0)
  27284. {
  27285. AudioPlayHead::CurrentPositionInfo position;
  27286. playHead->getCurrentPosition (position);
  27287. vstHostTime.tempo = position.bpm;
  27288. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27289. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27290. vstHostTime.ppqPos = position.ppqPosition;
  27291. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27292. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27293. if (position.isPlaying)
  27294. vstHostTime.flags |= kVstTransportPlaying;
  27295. else
  27296. vstHostTime.flags &= ~kVstTransportPlaying;
  27297. }
  27298. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27299. if (wantsMidiMessages)
  27300. {
  27301. midiEventsToSend.clear();
  27302. midiEventsToSend.ensureSize (1);
  27303. MidiBuffer::Iterator iter (midiMessages);
  27304. const uint8* midiData;
  27305. int numBytesOfMidiData, samplePosition;
  27306. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27307. {
  27308. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27309. jlimit (0, numSamples - 1, samplePosition));
  27310. }
  27311. try
  27312. {
  27313. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27314. }
  27315. catch (...)
  27316. {}
  27317. }
  27318. _clearfp();
  27319. if ((effect->flags & effFlagsCanReplacing) != 0)
  27320. {
  27321. try
  27322. {
  27323. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27324. }
  27325. catch (...)
  27326. {}
  27327. }
  27328. else
  27329. {
  27330. tempBuffer.setSize (effect->numOutputs, numSamples);
  27331. tempBuffer.clear();
  27332. try
  27333. {
  27334. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27335. }
  27336. catch (...)
  27337. {}
  27338. for (int i = effect->numOutputs; --i >= 0;)
  27339. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27340. }
  27341. }
  27342. else
  27343. {
  27344. // Not initialised, so just bypass..
  27345. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27346. buffer.clear (i, 0, buffer.getNumSamples());
  27347. }
  27348. {
  27349. // copy any incoming midi..
  27350. const ScopedLock sl (midiInLock);
  27351. midiMessages.swapWith (incomingMidi);
  27352. incomingMidi.clear();
  27353. }
  27354. }
  27355. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27356. {
  27357. if (events != 0)
  27358. {
  27359. const ScopedLock sl (midiInLock);
  27360. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27361. }
  27362. }
  27363. static Array <VSTPluginWindow*> activeVSTWindows;
  27364. class VSTPluginWindow : public AudioProcessorEditor,
  27365. #if ! JUCE_MAC
  27366. public ComponentMovementWatcher,
  27367. #endif
  27368. public Timer
  27369. {
  27370. public:
  27371. VSTPluginWindow (VSTPluginInstance& plugin_)
  27372. : AudioProcessorEditor (&plugin_),
  27373. #if ! JUCE_MAC
  27374. ComponentMovementWatcher (this),
  27375. #endif
  27376. plugin (plugin_),
  27377. isOpen (false),
  27378. wasShowing (false),
  27379. recursiveResize (false),
  27380. pluginWantsKeys (false),
  27381. pluginRefusesToResize (false),
  27382. alreadyInside (false)
  27383. {
  27384. #if JUCE_WINDOWS
  27385. sizeCheckCount = 0;
  27386. pluginHWND = 0;
  27387. #elif JUCE_LINUX
  27388. pluginWindow = None;
  27389. pluginProc = None;
  27390. #else
  27391. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27392. #endif
  27393. activeVSTWindows.add (this);
  27394. setSize (1, 1);
  27395. setOpaque (true);
  27396. setVisible (true);
  27397. }
  27398. ~VSTPluginWindow()
  27399. {
  27400. #if JUCE_MAC
  27401. innerWrapper = 0;
  27402. #else
  27403. closePluginWindow();
  27404. #endif
  27405. activeVSTWindows.removeValue (this);
  27406. plugin.editorBeingDeleted (this);
  27407. }
  27408. #if ! JUCE_MAC
  27409. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27410. {
  27411. if (recursiveResize)
  27412. return;
  27413. Component* const topComp = getTopLevelComponent();
  27414. if (topComp->getPeer() != 0)
  27415. {
  27416. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27417. recursiveResize = true;
  27418. #if JUCE_WINDOWS
  27419. if (pluginHWND != 0)
  27420. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27421. #elif JUCE_LINUX
  27422. if (pluginWindow != 0)
  27423. {
  27424. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27425. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27426. XMapRaised (display, pluginWindow);
  27427. }
  27428. #endif
  27429. recursiveResize = false;
  27430. }
  27431. }
  27432. void componentVisibilityChanged (Component&)
  27433. {
  27434. const bool isShowingNow = isShowing();
  27435. if (wasShowing != isShowingNow)
  27436. {
  27437. wasShowing = isShowingNow;
  27438. if (isShowingNow)
  27439. openPluginWindow();
  27440. else
  27441. closePluginWindow();
  27442. }
  27443. componentMovedOrResized (true, true);
  27444. }
  27445. void componentPeerChanged()
  27446. {
  27447. closePluginWindow();
  27448. openPluginWindow();
  27449. }
  27450. #endif
  27451. bool keyStateChanged (bool)
  27452. {
  27453. return pluginWantsKeys;
  27454. }
  27455. bool keyPressed (const KeyPress&)
  27456. {
  27457. return pluginWantsKeys;
  27458. }
  27459. #if JUCE_MAC
  27460. void paint (Graphics& g)
  27461. {
  27462. g.fillAll (Colours::black);
  27463. }
  27464. #else
  27465. void paint (Graphics& g)
  27466. {
  27467. if (isOpen)
  27468. {
  27469. ComponentPeer* const peer = getPeer();
  27470. if (peer != 0)
  27471. {
  27472. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27473. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27474. #if JUCE_LINUX
  27475. if (pluginWindow != 0)
  27476. {
  27477. const Rectangle<int> clip (g.getClipBounds());
  27478. XEvent ev;
  27479. zerostruct (ev);
  27480. ev.xexpose.type = Expose;
  27481. ev.xexpose.display = display;
  27482. ev.xexpose.window = pluginWindow;
  27483. ev.xexpose.x = clip.getX();
  27484. ev.xexpose.y = clip.getY();
  27485. ev.xexpose.width = clip.getWidth();
  27486. ev.xexpose.height = clip.getHeight();
  27487. sendEventToChild (&ev);
  27488. }
  27489. #endif
  27490. }
  27491. }
  27492. else
  27493. {
  27494. g.fillAll (Colours::black);
  27495. }
  27496. }
  27497. #endif
  27498. void timerCallback()
  27499. {
  27500. #if JUCE_WINDOWS
  27501. if (--sizeCheckCount <= 0)
  27502. {
  27503. sizeCheckCount = 10;
  27504. checkPluginWindowSize();
  27505. }
  27506. #endif
  27507. try
  27508. {
  27509. static bool reentrant = false;
  27510. if (! reentrant)
  27511. {
  27512. reentrant = true;
  27513. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27514. reentrant = false;
  27515. }
  27516. }
  27517. catch (...)
  27518. {}
  27519. }
  27520. void mouseDown (const MouseEvent& e)
  27521. {
  27522. #if JUCE_LINUX
  27523. if (pluginWindow == 0)
  27524. return;
  27525. toFront (true);
  27526. XEvent ev;
  27527. zerostruct (ev);
  27528. ev.xbutton.display = display;
  27529. ev.xbutton.type = ButtonPress;
  27530. ev.xbutton.window = pluginWindow;
  27531. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27532. ev.xbutton.time = CurrentTime;
  27533. ev.xbutton.x = e.x;
  27534. ev.xbutton.y = e.y;
  27535. ev.xbutton.x_root = e.getScreenX();
  27536. ev.xbutton.y_root = e.getScreenY();
  27537. translateJuceToXButtonModifiers (e, ev);
  27538. sendEventToChild (&ev);
  27539. #elif JUCE_WINDOWS
  27540. (void) e;
  27541. toFront (true);
  27542. #endif
  27543. }
  27544. void broughtToFront()
  27545. {
  27546. activeVSTWindows.removeValue (this);
  27547. activeVSTWindows.add (this);
  27548. #if JUCE_MAC
  27549. dispatch (effEditTop, 0, 0, 0, 0);
  27550. #endif
  27551. }
  27552. private:
  27553. VSTPluginInstance& plugin;
  27554. bool isOpen, wasShowing, recursiveResize;
  27555. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27556. #if JUCE_WINDOWS
  27557. HWND pluginHWND;
  27558. void* originalWndProc;
  27559. int sizeCheckCount;
  27560. #elif JUCE_LINUX
  27561. Window pluginWindow;
  27562. EventProcPtr pluginProc;
  27563. #endif
  27564. #if JUCE_MAC
  27565. void openPluginWindow (WindowRef parentWindow)
  27566. {
  27567. if (isOpen || parentWindow == 0)
  27568. return;
  27569. isOpen = true;
  27570. ERect* rect = 0;
  27571. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27572. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27573. // do this before and after like in the steinberg example
  27574. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27575. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27576. // Install keyboard hooks
  27577. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27578. // double-check it's not too tiny
  27579. int w = 250, h = 150;
  27580. if (rect != 0)
  27581. {
  27582. w = rect->right - rect->left;
  27583. h = rect->bottom - rect->top;
  27584. if (w == 0 || h == 0)
  27585. {
  27586. w = 250;
  27587. h = 150;
  27588. }
  27589. }
  27590. w = jmax (w, 32);
  27591. h = jmax (h, 32);
  27592. setSize (w, h);
  27593. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27594. repaint();
  27595. }
  27596. #else
  27597. void openPluginWindow()
  27598. {
  27599. if (isOpen || getWindowHandle() == 0)
  27600. return;
  27601. log ("Opening VST UI: " + plugin.name);
  27602. isOpen = true;
  27603. ERect* rect = 0;
  27604. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27605. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27606. // do this before and after like in the steinberg example
  27607. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27608. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27609. // Install keyboard hooks
  27610. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27611. #if JUCE_WINDOWS
  27612. originalWndProc = 0;
  27613. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27614. if (pluginHWND == 0)
  27615. {
  27616. isOpen = false;
  27617. setSize (300, 150);
  27618. return;
  27619. }
  27620. #pragma warning (push)
  27621. #pragma warning (disable: 4244)
  27622. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27623. if (! pluginWantsKeys)
  27624. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27625. #pragma warning (pop)
  27626. int w, h;
  27627. RECT r;
  27628. GetWindowRect (pluginHWND, &r);
  27629. w = r.right - r.left;
  27630. h = r.bottom - r.top;
  27631. if (rect != 0)
  27632. {
  27633. const int rw = rect->right - rect->left;
  27634. const int rh = rect->bottom - rect->top;
  27635. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27636. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27637. {
  27638. // very dodgy logic to decide which size is right.
  27639. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27640. {
  27641. SetWindowPos (pluginHWND, 0,
  27642. 0, 0, rw, rh,
  27643. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27644. GetWindowRect (pluginHWND, &r);
  27645. w = r.right - r.left;
  27646. h = r.bottom - r.top;
  27647. pluginRefusesToResize = (w != rw) || (h != rh);
  27648. w = rw;
  27649. h = rh;
  27650. }
  27651. }
  27652. }
  27653. #elif JUCE_LINUX
  27654. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27655. if (pluginWindow != 0)
  27656. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27657. XInternAtom (display, "_XEventProc", False));
  27658. int w = 250, h = 150;
  27659. if (rect != 0)
  27660. {
  27661. w = rect->right - rect->left;
  27662. h = rect->bottom - rect->top;
  27663. if (w == 0 || h == 0)
  27664. {
  27665. w = 250;
  27666. h = 150;
  27667. }
  27668. }
  27669. if (pluginWindow != 0)
  27670. XMapRaised (display, pluginWindow);
  27671. #endif
  27672. // double-check it's not too tiny
  27673. w = jmax (w, 32);
  27674. h = jmax (h, 32);
  27675. setSize (w, h);
  27676. #if JUCE_WINDOWS
  27677. checkPluginWindowSize();
  27678. #endif
  27679. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27680. repaint();
  27681. }
  27682. #endif
  27683. #if ! JUCE_MAC
  27684. void closePluginWindow()
  27685. {
  27686. if (isOpen)
  27687. {
  27688. log ("Closing VST UI: " + plugin.getName());
  27689. isOpen = false;
  27690. dispatch (effEditClose, 0, 0, 0, 0);
  27691. #if JUCE_WINDOWS
  27692. #pragma warning (push)
  27693. #pragma warning (disable: 4244)
  27694. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27695. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27696. #pragma warning (pop)
  27697. stopTimer();
  27698. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27699. DestroyWindow (pluginHWND);
  27700. pluginHWND = 0;
  27701. #elif JUCE_LINUX
  27702. stopTimer();
  27703. pluginWindow = 0;
  27704. pluginProc = 0;
  27705. #endif
  27706. }
  27707. }
  27708. #endif
  27709. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27710. {
  27711. return plugin.dispatch (opcode, index, value, ptr, opt);
  27712. }
  27713. #if JUCE_WINDOWS
  27714. void checkPluginWindowSize()
  27715. {
  27716. RECT r;
  27717. GetWindowRect (pluginHWND, &r);
  27718. const int w = r.right - r.left;
  27719. const int h = r.bottom - r.top;
  27720. if (isShowing() && w > 0 && h > 0
  27721. && (w != getWidth() || h != getHeight())
  27722. && ! pluginRefusesToResize)
  27723. {
  27724. setSize (w, h);
  27725. sizeCheckCount = 0;
  27726. }
  27727. }
  27728. // hooks to get keyboard events from VST windows..
  27729. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27730. {
  27731. for (int i = activeVSTWindows.size(); --i >= 0;)
  27732. {
  27733. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27734. if (w->pluginHWND == hW)
  27735. {
  27736. if (message == WM_CHAR
  27737. || message == WM_KEYDOWN
  27738. || message == WM_SYSKEYDOWN
  27739. || message == WM_KEYUP
  27740. || message == WM_SYSKEYUP
  27741. || message == WM_APPCOMMAND)
  27742. {
  27743. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27744. message, wParam, lParam);
  27745. }
  27746. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27747. (HWND) w->pluginHWND,
  27748. message,
  27749. wParam,
  27750. lParam);
  27751. }
  27752. }
  27753. return DefWindowProc (hW, message, wParam, lParam);
  27754. }
  27755. #endif
  27756. #if JUCE_LINUX
  27757. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27758. void sendEventToChild (XEvent* event)
  27759. {
  27760. if (pluginProc != 0)
  27761. {
  27762. // if the plugin publishes an event procedure, pass the event directly..
  27763. pluginProc (event);
  27764. }
  27765. else if (pluginWindow != 0)
  27766. {
  27767. // if the plugin has a window, then send the event to the window so that
  27768. // its message thread will pick it up..
  27769. XSendEvent (display, pluginWindow, False, 0L, event);
  27770. XFlush (display);
  27771. }
  27772. }
  27773. void mouseEnter (const MouseEvent& e)
  27774. {
  27775. if (pluginWindow != 0)
  27776. {
  27777. XEvent ev;
  27778. zerostruct (ev);
  27779. ev.xcrossing.display = display;
  27780. ev.xcrossing.type = EnterNotify;
  27781. ev.xcrossing.window = pluginWindow;
  27782. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27783. ev.xcrossing.time = CurrentTime;
  27784. ev.xcrossing.x = e.x;
  27785. ev.xcrossing.y = e.y;
  27786. ev.xcrossing.x_root = e.getScreenX();
  27787. ev.xcrossing.y_root = e.getScreenY();
  27788. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27789. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27790. translateJuceToXCrossingModifiers (e, ev);
  27791. sendEventToChild (&ev);
  27792. }
  27793. }
  27794. void mouseExit (const MouseEvent& e)
  27795. {
  27796. if (pluginWindow != 0)
  27797. {
  27798. XEvent ev;
  27799. zerostruct (ev);
  27800. ev.xcrossing.display = display;
  27801. ev.xcrossing.type = LeaveNotify;
  27802. ev.xcrossing.window = pluginWindow;
  27803. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27804. ev.xcrossing.time = CurrentTime;
  27805. ev.xcrossing.x = e.x;
  27806. ev.xcrossing.y = e.y;
  27807. ev.xcrossing.x_root = e.getScreenX();
  27808. ev.xcrossing.y_root = e.getScreenY();
  27809. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27810. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27811. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27812. translateJuceToXCrossingModifiers (e, ev);
  27813. sendEventToChild (&ev);
  27814. }
  27815. }
  27816. void mouseMove (const MouseEvent& e)
  27817. {
  27818. if (pluginWindow != 0)
  27819. {
  27820. XEvent ev;
  27821. zerostruct (ev);
  27822. ev.xmotion.display = display;
  27823. ev.xmotion.type = MotionNotify;
  27824. ev.xmotion.window = pluginWindow;
  27825. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27826. ev.xmotion.time = CurrentTime;
  27827. ev.xmotion.is_hint = NotifyNormal;
  27828. ev.xmotion.x = e.x;
  27829. ev.xmotion.y = e.y;
  27830. ev.xmotion.x_root = e.getScreenX();
  27831. ev.xmotion.y_root = e.getScreenY();
  27832. sendEventToChild (&ev);
  27833. }
  27834. }
  27835. void mouseDrag (const MouseEvent& e)
  27836. {
  27837. if (pluginWindow != 0)
  27838. {
  27839. XEvent ev;
  27840. zerostruct (ev);
  27841. ev.xmotion.display = display;
  27842. ev.xmotion.type = MotionNotify;
  27843. ev.xmotion.window = pluginWindow;
  27844. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27845. ev.xmotion.time = CurrentTime;
  27846. ev.xmotion.x = e.x ;
  27847. ev.xmotion.y = e.y;
  27848. ev.xmotion.x_root = e.getScreenX();
  27849. ev.xmotion.y_root = e.getScreenY();
  27850. ev.xmotion.is_hint = NotifyNormal;
  27851. translateJuceToXMotionModifiers (e, ev);
  27852. sendEventToChild (&ev);
  27853. }
  27854. }
  27855. void mouseUp (const MouseEvent& e)
  27856. {
  27857. if (pluginWindow != 0)
  27858. {
  27859. XEvent ev;
  27860. zerostruct (ev);
  27861. ev.xbutton.display = display;
  27862. ev.xbutton.type = ButtonRelease;
  27863. ev.xbutton.window = pluginWindow;
  27864. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27865. ev.xbutton.time = CurrentTime;
  27866. ev.xbutton.x = e.x;
  27867. ev.xbutton.y = e.y;
  27868. ev.xbutton.x_root = e.getScreenX();
  27869. ev.xbutton.y_root = e.getScreenY();
  27870. translateJuceToXButtonModifiers (e, ev);
  27871. sendEventToChild (&ev);
  27872. }
  27873. }
  27874. void mouseWheelMove (const MouseEvent& e,
  27875. float incrementX,
  27876. float incrementY)
  27877. {
  27878. if (pluginWindow != 0)
  27879. {
  27880. XEvent ev;
  27881. zerostruct (ev);
  27882. ev.xbutton.display = display;
  27883. ev.xbutton.type = ButtonPress;
  27884. ev.xbutton.window = pluginWindow;
  27885. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27886. ev.xbutton.time = CurrentTime;
  27887. ev.xbutton.x = e.x;
  27888. ev.xbutton.y = e.y;
  27889. ev.xbutton.x_root = e.getScreenX();
  27890. ev.xbutton.y_root = e.getScreenY();
  27891. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27892. sendEventToChild (&ev);
  27893. // TODO - put a usleep here ?
  27894. ev.xbutton.type = ButtonRelease;
  27895. sendEventToChild (&ev);
  27896. }
  27897. }
  27898. #endif
  27899. #if JUCE_MAC
  27900. #if ! JUCE_SUPPORT_CARBON
  27901. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27902. #endif
  27903. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27904. {
  27905. public:
  27906. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27907. : owner (owner_),
  27908. alreadyInside (false)
  27909. {
  27910. }
  27911. ~InnerWrapperComponent()
  27912. {
  27913. deleteWindow();
  27914. }
  27915. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27916. {
  27917. owner->openPluginWindow (windowRef);
  27918. return 0;
  27919. }
  27920. void removeView (HIViewRef)
  27921. {
  27922. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27923. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27924. }
  27925. bool getEmbeddedViewSize (int& w, int& h)
  27926. {
  27927. ERect* rect = 0;
  27928. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27929. w = rect->right - rect->left;
  27930. h = rect->bottom - rect->top;
  27931. return true;
  27932. }
  27933. void mouseDown (int x, int y)
  27934. {
  27935. if (! alreadyInside)
  27936. {
  27937. alreadyInside = true;
  27938. getTopLevelComponent()->toFront (true);
  27939. owner->dispatch (effEditMouse, x, y, 0, 0);
  27940. alreadyInside = false;
  27941. }
  27942. else
  27943. {
  27944. PostEvent (::mouseDown, 0);
  27945. }
  27946. }
  27947. void paint()
  27948. {
  27949. ComponentPeer* const peer = getPeer();
  27950. if (peer != 0)
  27951. {
  27952. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27953. ERect r;
  27954. r.left = pos.getX();
  27955. r.right = r.left + getWidth();
  27956. r.top = pos.getY();
  27957. r.bottom = r.top + getHeight();
  27958. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27959. }
  27960. }
  27961. private:
  27962. VSTPluginWindow* const owner;
  27963. bool alreadyInside;
  27964. };
  27965. friend class InnerWrapperComponent;
  27966. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27967. void resized()
  27968. {
  27969. innerWrapper->setSize (getWidth(), getHeight());
  27970. }
  27971. #endif
  27972. private:
  27973. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27974. };
  27975. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27976. {
  27977. if (hasEditor())
  27978. return new VSTPluginWindow (*this);
  27979. return 0;
  27980. }
  27981. void VSTPluginInstance::handleAsyncUpdate()
  27982. {
  27983. // indicates that something about the plugin has changed..
  27984. updateHostDisplay();
  27985. }
  27986. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27987. {
  27988. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27989. {
  27990. changeProgramName (getCurrentProgram(), prog->prgName);
  27991. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27992. setParameter (i, vst_swapFloat (prog->params[i]));
  27993. return true;
  27994. }
  27995. return false;
  27996. }
  27997. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27998. const int dataSize)
  27999. {
  28000. if (dataSize < 28)
  28001. return false;
  28002. const fxSet* const set = (const fxSet*) data;
  28003. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  28004. || vst_swap (set->version) > fxbVersionNum)
  28005. return false;
  28006. if (vst_swap (set->fxMagic) == 'FxBk')
  28007. {
  28008. // bank of programs
  28009. if (vst_swap (set->numPrograms) >= 0)
  28010. {
  28011. const int oldProg = getCurrentProgram();
  28012. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  28013. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28014. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  28015. {
  28016. if (i != oldProg)
  28017. {
  28018. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  28019. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28020. return false;
  28021. if (vst_swap (set->numPrograms) > 0)
  28022. setCurrentProgram (i);
  28023. if (! restoreProgramSettings (prog))
  28024. return false;
  28025. }
  28026. }
  28027. if (vst_swap (set->numPrograms) > 0)
  28028. setCurrentProgram (oldProg);
  28029. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  28030. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28031. return false;
  28032. if (! restoreProgramSettings (prog))
  28033. return false;
  28034. }
  28035. }
  28036. else if (vst_swap (set->fxMagic) == 'FxCk')
  28037. {
  28038. // single program
  28039. const fxProgram* const prog = (const fxProgram*) data;
  28040. if (vst_swap (prog->chunkMagic) != 'CcnK')
  28041. return false;
  28042. changeProgramName (getCurrentProgram(), prog->prgName);
  28043. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  28044. setParameter (i, vst_swapFloat (prog->params[i]));
  28045. }
  28046. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  28047. {
  28048. // non-preset chunk
  28049. const fxChunkSet* const cset = (const fxChunkSet*) data;
  28050. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  28051. return false;
  28052. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  28053. }
  28054. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  28055. {
  28056. // preset chunk
  28057. const fxProgramSet* const cset = (const fxProgramSet*) data;
  28058. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  28059. return false;
  28060. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  28061. changeProgramName (getCurrentProgram(), cset->name);
  28062. }
  28063. else
  28064. {
  28065. return false;
  28066. }
  28067. return true;
  28068. }
  28069. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  28070. {
  28071. const int numParams = getNumParameters();
  28072. prog->chunkMagic = vst_swap ('CcnK');
  28073. prog->byteSize = 0;
  28074. prog->fxMagic = vst_swap ('FxCk');
  28075. prog->version = vst_swap (fxbVersionNum);
  28076. prog->fxID = vst_swap (getUID());
  28077. prog->fxVersion = vst_swap (getVersionNumber());
  28078. prog->numParams = vst_swap (numParams);
  28079. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  28080. for (int i = 0; i < numParams; ++i)
  28081. prog->params[i] = vst_swapFloat (getParameter (i));
  28082. }
  28083. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  28084. {
  28085. const int numPrograms = getNumPrograms();
  28086. const int numParams = getNumParameters();
  28087. if (usesChunks())
  28088. {
  28089. if (isFXB)
  28090. {
  28091. MemoryBlock chunk;
  28092. getChunkData (chunk, false, maxSizeMB);
  28093. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  28094. dest.setSize (totalLen, true);
  28095. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  28096. set->chunkMagic = vst_swap ('CcnK');
  28097. set->byteSize = 0;
  28098. set->fxMagic = vst_swap ('FBCh');
  28099. set->version = vst_swap (fxbVersionNum);
  28100. set->fxID = vst_swap (getUID());
  28101. set->fxVersion = vst_swap (getVersionNumber());
  28102. set->numPrograms = vst_swap (numPrograms);
  28103. set->chunkSize = vst_swap ((long) chunk.getSize());
  28104. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28105. }
  28106. else
  28107. {
  28108. MemoryBlock chunk;
  28109. getChunkData (chunk, true, maxSizeMB);
  28110. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  28111. dest.setSize (totalLen, true);
  28112. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28113. set->chunkMagic = vst_swap ('CcnK');
  28114. set->byteSize = 0;
  28115. set->fxMagic = vst_swap ('FPCh');
  28116. set->version = vst_swap (fxbVersionNum);
  28117. set->fxID = vst_swap (getUID());
  28118. set->fxVersion = vst_swap (getVersionNumber());
  28119. set->numPrograms = vst_swap (numPrograms);
  28120. set->chunkSize = vst_swap ((long) chunk.getSize());
  28121. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28122. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28123. }
  28124. }
  28125. else
  28126. {
  28127. if (isFXB)
  28128. {
  28129. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28130. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28131. dest.setSize (len, true);
  28132. fxSet* const set = (fxSet*) dest.getData();
  28133. set->chunkMagic = vst_swap ('CcnK');
  28134. set->byteSize = 0;
  28135. set->fxMagic = vst_swap ('FxBk');
  28136. set->version = vst_swap (fxbVersionNum);
  28137. set->fxID = vst_swap (getUID());
  28138. set->fxVersion = vst_swap (getVersionNumber());
  28139. set->numPrograms = vst_swap (numPrograms);
  28140. const int oldProgram = getCurrentProgram();
  28141. MemoryBlock oldSettings;
  28142. createTempParameterStore (oldSettings);
  28143. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28144. for (int i = 0; i < numPrograms; ++i)
  28145. {
  28146. if (i != oldProgram)
  28147. {
  28148. setCurrentProgram (i);
  28149. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28150. }
  28151. }
  28152. setCurrentProgram (oldProgram);
  28153. restoreFromTempParameterStore (oldSettings);
  28154. }
  28155. else
  28156. {
  28157. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28158. dest.setSize (totalLen, true);
  28159. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28160. }
  28161. }
  28162. return true;
  28163. }
  28164. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28165. {
  28166. if (usesChunks())
  28167. {
  28168. void* data = 0;
  28169. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28170. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28171. {
  28172. mb.setSize (bytes);
  28173. mb.copyFrom (data, 0, bytes);
  28174. }
  28175. }
  28176. }
  28177. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28178. {
  28179. if (size > 0 && usesChunks())
  28180. {
  28181. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28182. if (! isPreset)
  28183. updateStoredProgramNames();
  28184. }
  28185. }
  28186. void VSTPluginInstance::timerCallback()
  28187. {
  28188. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28189. stopTimer();
  28190. }
  28191. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28192. {
  28193. const ScopedLock sl (lock);
  28194. ++insideVSTCallback;
  28195. int result = 0;
  28196. try
  28197. {
  28198. if (effect != 0)
  28199. {
  28200. #if JUCE_MAC
  28201. if (module->resFileId != 0)
  28202. UseResFile (module->resFileId);
  28203. #endif
  28204. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28205. #if JUCE_MAC
  28206. module->resFileId = CurResFile();
  28207. #endif
  28208. --insideVSTCallback;
  28209. return result;
  28210. }
  28211. }
  28212. catch (...)
  28213. {
  28214. }
  28215. --insideVSTCallback;
  28216. return result;
  28217. }
  28218. namespace
  28219. {
  28220. static const int defaultVSTSampleRateValue = 16384;
  28221. static const int defaultVSTBlockSizeValue = 512;
  28222. // handles non plugin-specific callbacks..
  28223. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28224. {
  28225. (void) index;
  28226. (void) value;
  28227. (void) opt;
  28228. switch (opcode)
  28229. {
  28230. case audioMasterCanDo:
  28231. {
  28232. static const char* canDos[] = { "supplyIdle",
  28233. "sendVstEvents",
  28234. "sendVstMidiEvent",
  28235. "sendVstTimeInfo",
  28236. "receiveVstEvents",
  28237. "receiveVstMidiEvent",
  28238. "supportShell",
  28239. "shellCategory" };
  28240. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28241. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28242. return 1;
  28243. return 0;
  28244. }
  28245. case audioMasterVersion: return 0x2400;
  28246. case audioMasterCurrentId: return shellUIDToCreate;
  28247. case audioMasterGetNumAutomatableParameters: return 0;
  28248. case audioMasterGetAutomationState: return 1;
  28249. case audioMasterGetVendorVersion: return 0x0101;
  28250. case audioMasterGetVendorString:
  28251. case audioMasterGetProductString:
  28252. {
  28253. String hostName ("Juce VST Host");
  28254. if (JUCEApplication::getInstance() != 0)
  28255. hostName = JUCEApplication::getInstance()->getApplicationName();
  28256. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28257. break;
  28258. }
  28259. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28260. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28261. case audioMasterSetOutputSampleRate: return 0;
  28262. default:
  28263. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28264. break;
  28265. }
  28266. return 0;
  28267. }
  28268. }
  28269. // handles callbacks for a specific plugin
  28270. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28271. {
  28272. switch (opcode)
  28273. {
  28274. case audioMasterAutomate:
  28275. sendParamChangeMessageToListeners (index, opt);
  28276. break;
  28277. case audioMasterProcessEvents:
  28278. handleMidiFromPlugin ((const VstEvents*) ptr);
  28279. break;
  28280. case audioMasterGetTime:
  28281. #if JUCE_MSVC
  28282. #pragma warning (push)
  28283. #pragma warning (disable: 4311)
  28284. #endif
  28285. return (VstIntPtr) &vstHostTime;
  28286. #if JUCE_MSVC
  28287. #pragma warning (pop)
  28288. #endif
  28289. break;
  28290. case audioMasterIdle:
  28291. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28292. {
  28293. ++insideVSTCallback;
  28294. #if JUCE_MAC
  28295. if (getActiveEditor() != 0)
  28296. dispatch (effEditIdle, 0, 0, 0, 0);
  28297. #endif
  28298. juce_callAnyTimersSynchronously();
  28299. handleUpdateNowIfNeeded();
  28300. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28301. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28302. --insideVSTCallback;
  28303. }
  28304. break;
  28305. case audioMasterUpdateDisplay:
  28306. triggerAsyncUpdate();
  28307. break;
  28308. case audioMasterTempoAt:
  28309. // returns (10000 * bpm)
  28310. break;
  28311. case audioMasterNeedIdle:
  28312. startTimer (50);
  28313. break;
  28314. case audioMasterSizeWindow:
  28315. if (getActiveEditor() != 0)
  28316. getActiveEditor()->setSize (index, value);
  28317. return 1;
  28318. case audioMasterGetSampleRate:
  28319. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28320. case audioMasterGetBlockSize:
  28321. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28322. case audioMasterWantMidi:
  28323. wantsMidiMessages = true;
  28324. break;
  28325. case audioMasterGetDirectory:
  28326. #if JUCE_MAC
  28327. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28328. #else
  28329. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28330. #endif
  28331. case audioMasterGetAutomationState:
  28332. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28333. break;
  28334. // none of these are handled (yet)..
  28335. case audioMasterBeginEdit:
  28336. case audioMasterEndEdit:
  28337. case audioMasterSetTime:
  28338. case audioMasterPinConnected:
  28339. case audioMasterGetParameterQuantization:
  28340. case audioMasterIOChanged:
  28341. case audioMasterGetInputLatency:
  28342. case audioMasterGetOutputLatency:
  28343. case audioMasterGetPreviousPlug:
  28344. case audioMasterGetNextPlug:
  28345. case audioMasterWillReplaceOrAccumulate:
  28346. case audioMasterGetCurrentProcessLevel:
  28347. case audioMasterOfflineStart:
  28348. case audioMasterOfflineRead:
  28349. case audioMasterOfflineWrite:
  28350. case audioMasterOfflineGetCurrentPass:
  28351. case audioMasterOfflineGetCurrentMetaPass:
  28352. case audioMasterVendorSpecific:
  28353. case audioMasterSetIcon:
  28354. case audioMasterGetLanguage:
  28355. case audioMasterOpenWindow:
  28356. case audioMasterCloseWindow:
  28357. break;
  28358. default:
  28359. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28360. }
  28361. return 0;
  28362. }
  28363. // entry point for all callbacks from the plugin
  28364. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28365. {
  28366. try
  28367. {
  28368. if (effect != 0 && effect->resvd2 != 0)
  28369. {
  28370. return ((VSTPluginInstance*)(effect->resvd2))
  28371. ->handleCallback (opcode, index, value, ptr, opt);
  28372. }
  28373. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28374. }
  28375. catch (...)
  28376. {
  28377. return 0;
  28378. }
  28379. }
  28380. const String VSTPluginInstance::getVersion() const
  28381. {
  28382. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28383. String s;
  28384. if (v == 0 || v == -1)
  28385. v = getVersionNumber();
  28386. if (v != 0)
  28387. {
  28388. int versionBits[4];
  28389. int n = 0;
  28390. while (v != 0)
  28391. {
  28392. versionBits [n++] = (v & 0xff);
  28393. v >>= 8;
  28394. }
  28395. s << 'V';
  28396. while (n > 0)
  28397. {
  28398. s << versionBits [--n];
  28399. if (n > 0)
  28400. s << '.';
  28401. }
  28402. }
  28403. return s;
  28404. }
  28405. int VSTPluginInstance::getUID() const
  28406. {
  28407. int uid = effect != 0 ? effect->uniqueID : 0;
  28408. if (uid == 0)
  28409. uid = module->file.hashCode();
  28410. return uid;
  28411. }
  28412. const String VSTPluginInstance::getCategory() const
  28413. {
  28414. const char* result = 0;
  28415. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28416. {
  28417. case kPlugCategEffect: result = "Effect"; break;
  28418. case kPlugCategSynth: result = "Synth"; break;
  28419. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28420. case kPlugCategMastering: result = "Mastering"; break;
  28421. case kPlugCategSpacializer: result = "Spacial"; break;
  28422. case kPlugCategRoomFx: result = "Reverb"; break;
  28423. case kPlugSurroundFx: result = "Surround"; break;
  28424. case kPlugCategRestoration: result = "Restoration"; break;
  28425. case kPlugCategGenerator: result = "Tone generation"; break;
  28426. default: break;
  28427. }
  28428. return result;
  28429. }
  28430. float VSTPluginInstance::getParameter (int index)
  28431. {
  28432. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28433. {
  28434. try
  28435. {
  28436. const ScopedLock sl (lock);
  28437. return effect->getParameter (effect, index);
  28438. }
  28439. catch (...)
  28440. {
  28441. }
  28442. }
  28443. return 0.0f;
  28444. }
  28445. void VSTPluginInstance::setParameter (int index, float newValue)
  28446. {
  28447. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28448. {
  28449. try
  28450. {
  28451. const ScopedLock sl (lock);
  28452. if (effect->getParameter (effect, index) != newValue)
  28453. effect->setParameter (effect, index, newValue);
  28454. }
  28455. catch (...)
  28456. {
  28457. }
  28458. }
  28459. }
  28460. const String VSTPluginInstance::getParameterName (int index)
  28461. {
  28462. if (effect != 0)
  28463. {
  28464. jassert (index >= 0 && index < effect->numParams);
  28465. char nm [256];
  28466. zerostruct (nm);
  28467. dispatch (effGetParamName, index, 0, nm, 0);
  28468. return String (nm).trim();
  28469. }
  28470. return String::empty;
  28471. }
  28472. const String VSTPluginInstance::getParameterLabel (int index) const
  28473. {
  28474. if (effect != 0)
  28475. {
  28476. jassert (index >= 0 && index < effect->numParams);
  28477. char nm [256];
  28478. zerostruct (nm);
  28479. dispatch (effGetParamLabel, index, 0, nm, 0);
  28480. return String (nm).trim();
  28481. }
  28482. return String::empty;
  28483. }
  28484. const String VSTPluginInstance::getParameterText (int index)
  28485. {
  28486. if (effect != 0)
  28487. {
  28488. jassert (index >= 0 && index < effect->numParams);
  28489. char nm [256];
  28490. zerostruct (nm);
  28491. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28492. return String (nm).trim();
  28493. }
  28494. return String::empty;
  28495. }
  28496. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28497. {
  28498. if (effect != 0)
  28499. {
  28500. jassert (index >= 0 && index < effect->numParams);
  28501. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28502. }
  28503. return false;
  28504. }
  28505. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28506. {
  28507. dest.setSize (64 + 4 * getNumParameters());
  28508. dest.fillWith (0);
  28509. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28510. float* const p = (float*) (((char*) dest.getData()) + 64);
  28511. for (int i = 0; i < getNumParameters(); ++i)
  28512. p[i] = getParameter(i);
  28513. }
  28514. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28515. {
  28516. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28517. float* p = (float*) (((char*) m.getData()) + 64);
  28518. for (int i = 0; i < getNumParameters(); ++i)
  28519. setParameter (i, p[i]);
  28520. }
  28521. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28522. {
  28523. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28524. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28525. }
  28526. const String VSTPluginInstance::getProgramName (int index)
  28527. {
  28528. if (index == getCurrentProgram())
  28529. {
  28530. return getCurrentProgramName();
  28531. }
  28532. else if (effect != 0)
  28533. {
  28534. char nm [256];
  28535. zerostruct (nm);
  28536. if (dispatch (effGetProgramNameIndexed,
  28537. jlimit (0, getNumPrograms(), index),
  28538. -1, nm, 0) != 0)
  28539. {
  28540. return String (nm).trim();
  28541. }
  28542. }
  28543. return programNames [index];
  28544. }
  28545. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28546. {
  28547. if (index == getCurrentProgram())
  28548. {
  28549. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28550. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28551. }
  28552. else
  28553. {
  28554. jassertfalse; // xxx not implemented!
  28555. }
  28556. }
  28557. void VSTPluginInstance::updateStoredProgramNames()
  28558. {
  28559. if (effect != 0 && getNumPrograms() > 0)
  28560. {
  28561. char nm [256];
  28562. zerostruct (nm);
  28563. // only do this if the plugin can't use indexed names..
  28564. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28565. {
  28566. const int oldProgram = getCurrentProgram();
  28567. MemoryBlock oldSettings;
  28568. createTempParameterStore (oldSettings);
  28569. for (int i = 0; i < getNumPrograms(); ++i)
  28570. {
  28571. setCurrentProgram (i);
  28572. getCurrentProgramName(); // (this updates the list)
  28573. }
  28574. setCurrentProgram (oldProgram);
  28575. restoreFromTempParameterStore (oldSettings);
  28576. }
  28577. }
  28578. }
  28579. const String VSTPluginInstance::getCurrentProgramName()
  28580. {
  28581. if (effect != 0)
  28582. {
  28583. char nm [256];
  28584. zerostruct (nm);
  28585. dispatch (effGetProgramName, 0, 0, nm, 0);
  28586. const int index = getCurrentProgram();
  28587. if (programNames[index].isEmpty())
  28588. {
  28589. while (programNames.size() < index)
  28590. programNames.add (String::empty);
  28591. programNames.set (index, String (nm).trim());
  28592. }
  28593. return String (nm).trim();
  28594. }
  28595. return String::empty;
  28596. }
  28597. const String VSTPluginInstance::getInputChannelName (int index) const
  28598. {
  28599. if (index >= 0 && index < getNumInputChannels())
  28600. {
  28601. VstPinProperties pinProps;
  28602. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28603. return String (pinProps.label, sizeof (pinProps.label));
  28604. }
  28605. return String::empty;
  28606. }
  28607. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28608. {
  28609. if (index < 0 || index >= getNumInputChannels())
  28610. return false;
  28611. VstPinProperties pinProps;
  28612. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28613. return (pinProps.flags & kVstPinIsStereo) != 0;
  28614. return true;
  28615. }
  28616. const String VSTPluginInstance::getOutputChannelName (int index) const
  28617. {
  28618. if (index >= 0 && index < getNumOutputChannels())
  28619. {
  28620. VstPinProperties pinProps;
  28621. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28622. return String (pinProps.label, sizeof (pinProps.label));
  28623. }
  28624. return String::empty;
  28625. }
  28626. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28627. {
  28628. if (index < 0 || index >= getNumOutputChannels())
  28629. return false;
  28630. VstPinProperties pinProps;
  28631. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28632. return (pinProps.flags & kVstPinIsStereo) != 0;
  28633. return true;
  28634. }
  28635. void VSTPluginInstance::setPower (const bool on)
  28636. {
  28637. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28638. isPowerOn = on;
  28639. }
  28640. const int defaultMaxSizeMB = 64;
  28641. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28642. {
  28643. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28644. }
  28645. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28646. {
  28647. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28648. }
  28649. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28650. {
  28651. loadFromFXBFile (data, sizeInBytes);
  28652. }
  28653. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28654. {
  28655. loadFromFXBFile (data, sizeInBytes);
  28656. }
  28657. VSTPluginFormat::VSTPluginFormat()
  28658. {
  28659. }
  28660. VSTPluginFormat::~VSTPluginFormat()
  28661. {
  28662. }
  28663. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28664. const String& fileOrIdentifier)
  28665. {
  28666. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28667. return;
  28668. PluginDescription desc;
  28669. desc.fileOrIdentifier = fileOrIdentifier;
  28670. desc.uid = 0;
  28671. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28672. if (instance == 0)
  28673. return;
  28674. try
  28675. {
  28676. #if JUCE_MAC
  28677. if (instance->module->resFileId != 0)
  28678. UseResFile (instance->module->resFileId);
  28679. #endif
  28680. instance->fillInPluginDescription (desc);
  28681. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28682. if (category != kPlugCategShell)
  28683. {
  28684. // Normal plugin...
  28685. results.add (new PluginDescription (desc));
  28686. ++insideVSTCallback;
  28687. instance->dispatch (effOpen, 0, 0, 0, 0);
  28688. --insideVSTCallback;
  28689. }
  28690. else
  28691. {
  28692. // It's a shell plugin, so iterate all the subtypes...
  28693. char shellEffectName [64];
  28694. for (;;)
  28695. {
  28696. zerostruct (shellEffectName);
  28697. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28698. if (uid == 0)
  28699. {
  28700. break;
  28701. }
  28702. else
  28703. {
  28704. desc.uid = uid;
  28705. desc.name = shellEffectName;
  28706. desc.descriptiveName = shellEffectName;
  28707. bool alreadyThere = false;
  28708. for (int i = results.size(); --i >= 0;)
  28709. {
  28710. PluginDescription* const d = results.getUnchecked(i);
  28711. if (d->isDuplicateOf (desc))
  28712. {
  28713. alreadyThere = true;
  28714. break;
  28715. }
  28716. }
  28717. if (! alreadyThere)
  28718. results.add (new PluginDescription (desc));
  28719. }
  28720. }
  28721. }
  28722. }
  28723. catch (...)
  28724. {
  28725. // crashed while loading...
  28726. }
  28727. }
  28728. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28729. {
  28730. ScopedPointer <VSTPluginInstance> result;
  28731. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28732. {
  28733. File file (desc.fileOrIdentifier);
  28734. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28735. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28736. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28737. if (module != 0)
  28738. {
  28739. shellUIDToCreate = desc.uid;
  28740. result = new VSTPluginInstance (module);
  28741. if (result->effect != 0)
  28742. {
  28743. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28744. result->initialise();
  28745. }
  28746. else
  28747. {
  28748. result = 0;
  28749. }
  28750. }
  28751. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28752. }
  28753. return result.release();
  28754. }
  28755. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28756. {
  28757. const File f (fileOrIdentifier);
  28758. #if JUCE_MAC
  28759. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28760. return true;
  28761. #if JUCE_PPC
  28762. FSRef fileRef;
  28763. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28764. {
  28765. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28766. if (resFileId != -1)
  28767. {
  28768. const int numEffects = Count1Resources ('aEff');
  28769. CloseResFile (resFileId);
  28770. if (numEffects > 0)
  28771. return true;
  28772. }
  28773. }
  28774. #endif
  28775. return false;
  28776. #elif JUCE_WINDOWS
  28777. return f.existsAsFile() && f.hasFileExtension (".dll");
  28778. #elif JUCE_LINUX
  28779. return f.existsAsFile() && f.hasFileExtension (".so");
  28780. #endif
  28781. }
  28782. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28783. {
  28784. return fileOrIdentifier;
  28785. }
  28786. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28787. {
  28788. return File (desc.fileOrIdentifier).exists();
  28789. }
  28790. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28791. {
  28792. StringArray results;
  28793. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28794. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28795. return results;
  28796. }
  28797. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28798. {
  28799. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28800. // .component or .vst directories.
  28801. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28802. while (iter.next())
  28803. {
  28804. const File f (iter.getFile());
  28805. bool isPlugin = false;
  28806. if (fileMightContainThisPluginType (f.getFullPathName()))
  28807. {
  28808. isPlugin = true;
  28809. results.add (f.getFullPathName());
  28810. }
  28811. if (recursive && (! isPlugin) && f.isDirectory())
  28812. recursiveFileSearch (results, f, true);
  28813. }
  28814. }
  28815. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28816. {
  28817. #if JUCE_MAC
  28818. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28819. #elif JUCE_WINDOWS
  28820. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28821. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28822. #elif JUCE_LINUX
  28823. return FileSearchPath ("/usr/lib/vst");
  28824. #endif
  28825. }
  28826. END_JUCE_NAMESPACE
  28827. #endif
  28828. #undef log
  28829. #endif
  28830. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28831. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28832. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28833. BEGIN_JUCE_NAMESPACE
  28834. AudioProcessor::AudioProcessor()
  28835. : playHead (0),
  28836. activeEditor (0),
  28837. sampleRate (0),
  28838. blockSize (0),
  28839. numInputChannels (0),
  28840. numOutputChannels (0),
  28841. latencySamples (0),
  28842. suspended (false),
  28843. nonRealtime (false)
  28844. {
  28845. }
  28846. AudioProcessor::~AudioProcessor()
  28847. {
  28848. // ooh, nasty - the editor should have been deleted before the filter
  28849. // that it refers to is deleted..
  28850. jassert (activeEditor == 0);
  28851. #if JUCE_DEBUG
  28852. // This will fail if you've called beginParameterChangeGesture() for one
  28853. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28854. jassert (changingParams.countNumberOfSetBits() == 0);
  28855. #endif
  28856. }
  28857. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28858. {
  28859. playHead = newPlayHead;
  28860. }
  28861. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28862. {
  28863. const ScopedLock sl (listenerLock);
  28864. listeners.addIfNotAlreadyThere (newListener);
  28865. }
  28866. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28867. {
  28868. const ScopedLock sl (listenerLock);
  28869. listeners.removeValue (listenerToRemove);
  28870. }
  28871. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28872. const int numOuts,
  28873. const double sampleRate_,
  28874. const int blockSize_) throw()
  28875. {
  28876. numInputChannels = numIns;
  28877. numOutputChannels = numOuts;
  28878. sampleRate = sampleRate_;
  28879. blockSize = blockSize_;
  28880. }
  28881. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28882. {
  28883. nonRealtime = nonRealtime_;
  28884. }
  28885. void AudioProcessor::setLatencySamples (const int newLatency)
  28886. {
  28887. if (latencySamples != newLatency)
  28888. {
  28889. latencySamples = newLatency;
  28890. updateHostDisplay();
  28891. }
  28892. }
  28893. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28894. const float newValue)
  28895. {
  28896. setParameter (parameterIndex, newValue);
  28897. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28898. }
  28899. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28900. {
  28901. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28902. for (int i = listeners.size(); --i >= 0;)
  28903. {
  28904. AudioProcessorListener* l;
  28905. {
  28906. const ScopedLock sl (listenerLock);
  28907. l = listeners [i];
  28908. }
  28909. if (l != 0)
  28910. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28911. }
  28912. }
  28913. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28914. {
  28915. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28916. #if JUCE_DEBUG
  28917. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28918. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28919. jassert (! changingParams [parameterIndex]);
  28920. changingParams.setBit (parameterIndex);
  28921. #endif
  28922. for (int i = listeners.size(); --i >= 0;)
  28923. {
  28924. AudioProcessorListener* l;
  28925. {
  28926. const ScopedLock sl (listenerLock);
  28927. l = listeners [i];
  28928. }
  28929. if (l != 0)
  28930. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28931. }
  28932. }
  28933. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28934. {
  28935. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28936. #if JUCE_DEBUG
  28937. // This means you've called endParameterChangeGesture without having previously called
  28938. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28939. // calls matched correctly.
  28940. jassert (changingParams [parameterIndex]);
  28941. changingParams.clearBit (parameterIndex);
  28942. #endif
  28943. for (int i = listeners.size(); --i >= 0;)
  28944. {
  28945. AudioProcessorListener* l;
  28946. {
  28947. const ScopedLock sl (listenerLock);
  28948. l = listeners [i];
  28949. }
  28950. if (l != 0)
  28951. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28952. }
  28953. }
  28954. void AudioProcessor::updateHostDisplay()
  28955. {
  28956. for (int i = listeners.size(); --i >= 0;)
  28957. {
  28958. AudioProcessorListener* l;
  28959. {
  28960. const ScopedLock sl (listenerLock);
  28961. l = listeners [i];
  28962. }
  28963. if (l != 0)
  28964. l->audioProcessorChanged (this);
  28965. }
  28966. }
  28967. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28968. {
  28969. return true;
  28970. }
  28971. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28972. {
  28973. return false;
  28974. }
  28975. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28976. {
  28977. const ScopedLock sl (callbackLock);
  28978. suspended = shouldBeSuspended;
  28979. }
  28980. void AudioProcessor::reset()
  28981. {
  28982. }
  28983. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28984. {
  28985. const ScopedLock sl (callbackLock);
  28986. jassert (activeEditor == editor);
  28987. if (activeEditor == editor)
  28988. activeEditor = 0;
  28989. }
  28990. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28991. {
  28992. if (activeEditor != 0)
  28993. return activeEditor;
  28994. AudioProcessorEditor* const ed = createEditor();
  28995. // You must make your hasEditor() method return a consistent result!
  28996. jassert (hasEditor() == (ed != 0));
  28997. if (ed != 0)
  28998. {
  28999. // you must give your editor comp a size before returning it..
  29000. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  29001. const ScopedLock sl (callbackLock);
  29002. activeEditor = ed;
  29003. }
  29004. return ed;
  29005. }
  29006. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  29007. {
  29008. getStateInformation (destData);
  29009. }
  29010. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  29011. {
  29012. setStateInformation (data, sizeInBytes);
  29013. }
  29014. // magic number to identify memory blocks that we've stored as XML
  29015. const uint32 magicXmlNumber = 0x21324356;
  29016. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  29017. JUCE_NAMESPACE::MemoryBlock& destData)
  29018. {
  29019. const String xmlString (xml.createDocument (String::empty, true, false));
  29020. const int stringLength = xmlString.getNumBytesAsUTF8();
  29021. destData.setSize (stringLength + 10);
  29022. char* const d = static_cast<char*> (destData.getData());
  29023. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  29024. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  29025. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  29026. }
  29027. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  29028. const int sizeInBytes)
  29029. {
  29030. if (sizeInBytes > 8
  29031. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  29032. {
  29033. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  29034. if (stringLength > 0)
  29035. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  29036. jmin ((sizeInBytes - 8), stringLength)));
  29037. }
  29038. return 0;
  29039. }
  29040. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  29041. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  29042. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  29043. {
  29044. return timeInSeconds == other.timeInSeconds
  29045. && ppqPosition == other.ppqPosition
  29046. && editOriginTime == other.editOriginTime
  29047. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  29048. && frameRate == other.frameRate
  29049. && isPlaying == other.isPlaying
  29050. && isRecording == other.isRecording
  29051. && bpm == other.bpm
  29052. && timeSigNumerator == other.timeSigNumerator
  29053. && timeSigDenominator == other.timeSigDenominator;
  29054. }
  29055. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  29056. {
  29057. return ! operator== (other);
  29058. }
  29059. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  29060. {
  29061. zerostruct (*this);
  29062. timeSigNumerator = 4;
  29063. timeSigDenominator = 4;
  29064. bpm = 120;
  29065. }
  29066. END_JUCE_NAMESPACE
  29067. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  29068. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  29069. BEGIN_JUCE_NAMESPACE
  29070. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  29071. : owner (owner_)
  29072. {
  29073. // the filter must be valid..
  29074. jassert (owner != 0);
  29075. }
  29076. AudioProcessorEditor::~AudioProcessorEditor()
  29077. {
  29078. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  29079. // filter for some reason..
  29080. jassert (owner->getActiveEditor() != this);
  29081. }
  29082. END_JUCE_NAMESPACE
  29083. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  29084. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  29085. BEGIN_JUCE_NAMESPACE
  29086. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  29087. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  29088. : id (id_),
  29089. processor (processor_),
  29090. isPrepared (false)
  29091. {
  29092. jassert (processor_ != 0);
  29093. }
  29094. AudioProcessorGraph::Node::~Node()
  29095. {
  29096. }
  29097. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  29098. AudioProcessorGraph* const graph)
  29099. {
  29100. if (! isPrepared)
  29101. {
  29102. isPrepared = true;
  29103. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29104. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  29105. if (ioProc != 0)
  29106. ioProc->setParentGraph (graph);
  29107. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  29108. processor->getNumOutputChannels(),
  29109. sampleRate, blockSize);
  29110. processor->prepareToPlay (sampleRate, blockSize);
  29111. }
  29112. }
  29113. void AudioProcessorGraph::Node::unprepare()
  29114. {
  29115. if (isPrepared)
  29116. {
  29117. isPrepared = false;
  29118. processor->releaseResources();
  29119. }
  29120. }
  29121. AudioProcessorGraph::AudioProcessorGraph()
  29122. : lastNodeId (0),
  29123. renderingBuffers (1, 1),
  29124. currentAudioOutputBuffer (1, 1)
  29125. {
  29126. }
  29127. AudioProcessorGraph::~AudioProcessorGraph()
  29128. {
  29129. clearRenderingSequence();
  29130. clear();
  29131. }
  29132. const String AudioProcessorGraph::getName() const
  29133. {
  29134. return "Audio Graph";
  29135. }
  29136. void AudioProcessorGraph::clear()
  29137. {
  29138. nodes.clear();
  29139. connections.clear();
  29140. triggerAsyncUpdate();
  29141. }
  29142. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29143. {
  29144. for (int i = nodes.size(); --i >= 0;)
  29145. if (nodes.getUnchecked(i)->id == nodeId)
  29146. return nodes.getUnchecked(i);
  29147. return 0;
  29148. }
  29149. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29150. uint32 nodeId)
  29151. {
  29152. if (newProcessor == 0)
  29153. {
  29154. jassertfalse;
  29155. return 0;
  29156. }
  29157. if (nodeId == 0)
  29158. {
  29159. nodeId = ++lastNodeId;
  29160. }
  29161. else
  29162. {
  29163. // you can't add a node with an id that already exists in the graph..
  29164. jassert (getNodeForId (nodeId) == 0);
  29165. removeNode (nodeId);
  29166. }
  29167. lastNodeId = nodeId;
  29168. Node* const n = new Node (nodeId, newProcessor);
  29169. nodes.add (n);
  29170. triggerAsyncUpdate();
  29171. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29172. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29173. if (ioProc != 0)
  29174. ioProc->setParentGraph (this);
  29175. return n;
  29176. }
  29177. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29178. {
  29179. disconnectNode (nodeId);
  29180. for (int i = nodes.size(); --i >= 0;)
  29181. {
  29182. if (nodes.getUnchecked(i)->id == nodeId)
  29183. {
  29184. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29185. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29186. if (ioProc != 0)
  29187. ioProc->setParentGraph (0);
  29188. nodes.remove (i);
  29189. triggerAsyncUpdate();
  29190. return true;
  29191. }
  29192. }
  29193. return false;
  29194. }
  29195. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29196. const int sourceChannelIndex,
  29197. const uint32 destNodeId,
  29198. const int destChannelIndex) const
  29199. {
  29200. for (int i = connections.size(); --i >= 0;)
  29201. {
  29202. const Connection* const c = connections.getUnchecked(i);
  29203. if (c->sourceNodeId == sourceNodeId
  29204. && c->destNodeId == destNodeId
  29205. && c->sourceChannelIndex == sourceChannelIndex
  29206. && c->destChannelIndex == destChannelIndex)
  29207. {
  29208. return c;
  29209. }
  29210. }
  29211. return 0;
  29212. }
  29213. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29214. const uint32 possibleDestNodeId) const
  29215. {
  29216. for (int i = connections.size(); --i >= 0;)
  29217. {
  29218. const Connection* const c = connections.getUnchecked(i);
  29219. if (c->sourceNodeId == possibleSourceNodeId
  29220. && c->destNodeId == possibleDestNodeId)
  29221. {
  29222. return true;
  29223. }
  29224. }
  29225. return false;
  29226. }
  29227. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29228. const int sourceChannelIndex,
  29229. const uint32 destNodeId,
  29230. const int destChannelIndex) const
  29231. {
  29232. if (sourceChannelIndex < 0
  29233. || destChannelIndex < 0
  29234. || sourceNodeId == destNodeId
  29235. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29236. return false;
  29237. const Node* const source = getNodeForId (sourceNodeId);
  29238. if (source == 0
  29239. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29240. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29241. return false;
  29242. const Node* const dest = getNodeForId (destNodeId);
  29243. if (dest == 0
  29244. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29245. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29246. return false;
  29247. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29248. destNodeId, destChannelIndex) == 0;
  29249. }
  29250. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29251. const int sourceChannelIndex,
  29252. const uint32 destNodeId,
  29253. const int destChannelIndex)
  29254. {
  29255. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29256. return false;
  29257. Connection* const c = new Connection();
  29258. c->sourceNodeId = sourceNodeId;
  29259. c->sourceChannelIndex = sourceChannelIndex;
  29260. c->destNodeId = destNodeId;
  29261. c->destChannelIndex = destChannelIndex;
  29262. connections.add (c);
  29263. triggerAsyncUpdate();
  29264. return true;
  29265. }
  29266. void AudioProcessorGraph::removeConnection (const int index)
  29267. {
  29268. connections.remove (index);
  29269. triggerAsyncUpdate();
  29270. }
  29271. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29272. const uint32 destNodeId, const int destChannelIndex)
  29273. {
  29274. bool doneAnything = false;
  29275. for (int i = connections.size(); --i >= 0;)
  29276. {
  29277. const Connection* const c = connections.getUnchecked(i);
  29278. if (c->sourceNodeId == sourceNodeId
  29279. && c->destNodeId == destNodeId
  29280. && c->sourceChannelIndex == sourceChannelIndex
  29281. && c->destChannelIndex == destChannelIndex)
  29282. {
  29283. removeConnection (i);
  29284. doneAnything = true;
  29285. triggerAsyncUpdate();
  29286. }
  29287. }
  29288. return doneAnything;
  29289. }
  29290. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29291. {
  29292. bool doneAnything = false;
  29293. for (int i = connections.size(); --i >= 0;)
  29294. {
  29295. const Connection* const c = connections.getUnchecked(i);
  29296. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29297. {
  29298. removeConnection (i);
  29299. doneAnything = true;
  29300. triggerAsyncUpdate();
  29301. }
  29302. }
  29303. return doneAnything;
  29304. }
  29305. bool AudioProcessorGraph::removeIllegalConnections()
  29306. {
  29307. bool doneAnything = false;
  29308. for (int i = connections.size(); --i >= 0;)
  29309. {
  29310. const Connection* const c = connections.getUnchecked(i);
  29311. const Node* const source = getNodeForId (c->sourceNodeId);
  29312. const Node* const dest = getNodeForId (c->destNodeId);
  29313. if (source == 0 || dest == 0
  29314. || (c->sourceChannelIndex != midiChannelIndex
  29315. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  29316. || (c->sourceChannelIndex == midiChannelIndex
  29317. && ! source->processor->producesMidi())
  29318. || (c->destChannelIndex != midiChannelIndex
  29319. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  29320. || (c->destChannelIndex == midiChannelIndex
  29321. && ! dest->processor->acceptsMidi()))
  29322. {
  29323. removeConnection (i);
  29324. doneAnything = true;
  29325. triggerAsyncUpdate();
  29326. }
  29327. }
  29328. return doneAnything;
  29329. }
  29330. namespace GraphRenderingOps
  29331. {
  29332. class AudioGraphRenderingOp
  29333. {
  29334. public:
  29335. AudioGraphRenderingOp() {}
  29336. virtual ~AudioGraphRenderingOp() {}
  29337. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29338. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29339. const int numSamples) = 0;
  29340. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29341. };
  29342. class ClearChannelOp : public AudioGraphRenderingOp
  29343. {
  29344. public:
  29345. ClearChannelOp (const int channelNum_)
  29346. : channelNum (channelNum_)
  29347. {}
  29348. ~ClearChannelOp() {}
  29349. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29350. {
  29351. sharedBufferChans.clear (channelNum, 0, numSamples);
  29352. }
  29353. private:
  29354. const int channelNum;
  29355. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29356. };
  29357. class CopyChannelOp : public AudioGraphRenderingOp
  29358. {
  29359. public:
  29360. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29361. : srcChannelNum (srcChannelNum_),
  29362. dstChannelNum (dstChannelNum_)
  29363. {}
  29364. ~CopyChannelOp() {}
  29365. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29366. {
  29367. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29368. }
  29369. private:
  29370. const int srcChannelNum, dstChannelNum;
  29371. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29372. };
  29373. class AddChannelOp : public AudioGraphRenderingOp
  29374. {
  29375. public:
  29376. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29377. : srcChannelNum (srcChannelNum_),
  29378. dstChannelNum (dstChannelNum_)
  29379. {}
  29380. ~AddChannelOp() {}
  29381. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29382. {
  29383. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29384. }
  29385. private:
  29386. const int srcChannelNum, dstChannelNum;
  29387. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29388. };
  29389. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29390. {
  29391. public:
  29392. ClearMidiBufferOp (const int bufferNum_)
  29393. : bufferNum (bufferNum_)
  29394. {}
  29395. ~ClearMidiBufferOp() {}
  29396. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29397. {
  29398. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29399. }
  29400. private:
  29401. const int bufferNum;
  29402. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29403. };
  29404. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29405. {
  29406. public:
  29407. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29408. : srcBufferNum (srcBufferNum_),
  29409. dstBufferNum (dstBufferNum_)
  29410. {}
  29411. ~CopyMidiBufferOp() {}
  29412. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29413. {
  29414. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29415. }
  29416. private:
  29417. const int srcBufferNum, dstBufferNum;
  29418. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29419. };
  29420. class AddMidiBufferOp : public AudioGraphRenderingOp
  29421. {
  29422. public:
  29423. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29424. : srcBufferNum (srcBufferNum_),
  29425. dstBufferNum (dstBufferNum_)
  29426. {}
  29427. ~AddMidiBufferOp() {}
  29428. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29429. {
  29430. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29431. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29432. }
  29433. private:
  29434. const int srcBufferNum, dstBufferNum;
  29435. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29436. };
  29437. class ProcessBufferOp : public AudioGraphRenderingOp
  29438. {
  29439. public:
  29440. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29441. const Array <int>& audioChannelsToUse_,
  29442. const int totalChans_,
  29443. const int midiBufferToUse_)
  29444. : node (node_),
  29445. processor (node_->getProcessor()),
  29446. audioChannelsToUse (audioChannelsToUse_),
  29447. totalChans (jmax (1, totalChans_)),
  29448. midiBufferToUse (midiBufferToUse_)
  29449. {
  29450. channels.calloc (totalChans);
  29451. while (audioChannelsToUse.size() < totalChans)
  29452. audioChannelsToUse.add (0);
  29453. }
  29454. ~ProcessBufferOp()
  29455. {
  29456. }
  29457. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29458. {
  29459. for (int i = totalChans; --i >= 0;)
  29460. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29461. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29462. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29463. }
  29464. const AudioProcessorGraph::Node::Ptr node;
  29465. AudioProcessor* const processor;
  29466. private:
  29467. Array <int> audioChannelsToUse;
  29468. HeapBlock <float*> channels;
  29469. int totalChans;
  29470. int midiBufferToUse;
  29471. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29472. };
  29473. /** Used to calculate the correct sequence of rendering ops needed, based on
  29474. the best re-use of shared buffers at each stage.
  29475. */
  29476. class RenderingOpSequenceCalculator
  29477. {
  29478. public:
  29479. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29480. const Array<void*>& orderedNodes_,
  29481. Array<void*>& renderingOps)
  29482. : graph (graph_),
  29483. orderedNodes (orderedNodes_)
  29484. {
  29485. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29486. channels.add (0);
  29487. midiNodeIds.add ((uint32) zeroNodeID);
  29488. for (int i = 0; i < orderedNodes.size(); ++i)
  29489. {
  29490. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29491. renderingOps, i);
  29492. markAnyUnusedBuffersAsFree (i);
  29493. }
  29494. }
  29495. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29496. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29497. private:
  29498. AudioProcessorGraph& graph;
  29499. const Array<void*>& orderedNodes;
  29500. Array <int> channels;
  29501. Array <uint32> nodeIds, midiNodeIds;
  29502. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29503. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29504. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29505. Array<void*>& renderingOps,
  29506. const int ourRenderingIndex)
  29507. {
  29508. const int numIns = node->getProcessor()->getNumInputChannels();
  29509. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29510. const int totalChans = jmax (numIns, numOuts);
  29511. Array <int> audioChannelsToUse;
  29512. int midiBufferToUse = -1;
  29513. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29514. {
  29515. // get a list of all the inputs to this node
  29516. Array <int> sourceNodes, sourceOutputChans;
  29517. for (int i = graph.getNumConnections(); --i >= 0;)
  29518. {
  29519. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29520. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29521. {
  29522. sourceNodes.add (c->sourceNodeId);
  29523. sourceOutputChans.add (c->sourceChannelIndex);
  29524. }
  29525. }
  29526. int bufIndex = -1;
  29527. if (sourceNodes.size() == 0)
  29528. {
  29529. // unconnected input channel
  29530. if (inputChan >= numOuts)
  29531. {
  29532. bufIndex = getReadOnlyEmptyBuffer();
  29533. jassert (bufIndex >= 0);
  29534. }
  29535. else
  29536. {
  29537. bufIndex = getFreeBuffer (false);
  29538. renderingOps.add (new ClearChannelOp (bufIndex));
  29539. }
  29540. }
  29541. else if (sourceNodes.size() == 1)
  29542. {
  29543. // channel with a straightforward single input..
  29544. const int srcNode = sourceNodes.getUnchecked(0);
  29545. const int srcChan = sourceOutputChans.getUnchecked(0);
  29546. bufIndex = getBufferContaining (srcNode, srcChan);
  29547. if (bufIndex < 0)
  29548. {
  29549. // if not found, this is probably a feedback loop
  29550. bufIndex = getReadOnlyEmptyBuffer();
  29551. jassert (bufIndex >= 0);
  29552. }
  29553. if (inputChan < numOuts
  29554. && isBufferNeededLater (ourRenderingIndex,
  29555. inputChan,
  29556. srcNode, srcChan))
  29557. {
  29558. // can't mess up this channel because it's needed later by another node, so we
  29559. // need to use a copy of it..
  29560. const int newFreeBuffer = getFreeBuffer (false);
  29561. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29562. bufIndex = newFreeBuffer;
  29563. }
  29564. }
  29565. else
  29566. {
  29567. // channel with a mix of several inputs..
  29568. // try to find a re-usable channel from our inputs..
  29569. int reusableInputIndex = -1;
  29570. for (int i = 0; i < sourceNodes.size(); ++i)
  29571. {
  29572. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29573. sourceOutputChans.getUnchecked(i));
  29574. if (sourceBufIndex >= 0
  29575. && ! isBufferNeededLater (ourRenderingIndex,
  29576. inputChan,
  29577. sourceNodes.getUnchecked(i),
  29578. sourceOutputChans.getUnchecked(i)))
  29579. {
  29580. // we've found one of our input chans that can be re-used..
  29581. reusableInputIndex = i;
  29582. bufIndex = sourceBufIndex;
  29583. break;
  29584. }
  29585. }
  29586. if (reusableInputIndex < 0)
  29587. {
  29588. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29589. bufIndex = getFreeBuffer (false);
  29590. jassert (bufIndex != 0);
  29591. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29592. sourceOutputChans.getUnchecked (0));
  29593. if (srcIndex < 0)
  29594. {
  29595. // if not found, this is probably a feedback loop
  29596. renderingOps.add (new ClearChannelOp (bufIndex));
  29597. }
  29598. else
  29599. {
  29600. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29601. }
  29602. reusableInputIndex = 0;
  29603. }
  29604. for (int j = 0; j < sourceNodes.size(); ++j)
  29605. {
  29606. if (j != reusableInputIndex)
  29607. {
  29608. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29609. sourceOutputChans.getUnchecked(j));
  29610. if (srcIndex >= 0)
  29611. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29612. }
  29613. }
  29614. }
  29615. jassert (bufIndex >= 0);
  29616. audioChannelsToUse.add (bufIndex);
  29617. if (inputChan < numOuts)
  29618. markBufferAsContaining (bufIndex, node->id, inputChan);
  29619. }
  29620. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29621. {
  29622. const int bufIndex = getFreeBuffer (false);
  29623. jassert (bufIndex != 0);
  29624. audioChannelsToUse.add (bufIndex);
  29625. markBufferAsContaining (bufIndex, node->id, outputChan);
  29626. }
  29627. // Now the same thing for midi..
  29628. Array <int> midiSourceNodes;
  29629. for (int i = graph.getNumConnections(); --i >= 0;)
  29630. {
  29631. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29632. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29633. midiSourceNodes.add (c->sourceNodeId);
  29634. }
  29635. if (midiSourceNodes.size() == 0)
  29636. {
  29637. // No midi inputs..
  29638. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29639. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29640. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29641. }
  29642. else if (midiSourceNodes.size() == 1)
  29643. {
  29644. // One midi input..
  29645. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29646. AudioProcessorGraph::midiChannelIndex);
  29647. if (midiBufferToUse >= 0)
  29648. {
  29649. if (isBufferNeededLater (ourRenderingIndex,
  29650. AudioProcessorGraph::midiChannelIndex,
  29651. midiSourceNodes.getUnchecked(0),
  29652. AudioProcessorGraph::midiChannelIndex))
  29653. {
  29654. // can't mess up this channel because it's needed later by another node, so we
  29655. // need to use a copy of it..
  29656. const int newFreeBuffer = getFreeBuffer (true);
  29657. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29658. midiBufferToUse = newFreeBuffer;
  29659. }
  29660. }
  29661. else
  29662. {
  29663. // probably a feedback loop, so just use an empty one..
  29664. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29665. }
  29666. }
  29667. else
  29668. {
  29669. // More than one midi input being mixed..
  29670. int reusableInputIndex = -1;
  29671. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29672. {
  29673. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29674. AudioProcessorGraph::midiChannelIndex);
  29675. if (sourceBufIndex >= 0
  29676. && ! isBufferNeededLater (ourRenderingIndex,
  29677. AudioProcessorGraph::midiChannelIndex,
  29678. midiSourceNodes.getUnchecked(i),
  29679. AudioProcessorGraph::midiChannelIndex))
  29680. {
  29681. // we've found one of our input buffers that can be re-used..
  29682. reusableInputIndex = i;
  29683. midiBufferToUse = sourceBufIndex;
  29684. break;
  29685. }
  29686. }
  29687. if (reusableInputIndex < 0)
  29688. {
  29689. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29690. midiBufferToUse = getFreeBuffer (true);
  29691. jassert (midiBufferToUse >= 0);
  29692. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29693. AudioProcessorGraph::midiChannelIndex);
  29694. if (srcIndex >= 0)
  29695. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29696. else
  29697. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29698. reusableInputIndex = 0;
  29699. }
  29700. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29701. {
  29702. if (j != reusableInputIndex)
  29703. {
  29704. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29705. AudioProcessorGraph::midiChannelIndex);
  29706. if (srcIndex >= 0)
  29707. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29708. }
  29709. }
  29710. }
  29711. if (node->getProcessor()->producesMidi())
  29712. markBufferAsContaining (midiBufferToUse, node->id,
  29713. AudioProcessorGraph::midiChannelIndex);
  29714. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29715. totalChans, midiBufferToUse));
  29716. }
  29717. int getFreeBuffer (const bool forMidi)
  29718. {
  29719. if (forMidi)
  29720. {
  29721. for (int i = 1; i < midiNodeIds.size(); ++i)
  29722. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29723. return i;
  29724. midiNodeIds.add ((uint32) freeNodeID);
  29725. return midiNodeIds.size() - 1;
  29726. }
  29727. else
  29728. {
  29729. for (int i = 1; i < nodeIds.size(); ++i)
  29730. if (nodeIds.getUnchecked(i) == freeNodeID)
  29731. return i;
  29732. nodeIds.add ((uint32) freeNodeID);
  29733. channels.add (0);
  29734. return nodeIds.size() - 1;
  29735. }
  29736. }
  29737. int getReadOnlyEmptyBuffer() const
  29738. {
  29739. return 0;
  29740. }
  29741. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29742. {
  29743. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29744. {
  29745. for (int i = midiNodeIds.size(); --i >= 0;)
  29746. if (midiNodeIds.getUnchecked(i) == nodeId)
  29747. return i;
  29748. }
  29749. else
  29750. {
  29751. for (int i = nodeIds.size(); --i >= 0;)
  29752. if (nodeIds.getUnchecked(i) == nodeId
  29753. && channels.getUnchecked(i) == outputChannel)
  29754. return i;
  29755. }
  29756. return -1;
  29757. }
  29758. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29759. {
  29760. int i;
  29761. for (i = 0; i < nodeIds.size(); ++i)
  29762. {
  29763. if (isNodeBusy (nodeIds.getUnchecked(i))
  29764. && ! isBufferNeededLater (stepIndex, -1,
  29765. nodeIds.getUnchecked(i),
  29766. channels.getUnchecked(i)))
  29767. {
  29768. nodeIds.set (i, (uint32) freeNodeID);
  29769. }
  29770. }
  29771. for (i = 0; i < midiNodeIds.size(); ++i)
  29772. {
  29773. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29774. && ! isBufferNeededLater (stepIndex, -1,
  29775. midiNodeIds.getUnchecked(i),
  29776. AudioProcessorGraph::midiChannelIndex))
  29777. {
  29778. midiNodeIds.set (i, (uint32) freeNodeID);
  29779. }
  29780. }
  29781. }
  29782. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29783. int inputChannelOfIndexToIgnore,
  29784. const uint32 nodeId,
  29785. const int outputChanIndex) const
  29786. {
  29787. while (stepIndexToSearchFrom < orderedNodes.size())
  29788. {
  29789. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29790. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29791. {
  29792. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29793. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29794. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29795. return true;
  29796. }
  29797. else
  29798. {
  29799. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29800. if (i != inputChannelOfIndexToIgnore
  29801. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29802. node->id, i) != 0)
  29803. return true;
  29804. }
  29805. inputChannelOfIndexToIgnore = -1;
  29806. ++stepIndexToSearchFrom;
  29807. }
  29808. return false;
  29809. }
  29810. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29811. {
  29812. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29813. {
  29814. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29815. midiNodeIds.set (bufferNum, nodeId);
  29816. }
  29817. else
  29818. {
  29819. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29820. nodeIds.set (bufferNum, nodeId);
  29821. channels.set (bufferNum, outputIndex);
  29822. }
  29823. }
  29824. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29825. };
  29826. }
  29827. void AudioProcessorGraph::clearRenderingSequence()
  29828. {
  29829. const ScopedLock sl (renderLock);
  29830. for (int i = renderingOps.size(); --i >= 0;)
  29831. {
  29832. GraphRenderingOps::AudioGraphRenderingOp* const r
  29833. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29834. renderingOps.remove (i);
  29835. delete r;
  29836. }
  29837. }
  29838. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29839. const uint32 possibleDestinationId,
  29840. const int recursionCheck) const
  29841. {
  29842. if (recursionCheck > 0)
  29843. {
  29844. for (int i = connections.size(); --i >= 0;)
  29845. {
  29846. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29847. if (c->destNodeId == possibleDestinationId
  29848. && (c->sourceNodeId == possibleInputId
  29849. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29850. return true;
  29851. }
  29852. }
  29853. return false;
  29854. }
  29855. void AudioProcessorGraph::buildRenderingSequence()
  29856. {
  29857. Array<void*> newRenderingOps;
  29858. int numRenderingBuffersNeeded = 2;
  29859. int numMidiBuffersNeeded = 1;
  29860. {
  29861. MessageManagerLock mml;
  29862. Array<void*> orderedNodes;
  29863. int i;
  29864. for (i = 0; i < nodes.size(); ++i)
  29865. {
  29866. Node* const node = nodes.getUnchecked(i);
  29867. node->prepare (getSampleRate(), getBlockSize(), this);
  29868. int j = 0;
  29869. for (; j < orderedNodes.size(); ++j)
  29870. if (isAnInputTo (node->id,
  29871. ((Node*) orderedNodes.getUnchecked (j))->id,
  29872. nodes.size() + 1))
  29873. break;
  29874. orderedNodes.insert (j, node);
  29875. }
  29876. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29877. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29878. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29879. }
  29880. Array<void*> oldRenderingOps (renderingOps);
  29881. {
  29882. // swap over to the new rendering sequence..
  29883. const ScopedLock sl (renderLock);
  29884. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29885. renderingBuffers.clear();
  29886. for (int i = midiBuffers.size(); --i >= 0;)
  29887. midiBuffers.getUnchecked(i)->clear();
  29888. while (midiBuffers.size() < numMidiBuffersNeeded)
  29889. midiBuffers.add (new MidiBuffer());
  29890. renderingOps = newRenderingOps;
  29891. }
  29892. for (int i = oldRenderingOps.size(); --i >= 0;)
  29893. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29894. }
  29895. void AudioProcessorGraph::handleAsyncUpdate()
  29896. {
  29897. buildRenderingSequence();
  29898. }
  29899. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29900. {
  29901. currentAudioInputBuffer = 0;
  29902. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29903. currentMidiInputBuffer = 0;
  29904. currentMidiOutputBuffer.clear();
  29905. clearRenderingSequence();
  29906. buildRenderingSequence();
  29907. }
  29908. void AudioProcessorGraph::releaseResources()
  29909. {
  29910. for (int i = 0; i < nodes.size(); ++i)
  29911. nodes.getUnchecked(i)->unprepare();
  29912. renderingBuffers.setSize (1, 1);
  29913. midiBuffers.clear();
  29914. currentAudioInputBuffer = 0;
  29915. currentAudioOutputBuffer.setSize (1, 1);
  29916. currentMidiInputBuffer = 0;
  29917. currentMidiOutputBuffer.clear();
  29918. }
  29919. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29920. {
  29921. const int numSamples = buffer.getNumSamples();
  29922. const ScopedLock sl (renderLock);
  29923. currentAudioInputBuffer = &buffer;
  29924. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29925. currentAudioOutputBuffer.clear();
  29926. currentMidiInputBuffer = &midiMessages;
  29927. currentMidiOutputBuffer.clear();
  29928. int i;
  29929. for (i = 0; i < renderingOps.size(); ++i)
  29930. {
  29931. GraphRenderingOps::AudioGraphRenderingOp* const op
  29932. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29933. op->perform (renderingBuffers, midiBuffers, numSamples);
  29934. }
  29935. for (i = 0; i < buffer.getNumChannels(); ++i)
  29936. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29937. midiMessages.clear();
  29938. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29939. }
  29940. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29941. {
  29942. return "Input " + String (channelIndex + 1);
  29943. }
  29944. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29945. {
  29946. return "Output " + String (channelIndex + 1);
  29947. }
  29948. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29949. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29950. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29951. bool AudioProcessorGraph::producesMidi() const { return true; }
  29952. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29953. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29954. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29955. : type (type_),
  29956. graph (0)
  29957. {
  29958. }
  29959. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29960. {
  29961. }
  29962. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29963. {
  29964. switch (type)
  29965. {
  29966. case audioOutputNode: return "Audio Output";
  29967. case audioInputNode: return "Audio Input";
  29968. case midiOutputNode: return "Midi Output";
  29969. case midiInputNode: return "Midi Input";
  29970. default: break;
  29971. }
  29972. return String::empty;
  29973. }
  29974. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29975. {
  29976. d.name = getName();
  29977. d.uid = d.name.hashCode();
  29978. d.category = "I/O devices";
  29979. d.pluginFormatName = "Internal";
  29980. d.manufacturerName = "Raw Material Software";
  29981. d.version = "1.0";
  29982. d.isInstrument = false;
  29983. d.numInputChannels = getNumInputChannels();
  29984. if (type == audioOutputNode && graph != 0)
  29985. d.numInputChannels = graph->getNumInputChannels();
  29986. d.numOutputChannels = getNumOutputChannels();
  29987. if (type == audioInputNode && graph != 0)
  29988. d.numOutputChannels = graph->getNumOutputChannels();
  29989. }
  29990. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29991. {
  29992. jassert (graph != 0);
  29993. }
  29994. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29995. {
  29996. }
  29997. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29998. MidiBuffer& midiMessages)
  29999. {
  30000. jassert (graph != 0);
  30001. switch (type)
  30002. {
  30003. case audioOutputNode:
  30004. {
  30005. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  30006. buffer.getNumChannels()); --i >= 0;)
  30007. {
  30008. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  30009. }
  30010. break;
  30011. }
  30012. case audioInputNode:
  30013. {
  30014. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  30015. buffer.getNumChannels()); --i >= 0;)
  30016. {
  30017. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  30018. }
  30019. break;
  30020. }
  30021. case midiOutputNode:
  30022. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  30023. break;
  30024. case midiInputNode:
  30025. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  30026. break;
  30027. default:
  30028. break;
  30029. }
  30030. }
  30031. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  30032. {
  30033. return type == midiOutputNode;
  30034. }
  30035. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  30036. {
  30037. return type == midiInputNode;
  30038. }
  30039. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  30040. {
  30041. switch (type)
  30042. {
  30043. case audioOutputNode: return "Output " + String (channelIndex + 1);
  30044. case midiOutputNode: return "Midi Output";
  30045. default: break;
  30046. }
  30047. return String::empty;
  30048. }
  30049. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  30050. {
  30051. switch (type)
  30052. {
  30053. case audioInputNode: return "Input " + String (channelIndex + 1);
  30054. case midiInputNode: return "Midi Input";
  30055. default: break;
  30056. }
  30057. return String::empty;
  30058. }
  30059. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  30060. {
  30061. return type == audioInputNode || type == audioOutputNode;
  30062. }
  30063. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  30064. {
  30065. return isInputChannelStereoPair (index);
  30066. }
  30067. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  30068. {
  30069. return type == audioInputNode || type == midiInputNode;
  30070. }
  30071. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  30072. {
  30073. return type == audioOutputNode || type == midiOutputNode;
  30074. }
  30075. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  30076. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  30077. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  30078. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  30079. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  30080. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  30081. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  30082. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  30083. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  30084. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  30085. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  30086. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  30087. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  30088. {
  30089. }
  30090. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  30091. {
  30092. }
  30093. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  30094. {
  30095. graph = newGraph;
  30096. if (graph != 0)
  30097. {
  30098. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  30099. type == audioInputNode ? graph->getNumInputChannels() : 0,
  30100. getSampleRate(),
  30101. getBlockSize());
  30102. updateHostDisplay();
  30103. }
  30104. }
  30105. END_JUCE_NAMESPACE
  30106. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30107. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30108. BEGIN_JUCE_NAMESPACE
  30109. AudioProcessorPlayer::AudioProcessorPlayer()
  30110. : processor (0),
  30111. sampleRate (0),
  30112. blockSize (0),
  30113. isPrepared (false),
  30114. numInputChans (0),
  30115. numOutputChans (0),
  30116. tempBuffer (1, 1)
  30117. {
  30118. }
  30119. AudioProcessorPlayer::~AudioProcessorPlayer()
  30120. {
  30121. setProcessor (0);
  30122. }
  30123. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30124. {
  30125. if (processor != processorToPlay)
  30126. {
  30127. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30128. {
  30129. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30130. sampleRate, blockSize);
  30131. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30132. }
  30133. AudioProcessor* oldOne;
  30134. {
  30135. const ScopedLock sl (lock);
  30136. oldOne = isPrepared ? processor : 0;
  30137. processor = processorToPlay;
  30138. isPrepared = true;
  30139. }
  30140. if (oldOne != 0)
  30141. oldOne->releaseResources();
  30142. }
  30143. }
  30144. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30145. const int numInputChannels,
  30146. float** const outputChannelData,
  30147. const int numOutputChannels,
  30148. const int numSamples)
  30149. {
  30150. // these should have been prepared by audioDeviceAboutToStart()...
  30151. jassert (sampleRate > 0 && blockSize > 0);
  30152. incomingMidi.clear();
  30153. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30154. int i, totalNumChans = 0;
  30155. if (numInputChannels > numOutputChannels)
  30156. {
  30157. // if there aren't enough output channels for the number of
  30158. // inputs, we need to create some temporary extra ones (can't
  30159. // use the input data in case it gets written to)
  30160. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30161. false, false, true);
  30162. for (i = 0; i < numOutputChannels; ++i)
  30163. {
  30164. channels[totalNumChans] = outputChannelData[i];
  30165. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30166. ++totalNumChans;
  30167. }
  30168. for (i = numOutputChannels; i < numInputChannels; ++i)
  30169. {
  30170. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30171. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30172. ++totalNumChans;
  30173. }
  30174. }
  30175. else
  30176. {
  30177. for (i = 0; i < numInputChannels; ++i)
  30178. {
  30179. channels[totalNumChans] = outputChannelData[i];
  30180. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30181. ++totalNumChans;
  30182. }
  30183. for (i = numInputChannels; i < numOutputChannels; ++i)
  30184. {
  30185. channels[totalNumChans] = outputChannelData[i];
  30186. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30187. ++totalNumChans;
  30188. }
  30189. }
  30190. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30191. const ScopedLock sl (lock);
  30192. if (processor != 0)
  30193. {
  30194. const ScopedLock sl (processor->getCallbackLock());
  30195. if (processor->isSuspended())
  30196. {
  30197. for (i = 0; i < numOutputChannels; ++i)
  30198. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30199. }
  30200. else
  30201. {
  30202. processor->processBlock (buffer, incomingMidi);
  30203. }
  30204. }
  30205. }
  30206. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30207. {
  30208. const ScopedLock sl (lock);
  30209. sampleRate = device->getCurrentSampleRate();
  30210. blockSize = device->getCurrentBufferSizeSamples();
  30211. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30212. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30213. messageCollector.reset (sampleRate);
  30214. zeromem (channels, sizeof (channels));
  30215. if (processor != 0)
  30216. {
  30217. if (isPrepared)
  30218. processor->releaseResources();
  30219. AudioProcessor* const oldProcessor = processor;
  30220. setProcessor (0);
  30221. setProcessor (oldProcessor);
  30222. }
  30223. }
  30224. void AudioProcessorPlayer::audioDeviceStopped()
  30225. {
  30226. const ScopedLock sl (lock);
  30227. if (processor != 0 && isPrepared)
  30228. processor->releaseResources();
  30229. sampleRate = 0.0;
  30230. blockSize = 0;
  30231. isPrepared = false;
  30232. tempBuffer.setSize (1, 1);
  30233. }
  30234. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30235. {
  30236. messageCollector.addMessageToQueue (message);
  30237. }
  30238. END_JUCE_NAMESPACE
  30239. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30240. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30241. BEGIN_JUCE_NAMESPACE
  30242. class ProcessorParameterPropertyComp : public PropertyComponent,
  30243. public AudioProcessorListener,
  30244. public Timer
  30245. {
  30246. public:
  30247. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30248. : PropertyComponent (name),
  30249. owner (owner_),
  30250. index (index_),
  30251. paramHasChanged (false),
  30252. slider (owner_, index_)
  30253. {
  30254. startTimer (100);
  30255. addAndMakeVisible (&slider);
  30256. owner_.addListener (this);
  30257. }
  30258. ~ProcessorParameterPropertyComp()
  30259. {
  30260. owner.removeListener (this);
  30261. }
  30262. void refresh()
  30263. {
  30264. paramHasChanged = false;
  30265. slider.setValue (owner.getParameter (index), false);
  30266. }
  30267. void audioProcessorChanged (AudioProcessor*) {}
  30268. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30269. {
  30270. if (parameterIndex == index)
  30271. paramHasChanged = true;
  30272. }
  30273. void timerCallback()
  30274. {
  30275. if (paramHasChanged)
  30276. {
  30277. refresh();
  30278. startTimer (1000 / 50);
  30279. }
  30280. else
  30281. {
  30282. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30283. }
  30284. }
  30285. private:
  30286. class ParamSlider : public Slider
  30287. {
  30288. public:
  30289. ParamSlider (AudioProcessor& owner_, const int index_)
  30290. : owner (owner_),
  30291. index (index_)
  30292. {
  30293. setRange (0.0, 1.0, 0.0);
  30294. setSliderStyle (Slider::LinearBar);
  30295. setTextBoxIsEditable (false);
  30296. setScrollWheelEnabled (false);
  30297. }
  30298. void valueChanged()
  30299. {
  30300. const float newVal = (float) getValue();
  30301. if (owner.getParameter (index) != newVal)
  30302. owner.setParameter (index, newVal);
  30303. }
  30304. const String getTextFromValue (double /*value*/)
  30305. {
  30306. return owner.getParameterText (index);
  30307. }
  30308. private:
  30309. AudioProcessor& owner;
  30310. const int index;
  30311. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  30312. };
  30313. AudioProcessor& owner;
  30314. const int index;
  30315. bool volatile paramHasChanged;
  30316. ParamSlider slider;
  30317. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  30318. };
  30319. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30320. : AudioProcessorEditor (owner_)
  30321. {
  30322. jassert (owner_ != 0);
  30323. setOpaque (true);
  30324. addAndMakeVisible (&panel);
  30325. Array <PropertyComponent*> params;
  30326. const int numParams = owner_->getNumParameters();
  30327. int totalHeight = 0;
  30328. for (int i = 0; i < numParams; ++i)
  30329. {
  30330. String name (owner_->getParameterName (i));
  30331. if (name.trim().isEmpty())
  30332. name = "Unnamed";
  30333. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30334. params.add (pc);
  30335. totalHeight += pc->getPreferredHeight();
  30336. }
  30337. panel.addProperties (params);
  30338. setSize (400, jlimit (25, 400, totalHeight));
  30339. }
  30340. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30341. {
  30342. }
  30343. void GenericAudioProcessorEditor::paint (Graphics& g)
  30344. {
  30345. g.fillAll (Colours::white);
  30346. }
  30347. void GenericAudioProcessorEditor::resized()
  30348. {
  30349. panel.setBounds (getLocalBounds());
  30350. }
  30351. END_JUCE_NAMESPACE
  30352. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30353. /*** Start of inlined file: juce_Sampler.cpp ***/
  30354. BEGIN_JUCE_NAMESPACE
  30355. SamplerSound::SamplerSound (const String& name_,
  30356. AudioFormatReader& source,
  30357. const BigInteger& midiNotes_,
  30358. const int midiNoteForNormalPitch,
  30359. const double attackTimeSecs,
  30360. const double releaseTimeSecs,
  30361. const double maxSampleLengthSeconds)
  30362. : name (name_),
  30363. midiNotes (midiNotes_),
  30364. midiRootNote (midiNoteForNormalPitch)
  30365. {
  30366. sourceSampleRate = source.sampleRate;
  30367. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30368. {
  30369. length = 0;
  30370. attackSamples = 0;
  30371. releaseSamples = 0;
  30372. }
  30373. else
  30374. {
  30375. length = jmin ((int) source.lengthInSamples,
  30376. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30377. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30378. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30379. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30380. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30381. }
  30382. }
  30383. SamplerSound::~SamplerSound()
  30384. {
  30385. }
  30386. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30387. {
  30388. return midiNotes [midiNoteNumber];
  30389. }
  30390. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30391. {
  30392. return true;
  30393. }
  30394. SamplerVoice::SamplerVoice()
  30395. : pitchRatio (0.0),
  30396. sourceSamplePosition (0.0),
  30397. lgain (0.0f),
  30398. rgain (0.0f),
  30399. isInAttack (false),
  30400. isInRelease (false)
  30401. {
  30402. }
  30403. SamplerVoice::~SamplerVoice()
  30404. {
  30405. }
  30406. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30407. {
  30408. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30409. }
  30410. void SamplerVoice::startNote (const int midiNoteNumber,
  30411. const float velocity,
  30412. SynthesiserSound* s,
  30413. const int /*currentPitchWheelPosition*/)
  30414. {
  30415. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30416. jassert (sound != 0); // this object can only play SamplerSounds!
  30417. if (sound != 0)
  30418. {
  30419. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30420. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30421. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30422. sourceSamplePosition = 0.0;
  30423. lgain = velocity;
  30424. rgain = velocity;
  30425. isInAttack = (sound->attackSamples > 0);
  30426. isInRelease = false;
  30427. if (isInAttack)
  30428. {
  30429. attackReleaseLevel = 0.0f;
  30430. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30431. }
  30432. else
  30433. {
  30434. attackReleaseLevel = 1.0f;
  30435. attackDelta = 0.0f;
  30436. }
  30437. if (sound->releaseSamples > 0)
  30438. {
  30439. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30440. }
  30441. else
  30442. {
  30443. releaseDelta = 0.0f;
  30444. }
  30445. }
  30446. }
  30447. void SamplerVoice::stopNote (const bool allowTailOff)
  30448. {
  30449. if (allowTailOff)
  30450. {
  30451. isInAttack = false;
  30452. isInRelease = true;
  30453. }
  30454. else
  30455. {
  30456. clearCurrentNote();
  30457. }
  30458. }
  30459. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30460. {
  30461. }
  30462. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30463. const int /*newValue*/)
  30464. {
  30465. }
  30466. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30467. {
  30468. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30469. if (playingSound != 0)
  30470. {
  30471. const float* const inL = playingSound->data->getSampleData (0, 0);
  30472. const float* const inR = playingSound->data->getNumChannels() > 1
  30473. ? playingSound->data->getSampleData (1, 0) : 0;
  30474. float* outL = outputBuffer.getSampleData (0, startSample);
  30475. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30476. while (--numSamples >= 0)
  30477. {
  30478. const int pos = (int) sourceSamplePosition;
  30479. const float alpha = (float) (sourceSamplePosition - pos);
  30480. const float invAlpha = 1.0f - alpha;
  30481. // just using a very simple linear interpolation here..
  30482. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30483. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30484. : l;
  30485. l *= lgain;
  30486. r *= rgain;
  30487. if (isInAttack)
  30488. {
  30489. l *= attackReleaseLevel;
  30490. r *= attackReleaseLevel;
  30491. attackReleaseLevel += attackDelta;
  30492. if (attackReleaseLevel >= 1.0f)
  30493. {
  30494. attackReleaseLevel = 1.0f;
  30495. isInAttack = false;
  30496. }
  30497. }
  30498. else if (isInRelease)
  30499. {
  30500. l *= attackReleaseLevel;
  30501. r *= attackReleaseLevel;
  30502. attackReleaseLevel += releaseDelta;
  30503. if (attackReleaseLevel <= 0.0f)
  30504. {
  30505. stopNote (false);
  30506. break;
  30507. }
  30508. }
  30509. if (outR != 0)
  30510. {
  30511. *outL++ += l;
  30512. *outR++ += r;
  30513. }
  30514. else
  30515. {
  30516. *outL++ += (l + r) * 0.5f;
  30517. }
  30518. sourceSamplePosition += pitchRatio;
  30519. if (sourceSamplePosition > playingSound->length)
  30520. {
  30521. stopNote (false);
  30522. break;
  30523. }
  30524. }
  30525. }
  30526. }
  30527. END_JUCE_NAMESPACE
  30528. /*** End of inlined file: juce_Sampler.cpp ***/
  30529. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30530. BEGIN_JUCE_NAMESPACE
  30531. SynthesiserSound::SynthesiserSound()
  30532. {
  30533. }
  30534. SynthesiserSound::~SynthesiserSound()
  30535. {
  30536. }
  30537. SynthesiserVoice::SynthesiserVoice()
  30538. : currentSampleRate (44100.0),
  30539. currentlyPlayingNote (-1),
  30540. noteOnTime (0),
  30541. currentlyPlayingSound (0)
  30542. {
  30543. }
  30544. SynthesiserVoice::~SynthesiserVoice()
  30545. {
  30546. }
  30547. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30548. {
  30549. return currentlyPlayingSound != 0
  30550. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30551. }
  30552. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30553. {
  30554. currentSampleRate = newRate;
  30555. }
  30556. void SynthesiserVoice::clearCurrentNote()
  30557. {
  30558. currentlyPlayingNote = -1;
  30559. currentlyPlayingSound = 0;
  30560. }
  30561. Synthesiser::Synthesiser()
  30562. : sampleRate (0),
  30563. lastNoteOnCounter (0),
  30564. shouldStealNotes (true)
  30565. {
  30566. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30567. lastPitchWheelValues[i] = 0x2000;
  30568. }
  30569. Synthesiser::~Synthesiser()
  30570. {
  30571. }
  30572. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30573. {
  30574. const ScopedLock sl (lock);
  30575. return voices [index];
  30576. }
  30577. void Synthesiser::clearVoices()
  30578. {
  30579. const ScopedLock sl (lock);
  30580. voices.clear();
  30581. }
  30582. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30583. {
  30584. const ScopedLock sl (lock);
  30585. voices.add (newVoice);
  30586. }
  30587. void Synthesiser::removeVoice (const int index)
  30588. {
  30589. const ScopedLock sl (lock);
  30590. voices.remove (index);
  30591. }
  30592. void Synthesiser::clearSounds()
  30593. {
  30594. const ScopedLock sl (lock);
  30595. sounds.clear();
  30596. }
  30597. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30598. {
  30599. const ScopedLock sl (lock);
  30600. sounds.add (newSound);
  30601. }
  30602. void Synthesiser::removeSound (const int index)
  30603. {
  30604. const ScopedLock sl (lock);
  30605. sounds.remove (index);
  30606. }
  30607. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30608. {
  30609. shouldStealNotes = shouldStealNotes_;
  30610. }
  30611. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30612. {
  30613. if (sampleRate != newRate)
  30614. {
  30615. const ScopedLock sl (lock);
  30616. allNotesOff (0, false);
  30617. sampleRate = newRate;
  30618. for (int i = voices.size(); --i >= 0;)
  30619. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30620. }
  30621. }
  30622. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30623. const MidiBuffer& midiData,
  30624. int startSample,
  30625. int numSamples)
  30626. {
  30627. // must set the sample rate before using this!
  30628. jassert (sampleRate != 0);
  30629. const ScopedLock sl (lock);
  30630. MidiBuffer::Iterator midiIterator (midiData);
  30631. midiIterator.setNextSamplePosition (startSample);
  30632. MidiMessage m (0xf4, 0.0);
  30633. while (numSamples > 0)
  30634. {
  30635. int midiEventPos;
  30636. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30637. && midiEventPos < startSample + numSamples;
  30638. const int numThisTime = useEvent ? midiEventPos - startSample
  30639. : numSamples;
  30640. if (numThisTime > 0)
  30641. {
  30642. for (int i = voices.size(); --i >= 0;)
  30643. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30644. }
  30645. if (useEvent)
  30646. {
  30647. if (m.isNoteOn())
  30648. {
  30649. const int channel = m.getChannel();
  30650. noteOn (channel,
  30651. m.getNoteNumber(),
  30652. m.getFloatVelocity());
  30653. }
  30654. else if (m.isNoteOff())
  30655. {
  30656. noteOff (m.getChannel(),
  30657. m.getNoteNumber(),
  30658. true);
  30659. }
  30660. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30661. {
  30662. allNotesOff (m.getChannel(), true);
  30663. }
  30664. else if (m.isPitchWheel())
  30665. {
  30666. const int channel = m.getChannel();
  30667. const int wheelPos = m.getPitchWheelValue();
  30668. lastPitchWheelValues [channel - 1] = wheelPos;
  30669. handlePitchWheel (channel, wheelPos);
  30670. }
  30671. else if (m.isController())
  30672. {
  30673. handleController (m.getChannel(),
  30674. m.getControllerNumber(),
  30675. m.getControllerValue());
  30676. }
  30677. }
  30678. startSample += numThisTime;
  30679. numSamples -= numThisTime;
  30680. }
  30681. }
  30682. void Synthesiser::noteOn (const int midiChannel,
  30683. const int midiNoteNumber,
  30684. const float velocity)
  30685. {
  30686. const ScopedLock sl (lock);
  30687. for (int i = sounds.size(); --i >= 0;)
  30688. {
  30689. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30690. if (sound->appliesToNote (midiNoteNumber)
  30691. && sound->appliesToChannel (midiChannel))
  30692. {
  30693. startVoice (findFreeVoice (sound, shouldStealNotes),
  30694. sound, midiChannel, midiNoteNumber, velocity);
  30695. }
  30696. }
  30697. }
  30698. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30699. SynthesiserSound* const sound,
  30700. const int midiChannel,
  30701. const int midiNoteNumber,
  30702. const float velocity)
  30703. {
  30704. if (voice != 0 && sound != 0)
  30705. {
  30706. if (voice->currentlyPlayingSound != 0)
  30707. voice->stopNote (false);
  30708. voice->startNote (midiNoteNumber,
  30709. velocity,
  30710. sound,
  30711. lastPitchWheelValues [midiChannel - 1]);
  30712. voice->currentlyPlayingNote = midiNoteNumber;
  30713. voice->noteOnTime = ++lastNoteOnCounter;
  30714. voice->currentlyPlayingSound = sound;
  30715. }
  30716. }
  30717. void Synthesiser::noteOff (const int midiChannel,
  30718. const int midiNoteNumber,
  30719. const bool allowTailOff)
  30720. {
  30721. const ScopedLock sl (lock);
  30722. for (int i = voices.size(); --i >= 0;)
  30723. {
  30724. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30725. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30726. {
  30727. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30728. if (sound != 0
  30729. && sound->appliesToNote (midiNoteNumber)
  30730. && sound->appliesToChannel (midiChannel))
  30731. {
  30732. voice->stopNote (allowTailOff);
  30733. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30734. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30735. }
  30736. }
  30737. }
  30738. }
  30739. void Synthesiser::allNotesOff (const int midiChannel,
  30740. const bool allowTailOff)
  30741. {
  30742. const ScopedLock sl (lock);
  30743. for (int i = voices.size(); --i >= 0;)
  30744. {
  30745. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30746. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30747. voice->stopNote (allowTailOff);
  30748. }
  30749. }
  30750. void Synthesiser::handlePitchWheel (const int midiChannel,
  30751. const int wheelValue)
  30752. {
  30753. const ScopedLock sl (lock);
  30754. for (int i = voices.size(); --i >= 0;)
  30755. {
  30756. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30757. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30758. {
  30759. voice->pitchWheelMoved (wheelValue);
  30760. }
  30761. }
  30762. }
  30763. void Synthesiser::handleController (const int midiChannel,
  30764. const int controllerNumber,
  30765. const int controllerValue)
  30766. {
  30767. const ScopedLock sl (lock);
  30768. for (int i = voices.size(); --i >= 0;)
  30769. {
  30770. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30771. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30772. voice->controllerMoved (controllerNumber, controllerValue);
  30773. }
  30774. }
  30775. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30776. const bool stealIfNoneAvailable) const
  30777. {
  30778. const ScopedLock sl (lock);
  30779. for (int i = voices.size(); --i >= 0;)
  30780. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30781. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30782. return voices.getUnchecked (i);
  30783. if (stealIfNoneAvailable)
  30784. {
  30785. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30786. SynthesiserVoice* oldest = 0;
  30787. for (int i = voices.size(); --i >= 0;)
  30788. {
  30789. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30790. if (voice->canPlaySound (soundToPlay)
  30791. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30792. oldest = voice;
  30793. }
  30794. jassert (oldest != 0);
  30795. return oldest;
  30796. }
  30797. return 0;
  30798. }
  30799. END_JUCE_NAMESPACE
  30800. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30801. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30802. BEGIN_JUCE_NAMESPACE
  30803. // special message of our own with a string in it
  30804. class ActionMessage : public Message
  30805. {
  30806. public:
  30807. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30808. : message (messageText)
  30809. {
  30810. pointerParameter = listener_;
  30811. }
  30812. const String message;
  30813. private:
  30814. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30815. };
  30816. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30817. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30818. {
  30819. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30820. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30821. if (owner->actionListeners.contains (target))
  30822. target->actionListenerCallback (am.message);
  30823. }
  30824. ActionBroadcaster::ActionBroadcaster()
  30825. {
  30826. // are you trying to create this object before or after juce has been intialised??
  30827. jassert (MessageManager::instance != 0);
  30828. callback.owner = this;
  30829. }
  30830. ActionBroadcaster::~ActionBroadcaster()
  30831. {
  30832. // all event-based objects must be deleted BEFORE juce is shut down!
  30833. jassert (MessageManager::instance != 0);
  30834. }
  30835. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30836. {
  30837. const ScopedLock sl (actionListenerLock);
  30838. if (listener != 0)
  30839. actionListeners.add (listener);
  30840. }
  30841. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30842. {
  30843. const ScopedLock sl (actionListenerLock);
  30844. actionListeners.removeValue (listener);
  30845. }
  30846. void ActionBroadcaster::removeAllActionListeners()
  30847. {
  30848. const ScopedLock sl (actionListenerLock);
  30849. actionListeners.clear();
  30850. }
  30851. void ActionBroadcaster::sendActionMessage (const String& message) const
  30852. {
  30853. const ScopedLock sl (actionListenerLock);
  30854. for (int i = actionListeners.size(); --i >= 0;)
  30855. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30856. }
  30857. END_JUCE_NAMESPACE
  30858. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30859. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30860. BEGIN_JUCE_NAMESPACE
  30861. class AsyncUpdaterMessage : public CallbackMessage
  30862. {
  30863. public:
  30864. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30865. : owner (owner_)
  30866. {
  30867. }
  30868. void messageCallback()
  30869. {
  30870. if (shouldDeliver.compareAndSetBool (0, 1))
  30871. owner.handleAsyncUpdate();
  30872. }
  30873. Atomic<int> shouldDeliver;
  30874. private:
  30875. AsyncUpdater& owner;
  30876. };
  30877. AsyncUpdater::AsyncUpdater()
  30878. {
  30879. message = new AsyncUpdaterMessage (*this);
  30880. }
  30881. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30882. {
  30883. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30884. }
  30885. AsyncUpdater::~AsyncUpdater()
  30886. {
  30887. // You're deleting this object with a background thread while there's an update
  30888. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30889. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30890. // deleting this object, or find some other way to avoid such a race condition.
  30891. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30892. getDeliveryFlag().set (0);
  30893. }
  30894. void AsyncUpdater::triggerAsyncUpdate()
  30895. {
  30896. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30897. message->post();
  30898. }
  30899. void AsyncUpdater::cancelPendingUpdate() throw()
  30900. {
  30901. getDeliveryFlag().set (0);
  30902. }
  30903. void AsyncUpdater::handleUpdateNowIfNeeded()
  30904. {
  30905. // This can only be called by the event thread.
  30906. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30907. if (getDeliveryFlag().exchange (0) != 0)
  30908. handleAsyncUpdate();
  30909. }
  30910. bool AsyncUpdater::isUpdatePending() const throw()
  30911. {
  30912. return getDeliveryFlag().value != 0;
  30913. }
  30914. END_JUCE_NAMESPACE
  30915. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30916. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30917. BEGIN_JUCE_NAMESPACE
  30918. ChangeBroadcaster::ChangeBroadcaster() throw()
  30919. {
  30920. // are you trying to create this object before or after juce has been intialised??
  30921. jassert (MessageManager::instance != 0);
  30922. callback.owner = this;
  30923. }
  30924. ChangeBroadcaster::~ChangeBroadcaster()
  30925. {
  30926. // all event-based objects must be deleted BEFORE juce is shut down!
  30927. jassert (MessageManager::instance != 0);
  30928. }
  30929. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30930. {
  30931. // Listeners can only be safely added when the event thread is locked
  30932. // You can use a MessageManagerLock if you need to call this from another thread.
  30933. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30934. changeListeners.add (listener);
  30935. }
  30936. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30937. {
  30938. // Listeners can only be safely added when the event thread is locked
  30939. // You can use a MessageManagerLock if you need to call this from another thread.
  30940. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30941. changeListeners.remove (listener);
  30942. }
  30943. void ChangeBroadcaster::removeAllChangeListeners()
  30944. {
  30945. // Listeners can only be safely added when the event thread is locked
  30946. // You can use a MessageManagerLock if you need to call this from another thread.
  30947. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30948. changeListeners.clear();
  30949. }
  30950. void ChangeBroadcaster::sendChangeMessage()
  30951. {
  30952. if (changeListeners.size() > 0)
  30953. callback.triggerAsyncUpdate();
  30954. }
  30955. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30956. {
  30957. // This can only be called by the event thread.
  30958. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30959. callback.cancelPendingUpdate();
  30960. callListeners();
  30961. }
  30962. void ChangeBroadcaster::dispatchPendingMessages()
  30963. {
  30964. callback.handleUpdateNowIfNeeded();
  30965. }
  30966. void ChangeBroadcaster::callListeners()
  30967. {
  30968. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30969. }
  30970. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30971. : owner (0)
  30972. {
  30973. }
  30974. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30975. {
  30976. jassert (owner != 0);
  30977. owner->callListeners();
  30978. }
  30979. END_JUCE_NAMESPACE
  30980. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30981. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30982. BEGIN_JUCE_NAMESPACE
  30983. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30984. const uint32 magicMessageHeaderNumber)
  30985. : Thread ("Juce IPC connection"),
  30986. callbackConnectionState (false),
  30987. useMessageThread (callbacksOnMessageThread),
  30988. magicMessageHeader (magicMessageHeaderNumber),
  30989. pipeReceiveMessageTimeout (-1)
  30990. {
  30991. }
  30992. InterprocessConnection::~InterprocessConnection()
  30993. {
  30994. callbackConnectionState = false;
  30995. disconnect();
  30996. }
  30997. bool InterprocessConnection::connectToSocket (const String& hostName,
  30998. const int portNumber,
  30999. const int timeOutMillisecs)
  31000. {
  31001. disconnect();
  31002. const ScopedLock sl (pipeAndSocketLock);
  31003. socket = new StreamingSocket();
  31004. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  31005. {
  31006. connectionMadeInt();
  31007. startThread();
  31008. return true;
  31009. }
  31010. else
  31011. {
  31012. socket = 0;
  31013. return false;
  31014. }
  31015. }
  31016. bool InterprocessConnection::connectToPipe (const String& pipeName,
  31017. const int pipeReceiveMessageTimeoutMs)
  31018. {
  31019. disconnect();
  31020. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31021. if (newPipe->openExisting (pipeName))
  31022. {
  31023. const ScopedLock sl (pipeAndSocketLock);
  31024. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31025. initialiseWithPipe (newPipe.release());
  31026. return true;
  31027. }
  31028. return false;
  31029. }
  31030. bool InterprocessConnection::createPipe (const String& pipeName,
  31031. const int pipeReceiveMessageTimeoutMs)
  31032. {
  31033. disconnect();
  31034. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31035. if (newPipe->createNewPipe (pipeName))
  31036. {
  31037. const ScopedLock sl (pipeAndSocketLock);
  31038. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31039. initialiseWithPipe (newPipe.release());
  31040. return true;
  31041. }
  31042. return false;
  31043. }
  31044. void InterprocessConnection::disconnect()
  31045. {
  31046. if (socket != 0)
  31047. socket->close();
  31048. if (pipe != 0)
  31049. {
  31050. pipe->cancelPendingReads();
  31051. pipe->close();
  31052. }
  31053. stopThread (4000);
  31054. {
  31055. const ScopedLock sl (pipeAndSocketLock);
  31056. socket = 0;
  31057. pipe = 0;
  31058. }
  31059. connectionLostInt();
  31060. }
  31061. bool InterprocessConnection::isConnected() const
  31062. {
  31063. const ScopedLock sl (pipeAndSocketLock);
  31064. return ((socket != 0 && socket->isConnected())
  31065. || (pipe != 0 && pipe->isOpen()))
  31066. && isThreadRunning();
  31067. }
  31068. const String InterprocessConnection::getConnectedHostName() const
  31069. {
  31070. if (pipe != 0)
  31071. {
  31072. return "localhost";
  31073. }
  31074. else if (socket != 0)
  31075. {
  31076. if (! socket->isLocal())
  31077. return socket->getHostName();
  31078. return "localhost";
  31079. }
  31080. return String::empty;
  31081. }
  31082. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31083. {
  31084. uint32 messageHeader[2];
  31085. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31086. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31087. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31088. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31089. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31090. size_t bytesWritten = 0;
  31091. const ScopedLock sl (pipeAndSocketLock);
  31092. if (socket != 0)
  31093. {
  31094. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31095. }
  31096. else if (pipe != 0)
  31097. {
  31098. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31099. }
  31100. if (bytesWritten < 0)
  31101. {
  31102. // error..
  31103. return false;
  31104. }
  31105. return (bytesWritten == messageData.getSize());
  31106. }
  31107. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31108. {
  31109. jassert (socket == 0);
  31110. socket = socket_;
  31111. connectionMadeInt();
  31112. startThread();
  31113. }
  31114. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31115. {
  31116. jassert (pipe == 0);
  31117. pipe = pipe_;
  31118. connectionMadeInt();
  31119. startThread();
  31120. }
  31121. const int messageMagicNumber = 0xb734128b;
  31122. void InterprocessConnection::handleMessage (const Message& message)
  31123. {
  31124. if (message.intParameter1 == messageMagicNumber)
  31125. {
  31126. switch (message.intParameter2)
  31127. {
  31128. case 0:
  31129. {
  31130. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31131. messageReceived (*data);
  31132. break;
  31133. }
  31134. case 1:
  31135. connectionMade();
  31136. break;
  31137. case 2:
  31138. connectionLost();
  31139. break;
  31140. }
  31141. }
  31142. }
  31143. void InterprocessConnection::connectionMadeInt()
  31144. {
  31145. if (! callbackConnectionState)
  31146. {
  31147. callbackConnectionState = true;
  31148. if (useMessageThread)
  31149. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31150. else
  31151. connectionMade();
  31152. }
  31153. }
  31154. void InterprocessConnection::connectionLostInt()
  31155. {
  31156. if (callbackConnectionState)
  31157. {
  31158. callbackConnectionState = false;
  31159. if (useMessageThread)
  31160. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31161. else
  31162. connectionLost();
  31163. }
  31164. }
  31165. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31166. {
  31167. jassert (callbackConnectionState);
  31168. if (useMessageThread)
  31169. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31170. else
  31171. messageReceived (data);
  31172. }
  31173. bool InterprocessConnection::readNextMessageInt()
  31174. {
  31175. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31176. uint32 messageHeader[2];
  31177. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31178. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31179. if (bytes == sizeof (messageHeader)
  31180. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31181. {
  31182. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31183. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31184. {
  31185. MemoryBlock messageData (bytesInMessage, true);
  31186. int bytesRead = 0;
  31187. while (bytesInMessage > 0)
  31188. {
  31189. if (threadShouldExit())
  31190. return false;
  31191. const int numThisTime = jmin (bytesInMessage, 65536);
  31192. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31193. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31194. if (bytesIn <= 0)
  31195. break;
  31196. bytesRead += bytesIn;
  31197. bytesInMessage -= bytesIn;
  31198. }
  31199. if (bytesRead >= 0)
  31200. deliverDataInt (messageData);
  31201. }
  31202. }
  31203. else if (bytes < 0)
  31204. {
  31205. {
  31206. const ScopedLock sl (pipeAndSocketLock);
  31207. socket = 0;
  31208. }
  31209. connectionLostInt();
  31210. return false;
  31211. }
  31212. return true;
  31213. }
  31214. void InterprocessConnection::run()
  31215. {
  31216. while (! threadShouldExit())
  31217. {
  31218. if (socket != 0)
  31219. {
  31220. const int ready = socket->waitUntilReady (true, 0);
  31221. if (ready < 0)
  31222. {
  31223. {
  31224. const ScopedLock sl (pipeAndSocketLock);
  31225. socket = 0;
  31226. }
  31227. connectionLostInt();
  31228. break;
  31229. }
  31230. else if (ready > 0)
  31231. {
  31232. if (! readNextMessageInt())
  31233. break;
  31234. }
  31235. else
  31236. {
  31237. Thread::sleep (2);
  31238. }
  31239. }
  31240. else if (pipe != 0)
  31241. {
  31242. if (! pipe->isOpen())
  31243. {
  31244. {
  31245. const ScopedLock sl (pipeAndSocketLock);
  31246. pipe = 0;
  31247. }
  31248. connectionLostInt();
  31249. break;
  31250. }
  31251. else
  31252. {
  31253. if (! readNextMessageInt())
  31254. break;
  31255. }
  31256. }
  31257. else
  31258. {
  31259. break;
  31260. }
  31261. }
  31262. }
  31263. END_JUCE_NAMESPACE
  31264. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31265. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31266. BEGIN_JUCE_NAMESPACE
  31267. InterprocessConnectionServer::InterprocessConnectionServer()
  31268. : Thread ("Juce IPC server")
  31269. {
  31270. }
  31271. InterprocessConnectionServer::~InterprocessConnectionServer()
  31272. {
  31273. stop();
  31274. }
  31275. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31276. {
  31277. stop();
  31278. socket = new StreamingSocket();
  31279. if (socket->createListener (portNumber))
  31280. {
  31281. startThread();
  31282. return true;
  31283. }
  31284. socket = 0;
  31285. return false;
  31286. }
  31287. void InterprocessConnectionServer::stop()
  31288. {
  31289. signalThreadShouldExit();
  31290. if (socket != 0)
  31291. socket->close();
  31292. stopThread (4000);
  31293. socket = 0;
  31294. }
  31295. void InterprocessConnectionServer::run()
  31296. {
  31297. while ((! threadShouldExit()) && socket != 0)
  31298. {
  31299. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31300. if (clientSocket != 0)
  31301. {
  31302. InterprocessConnection* newConnection = createConnectionObject();
  31303. if (newConnection != 0)
  31304. newConnection->initialiseWithSocket (clientSocket.release());
  31305. }
  31306. }
  31307. }
  31308. END_JUCE_NAMESPACE
  31309. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31310. /*** Start of inlined file: juce_Message.cpp ***/
  31311. BEGIN_JUCE_NAMESPACE
  31312. Message::Message() throw()
  31313. : intParameter1 (0),
  31314. intParameter2 (0),
  31315. intParameter3 (0),
  31316. pointerParameter (0),
  31317. messageRecipient (0)
  31318. {
  31319. }
  31320. Message::Message (const int intParameter1_,
  31321. const int intParameter2_,
  31322. const int intParameter3_,
  31323. void* const pointerParameter_) throw()
  31324. : intParameter1 (intParameter1_),
  31325. intParameter2 (intParameter2_),
  31326. intParameter3 (intParameter3_),
  31327. pointerParameter (pointerParameter_),
  31328. messageRecipient (0)
  31329. {
  31330. }
  31331. Message::~Message()
  31332. {
  31333. }
  31334. END_JUCE_NAMESPACE
  31335. /*** End of inlined file: juce_Message.cpp ***/
  31336. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31337. BEGIN_JUCE_NAMESPACE
  31338. MessageListener::MessageListener() throw()
  31339. {
  31340. // are you trying to create a messagelistener before or after juce has been intialised??
  31341. jassert (MessageManager::instance != 0);
  31342. if (MessageManager::instance != 0)
  31343. MessageManager::instance->messageListeners.add (this);
  31344. }
  31345. MessageListener::~MessageListener()
  31346. {
  31347. if (MessageManager::instance != 0)
  31348. MessageManager::instance->messageListeners.removeValue (this);
  31349. }
  31350. void MessageListener::postMessage (Message* const message) const throw()
  31351. {
  31352. message->messageRecipient = const_cast <MessageListener*> (this);
  31353. if (MessageManager::instance == 0)
  31354. MessageManager::getInstance();
  31355. MessageManager::instance->postMessageToQueue (message);
  31356. }
  31357. bool MessageListener::isValidMessageListener() const throw()
  31358. {
  31359. return (MessageManager::instance != 0)
  31360. && MessageManager::instance->messageListeners.contains (this);
  31361. }
  31362. END_JUCE_NAMESPACE
  31363. /*** End of inlined file: juce_MessageListener.cpp ***/
  31364. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31365. BEGIN_JUCE_NAMESPACE
  31366. // platform-specific functions..
  31367. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31368. bool juce_postMessageToSystemQueue (Message* message);
  31369. MessageManager* MessageManager::instance = 0;
  31370. static const int quitMessageId = 0xfffff321;
  31371. MessageManager::MessageManager() throw()
  31372. : quitMessagePosted (false),
  31373. quitMessageReceived (false),
  31374. threadWithLock (0)
  31375. {
  31376. messageThreadId = Thread::getCurrentThreadId();
  31377. if (JUCEApplication::isStandaloneApp())
  31378. Thread::setCurrentThreadName ("Juce Message Thread");
  31379. }
  31380. MessageManager::~MessageManager() throw()
  31381. {
  31382. broadcaster = 0;
  31383. doPlatformSpecificShutdown();
  31384. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31385. jassert (messageListeners.size() == 0);
  31386. jassert (instance == this);
  31387. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31388. }
  31389. MessageManager* MessageManager::getInstance() throw()
  31390. {
  31391. if (instance == 0)
  31392. {
  31393. instance = new MessageManager();
  31394. doPlatformSpecificInitialisation();
  31395. }
  31396. return instance;
  31397. }
  31398. void MessageManager::postMessageToQueue (Message* const message)
  31399. {
  31400. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31401. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31402. }
  31403. CallbackMessage::CallbackMessage() throw() {}
  31404. CallbackMessage::~CallbackMessage() {}
  31405. void CallbackMessage::post()
  31406. {
  31407. if (MessageManager::instance != 0)
  31408. MessageManager::instance->postMessageToQueue (this);
  31409. }
  31410. // not for public use..
  31411. void MessageManager::deliverMessage (Message* const message)
  31412. {
  31413. JUCE_TRY
  31414. {
  31415. MessageListener* const recipient = message->messageRecipient;
  31416. if (recipient == 0)
  31417. {
  31418. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31419. if (callbackMessage != 0)
  31420. {
  31421. callbackMessage->messageCallback();
  31422. }
  31423. else if (message->intParameter1 == quitMessageId)
  31424. {
  31425. quitMessageReceived = true;
  31426. }
  31427. }
  31428. else if (messageListeners.contains (recipient))
  31429. {
  31430. recipient->handleMessage (*message);
  31431. }
  31432. }
  31433. JUCE_CATCH_EXCEPTION
  31434. }
  31435. #if ! (JUCE_MAC || JUCE_IOS)
  31436. void MessageManager::runDispatchLoop()
  31437. {
  31438. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31439. runDispatchLoopUntil (-1);
  31440. }
  31441. void MessageManager::stopDispatchLoop()
  31442. {
  31443. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31444. quitMessagePosted = true;
  31445. }
  31446. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31447. {
  31448. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31449. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31450. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31451. && ! quitMessageReceived)
  31452. {
  31453. JUCE_TRY
  31454. {
  31455. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31456. {
  31457. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31458. if (msToWait > 0)
  31459. Thread::sleep (jmin (5, msToWait));
  31460. }
  31461. }
  31462. JUCE_CATCH_EXCEPTION
  31463. }
  31464. return ! quitMessageReceived;
  31465. }
  31466. #endif
  31467. void MessageManager::deliverBroadcastMessage (const String& value)
  31468. {
  31469. if (broadcaster != 0)
  31470. broadcaster->sendActionMessage (value);
  31471. }
  31472. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31473. {
  31474. if (broadcaster == 0)
  31475. broadcaster = new ActionBroadcaster();
  31476. broadcaster->addActionListener (listener);
  31477. }
  31478. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31479. {
  31480. if (broadcaster != 0)
  31481. broadcaster->removeActionListener (listener);
  31482. }
  31483. bool MessageManager::isThisTheMessageThread() const throw()
  31484. {
  31485. return Thread::getCurrentThreadId() == messageThreadId;
  31486. }
  31487. void MessageManager::setCurrentThreadAsMessageThread()
  31488. {
  31489. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31490. if (messageThreadId != thisThread)
  31491. {
  31492. messageThreadId = thisThread;
  31493. // This is needed on windows to make sure the message window is created by this thread
  31494. doPlatformSpecificShutdown();
  31495. doPlatformSpecificInitialisation();
  31496. }
  31497. }
  31498. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31499. {
  31500. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31501. return thisThread == messageThreadId || thisThread == threadWithLock;
  31502. }
  31503. /* The only safe way to lock the message thread while another thread does
  31504. some work is by posting a special message, whose purpose is to tie up the event
  31505. loop until the other thread has finished its business.
  31506. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31507. get locked before making an event callback, because if the same OS lock gets indirectly
  31508. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31509. in Cocoa).
  31510. */
  31511. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31512. {
  31513. public:
  31514. BlockingMessage() {}
  31515. void messageCallback()
  31516. {
  31517. lockedEvent.signal();
  31518. releaseEvent.wait();
  31519. }
  31520. WaitableEvent lockedEvent, releaseEvent;
  31521. private:
  31522. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31523. };
  31524. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31525. : locked (false)
  31526. {
  31527. init (threadToCheck, 0);
  31528. }
  31529. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31530. : locked (false)
  31531. {
  31532. init (0, jobToCheckForExitSignal);
  31533. }
  31534. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31535. {
  31536. if (MessageManager::instance != 0)
  31537. {
  31538. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31539. {
  31540. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31541. }
  31542. else
  31543. {
  31544. if (threadToCheck == 0 && job == 0)
  31545. {
  31546. MessageManager::instance->lockingLock.enter();
  31547. }
  31548. else
  31549. {
  31550. while (! MessageManager::instance->lockingLock.tryEnter())
  31551. {
  31552. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31553. || (job != 0 && job->shouldExit()))
  31554. return;
  31555. Thread::sleep (1);
  31556. }
  31557. }
  31558. blockingMessage = new BlockingMessage();
  31559. blockingMessage->post();
  31560. while (! blockingMessage->lockedEvent.wait (20))
  31561. {
  31562. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31563. || (job != 0 && job->shouldExit()))
  31564. {
  31565. blockingMessage->releaseEvent.signal();
  31566. blockingMessage = 0;
  31567. MessageManager::instance->lockingLock.exit();
  31568. return;
  31569. }
  31570. }
  31571. jassert (MessageManager::instance->threadWithLock == 0);
  31572. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31573. locked = true;
  31574. }
  31575. }
  31576. }
  31577. MessageManagerLock::~MessageManagerLock() throw()
  31578. {
  31579. if (blockingMessage != 0)
  31580. {
  31581. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31582. blockingMessage->releaseEvent.signal();
  31583. blockingMessage = 0;
  31584. if (MessageManager::instance != 0)
  31585. {
  31586. MessageManager::instance->threadWithLock = 0;
  31587. MessageManager::instance->lockingLock.exit();
  31588. }
  31589. }
  31590. }
  31591. END_JUCE_NAMESPACE
  31592. /*** End of inlined file: juce_MessageManager.cpp ***/
  31593. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31594. BEGIN_JUCE_NAMESPACE
  31595. class MultiTimer::MultiTimerCallback : public Timer
  31596. {
  31597. public:
  31598. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31599. : timerId (timerId_),
  31600. owner (owner_)
  31601. {
  31602. }
  31603. ~MultiTimerCallback()
  31604. {
  31605. }
  31606. void timerCallback()
  31607. {
  31608. owner.timerCallback (timerId);
  31609. }
  31610. const int timerId;
  31611. private:
  31612. MultiTimer& owner;
  31613. };
  31614. MultiTimer::MultiTimer() throw()
  31615. {
  31616. }
  31617. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31618. {
  31619. }
  31620. MultiTimer::~MultiTimer()
  31621. {
  31622. const ScopedLock sl (timerListLock);
  31623. timers.clear();
  31624. }
  31625. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31626. {
  31627. const ScopedLock sl (timerListLock);
  31628. for (int i = timers.size(); --i >= 0;)
  31629. {
  31630. MultiTimerCallback* const t = timers.getUnchecked(i);
  31631. if (t->timerId == timerId)
  31632. {
  31633. t->startTimer (intervalInMilliseconds);
  31634. return;
  31635. }
  31636. }
  31637. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31638. timers.add (newTimer);
  31639. newTimer->startTimer (intervalInMilliseconds);
  31640. }
  31641. void MultiTimer::stopTimer (const int timerId) throw()
  31642. {
  31643. const ScopedLock sl (timerListLock);
  31644. for (int i = timers.size(); --i >= 0;)
  31645. {
  31646. MultiTimerCallback* const t = timers.getUnchecked(i);
  31647. if (t->timerId == timerId)
  31648. t->stopTimer();
  31649. }
  31650. }
  31651. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31652. {
  31653. const ScopedLock sl (timerListLock);
  31654. for (int i = timers.size(); --i >= 0;)
  31655. {
  31656. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31657. if (t->timerId == timerId)
  31658. return t->isTimerRunning();
  31659. }
  31660. return false;
  31661. }
  31662. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31663. {
  31664. const ScopedLock sl (timerListLock);
  31665. for (int i = timers.size(); --i >= 0;)
  31666. {
  31667. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31668. if (t->timerId == timerId)
  31669. return t->getTimerInterval();
  31670. }
  31671. return 0;
  31672. }
  31673. END_JUCE_NAMESPACE
  31674. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31675. /*** Start of inlined file: juce_Timer.cpp ***/
  31676. BEGIN_JUCE_NAMESPACE
  31677. class InternalTimerThread : private Thread,
  31678. private MessageListener,
  31679. private DeletedAtShutdown,
  31680. private AsyncUpdater
  31681. {
  31682. public:
  31683. InternalTimerThread()
  31684. : Thread ("Juce Timer"),
  31685. firstTimer (0),
  31686. callbackNeeded (0)
  31687. {
  31688. triggerAsyncUpdate();
  31689. }
  31690. ~InternalTimerThread() throw()
  31691. {
  31692. stopThread (4000);
  31693. jassert (instance == this || instance == 0);
  31694. if (instance == this)
  31695. instance = 0;
  31696. }
  31697. void run()
  31698. {
  31699. uint32 lastTime = Time::getMillisecondCounter();
  31700. Message::Ptr message (new Message());
  31701. while (! threadShouldExit())
  31702. {
  31703. const uint32 now = Time::getMillisecondCounter();
  31704. if (now <= lastTime)
  31705. {
  31706. wait (2);
  31707. continue;
  31708. }
  31709. const int elapsed = now - lastTime;
  31710. lastTime = now;
  31711. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31712. if (timeUntilFirstTimer <= 0)
  31713. {
  31714. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31715. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31716. but if it fails it means the message-thread changed the value from under us so at least
  31717. some processing is happenening and we can just loop around and try again
  31718. */
  31719. if (callbackNeeded.compareAndSetBool (1, 0))
  31720. {
  31721. postMessage (message);
  31722. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31723. when the app has a modal loop), so this is how long to wait before assuming the
  31724. message has been lost and trying again.
  31725. */
  31726. const uint32 messageDeliveryTimeout = now + 2000;
  31727. while (callbackNeeded.get() != 0)
  31728. {
  31729. wait (4);
  31730. if (threadShouldExit())
  31731. return;
  31732. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31733. break;
  31734. }
  31735. }
  31736. }
  31737. else
  31738. {
  31739. // don't wait for too long because running this loop also helps keep the
  31740. // Time::getApproximateMillisecondTimer value stay up-to-date
  31741. wait (jlimit (1, 50, timeUntilFirstTimer));
  31742. }
  31743. }
  31744. }
  31745. void callTimers()
  31746. {
  31747. const ScopedLock sl (lock);
  31748. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31749. {
  31750. Timer* const t = firstTimer;
  31751. t->countdownMs = t->periodMs;
  31752. removeTimer (t);
  31753. addTimer (t);
  31754. const ScopedUnlock ul (lock);
  31755. JUCE_TRY
  31756. {
  31757. t->timerCallback();
  31758. }
  31759. JUCE_CATCH_EXCEPTION
  31760. }
  31761. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31762. before the boolean is set. This set should never fail since if it was false in the first place,
  31763. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31764. get a message then the value is true and the other thread can only set it to true again and
  31765. we will get another callback to set it to false.
  31766. */
  31767. callbackNeeded.set (0);
  31768. }
  31769. void handleMessage (const Message&)
  31770. {
  31771. callTimers();
  31772. }
  31773. void callTimersSynchronously()
  31774. {
  31775. if (! isThreadRunning())
  31776. {
  31777. // (This is relied on by some plugins in cases where the MM has
  31778. // had to restart and the async callback never started)
  31779. cancelPendingUpdate();
  31780. triggerAsyncUpdate();
  31781. }
  31782. callTimers();
  31783. }
  31784. static void callAnyTimersSynchronously()
  31785. {
  31786. if (InternalTimerThread::instance != 0)
  31787. InternalTimerThread::instance->callTimersSynchronously();
  31788. }
  31789. static inline void add (Timer* const tim) throw()
  31790. {
  31791. if (instance == 0)
  31792. instance = new InternalTimerThread();
  31793. const ScopedLock sl (instance->lock);
  31794. instance->addTimer (tim);
  31795. }
  31796. static inline void remove (Timer* const tim) throw()
  31797. {
  31798. if (instance != 0)
  31799. {
  31800. const ScopedLock sl (instance->lock);
  31801. instance->removeTimer (tim);
  31802. }
  31803. }
  31804. static inline void resetCounter (Timer* const tim,
  31805. const int newCounter) throw()
  31806. {
  31807. if (instance != 0)
  31808. {
  31809. tim->countdownMs = newCounter;
  31810. tim->periodMs = newCounter;
  31811. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31812. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31813. {
  31814. const ScopedLock sl (instance->lock);
  31815. instance->removeTimer (tim);
  31816. instance->addTimer (tim);
  31817. }
  31818. }
  31819. }
  31820. private:
  31821. friend class Timer;
  31822. static InternalTimerThread* instance;
  31823. static CriticalSection lock;
  31824. Timer* volatile firstTimer;
  31825. Atomic <int> callbackNeeded;
  31826. void addTimer (Timer* const t) throw()
  31827. {
  31828. #if JUCE_DEBUG
  31829. Timer* tt = firstTimer;
  31830. while (tt != 0)
  31831. {
  31832. // trying to add a timer that's already here - shouldn't get to this point,
  31833. // so if you get this assertion, let me know!
  31834. jassert (tt != t);
  31835. tt = tt->next;
  31836. }
  31837. jassert (t->previous == 0 && t->next == 0);
  31838. #endif
  31839. Timer* i = firstTimer;
  31840. if (i == 0 || i->countdownMs > t->countdownMs)
  31841. {
  31842. t->next = firstTimer;
  31843. firstTimer = t;
  31844. }
  31845. else
  31846. {
  31847. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31848. i = i->next;
  31849. jassert (i != 0);
  31850. t->next = i->next;
  31851. t->previous = i;
  31852. i->next = t;
  31853. }
  31854. if (t->next != 0)
  31855. t->next->previous = t;
  31856. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31857. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31858. notify();
  31859. }
  31860. void removeTimer (Timer* const t) throw()
  31861. {
  31862. #if JUCE_DEBUG
  31863. Timer* tt = firstTimer;
  31864. bool found = false;
  31865. while (tt != 0)
  31866. {
  31867. if (tt == t)
  31868. {
  31869. found = true;
  31870. break;
  31871. }
  31872. tt = tt->next;
  31873. }
  31874. // trying to remove a timer that's not here - shouldn't get to this point,
  31875. // so if you get this assertion, let me know!
  31876. jassert (found);
  31877. #endif
  31878. if (t->previous != 0)
  31879. {
  31880. jassert (firstTimer != t);
  31881. t->previous->next = t->next;
  31882. }
  31883. else
  31884. {
  31885. jassert (firstTimer == t);
  31886. firstTimer = t->next;
  31887. }
  31888. if (t->next != 0)
  31889. t->next->previous = t->previous;
  31890. t->next = 0;
  31891. t->previous = 0;
  31892. }
  31893. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31894. {
  31895. const ScopedLock sl (lock);
  31896. for (Timer* t = firstTimer; t != 0; t = t->next)
  31897. t->countdownMs -= numMillisecsElapsed;
  31898. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31899. }
  31900. void handleAsyncUpdate()
  31901. {
  31902. startThread (7);
  31903. }
  31904. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31905. };
  31906. InternalTimerThread* InternalTimerThread::instance = 0;
  31907. CriticalSection InternalTimerThread::lock;
  31908. void juce_callAnyTimersSynchronously()
  31909. {
  31910. InternalTimerThread::callAnyTimersSynchronously();
  31911. }
  31912. #if JUCE_DEBUG
  31913. static SortedSet <Timer*> activeTimers;
  31914. #endif
  31915. Timer::Timer() throw()
  31916. : countdownMs (0),
  31917. periodMs (0),
  31918. previous (0),
  31919. next (0)
  31920. {
  31921. #if JUCE_DEBUG
  31922. activeTimers.add (this);
  31923. #endif
  31924. }
  31925. Timer::Timer (const Timer&) throw()
  31926. : countdownMs (0),
  31927. periodMs (0),
  31928. previous (0),
  31929. next (0)
  31930. {
  31931. #if JUCE_DEBUG
  31932. activeTimers.add (this);
  31933. #endif
  31934. }
  31935. Timer::~Timer()
  31936. {
  31937. stopTimer();
  31938. #if JUCE_DEBUG
  31939. activeTimers.removeValue (this);
  31940. #endif
  31941. }
  31942. void Timer::startTimer (const int interval) throw()
  31943. {
  31944. const ScopedLock sl (InternalTimerThread::lock);
  31945. #if JUCE_DEBUG
  31946. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31947. jassert (activeTimers.contains (this));
  31948. #endif
  31949. if (periodMs == 0)
  31950. {
  31951. countdownMs = interval;
  31952. periodMs = jmax (1, interval);
  31953. InternalTimerThread::add (this);
  31954. }
  31955. else
  31956. {
  31957. InternalTimerThread::resetCounter (this, interval);
  31958. }
  31959. }
  31960. void Timer::stopTimer() throw()
  31961. {
  31962. const ScopedLock sl (InternalTimerThread::lock);
  31963. #if JUCE_DEBUG
  31964. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31965. jassert (activeTimers.contains (this));
  31966. #endif
  31967. if (periodMs > 0)
  31968. {
  31969. InternalTimerThread::remove (this);
  31970. periodMs = 0;
  31971. }
  31972. }
  31973. END_JUCE_NAMESPACE
  31974. /*** End of inlined file: juce_Timer.cpp ***/
  31975. #endif
  31976. #if JUCE_BUILD_GUI
  31977. /*** Start of inlined file: juce_Component.cpp ***/
  31978. BEGIN_JUCE_NAMESPACE
  31979. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31980. Component* Component::currentlyFocusedComponent = 0;
  31981. class Component::MouseListenerList
  31982. {
  31983. public:
  31984. MouseListenerList()
  31985. : numDeepMouseListeners (0)
  31986. {
  31987. }
  31988. ~MouseListenerList()
  31989. {
  31990. }
  31991. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31992. {
  31993. if (! listeners.contains (newListener))
  31994. {
  31995. if (wantsEventsForAllNestedChildComponents)
  31996. {
  31997. listeners.insert (0, newListener);
  31998. ++numDeepMouseListeners;
  31999. }
  32000. else
  32001. {
  32002. listeners.add (newListener);
  32003. }
  32004. }
  32005. }
  32006. void removeListener (MouseListener* const listenerToRemove)
  32007. {
  32008. const int index = listeners.indexOf (listenerToRemove);
  32009. if (index >= 0)
  32010. {
  32011. if (index < numDeepMouseListeners)
  32012. --numDeepMouseListeners;
  32013. listeners.remove (index);
  32014. }
  32015. }
  32016. static void sendMouseEvent (Component* comp, BailOutChecker& checker,
  32017. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  32018. {
  32019. if (checker.shouldBailOut())
  32020. return;
  32021. {
  32022. MouseListenerList* const list = comp->mouseListeners_;
  32023. if (list != 0)
  32024. {
  32025. for (int i = list->listeners.size(); --i >= 0;)
  32026. {
  32027. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  32028. if (checker.shouldBailOut())
  32029. return;
  32030. i = jmin (i, list->listeners.size());
  32031. }
  32032. }
  32033. }
  32034. Component* p = comp->parentComponent_;
  32035. while (p != 0)
  32036. {
  32037. MouseListenerList* const list = p->mouseListeners_;
  32038. if (list != 0 && list->numDeepMouseListeners > 0)
  32039. {
  32040. BailOutChecker checker2 (comp, p);
  32041. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32042. {
  32043. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  32044. if (checker2.shouldBailOut())
  32045. return;
  32046. i = jmin (i, list->numDeepMouseListeners);
  32047. }
  32048. }
  32049. p = p->parentComponent_;
  32050. }
  32051. }
  32052. static void sendWheelEvent (Component* comp, BailOutChecker& checker, const MouseEvent& e,
  32053. const float wheelIncrementX, const float wheelIncrementY)
  32054. {
  32055. if (checker.shouldBailOut())
  32056. return;
  32057. {
  32058. MouseListenerList* const list = comp->mouseListeners_;
  32059. if (list != 0)
  32060. {
  32061. for (int i = list->listeners.size(); --i >= 0;)
  32062. {
  32063. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32064. if (checker.shouldBailOut())
  32065. return;
  32066. i = jmin (i, list->listeners.size());
  32067. }
  32068. }
  32069. }
  32070. Component* p = comp->parentComponent_;
  32071. while (p != 0)
  32072. {
  32073. MouseListenerList* const list = p->mouseListeners_;
  32074. if (list != 0 && list->numDeepMouseListeners > 0)
  32075. {
  32076. BailOutChecker checker2 (comp, p);
  32077. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32078. {
  32079. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32080. if (checker2.shouldBailOut())
  32081. return;
  32082. i = jmin (i, list->numDeepMouseListeners);
  32083. }
  32084. }
  32085. p = p->parentComponent_;
  32086. }
  32087. }
  32088. private:
  32089. Array <MouseListener*> listeners;
  32090. int numDeepMouseListeners;
  32091. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  32092. };
  32093. class Component::ComponentHelpers
  32094. {
  32095. public:
  32096. static void* runModalLoopCallback (void* userData)
  32097. {
  32098. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32099. }
  32100. static const Identifier getColourPropertyId (const int colourId)
  32101. {
  32102. String s;
  32103. s.preallocateStorage (18);
  32104. s << "jcclr_" << String::toHexString (colourId);
  32105. return s;
  32106. }
  32107. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  32108. {
  32109. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  32110. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  32111. && comp.hitTest (localPoint.getX(), localPoint.getY());
  32112. }
  32113. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  32114. {
  32115. if (comp.affineTransform_ == 0)
  32116. return pointInParentSpace - comp.getPosition();
  32117. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform_->inverted()).toInt() - comp.getPosition();
  32118. }
  32119. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  32120. {
  32121. if (comp.affineTransform_ == 0)
  32122. return areaInParentSpace - comp.getPosition();
  32123. return areaInParentSpace.toFloat().transformed (comp.affineTransform_->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  32124. }
  32125. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  32126. {
  32127. if (comp.affineTransform_ == 0)
  32128. return pointInLocalSpace + comp.getPosition();
  32129. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform_).toInt();
  32130. }
  32131. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  32132. {
  32133. if (comp.affineTransform_ == 0)
  32134. return areaInLocalSpace + comp.getPosition();
  32135. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform_).getSmallestIntegerContainer();
  32136. }
  32137. template <typename Type>
  32138. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  32139. {
  32140. const Component* const directParent = target.getParentComponent();
  32141. jassert (directParent != 0);
  32142. if (directParent == parent)
  32143. return convertFromParentSpace (target, coordInParent);
  32144. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  32145. }
  32146. template <typename Type>
  32147. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  32148. {
  32149. while (source != 0)
  32150. {
  32151. if (source == target)
  32152. return p;
  32153. if (source->isParentOf (target))
  32154. return convertFromDistantParentSpace (source, *target, p);
  32155. if (source->isOnDesktop())
  32156. {
  32157. p = source->getPeer()->localToGlobal (p);
  32158. source = 0;
  32159. }
  32160. else
  32161. {
  32162. p = convertToParentSpace (*source, p);
  32163. source = source->getParentComponent();
  32164. }
  32165. }
  32166. jassert (source == 0);
  32167. if (target == 0)
  32168. return p;
  32169. const Component* const topLevelComp = target->getTopLevelComponent();
  32170. if (topLevelComp->isOnDesktop())
  32171. p = topLevelComp->getPeer()->globalToLocal (p);
  32172. else
  32173. p = convertFromParentSpace (*topLevelComp, p);
  32174. if (topLevelComp == target)
  32175. return p;
  32176. return convertFromDistantParentSpace (topLevelComp, *target, p);
  32177. }
  32178. static const Rectangle<int> getUnclippedArea (const Component& comp)
  32179. {
  32180. Rectangle<int> r (comp.getLocalBounds());
  32181. Component* const p = comp.getParentComponent();
  32182. if (p != 0)
  32183. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  32184. return r;
  32185. }
  32186. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  32187. {
  32188. for (int i = comp.childComponentList_.size(); --i >= 0;)
  32189. {
  32190. const Component& child = *comp.childComponentList_.getUnchecked(i);
  32191. if (child.isVisible() && ! child.isTransformed())
  32192. {
  32193. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds_));
  32194. if (! newClip.isEmpty())
  32195. {
  32196. if (child.isOpaque())
  32197. {
  32198. g.excludeClipRegion (newClip + delta);
  32199. }
  32200. else
  32201. {
  32202. const Point<int> childPos (child.getPosition());
  32203. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  32204. }
  32205. }
  32206. }
  32207. }
  32208. }
  32209. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  32210. const Point<int>& delta,
  32211. const Rectangle<int>& clipRect,
  32212. const Component* const compToAvoid)
  32213. {
  32214. for (int i = comp.childComponentList_.size(); --i >= 0;)
  32215. {
  32216. const Component* const c = comp.childComponentList_.getUnchecked(i);
  32217. if (c != compToAvoid && c->isVisible())
  32218. {
  32219. if (c->isOpaque())
  32220. {
  32221. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32222. childBounds.translate (delta.getX(), delta.getY());
  32223. result.subtract (childBounds);
  32224. }
  32225. else
  32226. {
  32227. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32228. newClip.translate (-c->getX(), -c->getY());
  32229. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  32230. newClip, compToAvoid);
  32231. }
  32232. }
  32233. }
  32234. }
  32235. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  32236. {
  32237. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  32238. : Desktop::getInstance().getMainMonitorArea();
  32239. }
  32240. };
  32241. Component::Component()
  32242. : parentComponent_ (0),
  32243. lookAndFeel_ (0),
  32244. effect_ (0),
  32245. bufferedImage_ (0),
  32246. componentFlags_ (0),
  32247. componentTransparency (0)
  32248. {
  32249. }
  32250. Component::Component (const String& name)
  32251. : componentName_ (name),
  32252. parentComponent_ (0),
  32253. lookAndFeel_ (0),
  32254. effect_ (0),
  32255. bufferedImage_ (0),
  32256. componentFlags_ (0),
  32257. componentTransparency (0)
  32258. {
  32259. }
  32260. Component::~Component()
  32261. {
  32262. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  32263. static_jassert (sizeof (flags) <= sizeof (componentFlags_));
  32264. #endif
  32265. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32266. weakReferenceMaster.clear();
  32267. while (childComponentList_.size() > 0)
  32268. removeChildComponent (childComponentList_.size() - 1, false, true);
  32269. if (parentComponent_ != 0)
  32270. parentComponent_->removeChildComponent (parentComponent_->childComponentList_.indexOf (this), true, false);
  32271. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32272. giveAwayFocus (currentlyFocusedComponent != this);
  32273. if (flags.hasHeavyweightPeerFlag)
  32274. removeFromDesktop();
  32275. // Something has added some children to this component during its destructor! Not a smart idea!
  32276. jassert (childComponentList_.size() == 0);
  32277. }
  32278. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  32279. {
  32280. return weakReferenceMaster (this);
  32281. }
  32282. void Component::setName (const String& name)
  32283. {
  32284. // if component methods are being called from threads other than the message
  32285. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32286. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32287. if (componentName_ != name)
  32288. {
  32289. componentName_ = name;
  32290. if (flags.hasHeavyweightPeerFlag)
  32291. {
  32292. ComponentPeer* const peer = getPeer();
  32293. jassert (peer != 0);
  32294. if (peer != 0)
  32295. peer->setTitle (name);
  32296. }
  32297. BailOutChecker checker (this);
  32298. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32299. }
  32300. }
  32301. void Component::setVisible (bool shouldBeVisible)
  32302. {
  32303. if (flags.visibleFlag != shouldBeVisible)
  32304. {
  32305. // if component methods are being called from threads other than the message
  32306. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32307. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32308. WeakReference<Component> safePointer (this);
  32309. flags.visibleFlag = shouldBeVisible;
  32310. internalRepaint (0, 0, getWidth(), getHeight());
  32311. sendFakeMouseMove();
  32312. if (! shouldBeVisible)
  32313. {
  32314. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32315. {
  32316. if (parentComponent_ != 0)
  32317. parentComponent_->grabKeyboardFocus();
  32318. else
  32319. giveAwayFocus (true);
  32320. }
  32321. }
  32322. if (safePointer != 0)
  32323. {
  32324. sendVisibilityChangeMessage();
  32325. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32326. {
  32327. ComponentPeer* const peer = getPeer();
  32328. jassert (peer != 0);
  32329. if (peer != 0)
  32330. {
  32331. peer->setVisible (shouldBeVisible);
  32332. internalHierarchyChanged();
  32333. }
  32334. }
  32335. }
  32336. }
  32337. }
  32338. void Component::visibilityChanged()
  32339. {
  32340. }
  32341. void Component::sendVisibilityChangeMessage()
  32342. {
  32343. BailOutChecker checker (this);
  32344. visibilityChanged();
  32345. if (! checker.shouldBailOut())
  32346. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32347. }
  32348. bool Component::isShowing() const
  32349. {
  32350. if (flags.visibleFlag)
  32351. {
  32352. if (parentComponent_ != 0)
  32353. {
  32354. return parentComponent_->isShowing();
  32355. }
  32356. else
  32357. {
  32358. const ComponentPeer* const peer = getPeer();
  32359. return peer != 0 && ! peer->isMinimised();
  32360. }
  32361. }
  32362. return false;
  32363. }
  32364. void* Component::getWindowHandle() const
  32365. {
  32366. const ComponentPeer* const peer = getPeer();
  32367. if (peer != 0)
  32368. return peer->getNativeHandle();
  32369. return 0;
  32370. }
  32371. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32372. {
  32373. // if component methods are being called from threads other than the message
  32374. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32375. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32376. if (isOpaque())
  32377. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32378. else
  32379. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32380. int currentStyleFlags = 0;
  32381. // don't use getPeer(), so that we only get the peer that's specifically
  32382. // for this comp, and not for one of its parents.
  32383. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32384. if (peer != 0)
  32385. currentStyleFlags = peer->getStyleFlags();
  32386. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32387. {
  32388. WeakReference<Component> safePointer (this);
  32389. #if JUCE_LINUX
  32390. // it's wise to give the component a non-zero size before
  32391. // putting it on the desktop, as X windows get confused by this, and
  32392. // a (1, 1) minimum size is enforced here.
  32393. setSize (jmax (1, getWidth()),
  32394. jmax (1, getHeight()));
  32395. #endif
  32396. const Point<int> topLeft (getScreenPosition());
  32397. bool wasFullscreen = false;
  32398. bool wasMinimised = false;
  32399. ComponentBoundsConstrainer* currentConstainer = 0;
  32400. Rectangle<int> oldNonFullScreenBounds;
  32401. if (peer != 0)
  32402. {
  32403. wasFullscreen = peer->isFullScreen();
  32404. wasMinimised = peer->isMinimised();
  32405. currentConstainer = peer->getConstrainer();
  32406. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32407. removeFromDesktop();
  32408. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32409. }
  32410. if (parentComponent_ != 0)
  32411. parentComponent_->removeChildComponent (this);
  32412. if (safePointer != 0)
  32413. {
  32414. flags.hasHeavyweightPeerFlag = true;
  32415. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32416. Desktop::getInstance().addDesktopComponent (this);
  32417. bounds_.setPosition (topLeft);
  32418. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32419. peer->setVisible (isVisible());
  32420. if (wasFullscreen)
  32421. {
  32422. peer->setFullScreen (true);
  32423. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32424. }
  32425. if (wasMinimised)
  32426. peer->setMinimised (true);
  32427. if (isAlwaysOnTop())
  32428. peer->setAlwaysOnTop (true);
  32429. peer->setConstrainer (currentConstainer);
  32430. repaint();
  32431. }
  32432. internalHierarchyChanged();
  32433. }
  32434. }
  32435. void Component::removeFromDesktop()
  32436. {
  32437. // if component methods are being called from threads other than the message
  32438. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32439. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32440. if (flags.hasHeavyweightPeerFlag)
  32441. {
  32442. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32443. flags.hasHeavyweightPeerFlag = false;
  32444. jassert (peer != 0);
  32445. delete peer;
  32446. Desktop::getInstance().removeDesktopComponent (this);
  32447. }
  32448. }
  32449. bool Component::isOnDesktop() const throw()
  32450. {
  32451. return flags.hasHeavyweightPeerFlag;
  32452. }
  32453. void Component::userTriedToCloseWindow()
  32454. {
  32455. /* This means that the user's trying to get rid of your window with the 'close window' system
  32456. menu option (on windows) or possibly the task manager - you should really handle this
  32457. and delete or hide your component in an appropriate way.
  32458. If you want to ignore the event and don't want to trigger this assertion, just override
  32459. this method and do nothing.
  32460. */
  32461. jassertfalse;
  32462. }
  32463. void Component::minimisationStateChanged (bool)
  32464. {
  32465. }
  32466. void Component::setOpaque (const bool shouldBeOpaque)
  32467. {
  32468. if (shouldBeOpaque != flags.opaqueFlag)
  32469. {
  32470. flags.opaqueFlag = shouldBeOpaque;
  32471. if (flags.hasHeavyweightPeerFlag)
  32472. {
  32473. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32474. if (peer != 0)
  32475. {
  32476. // to make it recreate the heavyweight window
  32477. addToDesktop (peer->getStyleFlags());
  32478. }
  32479. }
  32480. repaint();
  32481. }
  32482. }
  32483. bool Component::isOpaque() const throw()
  32484. {
  32485. return flags.opaqueFlag;
  32486. }
  32487. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32488. {
  32489. if (shouldBeBuffered != flags.bufferToImageFlag)
  32490. {
  32491. bufferedImage_ = Image::null;
  32492. flags.bufferToImageFlag = shouldBeBuffered;
  32493. }
  32494. }
  32495. void Component::toFront (const bool setAsForeground)
  32496. {
  32497. // if component methods are being called from threads other than the message
  32498. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32499. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32500. if (flags.hasHeavyweightPeerFlag)
  32501. {
  32502. ComponentPeer* const peer = getPeer();
  32503. if (peer != 0)
  32504. {
  32505. peer->toFront (setAsForeground);
  32506. if (setAsForeground && ! hasKeyboardFocus (true))
  32507. grabKeyboardFocus();
  32508. }
  32509. }
  32510. else if (parentComponent_ != 0)
  32511. {
  32512. Array<Component*>& childList = parentComponent_->childComponentList_;
  32513. if (childList.getLast() != this)
  32514. {
  32515. const int index = childList.indexOf (this);
  32516. if (index >= 0)
  32517. {
  32518. int insertIndex = -1;
  32519. if (! flags.alwaysOnTopFlag)
  32520. {
  32521. insertIndex = childList.size() - 1;
  32522. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32523. --insertIndex;
  32524. }
  32525. if (index != insertIndex)
  32526. {
  32527. childList.move (index, insertIndex);
  32528. sendFakeMouseMove();
  32529. repaintParent();
  32530. }
  32531. }
  32532. }
  32533. if (setAsForeground)
  32534. {
  32535. internalBroughtToFront();
  32536. grabKeyboardFocus();
  32537. }
  32538. }
  32539. }
  32540. void Component::toBehind (Component* const other)
  32541. {
  32542. if (other != 0 && other != this)
  32543. {
  32544. // the two components must belong to the same parent..
  32545. jassert (parentComponent_ == other->parentComponent_);
  32546. if (parentComponent_ != 0)
  32547. {
  32548. Array<Component*>& childList = parentComponent_->childComponentList_;
  32549. const int index = childList.indexOf (this);
  32550. if (index >= 0 && childList [index + 1] != other)
  32551. {
  32552. int otherIndex = childList.indexOf (other);
  32553. if (otherIndex >= 0)
  32554. {
  32555. if (index < otherIndex)
  32556. --otherIndex;
  32557. childList.move (index, otherIndex);
  32558. sendFakeMouseMove();
  32559. repaintParent();
  32560. }
  32561. }
  32562. }
  32563. else if (isOnDesktop())
  32564. {
  32565. jassert (other->isOnDesktop());
  32566. if (other->isOnDesktop())
  32567. {
  32568. ComponentPeer* const us = getPeer();
  32569. ComponentPeer* const them = other->getPeer();
  32570. jassert (us != 0 && them != 0);
  32571. if (us != 0 && them != 0)
  32572. us->toBehind (them);
  32573. }
  32574. }
  32575. }
  32576. }
  32577. void Component::toBack()
  32578. {
  32579. Array<Component*>& childList = parentComponent_->childComponentList_;
  32580. if (isOnDesktop())
  32581. {
  32582. jassertfalse; //xxx need to add this to native window
  32583. }
  32584. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32585. {
  32586. const int index = childList.indexOf (this);
  32587. if (index > 0)
  32588. {
  32589. int insertIndex = 0;
  32590. if (flags.alwaysOnTopFlag)
  32591. {
  32592. while (insertIndex < childList.size()
  32593. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32594. {
  32595. ++insertIndex;
  32596. }
  32597. }
  32598. if (index != insertIndex)
  32599. {
  32600. childList.move (index, insertIndex);
  32601. sendFakeMouseMove();
  32602. repaintParent();
  32603. }
  32604. }
  32605. }
  32606. }
  32607. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32608. {
  32609. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32610. {
  32611. flags.alwaysOnTopFlag = shouldStayOnTop;
  32612. if (isOnDesktop())
  32613. {
  32614. ComponentPeer* const peer = getPeer();
  32615. jassert (peer != 0);
  32616. if (peer != 0)
  32617. {
  32618. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32619. {
  32620. // some kinds of peer can't change their always-on-top status, so
  32621. // for these, we'll need to create a new window
  32622. const int oldFlags = peer->getStyleFlags();
  32623. removeFromDesktop();
  32624. addToDesktop (oldFlags);
  32625. }
  32626. }
  32627. }
  32628. if (shouldStayOnTop)
  32629. toFront (false);
  32630. internalHierarchyChanged();
  32631. }
  32632. }
  32633. bool Component::isAlwaysOnTop() const throw()
  32634. {
  32635. return flags.alwaysOnTopFlag;
  32636. }
  32637. int Component::proportionOfWidth (const float proportion) const throw()
  32638. {
  32639. return roundToInt (proportion * bounds_.getWidth());
  32640. }
  32641. int Component::proportionOfHeight (const float proportion) const throw()
  32642. {
  32643. return roundToInt (proportion * bounds_.getHeight());
  32644. }
  32645. int Component::getParentWidth() const throw()
  32646. {
  32647. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32648. : getParentMonitorArea().getWidth();
  32649. }
  32650. int Component::getParentHeight() const throw()
  32651. {
  32652. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32653. : getParentMonitorArea().getHeight();
  32654. }
  32655. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32656. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32657. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32658. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32659. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32660. {
  32661. return ComponentHelpers::convertCoordinate (this, source, point);
  32662. }
  32663. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32664. {
  32665. return ComponentHelpers::convertCoordinate (this, source, area);
  32666. }
  32667. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32668. {
  32669. return ComponentHelpers::convertCoordinate (0, this, point);
  32670. }
  32671. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32672. {
  32673. return ComponentHelpers::convertCoordinate (0, this, area);
  32674. }
  32675. /* Deprecated methods... */
  32676. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32677. {
  32678. return localPointToGlobal (relativePosition);
  32679. }
  32680. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32681. {
  32682. return getLocalPoint (0, screenPosition);
  32683. }
  32684. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32685. {
  32686. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32687. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32688. }
  32689. void Component::setBounds (const int x, const int y, int w, int h)
  32690. {
  32691. // if component methods are being called from threads other than the message
  32692. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32693. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32694. if (w < 0) w = 0;
  32695. if (h < 0) h = 0;
  32696. const bool wasResized = (getWidth() != w || getHeight() != h);
  32697. const bool wasMoved = (getX() != x || getY() != y);
  32698. #if JUCE_DEBUG
  32699. // It's a very bad idea to try to resize a window during its paint() method!
  32700. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32701. #endif
  32702. if (wasMoved || wasResized)
  32703. {
  32704. const bool showing = isShowing();
  32705. if (showing)
  32706. {
  32707. // send a fake mouse move to trigger enter/exit messages if needed..
  32708. sendFakeMouseMove();
  32709. if (! flags.hasHeavyweightPeerFlag)
  32710. repaintParent();
  32711. }
  32712. bounds_.setBounds (x, y, w, h);
  32713. if (showing)
  32714. {
  32715. if (wasResized)
  32716. repaint();
  32717. else if (! flags.hasHeavyweightPeerFlag)
  32718. repaintParent();
  32719. }
  32720. if (flags.hasHeavyweightPeerFlag)
  32721. {
  32722. ComponentPeer* const peer = getPeer();
  32723. if (peer != 0)
  32724. {
  32725. if (wasMoved && wasResized)
  32726. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32727. else if (wasMoved)
  32728. peer->setPosition (getX(), getY());
  32729. else if (wasResized)
  32730. peer->setSize (getWidth(), getHeight());
  32731. }
  32732. }
  32733. sendMovedResizedMessages (wasMoved, wasResized);
  32734. }
  32735. }
  32736. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32737. {
  32738. JUCE_TRY
  32739. {
  32740. if (wasMoved)
  32741. moved();
  32742. if (wasResized)
  32743. {
  32744. resized();
  32745. for (int i = childComponentList_.size(); --i >= 0;)
  32746. {
  32747. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32748. i = jmin (i, childComponentList_.size());
  32749. }
  32750. }
  32751. BailOutChecker checker (this);
  32752. if (parentComponent_ != 0)
  32753. parentComponent_->childBoundsChanged (this);
  32754. if (! checker.shouldBailOut())
  32755. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32756. *this, wasMoved, wasResized);
  32757. }
  32758. JUCE_CATCH_EXCEPTION
  32759. }
  32760. void Component::setSize (const int w, const int h)
  32761. {
  32762. setBounds (getX(), getY(), w, h);
  32763. }
  32764. void Component::setTopLeftPosition (const int x, const int y)
  32765. {
  32766. setBounds (x, y, getWidth(), getHeight());
  32767. }
  32768. void Component::setTopRightPosition (const int x, const int y)
  32769. {
  32770. setTopLeftPosition (x - getWidth(), y);
  32771. }
  32772. void Component::setBounds (const Rectangle<int>& r)
  32773. {
  32774. setBounds (r.getX(),
  32775. r.getY(),
  32776. r.getWidth(),
  32777. r.getHeight());
  32778. }
  32779. void Component::setBoundsRelative (const float x, const float y,
  32780. const float w, const float h)
  32781. {
  32782. const int pw = getParentWidth();
  32783. const int ph = getParentHeight();
  32784. setBounds (roundToInt (x * pw),
  32785. roundToInt (y * ph),
  32786. roundToInt (w * pw),
  32787. roundToInt (h * ph));
  32788. }
  32789. void Component::setCentrePosition (const int x, const int y)
  32790. {
  32791. setTopLeftPosition (x - getWidth() / 2,
  32792. y - getHeight() / 2);
  32793. }
  32794. void Component::setCentreRelative (const float x, const float y)
  32795. {
  32796. setCentrePosition (roundToInt (getParentWidth() * x),
  32797. roundToInt (getParentHeight() * y));
  32798. }
  32799. void Component::centreWithSize (const int width, const int height)
  32800. {
  32801. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32802. setBounds (parentArea.getCentreX() - width / 2,
  32803. parentArea.getCentreY() - height / 2,
  32804. width, height);
  32805. }
  32806. void Component::setBoundsInset (const BorderSize& borders)
  32807. {
  32808. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32809. }
  32810. void Component::setBoundsToFit (int x, int y, int width, int height,
  32811. const Justification& justification,
  32812. const bool onlyReduceInSize)
  32813. {
  32814. // it's no good calling this method unless both the component and
  32815. // target rectangle have a finite size.
  32816. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32817. if (getWidth() > 0 && getHeight() > 0
  32818. && width > 0 && height > 0)
  32819. {
  32820. int newW, newH;
  32821. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32822. {
  32823. newW = getWidth();
  32824. newH = getHeight();
  32825. }
  32826. else
  32827. {
  32828. const double imageRatio = getHeight() / (double) getWidth();
  32829. const double targetRatio = height / (double) width;
  32830. if (imageRatio <= targetRatio)
  32831. {
  32832. newW = width;
  32833. newH = jmin (height, roundToInt (newW * imageRatio));
  32834. }
  32835. else
  32836. {
  32837. newH = height;
  32838. newW = jmin (width, roundToInt (newH / imageRatio));
  32839. }
  32840. }
  32841. if (newW > 0 && newH > 0)
  32842. {
  32843. int newX, newY;
  32844. justification.applyToRectangle (newX, newY, newW, newH,
  32845. x, y, width, height);
  32846. setBounds (newX, newY, newW, newH);
  32847. }
  32848. }
  32849. }
  32850. bool Component::isTransformed() const throw()
  32851. {
  32852. return affineTransform_ != 0;
  32853. }
  32854. void Component::setTransform (const AffineTransform& newTransform)
  32855. {
  32856. // If you pass in a transform with no inverse, the component will have no dimensions,
  32857. // and there will be all sorts of maths errors when converting coordinates.
  32858. jassert (! newTransform.isSingularity());
  32859. if (newTransform.isIdentity())
  32860. {
  32861. if (affineTransform_ != 0)
  32862. {
  32863. repaint();
  32864. affineTransform_ = 0;
  32865. repaint();
  32866. sendMovedResizedMessages (false, false);
  32867. }
  32868. }
  32869. else if (affineTransform_ == 0)
  32870. {
  32871. repaint();
  32872. affineTransform_ = new AffineTransform (newTransform);
  32873. repaint();
  32874. sendMovedResizedMessages (false, false);
  32875. }
  32876. else if (*affineTransform_ != newTransform)
  32877. {
  32878. repaint();
  32879. *affineTransform_ = newTransform;
  32880. repaint();
  32881. sendMovedResizedMessages (false, false);
  32882. }
  32883. }
  32884. const AffineTransform Component::getTransform() const
  32885. {
  32886. return affineTransform_ != 0 ? *affineTransform_ : AffineTransform::identity;
  32887. }
  32888. bool Component::hitTest (int x, int y)
  32889. {
  32890. if (! flags.ignoresMouseClicksFlag)
  32891. return true;
  32892. if (flags.allowChildMouseClicksFlag)
  32893. {
  32894. for (int i = getNumChildComponents(); --i >= 0;)
  32895. {
  32896. Component& child = *getChildComponent (i);
  32897. if (child.isVisible()
  32898. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32899. return true;
  32900. }
  32901. }
  32902. return false;
  32903. }
  32904. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32905. const bool allowClicksOnChildComponents) throw()
  32906. {
  32907. flags.ignoresMouseClicksFlag = ! allowClicks;
  32908. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32909. }
  32910. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32911. bool& allowsClicksOnChildComponents) const throw()
  32912. {
  32913. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32914. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32915. }
  32916. bool Component::contains (const Point<int>& point)
  32917. {
  32918. if (ComponentHelpers::hitTest (*this, point))
  32919. {
  32920. if (parentComponent_ != 0)
  32921. {
  32922. return parentComponent_->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32923. }
  32924. else if (flags.hasHeavyweightPeerFlag)
  32925. {
  32926. const ComponentPeer* const peer = getPeer();
  32927. if (peer != 0)
  32928. return peer->contains (point, true);
  32929. }
  32930. }
  32931. return false;
  32932. }
  32933. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32934. {
  32935. if (! contains (point))
  32936. return false;
  32937. Component* const top = getTopLevelComponent();
  32938. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32939. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32940. }
  32941. Component* Component::getComponentAt (const Point<int>& position)
  32942. {
  32943. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32944. {
  32945. for (int i = childComponentList_.size(); --i >= 0;)
  32946. {
  32947. Component* child = childComponentList_.getUnchecked(i);
  32948. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32949. if (child != 0)
  32950. return child;
  32951. }
  32952. return this;
  32953. }
  32954. return 0;
  32955. }
  32956. Component* Component::getComponentAt (const int x, const int y)
  32957. {
  32958. return getComponentAt (Point<int> (x, y));
  32959. }
  32960. void Component::addChildComponent (Component* const child, int zOrder)
  32961. {
  32962. // if component methods are being called from threads other than the message
  32963. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32964. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32965. if (child != 0 && child->parentComponent_ != this)
  32966. {
  32967. if (child->parentComponent_ != 0)
  32968. child->parentComponent_->removeChildComponent (child);
  32969. else
  32970. child->removeFromDesktop();
  32971. child->parentComponent_ = this;
  32972. if (child->isVisible())
  32973. child->repaintParent();
  32974. if (! child->isAlwaysOnTop())
  32975. {
  32976. if (zOrder < 0 || zOrder > childComponentList_.size())
  32977. zOrder = childComponentList_.size();
  32978. while (zOrder > 0)
  32979. {
  32980. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32981. break;
  32982. --zOrder;
  32983. }
  32984. }
  32985. childComponentList_.insert (zOrder, child);
  32986. child->internalHierarchyChanged();
  32987. internalChildrenChanged();
  32988. }
  32989. }
  32990. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32991. {
  32992. if (child != 0)
  32993. {
  32994. child->setVisible (true);
  32995. addChildComponent (child, zOrder);
  32996. }
  32997. }
  32998. void Component::removeChildComponent (Component* const child)
  32999. {
  33000. removeChildComponent (childComponentList_.indexOf (child), true, true);
  33001. }
  33002. Component* Component::removeChildComponent (const int index)
  33003. {
  33004. return removeChildComponent (index, true, true);
  33005. }
  33006. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  33007. {
  33008. // if component methods are being called from threads other than the message
  33009. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33010. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33011. Component* const child = childComponentList_ [index];
  33012. if (child != 0)
  33013. {
  33014. sendParentEvents = sendParentEvents && child->isShowing();
  33015. if (sendParentEvents)
  33016. {
  33017. sendFakeMouseMove();
  33018. child->repaintParent();
  33019. }
  33020. childComponentList_.remove (index);
  33021. child->parentComponent_ = 0;
  33022. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  33023. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  33024. {
  33025. if (sendParentEvents)
  33026. {
  33027. const WeakReference<Component> thisPointer (this);
  33028. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  33029. if (thisPointer == 0)
  33030. return child;
  33031. grabKeyboardFocus();
  33032. }
  33033. else
  33034. {
  33035. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  33036. }
  33037. }
  33038. if (sendChildEvents)
  33039. child->internalHierarchyChanged();
  33040. if (sendParentEvents)
  33041. internalChildrenChanged();
  33042. }
  33043. return child;
  33044. }
  33045. void Component::removeAllChildren()
  33046. {
  33047. while (childComponentList_.size() > 0)
  33048. removeChildComponent (childComponentList_.size() - 1);
  33049. }
  33050. void Component::deleteAllChildren()
  33051. {
  33052. while (childComponentList_.size() > 0)
  33053. delete (removeChildComponent (childComponentList_.size() - 1));
  33054. }
  33055. int Component::getNumChildComponents() const throw()
  33056. {
  33057. return childComponentList_.size();
  33058. }
  33059. Component* Component::getChildComponent (const int index) const throw()
  33060. {
  33061. return childComponentList_ [index];
  33062. }
  33063. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  33064. {
  33065. return childComponentList_.indexOf (const_cast <Component*> (child));
  33066. }
  33067. Component* Component::getTopLevelComponent() const throw()
  33068. {
  33069. const Component* comp = this;
  33070. while (comp->parentComponent_ != 0)
  33071. comp = comp->parentComponent_;
  33072. return const_cast <Component*> (comp);
  33073. }
  33074. bool Component::isParentOf (const Component* possibleChild) const throw()
  33075. {
  33076. while (possibleChild != 0)
  33077. {
  33078. possibleChild = possibleChild->parentComponent_;
  33079. if (possibleChild == this)
  33080. return true;
  33081. }
  33082. return false;
  33083. }
  33084. void Component::parentHierarchyChanged()
  33085. {
  33086. }
  33087. void Component::childrenChanged()
  33088. {
  33089. }
  33090. void Component::internalChildrenChanged()
  33091. {
  33092. if (componentListeners.isEmpty())
  33093. {
  33094. childrenChanged();
  33095. }
  33096. else
  33097. {
  33098. BailOutChecker checker (this);
  33099. childrenChanged();
  33100. if (! checker.shouldBailOut())
  33101. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  33102. }
  33103. }
  33104. void Component::internalHierarchyChanged()
  33105. {
  33106. BailOutChecker checker (this);
  33107. parentHierarchyChanged();
  33108. if (checker.shouldBailOut())
  33109. return;
  33110. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  33111. if (checker.shouldBailOut())
  33112. return;
  33113. for (int i = childComponentList_.size(); --i >= 0;)
  33114. {
  33115. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  33116. if (checker.shouldBailOut())
  33117. {
  33118. // you really shouldn't delete the parent component during a callback telling you
  33119. // that it's changed..
  33120. jassertfalse;
  33121. return;
  33122. }
  33123. i = jmin (i, childComponentList_.size());
  33124. }
  33125. }
  33126. int Component::runModalLoop()
  33127. {
  33128. if (! MessageManager::getInstance()->isThisTheMessageThread())
  33129. {
  33130. // use a callback so this can be called from non-gui threads
  33131. return (int) (pointer_sized_int) MessageManager::getInstance()
  33132. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  33133. }
  33134. if (! isCurrentlyModal())
  33135. enterModalState (true);
  33136. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  33137. }
  33138. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  33139. {
  33140. // if component methods are being called from threads other than the message
  33141. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33142. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33143. // Check for an attempt to make a component modal when it already is!
  33144. // This can cause nasty problems..
  33145. jassert (! flags.currentlyModalFlag);
  33146. if (! isCurrentlyModal())
  33147. {
  33148. ModalComponentManager::getInstance()->startModal (this, callback);
  33149. flags.currentlyModalFlag = true;
  33150. setVisible (true);
  33151. if (takeKeyboardFocus_)
  33152. grabKeyboardFocus();
  33153. }
  33154. }
  33155. void Component::exitModalState (const int returnValue)
  33156. {
  33157. if (isCurrentlyModal())
  33158. {
  33159. if (MessageManager::getInstance()->isThisTheMessageThread())
  33160. {
  33161. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33162. flags.currentlyModalFlag = false;
  33163. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33164. }
  33165. else
  33166. {
  33167. class ExitModalStateMessage : public CallbackMessage
  33168. {
  33169. public:
  33170. ExitModalStateMessage (Component* const target_, const int result_)
  33171. : target (target_), result (result_) {}
  33172. void messageCallback()
  33173. {
  33174. if (target.get() != 0) // (get() required for VS2003 bug)
  33175. target->exitModalState (result);
  33176. }
  33177. private:
  33178. WeakReference<Component> target;
  33179. int result;
  33180. };
  33181. (new ExitModalStateMessage (this, returnValue))->post();
  33182. }
  33183. }
  33184. }
  33185. bool Component::isCurrentlyModal() const throw()
  33186. {
  33187. return flags.currentlyModalFlag
  33188. && getCurrentlyModalComponent() == this;
  33189. }
  33190. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33191. {
  33192. Component* const mc = getCurrentlyModalComponent();
  33193. return mc != 0
  33194. && mc != this
  33195. && (! mc->isParentOf (this))
  33196. && ! mc->canModalEventBeSentToComponent (this);
  33197. }
  33198. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33199. {
  33200. return ModalComponentManager::getInstance()->getNumModalComponents();
  33201. }
  33202. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33203. {
  33204. return ModalComponentManager::getInstance()->getModalComponent (index);
  33205. }
  33206. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33207. {
  33208. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33209. }
  33210. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33211. {
  33212. return flags.bringToFrontOnClickFlag;
  33213. }
  33214. void Component::setMouseCursor (const MouseCursor& cursor)
  33215. {
  33216. if (cursor_ != cursor)
  33217. {
  33218. cursor_ = cursor;
  33219. if (flags.visibleFlag)
  33220. updateMouseCursor();
  33221. }
  33222. }
  33223. const MouseCursor Component::getMouseCursor()
  33224. {
  33225. return cursor_;
  33226. }
  33227. void Component::updateMouseCursor() const
  33228. {
  33229. sendFakeMouseMove();
  33230. }
  33231. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33232. {
  33233. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33234. }
  33235. void Component::setAlpha (const float newAlpha)
  33236. {
  33237. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33238. if (componentTransparency != newIntAlpha)
  33239. {
  33240. componentTransparency = newIntAlpha;
  33241. if (flags.hasHeavyweightPeerFlag)
  33242. {
  33243. ComponentPeer* const peer = getPeer();
  33244. if (peer != 0)
  33245. peer->setAlpha (newAlpha);
  33246. }
  33247. else
  33248. {
  33249. repaint();
  33250. }
  33251. }
  33252. }
  33253. float Component::getAlpha() const
  33254. {
  33255. return (255 - componentTransparency) / 255.0f;
  33256. }
  33257. void Component::repaintParent()
  33258. {
  33259. if (flags.visibleFlag)
  33260. internalRepaint (0, 0, getWidth(), getHeight());
  33261. }
  33262. void Component::repaint()
  33263. {
  33264. repaint (0, 0, getWidth(), getHeight());
  33265. }
  33266. void Component::repaint (const int x, const int y,
  33267. const int w, const int h)
  33268. {
  33269. bufferedImage_ = Image::null;
  33270. if (flags.visibleFlag)
  33271. internalRepaint (x, y, w, h);
  33272. }
  33273. void Component::repaint (const Rectangle<int>& area)
  33274. {
  33275. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33276. }
  33277. void Component::internalRepaint (int x, int y, int w, int h)
  33278. {
  33279. // if component methods are being called from threads other than the message
  33280. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33281. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33282. if (x < 0)
  33283. {
  33284. w += x;
  33285. x = 0;
  33286. }
  33287. if (x + w > getWidth())
  33288. w = getWidth() - x;
  33289. if (w > 0)
  33290. {
  33291. if (y < 0)
  33292. {
  33293. h += y;
  33294. y = 0;
  33295. }
  33296. if (y + h > getHeight())
  33297. h = getHeight() - y;
  33298. if (h > 0)
  33299. {
  33300. if (parentComponent_ != 0)
  33301. {
  33302. if (parentComponent_->flags.visibleFlag)
  33303. {
  33304. if (affineTransform_ == 0)
  33305. {
  33306. parentComponent_->internalRepaint (x + getX(), y + getY(), w, h);
  33307. }
  33308. else
  33309. {
  33310. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  33311. parentComponent_->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  33312. }
  33313. }
  33314. }
  33315. else if (flags.hasHeavyweightPeerFlag)
  33316. {
  33317. ComponentPeer* const peer = getPeer();
  33318. if (peer != 0)
  33319. peer->repaint (Rectangle<int> (x, y, w, h));
  33320. }
  33321. }
  33322. }
  33323. }
  33324. void Component::paintComponent (Graphics& g)
  33325. {
  33326. if (flags.bufferToImageFlag)
  33327. {
  33328. if (bufferedImage_.isNull())
  33329. {
  33330. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33331. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33332. Graphics imG (bufferedImage_);
  33333. paint (imG);
  33334. }
  33335. g.setColour (Colours::black.withAlpha (getAlpha()));
  33336. g.drawImageAt (bufferedImage_, 0, 0);
  33337. }
  33338. else
  33339. {
  33340. paint (g);
  33341. }
  33342. }
  33343. void Component::paintWithinParentContext (Graphics& g)
  33344. {
  33345. g.setOrigin (getX(), getY());
  33346. paintEntireComponent (g, false);
  33347. }
  33348. void Component::paintComponentAndChildren (Graphics& g)
  33349. {
  33350. const Rectangle<int> clipBounds (g.getClipBounds());
  33351. if (flags.dontClipGraphicsFlag)
  33352. {
  33353. paintComponent (g);
  33354. }
  33355. else
  33356. {
  33357. g.saveState();
  33358. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33359. if (! g.isClipEmpty())
  33360. paintComponent (g);
  33361. g.restoreState();
  33362. }
  33363. for (int i = 0; i < childComponentList_.size(); ++i)
  33364. {
  33365. Component& child = *childComponentList_.getUnchecked (i);
  33366. if (child.isVisible())
  33367. {
  33368. if (child.affineTransform_ != 0)
  33369. {
  33370. g.saveState();
  33371. g.addTransform (*child.affineTransform_);
  33372. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33373. child.paintWithinParentContext (g);
  33374. g.restoreState();
  33375. }
  33376. else if (clipBounds.intersects (child.getBounds()))
  33377. {
  33378. g.saveState();
  33379. if (child.flags.dontClipGraphicsFlag)
  33380. {
  33381. child.paintWithinParentContext (g);
  33382. }
  33383. else if (g.reduceClipRegion (child.getBounds()))
  33384. {
  33385. bool nothingClipped = true;
  33386. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33387. {
  33388. const Component& sibling = *childComponentList_.getUnchecked (j);
  33389. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform_ == 0)
  33390. {
  33391. nothingClipped = false;
  33392. g.excludeClipRegion (sibling.getBounds());
  33393. }
  33394. }
  33395. if (nothingClipped || ! g.isClipEmpty())
  33396. child.paintWithinParentContext (g);
  33397. }
  33398. g.restoreState();
  33399. }
  33400. }
  33401. }
  33402. g.saveState();
  33403. paintOverChildren (g);
  33404. g.restoreState();
  33405. }
  33406. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33407. {
  33408. jassert (! g.isClipEmpty());
  33409. #if JUCE_DEBUG
  33410. flags.isInsidePaintCall = true;
  33411. #endif
  33412. if (effect_ != 0)
  33413. {
  33414. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33415. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33416. {
  33417. Graphics g2 (effectImage);
  33418. paintComponentAndChildren (g2);
  33419. }
  33420. effect_->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33421. }
  33422. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33423. {
  33424. if (componentTransparency < 255)
  33425. {
  33426. g.beginTransparencyLayer (getAlpha());
  33427. paintComponentAndChildren (g);
  33428. g.endTransparencyLayer();
  33429. }
  33430. }
  33431. else
  33432. {
  33433. paintComponentAndChildren (g);
  33434. }
  33435. #if JUCE_DEBUG
  33436. flags.isInsidePaintCall = false;
  33437. #endif
  33438. }
  33439. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33440. {
  33441. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33442. }
  33443. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33444. const bool clipImageToComponentBounds)
  33445. {
  33446. Rectangle<int> r (areaToGrab);
  33447. if (clipImageToComponentBounds)
  33448. r = r.getIntersection (getLocalBounds());
  33449. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33450. jmax (1, r.getWidth()),
  33451. jmax (1, r.getHeight()),
  33452. true);
  33453. Graphics imageContext (componentImage);
  33454. imageContext.setOrigin (-r.getX(), -r.getY());
  33455. paintEntireComponent (imageContext, true);
  33456. return componentImage;
  33457. }
  33458. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33459. {
  33460. if (effect_ != effect)
  33461. {
  33462. effect_ = effect;
  33463. repaint();
  33464. }
  33465. }
  33466. LookAndFeel& Component::getLookAndFeel() const throw()
  33467. {
  33468. const Component* c = this;
  33469. do
  33470. {
  33471. if (c->lookAndFeel_ != 0)
  33472. return *(c->lookAndFeel_);
  33473. c = c->parentComponent_;
  33474. }
  33475. while (c != 0);
  33476. return LookAndFeel::getDefaultLookAndFeel();
  33477. }
  33478. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33479. {
  33480. if (lookAndFeel_ != newLookAndFeel)
  33481. {
  33482. lookAndFeel_ = newLookAndFeel;
  33483. sendLookAndFeelChange();
  33484. }
  33485. }
  33486. void Component::lookAndFeelChanged()
  33487. {
  33488. }
  33489. void Component::sendLookAndFeelChange()
  33490. {
  33491. repaint();
  33492. WeakReference<Component> safePointer (this);
  33493. lookAndFeelChanged();
  33494. if (safePointer != 0)
  33495. {
  33496. for (int i = childComponentList_.size(); --i >= 0;)
  33497. {
  33498. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33499. if (safePointer == 0)
  33500. return;
  33501. i = jmin (i, childComponentList_.size());
  33502. }
  33503. }
  33504. }
  33505. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33506. {
  33507. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33508. if (v != 0)
  33509. return Colour ((int) *v);
  33510. if (inheritFromParent && parentComponent_ != 0)
  33511. return parentComponent_->findColour (colourId, true);
  33512. return getLookAndFeel().findColour (colourId);
  33513. }
  33514. bool Component::isColourSpecified (const int colourId) const
  33515. {
  33516. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33517. }
  33518. void Component::removeColour (const int colourId)
  33519. {
  33520. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33521. colourChanged();
  33522. }
  33523. void Component::setColour (const int colourId, const Colour& colour)
  33524. {
  33525. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33526. colourChanged();
  33527. }
  33528. void Component::copyAllExplicitColoursTo (Component& target) const
  33529. {
  33530. bool changed = false;
  33531. for (int i = properties.size(); --i >= 0;)
  33532. {
  33533. const Identifier name (properties.getName(i));
  33534. if (name.toString().startsWith ("jcclr_"))
  33535. if (target.properties.set (name, properties [name]))
  33536. changed = true;
  33537. }
  33538. if (changed)
  33539. target.colourChanged();
  33540. }
  33541. void Component::colourChanged()
  33542. {
  33543. }
  33544. const Rectangle<int> Component::getLocalBounds() const throw()
  33545. {
  33546. return Rectangle<int> (getWidth(), getHeight());
  33547. }
  33548. const Rectangle<int> Component::getBoundsInParent() const throw()
  33549. {
  33550. return affineTransform_ == 0 ? bounds_
  33551. : bounds_.toFloat().transformed (*affineTransform_).getSmallestIntegerContainer();
  33552. }
  33553. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33554. {
  33555. result.clear();
  33556. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33557. if (! unclipped.isEmpty())
  33558. {
  33559. result.add (unclipped);
  33560. if (includeSiblings)
  33561. {
  33562. const Component* const c = getTopLevelComponent();
  33563. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33564. c->getLocalBounds(), this);
  33565. }
  33566. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33567. result.consolidate();
  33568. }
  33569. }
  33570. void Component::mouseEnter (const MouseEvent&)
  33571. {
  33572. // base class does nothing
  33573. }
  33574. void Component::mouseExit (const MouseEvent&)
  33575. {
  33576. // base class does nothing
  33577. }
  33578. void Component::mouseDown (const MouseEvent&)
  33579. {
  33580. // base class does nothing
  33581. }
  33582. void Component::mouseUp (const MouseEvent&)
  33583. {
  33584. // base class does nothing
  33585. }
  33586. void Component::mouseDrag (const MouseEvent&)
  33587. {
  33588. // base class does nothing
  33589. }
  33590. void Component::mouseMove (const MouseEvent&)
  33591. {
  33592. // base class does nothing
  33593. }
  33594. void Component::mouseDoubleClick (const MouseEvent&)
  33595. {
  33596. // base class does nothing
  33597. }
  33598. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33599. {
  33600. // the base class just passes this event up to its parent..
  33601. if (parentComponent_ != 0)
  33602. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33603. wheelIncrementX, wheelIncrementY);
  33604. }
  33605. void Component::resized()
  33606. {
  33607. // base class does nothing
  33608. }
  33609. void Component::moved()
  33610. {
  33611. // base class does nothing
  33612. }
  33613. void Component::childBoundsChanged (Component*)
  33614. {
  33615. // base class does nothing
  33616. }
  33617. void Component::parentSizeChanged()
  33618. {
  33619. // base class does nothing
  33620. }
  33621. void Component::addComponentListener (ComponentListener* const newListener)
  33622. {
  33623. // if component methods are being called from threads other than the message
  33624. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33625. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33626. componentListeners.add (newListener);
  33627. }
  33628. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33629. {
  33630. componentListeners.remove (listenerToRemove);
  33631. }
  33632. void Component::inputAttemptWhenModal()
  33633. {
  33634. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33635. getLookAndFeel().playAlertSound();
  33636. }
  33637. bool Component::canModalEventBeSentToComponent (const Component*)
  33638. {
  33639. return false;
  33640. }
  33641. void Component::internalModalInputAttempt()
  33642. {
  33643. Component* const current = getCurrentlyModalComponent();
  33644. if (current != 0)
  33645. current->inputAttemptWhenModal();
  33646. }
  33647. void Component::paint (Graphics&)
  33648. {
  33649. // all painting is done in the subclasses
  33650. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33651. }
  33652. void Component::paintOverChildren (Graphics&)
  33653. {
  33654. // all painting is done in the subclasses
  33655. }
  33656. void Component::postCommandMessage (const int commandId)
  33657. {
  33658. class CustomCommandMessage : public CallbackMessage
  33659. {
  33660. public:
  33661. CustomCommandMessage (Component* const target_, const int commandId_)
  33662. : target (target_), commandId (commandId_) {}
  33663. void messageCallback()
  33664. {
  33665. if (target.get() != 0) // (get() required for VS2003 bug)
  33666. target->handleCommandMessage (commandId);
  33667. }
  33668. private:
  33669. WeakReference<Component> target;
  33670. int commandId;
  33671. };
  33672. (new CustomCommandMessage (this, commandId))->post();
  33673. }
  33674. void Component::handleCommandMessage (int)
  33675. {
  33676. // used by subclasses
  33677. }
  33678. void Component::addMouseListener (MouseListener* const newListener,
  33679. const bool wantsEventsForAllNestedChildComponents)
  33680. {
  33681. // if component methods are being called from threads other than the message
  33682. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33683. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33684. // If you register a component as a mouselistener for itself, it'll receive all the events
  33685. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33686. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33687. if (mouseListeners_ == 0)
  33688. mouseListeners_ = new MouseListenerList();
  33689. mouseListeners_->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33690. }
  33691. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33692. {
  33693. // if component methods are being called from threads other than the message
  33694. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33695. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33696. if (mouseListeners_ != 0)
  33697. mouseListeners_->removeListener (listenerToRemove);
  33698. }
  33699. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33700. {
  33701. if (isCurrentlyBlockedByAnotherModalComponent())
  33702. {
  33703. // if something else is modal, always just show a normal mouse cursor
  33704. source.showMouseCursor (MouseCursor::NormalCursor);
  33705. return;
  33706. }
  33707. if (! flags.mouseInsideFlag)
  33708. {
  33709. flags.mouseInsideFlag = true;
  33710. flags.mouseOverFlag = true;
  33711. flags.mouseDownFlag = false;
  33712. BailOutChecker checker (this);
  33713. if (flags.repaintOnMouseActivityFlag)
  33714. repaint();
  33715. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33716. this, this, time, relativePos, time, 0, false);
  33717. mouseEnter (me);
  33718. if (checker.shouldBailOut())
  33719. return;
  33720. Desktop& desktop = Desktop::getInstance();
  33721. desktop.resetTimer();
  33722. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33723. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseEnter, me);
  33724. }
  33725. }
  33726. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33727. {
  33728. BailOutChecker checker (this);
  33729. if (flags.mouseDownFlag)
  33730. {
  33731. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33732. if (checker.shouldBailOut())
  33733. return;
  33734. }
  33735. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33736. {
  33737. flags.mouseInsideFlag = false;
  33738. flags.mouseOverFlag = false;
  33739. flags.mouseDownFlag = false;
  33740. if (flags.repaintOnMouseActivityFlag)
  33741. repaint();
  33742. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33743. this, this, time, relativePos, time, 0, false);
  33744. mouseExit (me);
  33745. if (checker.shouldBailOut())
  33746. return;
  33747. Desktop& desktop = Desktop::getInstance();
  33748. desktop.resetTimer();
  33749. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33750. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseExit, me);
  33751. }
  33752. }
  33753. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33754. {
  33755. Desktop& desktop = Desktop::getInstance();
  33756. BailOutChecker checker (this);
  33757. if (isCurrentlyBlockedByAnotherModalComponent())
  33758. {
  33759. internalModalInputAttempt();
  33760. if (checker.shouldBailOut())
  33761. return;
  33762. // If processing the input attempt has exited the modal loop, we'll allow the event
  33763. // to be delivered..
  33764. if (isCurrentlyBlockedByAnotherModalComponent())
  33765. {
  33766. // allow blocked mouse-events to go to global listeners..
  33767. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33768. this, this, time, relativePos, time,
  33769. source.getNumberOfMultipleClicks(), false);
  33770. desktop.resetTimer();
  33771. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33772. return;
  33773. }
  33774. }
  33775. {
  33776. Component* c = this;
  33777. while (c != 0)
  33778. {
  33779. if (c->isBroughtToFrontOnMouseClick())
  33780. {
  33781. c->toFront (true);
  33782. if (checker.shouldBailOut())
  33783. return;
  33784. }
  33785. c = c->parentComponent_;
  33786. }
  33787. }
  33788. if (! flags.dontFocusOnMouseClickFlag)
  33789. {
  33790. grabFocusInternal (focusChangedByMouseClick);
  33791. if (checker.shouldBailOut())
  33792. return;
  33793. }
  33794. flags.mouseDownFlag = true;
  33795. flags.mouseOverFlag = true;
  33796. if (flags.repaintOnMouseActivityFlag)
  33797. repaint();
  33798. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33799. this, this, time, relativePos, time,
  33800. source.getNumberOfMultipleClicks(), false);
  33801. mouseDown (me);
  33802. if (checker.shouldBailOut())
  33803. return;
  33804. desktop.resetTimer();
  33805. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33806. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDown, me);
  33807. }
  33808. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33809. {
  33810. if (flags.mouseDownFlag)
  33811. {
  33812. flags.mouseDownFlag = false;
  33813. BailOutChecker checker (this);
  33814. if (flags.repaintOnMouseActivityFlag)
  33815. repaint();
  33816. const MouseEvent me (source, relativePos,
  33817. oldModifiers, this, this, time,
  33818. getLocalPoint (0, source.getLastMouseDownPosition()),
  33819. source.getLastMouseDownTime(),
  33820. source.getNumberOfMultipleClicks(),
  33821. source.hasMouseMovedSignificantlySincePressed());
  33822. mouseUp (me);
  33823. if (checker.shouldBailOut())
  33824. return;
  33825. Desktop& desktop = Desktop::getInstance();
  33826. desktop.resetTimer();
  33827. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33828. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseUp, me);
  33829. if (checker.shouldBailOut())
  33830. return;
  33831. // check for double-click
  33832. if (me.getNumberOfClicks() >= 2)
  33833. {
  33834. mouseDoubleClick (me);
  33835. if (checker.shouldBailOut())
  33836. return;
  33837. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33838. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDoubleClick, me);
  33839. }
  33840. }
  33841. }
  33842. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33843. {
  33844. if (flags.mouseDownFlag)
  33845. {
  33846. flags.mouseOverFlag = reallyContains (relativePos, false);
  33847. BailOutChecker checker (this);
  33848. const MouseEvent me (source, relativePos,
  33849. source.getCurrentModifiers(), this, this, time,
  33850. getLocalPoint (0, source.getLastMouseDownPosition()),
  33851. source.getLastMouseDownTime(),
  33852. source.getNumberOfMultipleClicks(),
  33853. source.hasMouseMovedSignificantlySincePressed());
  33854. mouseDrag (me);
  33855. if (checker.shouldBailOut())
  33856. return;
  33857. Desktop& desktop = Desktop::getInstance();
  33858. desktop.resetTimer();
  33859. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33860. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDrag, me);
  33861. }
  33862. }
  33863. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33864. {
  33865. Desktop& desktop = Desktop::getInstance();
  33866. BailOutChecker checker (this);
  33867. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33868. this, this, time, relativePos, time, 0, false);
  33869. if (isCurrentlyBlockedByAnotherModalComponent())
  33870. {
  33871. // allow blocked mouse-events to go to global listeners..
  33872. desktop.sendMouseMove();
  33873. }
  33874. else
  33875. {
  33876. flags.mouseOverFlag = true;
  33877. mouseMove (me);
  33878. if (checker.shouldBailOut())
  33879. return;
  33880. desktop.resetTimer();
  33881. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33882. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseMove, me);
  33883. }
  33884. }
  33885. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33886. const Time& time, const float amountX, const float amountY)
  33887. {
  33888. Desktop& desktop = Desktop::getInstance();
  33889. BailOutChecker checker (this);
  33890. const float wheelIncrementX = amountX / 256.0f;
  33891. const float wheelIncrementY = amountY / 256.0f;
  33892. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33893. this, this, time, relativePos, time, 0, false);
  33894. if (isCurrentlyBlockedByAnotherModalComponent())
  33895. {
  33896. // allow blocked mouse-events to go to global listeners..
  33897. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33898. }
  33899. else
  33900. {
  33901. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33902. if (checker.shouldBailOut())
  33903. return;
  33904. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33905. MouseListenerList::sendWheelEvent (this, checker, me, wheelIncrementX, wheelIncrementY);
  33906. }
  33907. }
  33908. void Component::sendFakeMouseMove() const
  33909. {
  33910. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33911. if (! mainMouse.isDragging())
  33912. mainMouse.triggerFakeMove();
  33913. }
  33914. void Component::beginDragAutoRepeat (const int interval)
  33915. {
  33916. Desktop::getInstance().beginDragAutoRepeat (interval);
  33917. }
  33918. void Component::broughtToFront()
  33919. {
  33920. }
  33921. void Component::internalBroughtToFront()
  33922. {
  33923. if (flags.hasHeavyweightPeerFlag)
  33924. Desktop::getInstance().componentBroughtToFront (this);
  33925. BailOutChecker checker (this);
  33926. broughtToFront();
  33927. if (checker.shouldBailOut())
  33928. return;
  33929. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33930. if (checker.shouldBailOut())
  33931. return;
  33932. // When brought to the front and there's a modal component blocking this one,
  33933. // we need to bring the modal one to the front instead..
  33934. Component* const cm = getCurrentlyModalComponent();
  33935. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33936. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33937. }
  33938. void Component::focusGained (FocusChangeType)
  33939. {
  33940. // base class does nothing
  33941. }
  33942. void Component::internalFocusGain (const FocusChangeType cause)
  33943. {
  33944. WeakReference<Component> safePointer (this);
  33945. focusGained (cause);
  33946. if (safePointer != 0)
  33947. internalChildFocusChange (cause);
  33948. }
  33949. void Component::focusLost (FocusChangeType)
  33950. {
  33951. // base class does nothing
  33952. }
  33953. void Component::internalFocusLoss (const FocusChangeType cause)
  33954. {
  33955. WeakReference<Component> safePointer (this);
  33956. focusLost (focusChangedDirectly);
  33957. if (safePointer != 0)
  33958. internalChildFocusChange (cause);
  33959. }
  33960. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33961. {
  33962. // base class does nothing
  33963. }
  33964. void Component::internalChildFocusChange (FocusChangeType cause)
  33965. {
  33966. const bool childIsNowFocused = hasKeyboardFocus (true);
  33967. if (flags.childCompFocusedFlag != childIsNowFocused)
  33968. {
  33969. flags.childCompFocusedFlag = childIsNowFocused;
  33970. WeakReference<Component> safePointer (this);
  33971. focusOfChildComponentChanged (cause);
  33972. if (safePointer == 0)
  33973. return;
  33974. }
  33975. if (parentComponent_ != 0)
  33976. parentComponent_->internalChildFocusChange (cause);
  33977. }
  33978. bool Component::isEnabled() const throw()
  33979. {
  33980. return (! flags.isDisabledFlag)
  33981. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33982. }
  33983. void Component::setEnabled (const bool shouldBeEnabled)
  33984. {
  33985. if (flags.isDisabledFlag == shouldBeEnabled)
  33986. {
  33987. flags.isDisabledFlag = ! shouldBeEnabled;
  33988. // if any parent components are disabled, setting our flag won't make a difference,
  33989. // so no need to send a change message
  33990. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33991. sendEnablementChangeMessage();
  33992. }
  33993. }
  33994. void Component::sendEnablementChangeMessage()
  33995. {
  33996. WeakReference<Component> safePointer (this);
  33997. enablementChanged();
  33998. if (safePointer == 0)
  33999. return;
  34000. for (int i = getNumChildComponents(); --i >= 0;)
  34001. {
  34002. Component* const c = getChildComponent (i);
  34003. if (c != 0)
  34004. {
  34005. c->sendEnablementChangeMessage();
  34006. if (safePointer == 0)
  34007. return;
  34008. }
  34009. }
  34010. }
  34011. void Component::enablementChanged()
  34012. {
  34013. }
  34014. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34015. {
  34016. flags.wantsFocusFlag = wantsFocus;
  34017. }
  34018. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34019. {
  34020. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34021. }
  34022. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34023. {
  34024. return ! flags.dontFocusOnMouseClickFlag;
  34025. }
  34026. bool Component::getWantsKeyboardFocus() const throw()
  34027. {
  34028. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34029. }
  34030. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34031. {
  34032. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34033. }
  34034. bool Component::isFocusContainer() const throw()
  34035. {
  34036. return flags.isFocusContainerFlag;
  34037. }
  34038. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34039. int Component::getExplicitFocusOrder() const
  34040. {
  34041. return properties [juce_explicitFocusOrderId];
  34042. }
  34043. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34044. {
  34045. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34046. }
  34047. KeyboardFocusTraverser* Component::createFocusTraverser()
  34048. {
  34049. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34050. return new KeyboardFocusTraverser();
  34051. return parentComponent_->createFocusTraverser();
  34052. }
  34053. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34054. {
  34055. // give the focus to this component
  34056. if (currentlyFocusedComponent != this)
  34057. {
  34058. JUCE_TRY
  34059. {
  34060. // get the focus onto our desktop window
  34061. ComponentPeer* const peer = getPeer();
  34062. if (peer != 0)
  34063. {
  34064. WeakReference<Component> safePointer (this);
  34065. peer->grabFocus();
  34066. if (peer->isFocused() && currentlyFocusedComponent != this)
  34067. {
  34068. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  34069. currentlyFocusedComponent = this;
  34070. Desktop::getInstance().triggerFocusCallback();
  34071. // call this after setting currentlyFocusedComponent so that the one that's
  34072. // losing it has a chance to see where focus is going
  34073. if (componentLosingFocus != 0)
  34074. componentLosingFocus->internalFocusLoss (cause);
  34075. if (currentlyFocusedComponent == this)
  34076. {
  34077. focusGained (cause);
  34078. if (safePointer != 0)
  34079. internalChildFocusChange (cause);
  34080. }
  34081. }
  34082. }
  34083. }
  34084. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34085. catch (const std::exception& e)
  34086. {
  34087. currentlyFocusedComponent = 0;
  34088. Desktop::getInstance().triggerFocusCallback();
  34089. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34090. }
  34091. catch (...)
  34092. {
  34093. currentlyFocusedComponent = 0;
  34094. Desktop::getInstance().triggerFocusCallback();
  34095. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34096. }
  34097. #endif
  34098. }
  34099. }
  34100. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34101. {
  34102. if (isShowing())
  34103. {
  34104. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34105. {
  34106. takeKeyboardFocus (cause);
  34107. }
  34108. else
  34109. {
  34110. if (isParentOf (currentlyFocusedComponent)
  34111. && currentlyFocusedComponent->isShowing())
  34112. {
  34113. // do nothing if the focused component is actually a child of ours..
  34114. }
  34115. else
  34116. {
  34117. // find the default child component..
  34118. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34119. if (traverser != 0)
  34120. {
  34121. Component* const defaultComp = traverser->getDefaultComponent (this);
  34122. traverser = 0;
  34123. if (defaultComp != 0)
  34124. {
  34125. defaultComp->grabFocusInternal (cause, false);
  34126. return;
  34127. }
  34128. }
  34129. if (canTryParent && parentComponent_ != 0)
  34130. {
  34131. // if no children want it and we're allowed to try our parent comp,
  34132. // then pass up to parent, which will try our siblings.
  34133. parentComponent_->grabFocusInternal (cause, true);
  34134. }
  34135. }
  34136. }
  34137. }
  34138. }
  34139. void Component::grabKeyboardFocus()
  34140. {
  34141. // if component methods are being called from threads other than the message
  34142. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34143. CHECK_MESSAGE_MANAGER_IS_LOCKED
  34144. grabFocusInternal (focusChangedDirectly);
  34145. }
  34146. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34147. {
  34148. // if component methods are being called from threads other than the message
  34149. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34150. CHECK_MESSAGE_MANAGER_IS_LOCKED
  34151. if (parentComponent_ != 0)
  34152. {
  34153. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34154. if (traverser != 0)
  34155. {
  34156. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34157. : traverser->getPreviousComponent (this);
  34158. traverser = 0;
  34159. if (nextComp != 0)
  34160. {
  34161. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34162. {
  34163. WeakReference<Component> nextCompPointer (nextComp);
  34164. internalModalInputAttempt();
  34165. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34166. return;
  34167. }
  34168. nextComp->grabFocusInternal (focusChangedByTabKey);
  34169. return;
  34170. }
  34171. }
  34172. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34173. }
  34174. }
  34175. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34176. {
  34177. return (currentlyFocusedComponent == this)
  34178. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34179. }
  34180. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34181. {
  34182. return currentlyFocusedComponent;
  34183. }
  34184. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  34185. {
  34186. Component* const componentLosingFocus = currentlyFocusedComponent;
  34187. currentlyFocusedComponent = 0;
  34188. if (sendFocusLossEvent && componentLosingFocus != 0)
  34189. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34190. Desktop::getInstance().triggerFocusCallback();
  34191. }
  34192. bool Component::isMouseOver (const bool includeChildren) const
  34193. {
  34194. if (flags.mouseOverFlag)
  34195. return true;
  34196. if (includeChildren)
  34197. {
  34198. Desktop& desktop = Desktop::getInstance();
  34199. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34200. {
  34201. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  34202. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  34203. return true;
  34204. }
  34205. }
  34206. return false;
  34207. }
  34208. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  34209. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  34210. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34211. {
  34212. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34213. }
  34214. const Point<int> Component::getMouseXYRelative() const
  34215. {
  34216. return getLocalPoint (0, Desktop::getMousePosition());
  34217. }
  34218. const Rectangle<int> Component::getParentMonitorArea() const
  34219. {
  34220. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  34221. }
  34222. void Component::addKeyListener (KeyListener* const newListener)
  34223. {
  34224. if (keyListeners_ == 0)
  34225. keyListeners_ = new Array <KeyListener*>();
  34226. keyListeners_->addIfNotAlreadyThere (newListener);
  34227. }
  34228. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34229. {
  34230. if (keyListeners_ != 0)
  34231. keyListeners_->removeValue (listenerToRemove);
  34232. }
  34233. bool Component::keyPressed (const KeyPress&)
  34234. {
  34235. return false;
  34236. }
  34237. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34238. {
  34239. return false;
  34240. }
  34241. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34242. {
  34243. if (parentComponent_ != 0)
  34244. parentComponent_->modifierKeysChanged (modifiers);
  34245. }
  34246. void Component::internalModifierKeysChanged()
  34247. {
  34248. sendFakeMouseMove();
  34249. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34250. }
  34251. ComponentPeer* Component::getPeer() const
  34252. {
  34253. if (flags.hasHeavyweightPeerFlag)
  34254. return ComponentPeer::getPeerFor (this);
  34255. else if (parentComponent_ == 0)
  34256. return 0;
  34257. return parentComponent_->getPeer();
  34258. }
  34259. Component::BailOutChecker::BailOutChecker (Component* const component)
  34260. : safePointer1 (component)
  34261. {
  34262. jassert (component != 0);
  34263. }
  34264. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2)
  34265. : safePointer1 (component1), safePointer2 (component2)
  34266. {
  34267. jassert (component1 != 0);
  34268. }
  34269. bool Component::BailOutChecker::shouldBailOut() const throw()
  34270. {
  34271. return safePointer1 == 0 || safePointer2.wasObjectDeleted();
  34272. }
  34273. END_JUCE_NAMESPACE
  34274. /*** End of inlined file: juce_Component.cpp ***/
  34275. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34276. BEGIN_JUCE_NAMESPACE
  34277. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34278. void ComponentListener::componentBroughtToFront (Component&) {}
  34279. void ComponentListener::componentVisibilityChanged (Component&) {}
  34280. void ComponentListener::componentChildrenChanged (Component&) {}
  34281. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34282. void ComponentListener::componentNameChanged (Component&) {}
  34283. void ComponentListener::componentBeingDeleted (Component&) {}
  34284. END_JUCE_NAMESPACE
  34285. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34286. /*** Start of inlined file: juce_Desktop.cpp ***/
  34287. BEGIN_JUCE_NAMESPACE
  34288. Desktop::Desktop()
  34289. : mouseClickCounter (0),
  34290. kioskModeComponent (0),
  34291. allowedOrientations (allOrientations)
  34292. {
  34293. createMouseInputSources();
  34294. refreshMonitorSizes();
  34295. }
  34296. Desktop::~Desktop()
  34297. {
  34298. jassert (instance == this);
  34299. instance = 0;
  34300. // doh! If you don't delete all your windows before exiting, you're going to
  34301. // be leaking memory!
  34302. jassert (desktopComponents.size() == 0);
  34303. }
  34304. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34305. {
  34306. if (instance == 0)
  34307. instance = new Desktop();
  34308. return *instance;
  34309. }
  34310. Desktop* Desktop::instance = 0;
  34311. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34312. const bool clipToWorkArea);
  34313. void Desktop::refreshMonitorSizes()
  34314. {
  34315. Array <Rectangle<int> > oldClipped, oldUnclipped;
  34316. oldClipped.swapWithArray (monitorCoordsClipped);
  34317. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  34318. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34319. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34320. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34321. if (oldClipped != monitorCoordsClipped
  34322. || oldUnclipped != monitorCoordsUnclipped)
  34323. {
  34324. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34325. {
  34326. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34327. if (p != 0)
  34328. p->handleScreenSizeChange();
  34329. }
  34330. }
  34331. }
  34332. int Desktop::getNumDisplayMonitors() const throw()
  34333. {
  34334. return monitorCoordsClipped.size();
  34335. }
  34336. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34337. {
  34338. return clippedToWorkArea ? monitorCoordsClipped [index]
  34339. : monitorCoordsUnclipped [index];
  34340. }
  34341. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34342. {
  34343. RectangleList rl;
  34344. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34345. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34346. return rl;
  34347. }
  34348. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34349. {
  34350. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34351. }
  34352. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34353. {
  34354. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34355. double bestDistance = 1.0e10;
  34356. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34357. {
  34358. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34359. if (rect.contains (position))
  34360. return rect;
  34361. const double distance = rect.getCentre().getDistanceFrom (position);
  34362. if (distance < bestDistance)
  34363. {
  34364. bestDistance = distance;
  34365. best = rect;
  34366. }
  34367. }
  34368. return best;
  34369. }
  34370. int Desktop::getNumComponents() const throw()
  34371. {
  34372. return desktopComponents.size();
  34373. }
  34374. Component* Desktop::getComponent (const int index) const throw()
  34375. {
  34376. return desktopComponents [index];
  34377. }
  34378. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34379. {
  34380. for (int i = desktopComponents.size(); --i >= 0;)
  34381. {
  34382. Component* const c = desktopComponents.getUnchecked(i);
  34383. if (c->isVisible())
  34384. {
  34385. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34386. if (c->contains (relative))
  34387. return c->getComponentAt (relative);
  34388. }
  34389. }
  34390. return 0;
  34391. }
  34392. void Desktop::addDesktopComponent (Component* const c)
  34393. {
  34394. jassert (c != 0);
  34395. jassert (! desktopComponents.contains (c));
  34396. desktopComponents.addIfNotAlreadyThere (c);
  34397. }
  34398. void Desktop::removeDesktopComponent (Component* const c)
  34399. {
  34400. desktopComponents.removeValue (c);
  34401. }
  34402. void Desktop::componentBroughtToFront (Component* const c)
  34403. {
  34404. const int index = desktopComponents.indexOf (c);
  34405. jassert (index >= 0);
  34406. if (index >= 0)
  34407. {
  34408. int newIndex = -1;
  34409. if (! c->isAlwaysOnTop())
  34410. {
  34411. newIndex = desktopComponents.size();
  34412. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34413. --newIndex;
  34414. --newIndex;
  34415. }
  34416. desktopComponents.move (index, newIndex);
  34417. }
  34418. }
  34419. const Point<int> Desktop::getMousePosition()
  34420. {
  34421. return getInstance().getMainMouseSource().getScreenPosition();
  34422. }
  34423. const Point<int> Desktop::getLastMouseDownPosition()
  34424. {
  34425. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34426. }
  34427. int Desktop::getMouseButtonClickCounter()
  34428. {
  34429. return getInstance().mouseClickCounter;
  34430. }
  34431. void Desktop::incrementMouseClickCounter() throw()
  34432. {
  34433. ++mouseClickCounter;
  34434. }
  34435. int Desktop::getNumDraggingMouseSources() const throw()
  34436. {
  34437. int num = 0;
  34438. for (int i = mouseSources.size(); --i >= 0;)
  34439. if (mouseSources.getUnchecked(i)->isDragging())
  34440. ++num;
  34441. return num;
  34442. }
  34443. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34444. {
  34445. int num = 0;
  34446. for (int i = mouseSources.size(); --i >= 0;)
  34447. {
  34448. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34449. if (mi->isDragging())
  34450. {
  34451. if (index == num)
  34452. return mi;
  34453. ++num;
  34454. }
  34455. }
  34456. return 0;
  34457. }
  34458. class MouseDragAutoRepeater : public Timer
  34459. {
  34460. public:
  34461. MouseDragAutoRepeater() {}
  34462. void timerCallback()
  34463. {
  34464. Desktop& desktop = Desktop::getInstance();
  34465. int numMiceDown = 0;
  34466. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34467. {
  34468. MouseInputSource* const source = desktop.getMouseSource(i);
  34469. if (source->isDragging())
  34470. {
  34471. source->triggerFakeMove();
  34472. ++numMiceDown;
  34473. }
  34474. }
  34475. if (numMiceDown == 0)
  34476. desktop.beginDragAutoRepeat (0);
  34477. }
  34478. private:
  34479. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34480. };
  34481. void Desktop::beginDragAutoRepeat (const int interval)
  34482. {
  34483. if (interval > 0)
  34484. {
  34485. if (dragRepeater == 0)
  34486. dragRepeater = new MouseDragAutoRepeater();
  34487. if (dragRepeater->getTimerInterval() != interval)
  34488. dragRepeater->startTimer (interval);
  34489. }
  34490. else
  34491. {
  34492. dragRepeater = 0;
  34493. }
  34494. }
  34495. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34496. {
  34497. focusListeners.add (listener);
  34498. }
  34499. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34500. {
  34501. focusListeners.remove (listener);
  34502. }
  34503. void Desktop::triggerFocusCallback()
  34504. {
  34505. triggerAsyncUpdate();
  34506. }
  34507. void Desktop::handleAsyncUpdate()
  34508. {
  34509. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34510. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34511. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34512. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34513. }
  34514. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34515. {
  34516. mouseListeners.add (listener);
  34517. resetTimer();
  34518. }
  34519. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34520. {
  34521. mouseListeners.remove (listener);
  34522. resetTimer();
  34523. }
  34524. void Desktop::timerCallback()
  34525. {
  34526. if (lastFakeMouseMove != getMousePosition())
  34527. sendMouseMove();
  34528. }
  34529. void Desktop::sendMouseMove()
  34530. {
  34531. if (! mouseListeners.isEmpty())
  34532. {
  34533. startTimer (20);
  34534. lastFakeMouseMove = getMousePosition();
  34535. Component* const target = findComponentAt (lastFakeMouseMove);
  34536. if (target != 0)
  34537. {
  34538. Component::BailOutChecker checker (target);
  34539. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34540. const Time now (Time::getCurrentTime());
  34541. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34542. target, target, now, pos, now, 0, false);
  34543. if (me.mods.isAnyMouseButtonDown())
  34544. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34545. else
  34546. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34547. }
  34548. }
  34549. }
  34550. void Desktop::resetTimer()
  34551. {
  34552. if (mouseListeners.size() == 0)
  34553. stopTimer();
  34554. else
  34555. startTimer (100);
  34556. lastFakeMouseMove = getMousePosition();
  34557. }
  34558. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34559. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34560. {
  34561. if (kioskModeComponent != componentToUse)
  34562. {
  34563. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34564. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34565. if (kioskModeComponent != 0)
  34566. {
  34567. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34568. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34569. }
  34570. kioskModeComponent = componentToUse;
  34571. if (kioskModeComponent != 0)
  34572. {
  34573. // Only components that are already on the desktop can be put into kiosk mode!
  34574. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34575. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34576. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34577. }
  34578. }
  34579. }
  34580. void Desktop::setOrientationsEnabled (const int newOrientations)
  34581. {
  34582. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34583. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34584. allowedOrientations = newOrientations;
  34585. }
  34586. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34587. {
  34588. // Make sure you only pass one valid flag in here...
  34589. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34590. return (allowedOrientations & orientation) != 0;
  34591. }
  34592. END_JUCE_NAMESPACE
  34593. /*** End of inlined file: juce_Desktop.cpp ***/
  34594. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34595. BEGIN_JUCE_NAMESPACE
  34596. class ModalComponentManager::ModalItem : public ComponentListener
  34597. {
  34598. public:
  34599. ModalItem (Component* const comp, Callback* const callback)
  34600. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34601. {
  34602. if (callback != 0)
  34603. callbacks.add (callback);
  34604. jassert (comp != 0);
  34605. component->addComponentListener (this);
  34606. }
  34607. ~ModalItem()
  34608. {
  34609. if (! isDeleted)
  34610. component->removeComponentListener (this);
  34611. }
  34612. void componentBeingDeleted (Component&)
  34613. {
  34614. isDeleted = true;
  34615. cancel();
  34616. }
  34617. void componentVisibilityChanged (Component&)
  34618. {
  34619. if (! component->isShowing())
  34620. cancel();
  34621. }
  34622. void componentParentHierarchyChanged (Component&)
  34623. {
  34624. if (! component->isShowing())
  34625. cancel();
  34626. }
  34627. void cancel()
  34628. {
  34629. if (isActive)
  34630. {
  34631. isActive = false;
  34632. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34633. }
  34634. }
  34635. Component* component;
  34636. OwnedArray<Callback> callbacks;
  34637. int returnValue;
  34638. bool isActive, isDeleted;
  34639. private:
  34640. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34641. };
  34642. ModalComponentManager::ModalComponentManager()
  34643. {
  34644. }
  34645. ModalComponentManager::~ModalComponentManager()
  34646. {
  34647. clearSingletonInstance();
  34648. }
  34649. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34650. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34651. {
  34652. if (component != 0)
  34653. stack.add (new ModalItem (component, callback));
  34654. }
  34655. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34656. {
  34657. if (callback != 0)
  34658. {
  34659. ScopedPointer<Callback> callbackDeleter (callback);
  34660. for (int i = stack.size(); --i >= 0;)
  34661. {
  34662. ModalItem* const item = stack.getUnchecked(i);
  34663. if (item->component == component)
  34664. {
  34665. item->callbacks.add (callback);
  34666. callbackDeleter.release();
  34667. break;
  34668. }
  34669. }
  34670. }
  34671. }
  34672. void ModalComponentManager::endModal (Component* component)
  34673. {
  34674. for (int i = stack.size(); --i >= 0;)
  34675. {
  34676. ModalItem* const item = stack.getUnchecked(i);
  34677. if (item->component == component)
  34678. item->cancel();
  34679. }
  34680. }
  34681. void ModalComponentManager::endModal (Component* component, int returnValue)
  34682. {
  34683. for (int i = stack.size(); --i >= 0;)
  34684. {
  34685. ModalItem* const item = stack.getUnchecked(i);
  34686. if (item->component == component)
  34687. {
  34688. item->returnValue = returnValue;
  34689. item->cancel();
  34690. }
  34691. }
  34692. }
  34693. int ModalComponentManager::getNumModalComponents() const
  34694. {
  34695. int n = 0;
  34696. for (int i = 0; i < stack.size(); ++i)
  34697. if (stack.getUnchecked(i)->isActive)
  34698. ++n;
  34699. return n;
  34700. }
  34701. Component* ModalComponentManager::getModalComponent (const int index) const
  34702. {
  34703. int n = 0;
  34704. for (int i = stack.size(); --i >= 0;)
  34705. {
  34706. const ModalItem* const item = stack.getUnchecked(i);
  34707. if (item->isActive)
  34708. if (n++ == index)
  34709. return item->component;
  34710. }
  34711. return 0;
  34712. }
  34713. bool ModalComponentManager::isModal (Component* const comp) const
  34714. {
  34715. for (int i = stack.size(); --i >= 0;)
  34716. {
  34717. const ModalItem* const item = stack.getUnchecked(i);
  34718. if (item->isActive && item->component == comp)
  34719. return true;
  34720. }
  34721. return false;
  34722. }
  34723. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34724. {
  34725. return comp == getModalComponent (0);
  34726. }
  34727. void ModalComponentManager::handleAsyncUpdate()
  34728. {
  34729. for (int i = stack.size(); --i >= 0;)
  34730. {
  34731. const ModalItem* const item = stack.getUnchecked(i);
  34732. if (! item->isActive)
  34733. {
  34734. for (int j = item->callbacks.size(); --j >= 0;)
  34735. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34736. stack.remove (i);
  34737. }
  34738. }
  34739. }
  34740. void ModalComponentManager::bringModalComponentsToFront()
  34741. {
  34742. ComponentPeer* lastOne = 0;
  34743. for (int i = 0; i < getNumModalComponents(); ++i)
  34744. {
  34745. Component* const c = getModalComponent (i);
  34746. if (c == 0)
  34747. break;
  34748. ComponentPeer* peer = c->getPeer();
  34749. if (peer != 0 && peer != lastOne)
  34750. {
  34751. if (lastOne == 0)
  34752. {
  34753. peer->toFront (true);
  34754. peer->grabFocus();
  34755. }
  34756. else
  34757. peer->toBehind (lastOne);
  34758. lastOne = peer;
  34759. }
  34760. }
  34761. }
  34762. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34763. {
  34764. public:
  34765. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34766. ~ReturnValueRetriever() {}
  34767. void modalStateFinished (int returnValue)
  34768. {
  34769. finished = true;
  34770. value = returnValue;
  34771. }
  34772. private:
  34773. int& value;
  34774. bool& finished;
  34775. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34776. };
  34777. int ModalComponentManager::runEventLoopForCurrentComponent()
  34778. {
  34779. // This can only be run from the message thread!
  34780. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34781. Component* currentlyModal = getModalComponent (0);
  34782. if (currentlyModal == 0)
  34783. return 0;
  34784. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34785. int returnValue = 0;
  34786. bool finished = false;
  34787. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34788. JUCE_TRY
  34789. {
  34790. while (! finished)
  34791. {
  34792. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34793. break;
  34794. }
  34795. }
  34796. JUCE_CATCH_EXCEPTION
  34797. if (prevFocused != 0)
  34798. prevFocused->grabKeyboardFocus();
  34799. return returnValue;
  34800. }
  34801. END_JUCE_NAMESPACE
  34802. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34803. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34804. BEGIN_JUCE_NAMESPACE
  34805. ArrowButton::ArrowButton (const String& name,
  34806. float arrowDirectionInRadians,
  34807. const Colour& arrowColour)
  34808. : Button (name),
  34809. colour (arrowColour)
  34810. {
  34811. path.lineTo (0.0f, 1.0f);
  34812. path.lineTo (1.0f, 0.5f);
  34813. path.closeSubPath();
  34814. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34815. 0.5f, 0.5f));
  34816. setComponentEffect (&shadow);
  34817. buttonStateChanged();
  34818. }
  34819. ArrowButton::~ArrowButton()
  34820. {
  34821. }
  34822. void ArrowButton::paintButton (Graphics& g,
  34823. bool /*isMouseOverButton*/,
  34824. bool /*isButtonDown*/)
  34825. {
  34826. g.setColour (colour);
  34827. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34828. (float) offset,
  34829. (float) (getWidth() - 3),
  34830. (float) (getHeight() - 3),
  34831. false));
  34832. }
  34833. void ArrowButton::buttonStateChanged()
  34834. {
  34835. offset = (isDown()) ? 1 : 0;
  34836. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34837. 0.3f, -1, 0);
  34838. }
  34839. END_JUCE_NAMESPACE
  34840. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34841. /*** Start of inlined file: juce_Button.cpp ***/
  34842. BEGIN_JUCE_NAMESPACE
  34843. class Button::RepeatTimer : public Timer
  34844. {
  34845. public:
  34846. RepeatTimer (Button& owner_) : owner (owner_) {}
  34847. void timerCallback() { owner.repeatTimerCallback(); }
  34848. private:
  34849. Button& owner;
  34850. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34851. };
  34852. Button::Button (const String& name)
  34853. : Component (name),
  34854. text (name),
  34855. buttonPressTime (0),
  34856. lastRepeatTime (0),
  34857. commandManagerToUse (0),
  34858. autoRepeatDelay (-1),
  34859. autoRepeatSpeed (0),
  34860. autoRepeatMinimumDelay (-1),
  34861. radioGroupId (0),
  34862. commandID (0),
  34863. connectedEdgeFlags (0),
  34864. buttonState (buttonNormal),
  34865. lastToggleState (false),
  34866. clickTogglesState (false),
  34867. needsToRelease (false),
  34868. needsRepainting (false),
  34869. isKeyDown (false),
  34870. triggerOnMouseDown (false),
  34871. generateTooltip (false)
  34872. {
  34873. setWantsKeyboardFocus (true);
  34874. isOn.addListener (this);
  34875. }
  34876. Button::~Button()
  34877. {
  34878. isOn.removeListener (this);
  34879. if (commandManagerToUse != 0)
  34880. commandManagerToUse->removeListener (this);
  34881. repeatTimer = 0;
  34882. clearShortcuts();
  34883. }
  34884. void Button::setButtonText (const String& newText)
  34885. {
  34886. if (text != newText)
  34887. {
  34888. text = newText;
  34889. repaint();
  34890. }
  34891. }
  34892. void Button::setTooltip (const String& newTooltip)
  34893. {
  34894. SettableTooltipClient::setTooltip (newTooltip);
  34895. generateTooltip = false;
  34896. }
  34897. const String Button::getTooltip()
  34898. {
  34899. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34900. {
  34901. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34902. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34903. for (int i = 0; i < keyPresses.size(); ++i)
  34904. {
  34905. const String key (keyPresses.getReference(i).getTextDescription());
  34906. tt << " [";
  34907. if (key.length() == 1)
  34908. tt << TRANS("shortcut") << ": '" << key << "']";
  34909. else
  34910. tt << key << ']';
  34911. }
  34912. return tt;
  34913. }
  34914. return SettableTooltipClient::getTooltip();
  34915. }
  34916. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34917. {
  34918. if (connectedEdgeFlags != connectedEdgeFlags_)
  34919. {
  34920. connectedEdgeFlags = connectedEdgeFlags_;
  34921. repaint();
  34922. }
  34923. }
  34924. void Button::setToggleState (const bool shouldBeOn,
  34925. const bool sendChangeNotification)
  34926. {
  34927. if (shouldBeOn != lastToggleState)
  34928. {
  34929. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34930. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34931. lastToggleState = shouldBeOn;
  34932. repaint();
  34933. if (sendChangeNotification)
  34934. {
  34935. WeakReference<Component> deletionWatcher (this);
  34936. sendClickMessage (ModifierKeys());
  34937. if (deletionWatcher == 0)
  34938. return;
  34939. }
  34940. if (lastToggleState)
  34941. turnOffOtherButtonsInGroup (sendChangeNotification);
  34942. }
  34943. }
  34944. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34945. {
  34946. clickTogglesState = shouldToggle;
  34947. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34948. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34949. // it is that this button represents, and the button will update its state to reflect this
  34950. // in the applicationCommandListChanged() method.
  34951. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34952. }
  34953. bool Button::getClickingTogglesState() const throw()
  34954. {
  34955. return clickTogglesState;
  34956. }
  34957. void Button::valueChanged (Value& value)
  34958. {
  34959. if (value.refersToSameSourceAs (isOn))
  34960. setToggleState (isOn.getValue(), true);
  34961. }
  34962. void Button::setRadioGroupId (const int newGroupId)
  34963. {
  34964. if (radioGroupId != newGroupId)
  34965. {
  34966. radioGroupId = newGroupId;
  34967. if (lastToggleState)
  34968. turnOffOtherButtonsInGroup (true);
  34969. }
  34970. }
  34971. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34972. {
  34973. Component* const p = getParentComponent();
  34974. if (p != 0 && radioGroupId != 0)
  34975. {
  34976. WeakReference<Component> deletionWatcher (this);
  34977. for (int i = p->getNumChildComponents(); --i >= 0;)
  34978. {
  34979. Component* const c = p->getChildComponent (i);
  34980. if (c != this)
  34981. {
  34982. Button* const b = dynamic_cast <Button*> (c);
  34983. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34984. {
  34985. b->setToggleState (false, sendChangeNotification);
  34986. if (deletionWatcher == 0)
  34987. return;
  34988. }
  34989. }
  34990. }
  34991. }
  34992. }
  34993. void Button::enablementChanged()
  34994. {
  34995. updateState();
  34996. repaint();
  34997. }
  34998. Button::ButtonState Button::updateState()
  34999. {
  35000. return updateState (isMouseOver (true), isMouseButtonDown());
  35001. }
  35002. Button::ButtonState Button::updateState (const bool over, const bool down)
  35003. {
  35004. ButtonState newState = buttonNormal;
  35005. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  35006. {
  35007. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  35008. newState = buttonDown;
  35009. else if (over)
  35010. newState = buttonOver;
  35011. }
  35012. setState (newState);
  35013. return newState;
  35014. }
  35015. void Button::setState (const ButtonState newState)
  35016. {
  35017. if (buttonState != newState)
  35018. {
  35019. buttonState = newState;
  35020. repaint();
  35021. if (buttonState == buttonDown)
  35022. {
  35023. buttonPressTime = Time::getApproximateMillisecondCounter();
  35024. lastRepeatTime = 0;
  35025. }
  35026. sendStateMessage();
  35027. }
  35028. }
  35029. bool Button::isDown() const throw()
  35030. {
  35031. return buttonState == buttonDown;
  35032. }
  35033. bool Button::isOver() const throw()
  35034. {
  35035. return buttonState != buttonNormal;
  35036. }
  35037. void Button::buttonStateChanged()
  35038. {
  35039. }
  35040. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35041. {
  35042. const uint32 now = Time::getApproximateMillisecondCounter();
  35043. return now > buttonPressTime ? now - buttonPressTime : 0;
  35044. }
  35045. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35046. {
  35047. triggerOnMouseDown = isTriggeredOnMouseDown;
  35048. }
  35049. void Button::clicked()
  35050. {
  35051. }
  35052. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35053. {
  35054. clicked();
  35055. }
  35056. static const int clickMessageId = 0x2f3f4f99;
  35057. void Button::triggerClick()
  35058. {
  35059. postCommandMessage (clickMessageId);
  35060. }
  35061. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35062. {
  35063. if (clickTogglesState)
  35064. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35065. sendClickMessage (modifiers);
  35066. }
  35067. void Button::flashButtonState()
  35068. {
  35069. if (isEnabled())
  35070. {
  35071. needsToRelease = true;
  35072. setState (buttonDown);
  35073. getRepeatTimer().startTimer (100);
  35074. }
  35075. }
  35076. void Button::handleCommandMessage (int commandId)
  35077. {
  35078. if (commandId == clickMessageId)
  35079. {
  35080. if (isEnabled())
  35081. {
  35082. flashButtonState();
  35083. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35084. }
  35085. }
  35086. else
  35087. {
  35088. Component::handleCommandMessage (commandId);
  35089. }
  35090. }
  35091. void Button::addListener (ButtonListener* const newListener)
  35092. {
  35093. buttonListeners.add (newListener);
  35094. }
  35095. void Button::removeListener (ButtonListener* const listener)
  35096. {
  35097. buttonListeners.remove (listener);
  35098. }
  35099. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  35100. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  35101. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35102. {
  35103. Component::BailOutChecker checker (this);
  35104. if (commandManagerToUse != 0 && commandID != 0)
  35105. {
  35106. ApplicationCommandTarget::InvocationInfo info (commandID);
  35107. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35108. info.originatingComponent = this;
  35109. commandManagerToUse->invoke (info, true);
  35110. }
  35111. clicked (modifiers);
  35112. if (! checker.shouldBailOut())
  35113. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35114. }
  35115. void Button::sendStateMessage()
  35116. {
  35117. Component::BailOutChecker checker (this);
  35118. buttonStateChanged();
  35119. if (! checker.shouldBailOut())
  35120. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35121. }
  35122. void Button::paint (Graphics& g)
  35123. {
  35124. if (needsToRelease && isEnabled())
  35125. {
  35126. needsToRelease = false;
  35127. needsRepainting = true;
  35128. }
  35129. paintButton (g, isOver(), isDown());
  35130. }
  35131. void Button::mouseEnter (const MouseEvent&)
  35132. {
  35133. updateState (true, false);
  35134. }
  35135. void Button::mouseExit (const MouseEvent&)
  35136. {
  35137. updateState (false, false);
  35138. }
  35139. void Button::mouseDown (const MouseEvent& e)
  35140. {
  35141. updateState (true, true);
  35142. if (isDown())
  35143. {
  35144. if (autoRepeatDelay >= 0)
  35145. getRepeatTimer().startTimer (autoRepeatDelay);
  35146. if (triggerOnMouseDown)
  35147. internalClickCallback (e.mods);
  35148. }
  35149. }
  35150. void Button::mouseUp (const MouseEvent& e)
  35151. {
  35152. const bool wasDown = isDown();
  35153. updateState (isMouseOver(), false);
  35154. if (wasDown && isOver() && ! triggerOnMouseDown)
  35155. internalClickCallback (e.mods);
  35156. }
  35157. void Button::mouseDrag (const MouseEvent&)
  35158. {
  35159. const ButtonState oldState = buttonState;
  35160. updateState (isMouseOver(), true);
  35161. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35162. getRepeatTimer().startTimer (autoRepeatSpeed);
  35163. }
  35164. void Button::focusGained (FocusChangeType)
  35165. {
  35166. updateState();
  35167. repaint();
  35168. }
  35169. void Button::focusLost (FocusChangeType)
  35170. {
  35171. updateState();
  35172. repaint();
  35173. }
  35174. void Button::visibilityChanged()
  35175. {
  35176. needsToRelease = false;
  35177. updateState();
  35178. }
  35179. void Button::parentHierarchyChanged()
  35180. {
  35181. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35182. if (newKeySource != keySource.get())
  35183. {
  35184. if (keySource != 0)
  35185. keySource->removeKeyListener (this);
  35186. keySource = newKeySource;
  35187. if (keySource != 0)
  35188. keySource->addKeyListener (this);
  35189. }
  35190. }
  35191. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35192. const int commandID_,
  35193. const bool generateTooltip_)
  35194. {
  35195. commandID = commandID_;
  35196. generateTooltip = generateTooltip_;
  35197. if (commandManagerToUse != commandManagerToUse_)
  35198. {
  35199. if (commandManagerToUse != 0)
  35200. commandManagerToUse->removeListener (this);
  35201. commandManagerToUse = commandManagerToUse_;
  35202. if (commandManagerToUse != 0)
  35203. commandManagerToUse->addListener (this);
  35204. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35205. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35206. // it is that this button represents, and the button will update its state to reflect this
  35207. // in the applicationCommandListChanged() method.
  35208. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35209. }
  35210. if (commandManagerToUse != 0)
  35211. applicationCommandListChanged();
  35212. else
  35213. setEnabled (true);
  35214. }
  35215. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35216. {
  35217. if (info.commandID == commandID
  35218. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35219. {
  35220. flashButtonState();
  35221. }
  35222. }
  35223. void Button::applicationCommandListChanged()
  35224. {
  35225. if (commandManagerToUse != 0)
  35226. {
  35227. ApplicationCommandInfo info (0);
  35228. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35229. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35230. if (target != 0)
  35231. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35232. }
  35233. }
  35234. void Button::addShortcut (const KeyPress& key)
  35235. {
  35236. if (key.isValid())
  35237. {
  35238. jassert (! isRegisteredForShortcut (key)); // already registered!
  35239. shortcuts.add (key);
  35240. parentHierarchyChanged();
  35241. }
  35242. }
  35243. void Button::clearShortcuts()
  35244. {
  35245. shortcuts.clear();
  35246. parentHierarchyChanged();
  35247. }
  35248. bool Button::isShortcutPressed() const
  35249. {
  35250. if (! isCurrentlyBlockedByAnotherModalComponent())
  35251. {
  35252. for (int i = shortcuts.size(); --i >= 0;)
  35253. if (shortcuts.getReference(i).isCurrentlyDown())
  35254. return true;
  35255. }
  35256. return false;
  35257. }
  35258. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35259. {
  35260. for (int i = shortcuts.size(); --i >= 0;)
  35261. if (key == shortcuts.getReference(i))
  35262. return true;
  35263. return false;
  35264. }
  35265. bool Button::keyStateChanged (const bool, Component*)
  35266. {
  35267. if (! isEnabled())
  35268. return false;
  35269. const bool wasDown = isKeyDown;
  35270. isKeyDown = isShortcutPressed();
  35271. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35272. getRepeatTimer().startTimer (autoRepeatDelay);
  35273. updateState();
  35274. if (isEnabled() && wasDown && ! isKeyDown)
  35275. {
  35276. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35277. // (return immediately - this button may now have been deleted)
  35278. return true;
  35279. }
  35280. return wasDown || isKeyDown;
  35281. }
  35282. bool Button::keyPressed (const KeyPress&, Component*)
  35283. {
  35284. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35285. return isShortcutPressed();
  35286. }
  35287. bool Button::keyPressed (const KeyPress& key)
  35288. {
  35289. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35290. {
  35291. triggerClick();
  35292. return true;
  35293. }
  35294. return false;
  35295. }
  35296. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35297. const int repeatMillisecs,
  35298. const int minimumDelayInMillisecs) throw()
  35299. {
  35300. autoRepeatDelay = initialDelayMillisecs;
  35301. autoRepeatSpeed = repeatMillisecs;
  35302. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35303. }
  35304. void Button::repeatTimerCallback()
  35305. {
  35306. if (needsRepainting)
  35307. {
  35308. getRepeatTimer().stopTimer();
  35309. updateState();
  35310. needsRepainting = false;
  35311. }
  35312. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  35313. {
  35314. int repeatSpeed = autoRepeatSpeed;
  35315. if (autoRepeatMinimumDelay >= 0)
  35316. {
  35317. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35318. timeHeldDown *= timeHeldDown;
  35319. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35320. }
  35321. repeatSpeed = jmax (1, repeatSpeed);
  35322. const uint32 now = Time::getMillisecondCounter();
  35323. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35324. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35325. repeatSpeed = jmax (1, repeatSpeed / 2);
  35326. lastRepeatTime = now;
  35327. getRepeatTimer().startTimer (repeatSpeed);
  35328. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35329. }
  35330. else if (! needsToRelease)
  35331. {
  35332. getRepeatTimer().stopTimer();
  35333. }
  35334. }
  35335. Button::RepeatTimer& Button::getRepeatTimer()
  35336. {
  35337. if (repeatTimer == 0)
  35338. repeatTimer = new RepeatTimer (*this);
  35339. return *repeatTimer;
  35340. }
  35341. END_JUCE_NAMESPACE
  35342. /*** End of inlined file: juce_Button.cpp ***/
  35343. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35344. BEGIN_JUCE_NAMESPACE
  35345. DrawableButton::DrawableButton (const String& name,
  35346. const DrawableButton::ButtonStyle buttonStyle)
  35347. : Button (name),
  35348. style (buttonStyle),
  35349. currentImage (0),
  35350. edgeIndent (3)
  35351. {
  35352. if (buttonStyle == ImageOnButtonBackground)
  35353. {
  35354. backgroundOff = Colour (0xffbbbbff);
  35355. backgroundOn = Colour (0xff3333ff);
  35356. }
  35357. else
  35358. {
  35359. backgroundOff = Colours::transparentBlack;
  35360. backgroundOn = Colour (0xaabbbbff);
  35361. }
  35362. }
  35363. DrawableButton::~DrawableButton()
  35364. {
  35365. }
  35366. void DrawableButton::setImages (const Drawable* normal,
  35367. const Drawable* over,
  35368. const Drawable* down,
  35369. const Drawable* disabled,
  35370. const Drawable* normalOn,
  35371. const Drawable* overOn,
  35372. const Drawable* downOn,
  35373. const Drawable* disabledOn)
  35374. {
  35375. jassert (normal != 0); // you really need to give it at least a normal image..
  35376. if (normal != 0) normalImage = normal->createCopy();
  35377. if (over != 0) overImage = over->createCopy();
  35378. if (down != 0) downImage = down->createCopy();
  35379. if (disabled != 0) disabledImage = disabled->createCopy();
  35380. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35381. if (overOn != 0) overImageOn = overOn->createCopy();
  35382. if (downOn != 0) downImageOn = downOn->createCopy();
  35383. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35384. buttonStateChanged();
  35385. }
  35386. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35387. {
  35388. if (style != newStyle)
  35389. {
  35390. style = newStyle;
  35391. buttonStateChanged();
  35392. }
  35393. }
  35394. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35395. const Colour& toggledOnColour)
  35396. {
  35397. if (backgroundOff != toggledOffColour
  35398. || backgroundOn != toggledOnColour)
  35399. {
  35400. backgroundOff = toggledOffColour;
  35401. backgroundOn = toggledOnColour;
  35402. repaint();
  35403. }
  35404. }
  35405. const Colour& DrawableButton::getBackgroundColour() const throw()
  35406. {
  35407. return getToggleState() ? backgroundOn
  35408. : backgroundOff;
  35409. }
  35410. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35411. {
  35412. edgeIndent = numPixelsIndent;
  35413. repaint();
  35414. resized();
  35415. }
  35416. void DrawableButton::resized()
  35417. {
  35418. Button::resized();
  35419. if (currentImage != 0)
  35420. {
  35421. if (style == ImageRaw)
  35422. {
  35423. currentImage->setOriginWithOriginalSize (Point<float>());
  35424. }
  35425. else
  35426. {
  35427. Rectangle<int> imageSpace;
  35428. if (style == ImageOnButtonBackground)
  35429. {
  35430. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35431. }
  35432. else
  35433. {
  35434. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35435. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35436. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35437. imageSpace.setBounds (indentX, indentY,
  35438. getWidth() - indentX * 2,
  35439. getHeight() - indentY * 2 - textH);
  35440. }
  35441. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35442. }
  35443. }
  35444. }
  35445. void DrawableButton::buttonStateChanged()
  35446. {
  35447. repaint();
  35448. Drawable* imageToDraw = 0;
  35449. float opacity = 1.0f;
  35450. if (isEnabled())
  35451. {
  35452. imageToDraw = getCurrentImage();
  35453. }
  35454. else
  35455. {
  35456. imageToDraw = getToggleState() ? disabledImageOn
  35457. : disabledImage;
  35458. if (imageToDraw == 0)
  35459. {
  35460. opacity = 0.4f;
  35461. imageToDraw = getNormalImage();
  35462. }
  35463. }
  35464. if (imageToDraw != currentImage)
  35465. {
  35466. removeChildComponent (currentImage);
  35467. currentImage = imageToDraw;
  35468. if (currentImage != 0)
  35469. {
  35470. addAndMakeVisible (currentImage);
  35471. DrawableButton::resized();
  35472. }
  35473. }
  35474. if (currentImage != 0)
  35475. currentImage->setAlpha (opacity);
  35476. }
  35477. void DrawableButton::paintButton (Graphics& g,
  35478. bool isMouseOverButton,
  35479. bool isButtonDown)
  35480. {
  35481. if (style == ImageOnButtonBackground)
  35482. {
  35483. getLookAndFeel().drawButtonBackground (g, *this,
  35484. getBackgroundColour(),
  35485. isMouseOverButton,
  35486. isButtonDown);
  35487. }
  35488. else
  35489. {
  35490. g.fillAll (getBackgroundColour());
  35491. const int textH = (style == ImageAboveTextLabel)
  35492. ? jmin (16, proportionOfHeight (0.25f))
  35493. : 0;
  35494. if (textH > 0)
  35495. {
  35496. g.setFont ((float) textH);
  35497. g.setColour (findColour (DrawableButton::textColourId)
  35498. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35499. g.drawFittedText (getButtonText(),
  35500. 2, getHeight() - textH - 1,
  35501. getWidth() - 4, textH,
  35502. Justification::centred, 1);
  35503. }
  35504. }
  35505. }
  35506. Drawable* DrawableButton::getCurrentImage() const throw()
  35507. {
  35508. if (isDown())
  35509. return getDownImage();
  35510. if (isOver())
  35511. return getOverImage();
  35512. return getNormalImage();
  35513. }
  35514. Drawable* DrawableButton::getNormalImage() const throw()
  35515. {
  35516. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35517. : normalImage;
  35518. }
  35519. Drawable* DrawableButton::getOverImage() const throw()
  35520. {
  35521. Drawable* d = normalImage;
  35522. if (getToggleState())
  35523. {
  35524. if (overImageOn != 0)
  35525. d = overImageOn;
  35526. else if (normalImageOn != 0)
  35527. d = normalImageOn;
  35528. else if (overImage != 0)
  35529. d = overImage;
  35530. }
  35531. else
  35532. {
  35533. if (overImage != 0)
  35534. d = overImage;
  35535. }
  35536. return d;
  35537. }
  35538. Drawable* DrawableButton::getDownImage() const throw()
  35539. {
  35540. Drawable* d = normalImage;
  35541. if (getToggleState())
  35542. {
  35543. if (downImageOn != 0)
  35544. d = downImageOn;
  35545. else if (overImageOn != 0)
  35546. d = overImageOn;
  35547. else if (normalImageOn != 0)
  35548. d = normalImageOn;
  35549. else if (downImage != 0)
  35550. d = downImage;
  35551. else
  35552. d = getOverImage();
  35553. }
  35554. else
  35555. {
  35556. if (downImage != 0)
  35557. d = downImage;
  35558. else
  35559. d = getOverImage();
  35560. }
  35561. return d;
  35562. }
  35563. END_JUCE_NAMESPACE
  35564. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35565. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35566. BEGIN_JUCE_NAMESPACE
  35567. HyperlinkButton::HyperlinkButton (const String& linkText,
  35568. const URL& linkURL)
  35569. : Button (linkText),
  35570. url (linkURL),
  35571. font (14.0f, Font::underlined),
  35572. resizeFont (true),
  35573. justification (Justification::centred)
  35574. {
  35575. setMouseCursor (MouseCursor::PointingHandCursor);
  35576. setTooltip (linkURL.toString (false));
  35577. }
  35578. HyperlinkButton::~HyperlinkButton()
  35579. {
  35580. }
  35581. void HyperlinkButton::setFont (const Font& newFont,
  35582. const bool resizeToMatchComponentHeight,
  35583. const Justification& justificationType)
  35584. {
  35585. font = newFont;
  35586. resizeFont = resizeToMatchComponentHeight;
  35587. justification = justificationType;
  35588. repaint();
  35589. }
  35590. void HyperlinkButton::setURL (const URL& newURL) throw()
  35591. {
  35592. url = newURL;
  35593. setTooltip (newURL.toString (false));
  35594. }
  35595. const Font HyperlinkButton::getFontToUse() const
  35596. {
  35597. Font f (font);
  35598. if (resizeFont)
  35599. f.setHeight (getHeight() * 0.7f);
  35600. return f;
  35601. }
  35602. void HyperlinkButton::changeWidthToFitText()
  35603. {
  35604. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35605. }
  35606. void HyperlinkButton::colourChanged()
  35607. {
  35608. repaint();
  35609. }
  35610. void HyperlinkButton::clicked()
  35611. {
  35612. if (url.isWellFormed())
  35613. url.launchInDefaultBrowser();
  35614. }
  35615. void HyperlinkButton::paintButton (Graphics& g,
  35616. bool isMouseOverButton,
  35617. bool isButtonDown)
  35618. {
  35619. const Colour textColour (findColour (textColourId));
  35620. if (isEnabled())
  35621. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35622. : textColour);
  35623. else
  35624. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35625. g.setFont (getFontToUse());
  35626. g.drawText (getButtonText(),
  35627. 2, 0, getWidth() - 2, getHeight(),
  35628. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35629. true);
  35630. }
  35631. END_JUCE_NAMESPACE
  35632. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35633. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35634. BEGIN_JUCE_NAMESPACE
  35635. ImageButton::ImageButton (const String& text_)
  35636. : Button (text_),
  35637. scaleImageToFit (true),
  35638. preserveProportions (true),
  35639. alphaThreshold (0),
  35640. imageX (0),
  35641. imageY (0),
  35642. imageW (0),
  35643. imageH (0),
  35644. normalImage (0),
  35645. overImage (0),
  35646. downImage (0)
  35647. {
  35648. }
  35649. ImageButton::~ImageButton()
  35650. {
  35651. }
  35652. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35653. const bool rescaleImagesWhenButtonSizeChanges,
  35654. const bool preserveImageProportions,
  35655. const Image& normalImage_,
  35656. const float imageOpacityWhenNormal,
  35657. const Colour& overlayColourWhenNormal,
  35658. const Image& overImage_,
  35659. const float imageOpacityWhenOver,
  35660. const Colour& overlayColourWhenOver,
  35661. const Image& downImage_,
  35662. const float imageOpacityWhenDown,
  35663. const Colour& overlayColourWhenDown,
  35664. const float hitTestAlphaThreshold)
  35665. {
  35666. normalImage = normalImage_;
  35667. overImage = overImage_;
  35668. downImage = downImage_;
  35669. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35670. {
  35671. imageW = normalImage.getWidth();
  35672. imageH = normalImage.getHeight();
  35673. setSize (imageW, imageH);
  35674. }
  35675. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35676. preserveProportions = preserveImageProportions;
  35677. normalOpacity = imageOpacityWhenNormal;
  35678. normalOverlay = overlayColourWhenNormal;
  35679. overOpacity = imageOpacityWhenOver;
  35680. overOverlay = overlayColourWhenOver;
  35681. downOpacity = imageOpacityWhenDown;
  35682. downOverlay = overlayColourWhenDown;
  35683. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35684. repaint();
  35685. }
  35686. const Image ImageButton::getCurrentImage() const
  35687. {
  35688. if (isDown() || getToggleState())
  35689. return getDownImage();
  35690. if (isOver())
  35691. return getOverImage();
  35692. return getNormalImage();
  35693. }
  35694. const Image ImageButton::getNormalImage() const
  35695. {
  35696. return normalImage;
  35697. }
  35698. const Image ImageButton::getOverImage() const
  35699. {
  35700. return overImage.isValid() ? overImage
  35701. : normalImage;
  35702. }
  35703. const Image ImageButton::getDownImage() const
  35704. {
  35705. return downImage.isValid() ? downImage
  35706. : getOverImage();
  35707. }
  35708. void ImageButton::paintButton (Graphics& g,
  35709. bool isMouseOverButton,
  35710. bool isButtonDown)
  35711. {
  35712. if (! isEnabled())
  35713. {
  35714. isMouseOverButton = false;
  35715. isButtonDown = false;
  35716. }
  35717. Image im (getCurrentImage());
  35718. if (im.isValid())
  35719. {
  35720. const int iw = im.getWidth();
  35721. const int ih = im.getHeight();
  35722. imageW = getWidth();
  35723. imageH = getHeight();
  35724. imageX = (imageW - iw) >> 1;
  35725. imageY = (imageH - ih) >> 1;
  35726. if (scaleImageToFit)
  35727. {
  35728. if (preserveProportions)
  35729. {
  35730. int newW, newH;
  35731. const float imRatio = ih / (float)iw;
  35732. const float destRatio = imageH / (float)imageW;
  35733. if (imRatio > destRatio)
  35734. {
  35735. newW = roundToInt (imageH / imRatio);
  35736. newH = imageH;
  35737. }
  35738. else
  35739. {
  35740. newW = imageW;
  35741. newH = roundToInt (imageW * imRatio);
  35742. }
  35743. imageX = (imageW - newW) / 2;
  35744. imageY = (imageH - newH) / 2;
  35745. imageW = newW;
  35746. imageH = newH;
  35747. }
  35748. else
  35749. {
  35750. imageX = 0;
  35751. imageY = 0;
  35752. }
  35753. }
  35754. if (! scaleImageToFit)
  35755. {
  35756. imageW = iw;
  35757. imageH = ih;
  35758. }
  35759. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35760. isButtonDown ? downOverlay
  35761. : (isMouseOverButton ? overOverlay
  35762. : normalOverlay),
  35763. isButtonDown ? downOpacity
  35764. : (isMouseOverButton ? overOpacity
  35765. : normalOpacity),
  35766. *this);
  35767. }
  35768. }
  35769. bool ImageButton::hitTest (int x, int y)
  35770. {
  35771. if (alphaThreshold == 0)
  35772. return true;
  35773. Image im (getCurrentImage());
  35774. return im.isNull() || (imageW > 0 && imageH > 0
  35775. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35776. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35777. }
  35778. END_JUCE_NAMESPACE
  35779. /*** End of inlined file: juce_ImageButton.cpp ***/
  35780. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35781. BEGIN_JUCE_NAMESPACE
  35782. ShapeButton::ShapeButton (const String& text_,
  35783. const Colour& normalColour_,
  35784. const Colour& overColour_,
  35785. const Colour& downColour_)
  35786. : Button (text_),
  35787. normalColour (normalColour_),
  35788. overColour (overColour_),
  35789. downColour (downColour_),
  35790. maintainShapeProportions (false),
  35791. outlineWidth (0.0f)
  35792. {
  35793. }
  35794. ShapeButton::~ShapeButton()
  35795. {
  35796. }
  35797. void ShapeButton::setColours (const Colour& newNormalColour,
  35798. const Colour& newOverColour,
  35799. const Colour& newDownColour)
  35800. {
  35801. normalColour = newNormalColour;
  35802. overColour = newOverColour;
  35803. downColour = newDownColour;
  35804. }
  35805. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35806. const float newOutlineWidth)
  35807. {
  35808. outlineColour = newOutlineColour;
  35809. outlineWidth = newOutlineWidth;
  35810. }
  35811. void ShapeButton::setShape (const Path& newShape,
  35812. const bool resizeNowToFitThisShape,
  35813. const bool maintainShapeProportions_,
  35814. const bool hasShadow)
  35815. {
  35816. shape = newShape;
  35817. maintainShapeProportions = maintainShapeProportions_;
  35818. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35819. setComponentEffect ((hasShadow) ? &shadow : 0);
  35820. if (resizeNowToFitThisShape)
  35821. {
  35822. Rectangle<float> bounds (shape.getBounds());
  35823. if (hasShadow)
  35824. bounds.expand (4.0f, 4.0f);
  35825. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35826. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35827. 1 + (int) (bounds.getHeight() + outlineWidth));
  35828. }
  35829. }
  35830. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35831. {
  35832. if (! isEnabled())
  35833. {
  35834. isMouseOverButton = false;
  35835. isButtonDown = false;
  35836. }
  35837. g.setColour ((isButtonDown) ? downColour
  35838. : (isMouseOverButton) ? overColour
  35839. : normalColour);
  35840. int w = getWidth();
  35841. int h = getHeight();
  35842. if (getComponentEffect() != 0)
  35843. {
  35844. w -= 4;
  35845. h -= 4;
  35846. }
  35847. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35848. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35849. w - offset - outlineWidth,
  35850. h - offset - outlineWidth,
  35851. maintainShapeProportions));
  35852. g.fillPath (shape, trans);
  35853. if (outlineWidth > 0.0f)
  35854. {
  35855. g.setColour (outlineColour);
  35856. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35857. }
  35858. }
  35859. END_JUCE_NAMESPACE
  35860. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35861. /*** Start of inlined file: juce_TextButton.cpp ***/
  35862. BEGIN_JUCE_NAMESPACE
  35863. TextButton::TextButton (const String& name,
  35864. const String& toolTip)
  35865. : Button (name)
  35866. {
  35867. setTooltip (toolTip);
  35868. }
  35869. TextButton::~TextButton()
  35870. {
  35871. }
  35872. void TextButton::paintButton (Graphics& g,
  35873. bool isMouseOverButton,
  35874. bool isButtonDown)
  35875. {
  35876. getLookAndFeel().drawButtonBackground (g, *this,
  35877. findColour (getToggleState() ? buttonOnColourId
  35878. : buttonColourId),
  35879. isMouseOverButton,
  35880. isButtonDown);
  35881. getLookAndFeel().drawButtonText (g, *this,
  35882. isMouseOverButton,
  35883. isButtonDown);
  35884. }
  35885. void TextButton::colourChanged()
  35886. {
  35887. repaint();
  35888. }
  35889. const Font TextButton::getFont()
  35890. {
  35891. return Font (jmin (15.0f, getHeight() * 0.6f));
  35892. }
  35893. void TextButton::changeWidthToFitText (const int newHeight)
  35894. {
  35895. if (newHeight >= 0)
  35896. setSize (jmax (1, getWidth()), newHeight);
  35897. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35898. getHeight());
  35899. }
  35900. END_JUCE_NAMESPACE
  35901. /*** End of inlined file: juce_TextButton.cpp ***/
  35902. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35903. BEGIN_JUCE_NAMESPACE
  35904. ToggleButton::ToggleButton (const String& buttonText)
  35905. : Button (buttonText)
  35906. {
  35907. setClickingTogglesState (true);
  35908. }
  35909. ToggleButton::~ToggleButton()
  35910. {
  35911. }
  35912. void ToggleButton::paintButton (Graphics& g,
  35913. bool isMouseOverButton,
  35914. bool isButtonDown)
  35915. {
  35916. getLookAndFeel().drawToggleButton (g, *this,
  35917. isMouseOverButton,
  35918. isButtonDown);
  35919. }
  35920. void ToggleButton::changeWidthToFitText()
  35921. {
  35922. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35923. }
  35924. void ToggleButton::colourChanged()
  35925. {
  35926. repaint();
  35927. }
  35928. END_JUCE_NAMESPACE
  35929. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35930. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35931. BEGIN_JUCE_NAMESPACE
  35932. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35933. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35934. : ToolbarItemComponent (itemId_, buttonText, true),
  35935. normalImage (normalImage_),
  35936. toggledOnImage (toggledOnImage_),
  35937. currentImage (0)
  35938. {
  35939. jassert (normalImage_ != 0);
  35940. }
  35941. ToolbarButton::~ToolbarButton()
  35942. {
  35943. }
  35944. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35945. {
  35946. preferredSize = minSize = maxSize = toolbarDepth;
  35947. return true;
  35948. }
  35949. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35950. {
  35951. }
  35952. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35953. {
  35954. buttonStateChanged();
  35955. }
  35956. void ToolbarButton::updateDrawable()
  35957. {
  35958. if (currentImage != 0)
  35959. {
  35960. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35961. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35962. }
  35963. }
  35964. void ToolbarButton::resized()
  35965. {
  35966. ToolbarItemComponent::resized();
  35967. updateDrawable();
  35968. }
  35969. void ToolbarButton::enablementChanged()
  35970. {
  35971. ToolbarItemComponent::enablementChanged();
  35972. updateDrawable();
  35973. }
  35974. void ToolbarButton::buttonStateChanged()
  35975. {
  35976. Drawable* d = normalImage;
  35977. if (getToggleState() && toggledOnImage != 0)
  35978. d = toggledOnImage;
  35979. if (d != currentImage)
  35980. {
  35981. removeChildComponent (currentImage);
  35982. currentImage = d;
  35983. if (d != 0)
  35984. {
  35985. enablementChanged();
  35986. addAndMakeVisible (d);
  35987. updateDrawable();
  35988. }
  35989. }
  35990. }
  35991. END_JUCE_NAMESPACE
  35992. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35993. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35994. BEGIN_JUCE_NAMESPACE
  35995. class CodeDocumentLine
  35996. {
  35997. public:
  35998. CodeDocumentLine (const juce_wchar* const line_,
  35999. const int lineLength_,
  36000. const int numNewLineChars,
  36001. const int lineStartInFile_)
  36002. : line (line_, lineLength_),
  36003. lineStartInFile (lineStartInFile_),
  36004. lineLength (lineLength_),
  36005. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  36006. {
  36007. }
  36008. ~CodeDocumentLine()
  36009. {
  36010. }
  36011. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  36012. {
  36013. const juce_wchar* const t = text;
  36014. int pos = 0;
  36015. while (t [pos] != 0)
  36016. {
  36017. const int startOfLine = pos;
  36018. int numNewLineChars = 0;
  36019. while (t[pos] != 0)
  36020. {
  36021. if (t[pos] == '\r')
  36022. {
  36023. ++numNewLineChars;
  36024. ++pos;
  36025. if (t[pos] == '\n')
  36026. {
  36027. ++numNewLineChars;
  36028. ++pos;
  36029. }
  36030. break;
  36031. }
  36032. if (t[pos] == '\n')
  36033. {
  36034. ++numNewLineChars;
  36035. ++pos;
  36036. break;
  36037. }
  36038. ++pos;
  36039. }
  36040. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36041. numNewLineChars, startOfLine));
  36042. }
  36043. jassert (pos == text.length());
  36044. }
  36045. bool endsWithLineBreak() const throw()
  36046. {
  36047. return lineLengthWithoutNewLines != lineLength;
  36048. }
  36049. void updateLength() throw()
  36050. {
  36051. lineLengthWithoutNewLines = lineLength = line.length();
  36052. while (lineLengthWithoutNewLines > 0
  36053. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36054. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36055. {
  36056. --lineLengthWithoutNewLines;
  36057. }
  36058. }
  36059. String line;
  36060. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36061. };
  36062. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36063. : document (document_),
  36064. currentLine (document_->lines[0]),
  36065. line (0),
  36066. position (0)
  36067. {
  36068. }
  36069. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36070. : document (other.document),
  36071. currentLine (other.currentLine),
  36072. line (other.line),
  36073. position (other.position)
  36074. {
  36075. }
  36076. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36077. {
  36078. document = other.document;
  36079. currentLine = other.currentLine;
  36080. line = other.line;
  36081. position = other.position;
  36082. return *this;
  36083. }
  36084. CodeDocument::Iterator::~Iterator() throw()
  36085. {
  36086. }
  36087. juce_wchar CodeDocument::Iterator::nextChar()
  36088. {
  36089. if (currentLine == 0)
  36090. return 0;
  36091. jassert (currentLine == document->lines.getUnchecked (line));
  36092. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36093. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36094. {
  36095. ++line;
  36096. currentLine = document->lines [line];
  36097. }
  36098. return result;
  36099. }
  36100. void CodeDocument::Iterator::skip()
  36101. {
  36102. if (currentLine != 0)
  36103. {
  36104. jassert (currentLine == document->lines.getUnchecked (line));
  36105. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36106. {
  36107. ++line;
  36108. currentLine = document->lines [line];
  36109. }
  36110. }
  36111. }
  36112. void CodeDocument::Iterator::skipToEndOfLine()
  36113. {
  36114. if (currentLine != 0)
  36115. {
  36116. jassert (currentLine == document->lines.getUnchecked (line));
  36117. ++line;
  36118. currentLine = document->lines [line];
  36119. if (currentLine != 0)
  36120. position = currentLine->lineStartInFile;
  36121. else
  36122. position = document->getNumCharacters();
  36123. }
  36124. }
  36125. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36126. {
  36127. if (currentLine == 0)
  36128. return 0;
  36129. jassert (currentLine == document->lines.getUnchecked (line));
  36130. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36131. }
  36132. void CodeDocument::Iterator::skipWhitespace()
  36133. {
  36134. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36135. skip();
  36136. }
  36137. bool CodeDocument::Iterator::isEOF() const throw()
  36138. {
  36139. return currentLine == 0;
  36140. }
  36141. CodeDocument::Position::Position() throw()
  36142. : owner (0), characterPos (0), line (0),
  36143. indexInLine (0), positionMaintained (false)
  36144. {
  36145. }
  36146. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36147. const int line_, const int indexInLine_) throw()
  36148. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36149. characterPos (0), line (line_),
  36150. indexInLine (indexInLine_), positionMaintained (false)
  36151. {
  36152. setLineAndIndex (line_, indexInLine_);
  36153. }
  36154. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36155. const int characterPos_) throw()
  36156. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36157. positionMaintained (false)
  36158. {
  36159. setPosition (characterPos_);
  36160. }
  36161. CodeDocument::Position::Position (const Position& other) throw()
  36162. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36163. indexInLine (other.indexInLine), positionMaintained (false)
  36164. {
  36165. jassert (*this == other);
  36166. }
  36167. CodeDocument::Position::~Position()
  36168. {
  36169. setPositionMaintained (false);
  36170. }
  36171. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36172. {
  36173. if (this != &other)
  36174. {
  36175. const bool wasPositionMaintained = positionMaintained;
  36176. if (owner != other.owner)
  36177. setPositionMaintained (false);
  36178. owner = other.owner;
  36179. line = other.line;
  36180. indexInLine = other.indexInLine;
  36181. characterPos = other.characterPos;
  36182. setPositionMaintained (wasPositionMaintained);
  36183. jassert (*this == other);
  36184. }
  36185. return *this;
  36186. }
  36187. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36188. {
  36189. jassert ((characterPos == other.characterPos)
  36190. == (line == other.line && indexInLine == other.indexInLine));
  36191. return characterPos == other.characterPos
  36192. && line == other.line
  36193. && indexInLine == other.indexInLine
  36194. && owner == other.owner;
  36195. }
  36196. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36197. {
  36198. return ! operator== (other);
  36199. }
  36200. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36201. {
  36202. jassert (owner != 0);
  36203. if (owner->lines.size() == 0)
  36204. {
  36205. line = 0;
  36206. indexInLine = 0;
  36207. characterPos = 0;
  36208. }
  36209. else
  36210. {
  36211. if (newLine >= owner->lines.size())
  36212. {
  36213. line = owner->lines.size() - 1;
  36214. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36215. jassert (l != 0);
  36216. indexInLine = l->lineLengthWithoutNewLines;
  36217. characterPos = l->lineStartInFile + indexInLine;
  36218. }
  36219. else
  36220. {
  36221. line = jmax (0, newLine);
  36222. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36223. jassert (l != 0);
  36224. if (l->lineLengthWithoutNewLines > 0)
  36225. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36226. else
  36227. indexInLine = 0;
  36228. characterPos = l->lineStartInFile + indexInLine;
  36229. }
  36230. }
  36231. }
  36232. void CodeDocument::Position::setPosition (const int newPosition)
  36233. {
  36234. jassert (owner != 0);
  36235. line = 0;
  36236. indexInLine = 0;
  36237. characterPos = 0;
  36238. if (newPosition > 0)
  36239. {
  36240. int lineStart = 0;
  36241. int lineEnd = owner->lines.size();
  36242. for (;;)
  36243. {
  36244. if (lineEnd - lineStart < 4)
  36245. {
  36246. for (int i = lineStart; i < lineEnd; ++i)
  36247. {
  36248. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36249. int index = newPosition - l->lineStartInFile;
  36250. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36251. {
  36252. line = i;
  36253. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36254. characterPos = l->lineStartInFile + indexInLine;
  36255. }
  36256. }
  36257. break;
  36258. }
  36259. else
  36260. {
  36261. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36262. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36263. if (newPosition >= mid->lineStartInFile)
  36264. lineStart = midIndex;
  36265. else
  36266. lineEnd = midIndex;
  36267. }
  36268. }
  36269. }
  36270. }
  36271. void CodeDocument::Position::moveBy (int characterDelta)
  36272. {
  36273. jassert (owner != 0);
  36274. if (characterDelta == 1)
  36275. {
  36276. setPosition (getPosition());
  36277. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36278. if (line < owner->lines.size())
  36279. {
  36280. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36281. if (indexInLine + characterDelta < l->lineLength
  36282. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36283. ++characterDelta;
  36284. }
  36285. }
  36286. setPosition (characterPos + characterDelta);
  36287. }
  36288. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36289. {
  36290. CodeDocument::Position p (*this);
  36291. p.moveBy (characterDelta);
  36292. return p;
  36293. }
  36294. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36295. {
  36296. CodeDocument::Position p (*this);
  36297. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36298. return p;
  36299. }
  36300. const juce_wchar CodeDocument::Position::getCharacter() const
  36301. {
  36302. const CodeDocumentLine* const l = owner->lines [line];
  36303. return l == 0 ? 0 : l->line [getIndexInLine()];
  36304. }
  36305. const String CodeDocument::Position::getLineText() const
  36306. {
  36307. const CodeDocumentLine* const l = owner->lines [line];
  36308. return l == 0 ? String::empty : l->line;
  36309. }
  36310. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36311. {
  36312. if (isMaintained != positionMaintained)
  36313. {
  36314. positionMaintained = isMaintained;
  36315. if (owner != 0)
  36316. {
  36317. if (isMaintained)
  36318. {
  36319. jassert (! owner->positionsToMaintain.contains (this));
  36320. owner->positionsToMaintain.add (this);
  36321. }
  36322. else
  36323. {
  36324. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36325. jassert (owner->positionsToMaintain.contains (this));
  36326. owner->positionsToMaintain.removeValue (this);
  36327. }
  36328. }
  36329. }
  36330. }
  36331. CodeDocument::CodeDocument()
  36332. : undoManager (std::numeric_limits<int>::max(), 10000),
  36333. currentActionIndex (0),
  36334. indexOfSavedState (-1),
  36335. maximumLineLength (-1),
  36336. newLineChars ("\r\n")
  36337. {
  36338. }
  36339. CodeDocument::~CodeDocument()
  36340. {
  36341. }
  36342. const String CodeDocument::getAllContent() const
  36343. {
  36344. return getTextBetween (Position (this, 0),
  36345. Position (this, lines.size(), 0));
  36346. }
  36347. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36348. {
  36349. if (end.getPosition() <= start.getPosition())
  36350. return String::empty;
  36351. const int startLine = start.getLineNumber();
  36352. const int endLine = end.getLineNumber();
  36353. if (startLine == endLine)
  36354. {
  36355. CodeDocumentLine* const line = lines [startLine];
  36356. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36357. }
  36358. String result;
  36359. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36360. String::Concatenator concatenator (result);
  36361. const int maxLine = jmin (lines.size() - 1, endLine);
  36362. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36363. {
  36364. const CodeDocumentLine* line = lines.getUnchecked(i);
  36365. int len = line->lineLength;
  36366. if (i == startLine)
  36367. {
  36368. const int index = start.getIndexInLine();
  36369. concatenator.append (line->line.substring (index, len));
  36370. }
  36371. else if (i == endLine)
  36372. {
  36373. len = end.getIndexInLine();
  36374. concatenator.append (line->line.substring (0, len));
  36375. }
  36376. else
  36377. {
  36378. concatenator.append (line->line);
  36379. }
  36380. }
  36381. return result;
  36382. }
  36383. int CodeDocument::getNumCharacters() const throw()
  36384. {
  36385. const CodeDocumentLine* const lastLine = lines.getLast();
  36386. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36387. }
  36388. const String CodeDocument::getLine (const int lineIndex) const throw()
  36389. {
  36390. const CodeDocumentLine* const line = lines [lineIndex];
  36391. return (line == 0) ? String::empty : line->line;
  36392. }
  36393. int CodeDocument::getMaximumLineLength() throw()
  36394. {
  36395. if (maximumLineLength < 0)
  36396. {
  36397. maximumLineLength = 0;
  36398. for (int i = lines.size(); --i >= 0;)
  36399. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36400. }
  36401. return maximumLineLength;
  36402. }
  36403. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36404. {
  36405. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36406. }
  36407. void CodeDocument::insertText (const Position& position, const String& text)
  36408. {
  36409. insert (text, position.getPosition(), true);
  36410. }
  36411. void CodeDocument::replaceAllContent (const String& newContent)
  36412. {
  36413. remove (0, getNumCharacters(), true);
  36414. insert (newContent, 0, true);
  36415. }
  36416. bool CodeDocument::loadFromStream (InputStream& stream)
  36417. {
  36418. replaceAllContent (stream.readEntireStreamAsString());
  36419. setSavePoint();
  36420. clearUndoHistory();
  36421. return true;
  36422. }
  36423. bool CodeDocument::writeToStream (OutputStream& stream)
  36424. {
  36425. for (int i = 0; i < lines.size(); ++i)
  36426. {
  36427. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36428. const char* utf8 = temp.toUTF8();
  36429. if (! stream.write (utf8, (int) strlen (utf8)))
  36430. return false;
  36431. }
  36432. return true;
  36433. }
  36434. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36435. {
  36436. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36437. newLineChars = newLine;
  36438. }
  36439. void CodeDocument::newTransaction()
  36440. {
  36441. undoManager.beginNewTransaction (String::empty);
  36442. }
  36443. void CodeDocument::undo()
  36444. {
  36445. newTransaction();
  36446. undoManager.undo();
  36447. }
  36448. void CodeDocument::redo()
  36449. {
  36450. undoManager.redo();
  36451. }
  36452. void CodeDocument::clearUndoHistory()
  36453. {
  36454. undoManager.clearUndoHistory();
  36455. }
  36456. void CodeDocument::setSavePoint() throw()
  36457. {
  36458. indexOfSavedState = currentActionIndex;
  36459. }
  36460. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36461. {
  36462. return currentActionIndex != indexOfSavedState;
  36463. }
  36464. namespace CodeDocumentHelpers
  36465. {
  36466. int getCharacterType (const juce_wchar character) throw()
  36467. {
  36468. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36469. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36470. }
  36471. }
  36472. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36473. {
  36474. Position p (position);
  36475. const int maxDistance = 256;
  36476. int i = 0;
  36477. while (i < maxDistance
  36478. && CharacterFunctions::isWhitespace (p.getCharacter())
  36479. && (i == 0 || (p.getCharacter() != '\n'
  36480. && p.getCharacter() != '\r')))
  36481. {
  36482. ++i;
  36483. p.moveBy (1);
  36484. }
  36485. if (i == 0)
  36486. {
  36487. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36488. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36489. {
  36490. ++i;
  36491. p.moveBy (1);
  36492. }
  36493. while (i < maxDistance
  36494. && CharacterFunctions::isWhitespace (p.getCharacter())
  36495. && (i == 0 || (p.getCharacter() != '\n'
  36496. && p.getCharacter() != '\r')))
  36497. {
  36498. ++i;
  36499. p.moveBy (1);
  36500. }
  36501. }
  36502. return p;
  36503. }
  36504. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36505. {
  36506. Position p (position);
  36507. const int maxDistance = 256;
  36508. int i = 0;
  36509. bool stoppedAtLineStart = false;
  36510. while (i < maxDistance)
  36511. {
  36512. const juce_wchar c = p.movedBy (-1).getCharacter();
  36513. if (c == '\r' || c == '\n')
  36514. {
  36515. stoppedAtLineStart = true;
  36516. if (i > 0)
  36517. break;
  36518. }
  36519. if (! CharacterFunctions::isWhitespace (c))
  36520. break;
  36521. p.moveBy (-1);
  36522. ++i;
  36523. }
  36524. if (i < maxDistance && ! stoppedAtLineStart)
  36525. {
  36526. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36527. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36528. {
  36529. p.moveBy (-1);
  36530. ++i;
  36531. }
  36532. }
  36533. return p;
  36534. }
  36535. void CodeDocument::checkLastLineStatus()
  36536. {
  36537. while (lines.size() > 0
  36538. && lines.getLast()->lineLength == 0
  36539. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36540. {
  36541. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36542. lines.removeLast();
  36543. }
  36544. const CodeDocumentLine* const lastLine = lines.getLast();
  36545. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36546. {
  36547. // check that there's an empty line at the end if the preceding one ends in a newline..
  36548. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36549. }
  36550. }
  36551. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36552. {
  36553. listeners.add (listener);
  36554. }
  36555. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36556. {
  36557. listeners.remove (listener);
  36558. }
  36559. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36560. {
  36561. Position startPos (this, startLine, 0);
  36562. Position endPos (this, endLine, 0);
  36563. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36564. }
  36565. class CodeDocumentInsertAction : public UndoableAction
  36566. {
  36567. public:
  36568. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36569. : owner (owner_),
  36570. text (text_),
  36571. insertPos (insertPos_)
  36572. {
  36573. }
  36574. bool perform()
  36575. {
  36576. owner.currentActionIndex++;
  36577. owner.insert (text, insertPos, false);
  36578. return true;
  36579. }
  36580. bool undo()
  36581. {
  36582. owner.currentActionIndex--;
  36583. owner.remove (insertPos, insertPos + text.length(), false);
  36584. return true;
  36585. }
  36586. int getSizeInUnits() { return text.length() + 32; }
  36587. private:
  36588. CodeDocument& owner;
  36589. const String text;
  36590. int insertPos;
  36591. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36592. };
  36593. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36594. {
  36595. if (text.isEmpty())
  36596. return;
  36597. if (undoable)
  36598. {
  36599. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36600. }
  36601. else
  36602. {
  36603. Position pos (this, insertPos);
  36604. const int firstAffectedLine = pos.getLineNumber();
  36605. int lastAffectedLine = firstAffectedLine + 1;
  36606. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36607. String textInsideOriginalLine (text);
  36608. if (firstLine != 0)
  36609. {
  36610. const int index = pos.getIndexInLine();
  36611. textInsideOriginalLine = firstLine->line.substring (0, index)
  36612. + textInsideOriginalLine
  36613. + firstLine->line.substring (index);
  36614. }
  36615. maximumLineLength = -1;
  36616. Array <CodeDocumentLine*> newLines;
  36617. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36618. jassert (newLines.size() > 0);
  36619. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36620. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36621. lines.set (firstAffectedLine, newFirstLine);
  36622. if (newLines.size() > 1)
  36623. {
  36624. for (int i = 1; i < newLines.size(); ++i)
  36625. {
  36626. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36627. lines.insert (firstAffectedLine + i, l);
  36628. }
  36629. lastAffectedLine = lines.size();
  36630. }
  36631. int i, lineStart = newFirstLine->lineStartInFile;
  36632. for (i = firstAffectedLine; i < lines.size(); ++i)
  36633. {
  36634. CodeDocumentLine* const l = lines.getUnchecked (i);
  36635. l->lineStartInFile = lineStart;
  36636. lineStart += l->lineLength;
  36637. }
  36638. checkLastLineStatus();
  36639. const int newTextLength = text.length();
  36640. for (i = 0; i < positionsToMaintain.size(); ++i)
  36641. {
  36642. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36643. if (p->getPosition() >= insertPos)
  36644. p->setPosition (p->getPosition() + newTextLength);
  36645. }
  36646. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36647. }
  36648. }
  36649. class CodeDocumentDeleteAction : public UndoableAction
  36650. {
  36651. public:
  36652. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36653. : owner (owner_),
  36654. startPos (startPos_),
  36655. endPos (endPos_)
  36656. {
  36657. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36658. CodeDocument::Position (&owner, endPos));
  36659. }
  36660. bool perform()
  36661. {
  36662. owner.currentActionIndex++;
  36663. owner.remove (startPos, endPos, false);
  36664. return true;
  36665. }
  36666. bool undo()
  36667. {
  36668. owner.currentActionIndex--;
  36669. owner.insert (removedText, startPos, false);
  36670. return true;
  36671. }
  36672. int getSizeInUnits() { return removedText.length() + 32; }
  36673. private:
  36674. CodeDocument& owner;
  36675. int startPos, endPos;
  36676. String removedText;
  36677. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36678. };
  36679. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36680. {
  36681. if (endPos <= startPos)
  36682. return;
  36683. if (undoable)
  36684. {
  36685. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36686. }
  36687. else
  36688. {
  36689. Position startPosition (this, startPos);
  36690. Position endPosition (this, endPos);
  36691. maximumLineLength = -1;
  36692. const int firstAffectedLine = startPosition.getLineNumber();
  36693. const int endLine = endPosition.getLineNumber();
  36694. int lastAffectedLine = firstAffectedLine + 1;
  36695. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36696. if (firstAffectedLine == endLine)
  36697. {
  36698. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36699. + firstLine->line.substring (endPosition.getIndexInLine());
  36700. firstLine->updateLength();
  36701. }
  36702. else
  36703. {
  36704. lastAffectedLine = lines.size();
  36705. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36706. jassert (lastLine != 0);
  36707. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36708. + lastLine->line.substring (endPosition.getIndexInLine());
  36709. firstLine->updateLength();
  36710. int numLinesToRemove = endLine - firstAffectedLine;
  36711. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36712. }
  36713. int i;
  36714. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36715. {
  36716. CodeDocumentLine* const l = lines.getUnchecked (i);
  36717. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36718. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36719. }
  36720. checkLastLineStatus();
  36721. const int totalChars = getNumCharacters();
  36722. for (i = 0; i < positionsToMaintain.size(); ++i)
  36723. {
  36724. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36725. if (p->getPosition() > startPosition.getPosition())
  36726. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36727. if (p->getPosition() > totalChars)
  36728. p->setPosition (totalChars);
  36729. }
  36730. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36731. }
  36732. }
  36733. END_JUCE_NAMESPACE
  36734. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36735. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36736. BEGIN_JUCE_NAMESPACE
  36737. class CodeEditorComponent::CaretComponent : public Component,
  36738. public Timer
  36739. {
  36740. public:
  36741. CaretComponent (CodeEditorComponent& owner_)
  36742. : owner (owner_)
  36743. {
  36744. setAlwaysOnTop (true);
  36745. setInterceptsMouseClicks (false, false);
  36746. }
  36747. void paint (Graphics& g)
  36748. {
  36749. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36750. }
  36751. void timerCallback()
  36752. {
  36753. setVisible (shouldBeShown() && ! isVisible());
  36754. }
  36755. void updatePosition()
  36756. {
  36757. startTimer (400);
  36758. setVisible (shouldBeShown());
  36759. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36760. }
  36761. private:
  36762. CodeEditorComponent& owner;
  36763. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36764. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36765. };
  36766. class CodeEditorComponent::CodeEditorLine
  36767. {
  36768. public:
  36769. CodeEditorLine() throw()
  36770. : highlightColumnStart (0), highlightColumnEnd (0)
  36771. {
  36772. }
  36773. bool update (CodeDocument& document, int lineNum,
  36774. CodeDocument::Iterator& source,
  36775. CodeTokeniser* analyser, const int spacesPerTab,
  36776. const CodeDocument::Position& selectionStart,
  36777. const CodeDocument::Position& selectionEnd)
  36778. {
  36779. Array <SyntaxToken> newTokens;
  36780. newTokens.ensureStorageAllocated (8);
  36781. if (analyser == 0)
  36782. {
  36783. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36784. }
  36785. else if (lineNum < document.getNumLines())
  36786. {
  36787. const CodeDocument::Position pos (&document, lineNum, 0);
  36788. createTokens (pos.getPosition(), pos.getLineText(),
  36789. source, analyser, newTokens);
  36790. }
  36791. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36792. int newHighlightStart = 0;
  36793. int newHighlightEnd = 0;
  36794. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36795. {
  36796. const String line (document.getLine (lineNum));
  36797. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36798. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36799. line, spacesPerTab);
  36800. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36801. line, spacesPerTab);
  36802. }
  36803. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36804. {
  36805. highlightColumnStart = newHighlightStart;
  36806. highlightColumnEnd = newHighlightEnd;
  36807. }
  36808. else
  36809. {
  36810. if (tokens.size() == newTokens.size())
  36811. {
  36812. bool allTheSame = true;
  36813. for (int i = newTokens.size(); --i >= 0;)
  36814. {
  36815. if (tokens.getReference(i) != newTokens.getReference(i))
  36816. {
  36817. allTheSame = false;
  36818. break;
  36819. }
  36820. }
  36821. if (allTheSame)
  36822. return false;
  36823. }
  36824. }
  36825. tokens.swapWithArray (newTokens);
  36826. return true;
  36827. }
  36828. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36829. float x, const int y, const int baselineOffset, const int lineHeight,
  36830. const Colour& highlightColour) const
  36831. {
  36832. if (highlightColumnStart < highlightColumnEnd)
  36833. {
  36834. g.setColour (highlightColour);
  36835. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36836. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36837. }
  36838. int lastType = std::numeric_limits<int>::min();
  36839. for (int i = 0; i < tokens.size(); ++i)
  36840. {
  36841. SyntaxToken& token = tokens.getReference(i);
  36842. if (lastType != token.tokenType)
  36843. {
  36844. lastType = token.tokenType;
  36845. g.setColour (owner.getColourForTokenType (lastType));
  36846. }
  36847. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36848. if (i < tokens.size() - 1)
  36849. {
  36850. if (token.width < 0)
  36851. token.width = font.getStringWidthFloat (token.text);
  36852. x += token.width;
  36853. }
  36854. }
  36855. }
  36856. private:
  36857. struct SyntaxToken
  36858. {
  36859. SyntaxToken (const String& text_, const int type) throw()
  36860. : text (text_), tokenType (type), width (-1.0f)
  36861. {
  36862. }
  36863. bool operator!= (const SyntaxToken& other) const throw()
  36864. {
  36865. return text != other.text || tokenType != other.tokenType;
  36866. }
  36867. String text;
  36868. int tokenType;
  36869. float width;
  36870. };
  36871. Array <SyntaxToken> tokens;
  36872. int highlightColumnStart, highlightColumnEnd;
  36873. static void createTokens (int startPosition, const String& lineText,
  36874. CodeDocument::Iterator& source,
  36875. CodeTokeniser* analyser,
  36876. Array <SyntaxToken>& newTokens)
  36877. {
  36878. CodeDocument::Iterator lastIterator (source);
  36879. const int lineLength = lineText.length();
  36880. for (;;)
  36881. {
  36882. int tokenType = analyser->readNextToken (source);
  36883. int tokenStart = lastIterator.getPosition();
  36884. int tokenEnd = source.getPosition();
  36885. if (tokenEnd <= tokenStart)
  36886. break;
  36887. tokenEnd -= startPosition;
  36888. if (tokenEnd > 0)
  36889. {
  36890. tokenStart -= startPosition;
  36891. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36892. tokenType));
  36893. if (tokenEnd >= lineLength)
  36894. break;
  36895. }
  36896. lastIterator = source;
  36897. }
  36898. source = lastIterator;
  36899. }
  36900. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36901. {
  36902. int x = 0;
  36903. for (int i = 0; i < tokens.size(); ++i)
  36904. {
  36905. SyntaxToken& t = tokens.getReference(i);
  36906. for (;;)
  36907. {
  36908. int tabPos = t.text.indexOfChar ('\t');
  36909. if (tabPos < 0)
  36910. break;
  36911. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36912. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36913. }
  36914. x += t.text.length();
  36915. }
  36916. }
  36917. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36918. {
  36919. jassert (index <= line.length());
  36920. int col = 0;
  36921. for (int i = 0; i < index; ++i)
  36922. {
  36923. if (line[i] != '\t')
  36924. ++col;
  36925. else
  36926. col += spacesPerTab - (col % spacesPerTab);
  36927. }
  36928. return col;
  36929. }
  36930. };
  36931. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36932. CodeTokeniser* const codeTokeniser_)
  36933. : document (document_),
  36934. firstLineOnScreen (0),
  36935. gutter (5),
  36936. spacesPerTab (4),
  36937. lineHeight (0),
  36938. linesOnScreen (0),
  36939. columnsOnScreen (0),
  36940. scrollbarThickness (16),
  36941. columnToTryToMaintain (-1),
  36942. useSpacesForTabs (false),
  36943. xOffset (0),
  36944. verticalScrollBar (true),
  36945. horizontalScrollBar (false),
  36946. codeTokeniser (codeTokeniser_)
  36947. {
  36948. caretPos = CodeDocument::Position (&document_, 0, 0);
  36949. caretPos.setPositionMaintained (true);
  36950. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36951. selectionStart.setPositionMaintained (true);
  36952. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36953. selectionEnd.setPositionMaintained (true);
  36954. setOpaque (true);
  36955. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36956. setWantsKeyboardFocus (true);
  36957. addAndMakeVisible (&verticalScrollBar);
  36958. verticalScrollBar.setSingleStepSize (1.0);
  36959. addAndMakeVisible (&horizontalScrollBar);
  36960. horizontalScrollBar.setSingleStepSize (1.0);
  36961. addAndMakeVisible (caret = new CaretComponent (*this));
  36962. Font f (12.0f);
  36963. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36964. setFont (f);
  36965. resetToDefaultColours();
  36966. verticalScrollBar.addListener (this);
  36967. horizontalScrollBar.addListener (this);
  36968. document.addListener (this);
  36969. }
  36970. CodeEditorComponent::~CodeEditorComponent()
  36971. {
  36972. document.removeListener (this);
  36973. }
  36974. void CodeEditorComponent::loadContent (const String& newContent)
  36975. {
  36976. clearCachedIterators (0);
  36977. document.replaceAllContent (newContent);
  36978. document.clearUndoHistory();
  36979. document.setSavePoint();
  36980. caretPos.setPosition (0);
  36981. selectionStart.setPosition (0);
  36982. selectionEnd.setPosition (0);
  36983. scrollToLine (0);
  36984. }
  36985. bool CodeEditorComponent::isTextInputActive() const
  36986. {
  36987. return true;
  36988. }
  36989. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36990. const CodeDocument::Position& affectedTextEnd)
  36991. {
  36992. clearCachedIterators (affectedTextStart.getLineNumber());
  36993. triggerAsyncUpdate();
  36994. caret->updatePosition();
  36995. columnToTryToMaintain = -1;
  36996. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36997. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36998. deselectAll();
  36999. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  37000. || caretPos.getPosition() < affectedTextStart.getPosition())
  37001. moveCaretTo (affectedTextStart, false);
  37002. updateScrollBars();
  37003. }
  37004. void CodeEditorComponent::resized()
  37005. {
  37006. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  37007. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  37008. lines.clear();
  37009. rebuildLineTokens();
  37010. caret->updatePosition();
  37011. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  37012. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  37013. updateScrollBars();
  37014. }
  37015. void CodeEditorComponent::paint (Graphics& g)
  37016. {
  37017. handleUpdateNowIfNeeded();
  37018. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  37019. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  37020. g.setFont (font);
  37021. const int baselineOffset = (int) font.getAscent();
  37022. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  37023. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  37024. const Rectangle<int> clip (g.getClipBounds());
  37025. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  37026. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  37027. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37028. {
  37029. lines.getUnchecked(j)->draw (*this, g, font,
  37030. (float) (gutter - xOffset * charWidth),
  37031. lineHeight * j, baselineOffset, lineHeight,
  37032. highlightColour);
  37033. }
  37034. }
  37035. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37036. {
  37037. if (scrollbarThickness != thickness)
  37038. {
  37039. scrollbarThickness = thickness;
  37040. resized();
  37041. }
  37042. }
  37043. void CodeEditorComponent::handleAsyncUpdate()
  37044. {
  37045. rebuildLineTokens();
  37046. }
  37047. void CodeEditorComponent::rebuildLineTokens()
  37048. {
  37049. cancelPendingUpdate();
  37050. const int numNeeded = linesOnScreen + 1;
  37051. int minLineToRepaint = numNeeded;
  37052. int maxLineToRepaint = 0;
  37053. if (numNeeded != lines.size())
  37054. {
  37055. lines.clear();
  37056. for (int i = numNeeded; --i >= 0;)
  37057. lines.add (new CodeEditorLine());
  37058. minLineToRepaint = 0;
  37059. maxLineToRepaint = numNeeded;
  37060. }
  37061. jassert (numNeeded == lines.size());
  37062. CodeDocument::Iterator source (&document);
  37063. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37064. for (int i = 0; i < numNeeded; ++i)
  37065. {
  37066. CodeEditorLine* const line = lines.getUnchecked(i);
  37067. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37068. selectionStart, selectionEnd))
  37069. {
  37070. minLineToRepaint = jmin (minLineToRepaint, i);
  37071. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37072. }
  37073. }
  37074. if (minLineToRepaint <= maxLineToRepaint)
  37075. {
  37076. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37077. verticalScrollBar.getX() - gutter,
  37078. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37079. }
  37080. }
  37081. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37082. {
  37083. caretPos = newPos;
  37084. columnToTryToMaintain = -1;
  37085. if (highlighting)
  37086. {
  37087. if (dragType == notDragging)
  37088. {
  37089. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37090. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37091. dragType = draggingSelectionStart;
  37092. else
  37093. dragType = draggingSelectionEnd;
  37094. }
  37095. if (dragType == draggingSelectionStart)
  37096. {
  37097. selectionStart = caretPos;
  37098. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37099. {
  37100. const CodeDocument::Position temp (selectionStart);
  37101. selectionStart = selectionEnd;
  37102. selectionEnd = temp;
  37103. dragType = draggingSelectionEnd;
  37104. }
  37105. }
  37106. else
  37107. {
  37108. selectionEnd = caretPos;
  37109. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37110. {
  37111. const CodeDocument::Position temp (selectionStart);
  37112. selectionStart = selectionEnd;
  37113. selectionEnd = temp;
  37114. dragType = draggingSelectionStart;
  37115. }
  37116. }
  37117. triggerAsyncUpdate();
  37118. }
  37119. else
  37120. {
  37121. deselectAll();
  37122. }
  37123. caret->updatePosition();
  37124. scrollToKeepCaretOnScreen();
  37125. updateScrollBars();
  37126. }
  37127. void CodeEditorComponent::deselectAll()
  37128. {
  37129. if (selectionStart != selectionEnd)
  37130. triggerAsyncUpdate();
  37131. selectionStart = caretPos;
  37132. selectionEnd = caretPos;
  37133. }
  37134. void CodeEditorComponent::updateScrollBars()
  37135. {
  37136. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37137. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  37138. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37139. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  37140. }
  37141. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37142. {
  37143. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37144. newFirstLineOnScreen);
  37145. if (newFirstLineOnScreen != firstLineOnScreen)
  37146. {
  37147. firstLineOnScreen = newFirstLineOnScreen;
  37148. caret->updatePosition();
  37149. updateCachedIterators (firstLineOnScreen);
  37150. triggerAsyncUpdate();
  37151. }
  37152. }
  37153. void CodeEditorComponent::scrollToColumnInternal (double column)
  37154. {
  37155. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37156. if (xOffset != newOffset)
  37157. {
  37158. xOffset = newOffset;
  37159. caret->updatePosition();
  37160. repaint();
  37161. }
  37162. }
  37163. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37164. {
  37165. scrollToLineInternal (newFirstLineOnScreen);
  37166. updateScrollBars();
  37167. }
  37168. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37169. {
  37170. scrollToColumnInternal (newFirstColumnOnScreen);
  37171. updateScrollBars();
  37172. }
  37173. void CodeEditorComponent::scrollBy (int deltaLines)
  37174. {
  37175. scrollToLine (firstLineOnScreen + deltaLines);
  37176. }
  37177. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37178. {
  37179. if (caretPos.getLineNumber() < firstLineOnScreen)
  37180. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37181. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37182. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37183. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37184. if (column >= xOffset + columnsOnScreen - 1)
  37185. scrollToColumn (column + 1 - columnsOnScreen);
  37186. else if (column < xOffset)
  37187. scrollToColumn (column);
  37188. }
  37189. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37190. {
  37191. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37192. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37193. roundToInt (charWidth),
  37194. lineHeight);
  37195. }
  37196. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37197. {
  37198. const int line = y / lineHeight + firstLineOnScreen;
  37199. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37200. const int index = columnToIndex (line, column);
  37201. return CodeDocument::Position (&document, line, index);
  37202. }
  37203. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37204. {
  37205. document.deleteSection (selectionStart, selectionEnd);
  37206. if (newText.isNotEmpty())
  37207. document.insertText (caretPos, newText);
  37208. scrollToKeepCaretOnScreen();
  37209. }
  37210. void CodeEditorComponent::insertTabAtCaret()
  37211. {
  37212. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37213. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37214. {
  37215. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37216. }
  37217. if (useSpacesForTabs)
  37218. {
  37219. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37220. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37221. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37222. }
  37223. else
  37224. {
  37225. insertTextAtCaret ("\t");
  37226. }
  37227. }
  37228. void CodeEditorComponent::cut()
  37229. {
  37230. insertTextAtCaret (String::empty);
  37231. }
  37232. void CodeEditorComponent::copy()
  37233. {
  37234. newTransaction();
  37235. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37236. if (selection.isNotEmpty())
  37237. SystemClipboard::copyTextToClipboard (selection);
  37238. }
  37239. void CodeEditorComponent::copyThenCut()
  37240. {
  37241. copy();
  37242. cut();
  37243. newTransaction();
  37244. }
  37245. void CodeEditorComponent::paste()
  37246. {
  37247. newTransaction();
  37248. const String clip (SystemClipboard::getTextFromClipboard());
  37249. if (clip.isNotEmpty())
  37250. insertTextAtCaret (clip);
  37251. newTransaction();
  37252. }
  37253. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37254. {
  37255. newTransaction();
  37256. if (moveInWholeWordSteps)
  37257. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37258. else
  37259. moveCaretTo (caretPos.movedBy (-1), selecting);
  37260. }
  37261. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37262. {
  37263. newTransaction();
  37264. if (moveInWholeWordSteps)
  37265. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37266. else
  37267. moveCaretTo (caretPos.movedBy (1), selecting);
  37268. }
  37269. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37270. {
  37271. CodeDocument::Position pos (caretPos);
  37272. const int newLineNum = pos.getLineNumber() + delta;
  37273. if (columnToTryToMaintain < 0)
  37274. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37275. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37276. const int colToMaintain = columnToTryToMaintain;
  37277. moveCaretTo (pos, selecting);
  37278. columnToTryToMaintain = colToMaintain;
  37279. }
  37280. void CodeEditorComponent::cursorDown (const bool selecting)
  37281. {
  37282. newTransaction();
  37283. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37284. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37285. else
  37286. moveLineDelta (1, selecting);
  37287. }
  37288. void CodeEditorComponent::cursorUp (const bool selecting)
  37289. {
  37290. newTransaction();
  37291. if (caretPos.getLineNumber() == 0)
  37292. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37293. else
  37294. moveLineDelta (-1, selecting);
  37295. }
  37296. void CodeEditorComponent::pageDown (const bool selecting)
  37297. {
  37298. newTransaction();
  37299. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37300. moveLineDelta (linesOnScreen, selecting);
  37301. }
  37302. void CodeEditorComponent::pageUp (const bool selecting)
  37303. {
  37304. newTransaction();
  37305. scrollBy (-linesOnScreen);
  37306. moveLineDelta (-linesOnScreen, selecting);
  37307. }
  37308. void CodeEditorComponent::scrollUp()
  37309. {
  37310. newTransaction();
  37311. scrollBy (1);
  37312. if (caretPos.getLineNumber() < firstLineOnScreen)
  37313. moveLineDelta (1, false);
  37314. }
  37315. void CodeEditorComponent::scrollDown()
  37316. {
  37317. newTransaction();
  37318. scrollBy (-1);
  37319. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37320. moveLineDelta (-1, false);
  37321. }
  37322. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37323. {
  37324. newTransaction();
  37325. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37326. }
  37327. namespace CodeEditorHelpers
  37328. {
  37329. int findFirstNonWhitespaceChar (const String& line) throw()
  37330. {
  37331. const int len = line.length();
  37332. for (int i = 0; i < len; ++i)
  37333. if (! CharacterFunctions::isWhitespace (line [i]))
  37334. return i;
  37335. return 0;
  37336. }
  37337. }
  37338. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37339. {
  37340. newTransaction();
  37341. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37342. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37343. index = 0;
  37344. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37345. }
  37346. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37347. {
  37348. newTransaction();
  37349. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37350. }
  37351. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37352. {
  37353. newTransaction();
  37354. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37355. }
  37356. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37357. {
  37358. if (moveInWholeWordSteps)
  37359. {
  37360. cut(); // in case something is already highlighted
  37361. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37362. }
  37363. else
  37364. {
  37365. if (selectionStart == selectionEnd)
  37366. selectionStart.moveBy (-1);
  37367. }
  37368. cut();
  37369. }
  37370. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37371. {
  37372. if (moveInWholeWordSteps)
  37373. {
  37374. cut(); // in case something is already highlighted
  37375. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37376. }
  37377. else
  37378. {
  37379. if (selectionStart == selectionEnd)
  37380. selectionEnd.moveBy (1);
  37381. else
  37382. newTransaction();
  37383. }
  37384. cut();
  37385. }
  37386. void CodeEditorComponent::selectAll()
  37387. {
  37388. newTransaction();
  37389. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37390. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37391. }
  37392. void CodeEditorComponent::undo()
  37393. {
  37394. document.undo();
  37395. scrollToKeepCaretOnScreen();
  37396. }
  37397. void CodeEditorComponent::redo()
  37398. {
  37399. document.redo();
  37400. scrollToKeepCaretOnScreen();
  37401. }
  37402. void CodeEditorComponent::newTransaction()
  37403. {
  37404. document.newTransaction();
  37405. startTimer (600);
  37406. }
  37407. void CodeEditorComponent::timerCallback()
  37408. {
  37409. newTransaction();
  37410. }
  37411. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37412. {
  37413. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37414. }
  37415. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37416. {
  37417. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37418. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37419. }
  37420. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37421. {
  37422. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37423. CodeDocument::Position (&document, range.getEnd()));
  37424. }
  37425. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37426. {
  37427. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37428. const bool shiftDown = key.getModifiers().isShiftDown();
  37429. if (key.isKeyCode (KeyPress::leftKey))
  37430. {
  37431. cursorLeft (moveInWholeWordSteps, shiftDown);
  37432. }
  37433. else if (key.isKeyCode (KeyPress::rightKey))
  37434. {
  37435. cursorRight (moveInWholeWordSteps, shiftDown);
  37436. }
  37437. else if (key.isKeyCode (KeyPress::upKey))
  37438. {
  37439. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37440. scrollDown();
  37441. #if JUCE_MAC
  37442. else if (key.getModifiers().isCommandDown())
  37443. goToStartOfDocument (shiftDown);
  37444. #endif
  37445. else
  37446. cursorUp (shiftDown);
  37447. }
  37448. else if (key.isKeyCode (KeyPress::downKey))
  37449. {
  37450. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37451. scrollUp();
  37452. #if JUCE_MAC
  37453. else if (key.getModifiers().isCommandDown())
  37454. goToEndOfDocument (shiftDown);
  37455. #endif
  37456. else
  37457. cursorDown (shiftDown);
  37458. }
  37459. else if (key.isKeyCode (KeyPress::pageDownKey))
  37460. {
  37461. pageDown (shiftDown);
  37462. }
  37463. else if (key.isKeyCode (KeyPress::pageUpKey))
  37464. {
  37465. pageUp (shiftDown);
  37466. }
  37467. else if (key.isKeyCode (KeyPress::homeKey))
  37468. {
  37469. if (moveInWholeWordSteps)
  37470. goToStartOfDocument (shiftDown);
  37471. else
  37472. goToStartOfLine (shiftDown);
  37473. }
  37474. else if (key.isKeyCode (KeyPress::endKey))
  37475. {
  37476. if (moveInWholeWordSteps)
  37477. goToEndOfDocument (shiftDown);
  37478. else
  37479. goToEndOfLine (shiftDown);
  37480. }
  37481. else if (key.isKeyCode (KeyPress::backspaceKey))
  37482. {
  37483. backspace (moveInWholeWordSteps);
  37484. }
  37485. else if (key.isKeyCode (KeyPress::deleteKey))
  37486. {
  37487. deleteForward (moveInWholeWordSteps);
  37488. }
  37489. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37490. {
  37491. copy();
  37492. }
  37493. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37494. {
  37495. copyThenCut();
  37496. }
  37497. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37498. {
  37499. paste();
  37500. }
  37501. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37502. {
  37503. undo();
  37504. }
  37505. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37506. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37507. {
  37508. redo();
  37509. }
  37510. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37511. {
  37512. selectAll();
  37513. }
  37514. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37515. {
  37516. insertTabAtCaret();
  37517. }
  37518. else if (key == KeyPress::returnKey)
  37519. {
  37520. newTransaction();
  37521. insertTextAtCaret (document.getNewLineCharacters());
  37522. }
  37523. else if (key.isKeyCode (KeyPress::escapeKey))
  37524. {
  37525. newTransaction();
  37526. }
  37527. else if (key.getTextCharacter() >= ' ')
  37528. {
  37529. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37530. }
  37531. else
  37532. {
  37533. return false;
  37534. }
  37535. return true;
  37536. }
  37537. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37538. {
  37539. newTransaction();
  37540. dragType = notDragging;
  37541. if (! e.mods.isPopupMenu())
  37542. {
  37543. beginDragAutoRepeat (100);
  37544. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37545. }
  37546. else
  37547. {
  37548. /*PopupMenu m;
  37549. addPopupMenuItems (m, &e);
  37550. const int result = m.show();
  37551. if (result != 0)
  37552. performPopupMenuAction (result);
  37553. */
  37554. }
  37555. }
  37556. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37557. {
  37558. if (! e.mods.isPopupMenu())
  37559. moveCaretTo (getPositionAt (e.x, e.y), true);
  37560. }
  37561. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37562. {
  37563. newTransaction();
  37564. beginDragAutoRepeat (0);
  37565. dragType = notDragging;
  37566. }
  37567. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37568. {
  37569. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37570. CodeDocument::Position tokenEnd (tokenStart);
  37571. if (e.getNumberOfClicks() > 2)
  37572. {
  37573. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37574. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37575. }
  37576. else
  37577. {
  37578. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37579. tokenEnd.moveBy (1);
  37580. tokenStart = tokenEnd;
  37581. while (tokenStart.getIndexInLine() > 0
  37582. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37583. tokenStart.moveBy (-1);
  37584. }
  37585. moveCaretTo (tokenEnd, false);
  37586. moveCaretTo (tokenStart, true);
  37587. }
  37588. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37589. {
  37590. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37591. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37592. {
  37593. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37594. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37595. }
  37596. else
  37597. {
  37598. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37599. }
  37600. }
  37601. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37602. {
  37603. if (scrollBarThatHasMoved == &verticalScrollBar)
  37604. scrollToLineInternal ((int) newRangeStart);
  37605. else
  37606. scrollToColumnInternal (newRangeStart);
  37607. }
  37608. void CodeEditorComponent::focusGained (FocusChangeType)
  37609. {
  37610. caret->updatePosition();
  37611. }
  37612. void CodeEditorComponent::focusLost (FocusChangeType)
  37613. {
  37614. caret->updatePosition();
  37615. }
  37616. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37617. {
  37618. useSpacesForTabs = insertSpaces;
  37619. if (spacesPerTab != numSpaces)
  37620. {
  37621. spacesPerTab = numSpaces;
  37622. triggerAsyncUpdate();
  37623. }
  37624. }
  37625. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37626. {
  37627. const String line (document.getLine (lineNum));
  37628. jassert (index <= line.length());
  37629. int col = 0;
  37630. for (int i = 0; i < index; ++i)
  37631. {
  37632. if (line[i] != '\t')
  37633. ++col;
  37634. else
  37635. col += getTabSize() - (col % getTabSize());
  37636. }
  37637. return col;
  37638. }
  37639. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37640. {
  37641. const String line (document.getLine (lineNum));
  37642. const int lineLength = line.length();
  37643. int i, col = 0;
  37644. for (i = 0; i < lineLength; ++i)
  37645. {
  37646. if (line[i] != '\t')
  37647. ++col;
  37648. else
  37649. col += getTabSize() - (col % getTabSize());
  37650. if (col > column)
  37651. break;
  37652. }
  37653. return i;
  37654. }
  37655. void CodeEditorComponent::setFont (const Font& newFont)
  37656. {
  37657. font = newFont;
  37658. charWidth = font.getStringWidthFloat ("0");
  37659. lineHeight = roundToInt (font.getHeight());
  37660. resized();
  37661. }
  37662. void CodeEditorComponent::resetToDefaultColours()
  37663. {
  37664. coloursForTokenCategories.clear();
  37665. if (codeTokeniser != 0)
  37666. {
  37667. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37668. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37669. }
  37670. }
  37671. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37672. {
  37673. jassert (tokenType < 256);
  37674. while (coloursForTokenCategories.size() < tokenType)
  37675. coloursForTokenCategories.add (Colours::black);
  37676. coloursForTokenCategories.set (tokenType, colour);
  37677. repaint();
  37678. }
  37679. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37680. {
  37681. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37682. return findColour (CodeEditorComponent::defaultTextColourId);
  37683. return coloursForTokenCategories.getReference (tokenType);
  37684. }
  37685. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37686. {
  37687. int i;
  37688. for (i = cachedIterators.size(); --i >= 0;)
  37689. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37690. break;
  37691. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37692. }
  37693. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37694. {
  37695. const int maxNumCachedPositions = 5000;
  37696. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37697. if (cachedIterators.size() == 0)
  37698. cachedIterators.add (new CodeDocument::Iterator (&document));
  37699. if (codeTokeniser == 0)
  37700. return;
  37701. for (;;)
  37702. {
  37703. CodeDocument::Iterator* last = cachedIterators.getLast();
  37704. if (last->getLine() >= maxLineNum)
  37705. break;
  37706. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37707. cachedIterators.add (t);
  37708. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37709. for (;;)
  37710. {
  37711. codeTokeniser->readNextToken (*t);
  37712. if (t->getLine() >= targetLine)
  37713. break;
  37714. if (t->isEOF())
  37715. return;
  37716. }
  37717. }
  37718. }
  37719. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37720. {
  37721. if (codeTokeniser == 0)
  37722. return;
  37723. for (int i = cachedIterators.size(); --i >= 0;)
  37724. {
  37725. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37726. if (t->getPosition() <= position)
  37727. {
  37728. source = *t;
  37729. break;
  37730. }
  37731. }
  37732. while (source.getPosition() < position)
  37733. {
  37734. const CodeDocument::Iterator original (source);
  37735. codeTokeniser->readNextToken (source);
  37736. if (source.getPosition() > position || source.isEOF())
  37737. {
  37738. source = original;
  37739. break;
  37740. }
  37741. }
  37742. }
  37743. END_JUCE_NAMESPACE
  37744. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37745. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37746. BEGIN_JUCE_NAMESPACE
  37747. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37748. {
  37749. }
  37750. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37751. {
  37752. }
  37753. namespace CppTokeniser
  37754. {
  37755. bool isIdentifierStart (const juce_wchar c) throw()
  37756. {
  37757. return CharacterFunctions::isLetter (c)
  37758. || c == '_' || c == '@';
  37759. }
  37760. bool isIdentifierBody (const juce_wchar c) throw()
  37761. {
  37762. return CharacterFunctions::isLetterOrDigit (c)
  37763. || c == '_' || c == '@';
  37764. }
  37765. bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37766. {
  37767. static const juce_wchar* const keywords2Char[] =
  37768. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37769. static const juce_wchar* const keywords3Char[] =
  37770. { 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 };
  37771. static const juce_wchar* const keywords4Char[] =
  37772. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37773. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37774. static const juce_wchar* const keywords5Char[] =
  37775. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37776. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37777. static const juce_wchar* const keywords6Char[] =
  37778. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37779. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37780. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37781. static const juce_wchar* const keywordsOther[] =
  37782. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37783. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37784. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37785. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37786. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37787. const juce_wchar* const* k;
  37788. switch (tokenLength)
  37789. {
  37790. case 2: k = keywords2Char; break;
  37791. case 3: k = keywords3Char; break;
  37792. case 4: k = keywords4Char; break;
  37793. case 5: k = keywords5Char; break;
  37794. case 6: k = keywords6Char; break;
  37795. default:
  37796. if (tokenLength < 2 || tokenLength > 16)
  37797. return false;
  37798. k = keywordsOther;
  37799. break;
  37800. }
  37801. int i = 0;
  37802. while (k[i] != 0)
  37803. {
  37804. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37805. return true;
  37806. ++i;
  37807. }
  37808. return false;
  37809. }
  37810. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37811. {
  37812. int tokenLength = 0;
  37813. juce_wchar possibleIdentifier [19];
  37814. while (isIdentifierBody (source.peekNextChar()))
  37815. {
  37816. const juce_wchar c = source.nextChar();
  37817. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37818. possibleIdentifier [tokenLength] = c;
  37819. ++tokenLength;
  37820. }
  37821. if (tokenLength > 1 && tokenLength <= 16)
  37822. {
  37823. possibleIdentifier [tokenLength] = 0;
  37824. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37825. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37826. }
  37827. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37828. }
  37829. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37830. {
  37831. const juce_wchar c = source.peekNextChar();
  37832. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37833. source.skip();
  37834. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37835. return false;
  37836. return true;
  37837. }
  37838. bool isHexDigit (const juce_wchar c) throw()
  37839. {
  37840. return (c >= '0' && c <= '9')
  37841. || (c >= 'a' && c <= 'f')
  37842. || (c >= 'A' && c <= 'F');
  37843. }
  37844. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37845. {
  37846. if (source.nextChar() != '0')
  37847. return false;
  37848. juce_wchar c = source.nextChar();
  37849. if (c != 'x' && c != 'X')
  37850. return false;
  37851. int numDigits = 0;
  37852. while (isHexDigit (source.peekNextChar()))
  37853. {
  37854. ++numDigits;
  37855. source.skip();
  37856. }
  37857. if (numDigits == 0)
  37858. return false;
  37859. return skipNumberSuffix (source);
  37860. }
  37861. bool isOctalDigit (const juce_wchar c) throw()
  37862. {
  37863. return c >= '0' && c <= '7';
  37864. }
  37865. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37866. {
  37867. if (source.nextChar() != '0')
  37868. return false;
  37869. if (! isOctalDigit (source.nextChar()))
  37870. return false;
  37871. while (isOctalDigit (source.peekNextChar()))
  37872. source.skip();
  37873. return skipNumberSuffix (source);
  37874. }
  37875. bool isDecimalDigit (const juce_wchar c) throw()
  37876. {
  37877. return c >= '0' && c <= '9';
  37878. }
  37879. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37880. {
  37881. int numChars = 0;
  37882. while (isDecimalDigit (source.peekNextChar()))
  37883. {
  37884. ++numChars;
  37885. source.skip();
  37886. }
  37887. if (numChars == 0)
  37888. return false;
  37889. return skipNumberSuffix (source);
  37890. }
  37891. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37892. {
  37893. int numDigits = 0;
  37894. while (isDecimalDigit (source.peekNextChar()))
  37895. {
  37896. source.skip();
  37897. ++numDigits;
  37898. }
  37899. const bool hasPoint = (source.peekNextChar() == '.');
  37900. if (hasPoint)
  37901. {
  37902. source.skip();
  37903. while (isDecimalDigit (source.peekNextChar()))
  37904. {
  37905. source.skip();
  37906. ++numDigits;
  37907. }
  37908. }
  37909. if (numDigits == 0)
  37910. return false;
  37911. juce_wchar c = source.peekNextChar();
  37912. const bool hasExponent = (c == 'e' || c == 'E');
  37913. if (hasExponent)
  37914. {
  37915. source.skip();
  37916. c = source.peekNextChar();
  37917. if (c == '+' || c == '-')
  37918. source.skip();
  37919. int numExpDigits = 0;
  37920. while (isDecimalDigit (source.peekNextChar()))
  37921. {
  37922. source.skip();
  37923. ++numExpDigits;
  37924. }
  37925. if (numExpDigits == 0)
  37926. return false;
  37927. }
  37928. c = source.peekNextChar();
  37929. if (c == 'f' || c == 'F')
  37930. source.skip();
  37931. else if (! (hasExponent || hasPoint))
  37932. return false;
  37933. return true;
  37934. }
  37935. int parseNumber (CodeDocument::Iterator& source)
  37936. {
  37937. const CodeDocument::Iterator original (source);
  37938. if (parseFloatLiteral (source))
  37939. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37940. source = original;
  37941. if (parseHexLiteral (source))
  37942. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37943. source = original;
  37944. if (parseOctalLiteral (source))
  37945. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37946. source = original;
  37947. if (parseDecimalLiteral (source))
  37948. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37949. source = original;
  37950. source.skip();
  37951. return CPlusPlusCodeTokeniser::tokenType_error;
  37952. }
  37953. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37954. {
  37955. const juce_wchar quote = source.nextChar();
  37956. for (;;)
  37957. {
  37958. const juce_wchar c = source.nextChar();
  37959. if (c == quote || c == 0)
  37960. break;
  37961. if (c == '\\')
  37962. source.skip();
  37963. }
  37964. }
  37965. void skipComment (CodeDocument::Iterator& source) throw()
  37966. {
  37967. bool lastWasStar = false;
  37968. for (;;)
  37969. {
  37970. const juce_wchar c = source.nextChar();
  37971. if (c == 0 || (c == '/' && lastWasStar))
  37972. break;
  37973. lastWasStar = (c == '*');
  37974. }
  37975. }
  37976. }
  37977. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37978. {
  37979. int result = tokenType_error;
  37980. source.skipWhitespace();
  37981. juce_wchar firstChar = source.peekNextChar();
  37982. switch (firstChar)
  37983. {
  37984. case 0:
  37985. source.skip();
  37986. break;
  37987. case '0':
  37988. case '1':
  37989. case '2':
  37990. case '3':
  37991. case '4':
  37992. case '5':
  37993. case '6':
  37994. case '7':
  37995. case '8':
  37996. case '9':
  37997. result = CppTokeniser::parseNumber (source);
  37998. break;
  37999. case '.':
  38000. result = CppTokeniser::parseNumber (source);
  38001. if (result == tokenType_error)
  38002. result = tokenType_punctuation;
  38003. break;
  38004. case ',':
  38005. case ';':
  38006. case ':':
  38007. source.skip();
  38008. result = tokenType_punctuation;
  38009. break;
  38010. case '(':
  38011. case ')':
  38012. case '{':
  38013. case '}':
  38014. case '[':
  38015. case ']':
  38016. source.skip();
  38017. result = tokenType_bracket;
  38018. break;
  38019. case '"':
  38020. case '\'':
  38021. CppTokeniser::skipQuotedString (source);
  38022. result = tokenType_stringLiteral;
  38023. break;
  38024. case '+':
  38025. result = tokenType_operator;
  38026. source.skip();
  38027. if (source.peekNextChar() == '+')
  38028. source.skip();
  38029. else if (source.peekNextChar() == '=')
  38030. source.skip();
  38031. break;
  38032. case '-':
  38033. source.skip();
  38034. result = CppTokeniser::parseNumber (source);
  38035. if (result == tokenType_error)
  38036. {
  38037. result = tokenType_operator;
  38038. if (source.peekNextChar() == '-')
  38039. source.skip();
  38040. else if (source.peekNextChar() == '=')
  38041. source.skip();
  38042. }
  38043. break;
  38044. case '*':
  38045. case '%':
  38046. case '=':
  38047. case '!':
  38048. result = tokenType_operator;
  38049. source.skip();
  38050. if (source.peekNextChar() == '=')
  38051. source.skip();
  38052. break;
  38053. case '/':
  38054. result = tokenType_operator;
  38055. source.skip();
  38056. if (source.peekNextChar() == '=')
  38057. {
  38058. source.skip();
  38059. }
  38060. else if (source.peekNextChar() == '/')
  38061. {
  38062. result = tokenType_comment;
  38063. source.skipToEndOfLine();
  38064. }
  38065. else if (source.peekNextChar() == '*')
  38066. {
  38067. source.skip();
  38068. result = tokenType_comment;
  38069. CppTokeniser::skipComment (source);
  38070. }
  38071. break;
  38072. case '?':
  38073. case '~':
  38074. source.skip();
  38075. result = tokenType_operator;
  38076. break;
  38077. case '<':
  38078. source.skip();
  38079. result = tokenType_operator;
  38080. if (source.peekNextChar() == '=')
  38081. {
  38082. source.skip();
  38083. }
  38084. else if (source.peekNextChar() == '<')
  38085. {
  38086. source.skip();
  38087. if (source.peekNextChar() == '=')
  38088. source.skip();
  38089. }
  38090. break;
  38091. case '>':
  38092. source.skip();
  38093. result = tokenType_operator;
  38094. if (source.peekNextChar() == '=')
  38095. {
  38096. source.skip();
  38097. }
  38098. else if (source.peekNextChar() == '<')
  38099. {
  38100. source.skip();
  38101. if (source.peekNextChar() == '=')
  38102. source.skip();
  38103. }
  38104. break;
  38105. case '|':
  38106. source.skip();
  38107. result = tokenType_operator;
  38108. if (source.peekNextChar() == '=')
  38109. {
  38110. source.skip();
  38111. }
  38112. else if (source.peekNextChar() == '|')
  38113. {
  38114. source.skip();
  38115. if (source.peekNextChar() == '=')
  38116. source.skip();
  38117. }
  38118. break;
  38119. case '&':
  38120. source.skip();
  38121. result = tokenType_operator;
  38122. if (source.peekNextChar() == '=')
  38123. {
  38124. source.skip();
  38125. }
  38126. else if (source.peekNextChar() == '&')
  38127. {
  38128. source.skip();
  38129. if (source.peekNextChar() == '=')
  38130. source.skip();
  38131. }
  38132. break;
  38133. case '^':
  38134. source.skip();
  38135. result = tokenType_operator;
  38136. if (source.peekNextChar() == '=')
  38137. {
  38138. source.skip();
  38139. }
  38140. else if (source.peekNextChar() == '^')
  38141. {
  38142. source.skip();
  38143. if (source.peekNextChar() == '=')
  38144. source.skip();
  38145. }
  38146. break;
  38147. case '#':
  38148. result = tokenType_preprocessor;
  38149. source.skipToEndOfLine();
  38150. break;
  38151. default:
  38152. if (CppTokeniser::isIdentifierStart (firstChar))
  38153. result = CppTokeniser::parseIdentifier (source);
  38154. else
  38155. source.skip();
  38156. break;
  38157. }
  38158. return result;
  38159. }
  38160. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38161. {
  38162. const char* const types[] =
  38163. {
  38164. "Error",
  38165. "Comment",
  38166. "C++ keyword",
  38167. "Identifier",
  38168. "Integer literal",
  38169. "Float literal",
  38170. "String literal",
  38171. "Operator",
  38172. "Bracket",
  38173. "Punctuation",
  38174. "Preprocessor line",
  38175. 0
  38176. };
  38177. return StringArray (types);
  38178. }
  38179. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38180. {
  38181. const uint32 colours[] =
  38182. {
  38183. 0xffcc0000, // error
  38184. 0xff00aa00, // comment
  38185. 0xff0000cc, // keyword
  38186. 0xff000000, // identifier
  38187. 0xff880000, // int literal
  38188. 0xff885500, // float literal
  38189. 0xff990099, // string literal
  38190. 0xff225500, // operator
  38191. 0xff000055, // bracket
  38192. 0xff004400, // punctuation
  38193. 0xff660000 // preprocessor
  38194. };
  38195. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38196. return Colour (colours [tokenType]);
  38197. return Colours::black;
  38198. }
  38199. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38200. {
  38201. return CppTokeniser::isReservedKeyword (token, token.length());
  38202. }
  38203. END_JUCE_NAMESPACE
  38204. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38205. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38206. BEGIN_JUCE_NAMESPACE
  38207. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  38208. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  38209. {
  38210. }
  38211. bool ComboBox::ItemInfo::isSeparator() const throw()
  38212. {
  38213. return name.isEmpty();
  38214. }
  38215. bool ComboBox::ItemInfo::isRealItem() const throw()
  38216. {
  38217. return ! (isHeading || name.isEmpty());
  38218. }
  38219. ComboBox::ComboBox (const String& name)
  38220. : Component (name),
  38221. lastCurrentId (0),
  38222. isButtonDown (false),
  38223. separatorPending (false),
  38224. menuActive (false),
  38225. noChoicesMessage (TRANS("(no choices)"))
  38226. {
  38227. setRepaintsOnMouseActivity (true);
  38228. lookAndFeelChanged();
  38229. currentId.addListener (this);
  38230. }
  38231. ComboBox::~ComboBox()
  38232. {
  38233. currentId.removeListener (this);
  38234. if (menuActive)
  38235. PopupMenu::dismissAllActiveMenus();
  38236. label = 0;
  38237. }
  38238. void ComboBox::setEditableText (const bool isEditable)
  38239. {
  38240. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38241. {
  38242. label->setEditable (isEditable, isEditable, false);
  38243. setWantsKeyboardFocus (! isEditable);
  38244. resized();
  38245. }
  38246. }
  38247. bool ComboBox::isTextEditable() const throw()
  38248. {
  38249. return label->isEditable();
  38250. }
  38251. void ComboBox::setJustificationType (const Justification& justification)
  38252. {
  38253. label->setJustificationType (justification);
  38254. }
  38255. const Justification ComboBox::getJustificationType() const throw()
  38256. {
  38257. return label->getJustificationType();
  38258. }
  38259. void ComboBox::setTooltip (const String& newTooltip)
  38260. {
  38261. SettableTooltipClient::setTooltip (newTooltip);
  38262. label->setTooltip (newTooltip);
  38263. }
  38264. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38265. {
  38266. // you can't add empty strings to the list..
  38267. jassert (newItemText.isNotEmpty());
  38268. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38269. jassert (newItemId != 0);
  38270. // you shouldn't use duplicate item IDs!
  38271. jassert (getItemForId (newItemId) == 0);
  38272. if (newItemText.isNotEmpty() && newItemId != 0)
  38273. {
  38274. if (separatorPending)
  38275. {
  38276. separatorPending = false;
  38277. items.add (new ItemInfo (String::empty, 0, false, false));
  38278. }
  38279. items.add (new ItemInfo (newItemText, newItemId, true, false));
  38280. }
  38281. }
  38282. void ComboBox::addSeparator()
  38283. {
  38284. separatorPending = (items.size() > 0);
  38285. }
  38286. void ComboBox::addSectionHeading (const String& headingName)
  38287. {
  38288. // you can't add empty strings to the list..
  38289. jassert (headingName.isNotEmpty());
  38290. if (headingName.isNotEmpty())
  38291. {
  38292. if (separatorPending)
  38293. {
  38294. separatorPending = false;
  38295. items.add (new ItemInfo (String::empty, 0, false, false));
  38296. }
  38297. items.add (new ItemInfo (headingName, 0, true, true));
  38298. }
  38299. }
  38300. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38301. {
  38302. ItemInfo* const item = getItemForId (itemId);
  38303. if (item != 0)
  38304. item->isEnabled = shouldBeEnabled;
  38305. }
  38306. void ComboBox::changeItemText (const int itemId, const String& newText)
  38307. {
  38308. ItemInfo* const item = getItemForId (itemId);
  38309. jassert (item != 0);
  38310. if (item != 0)
  38311. item->name = newText;
  38312. }
  38313. void ComboBox::clear (const bool dontSendChangeMessage)
  38314. {
  38315. items.clear();
  38316. separatorPending = false;
  38317. if (! label->isEditable())
  38318. setSelectedItemIndex (-1, dontSendChangeMessage);
  38319. }
  38320. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38321. {
  38322. if (itemId != 0)
  38323. {
  38324. for (int i = items.size(); --i >= 0;)
  38325. if (items.getUnchecked(i)->itemId == itemId)
  38326. return items.getUnchecked(i);
  38327. }
  38328. return 0;
  38329. }
  38330. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38331. {
  38332. for (int n = 0, i = 0; i < items.size(); ++i)
  38333. {
  38334. ItemInfo* const item = items.getUnchecked(i);
  38335. if (item->isRealItem())
  38336. if (n++ == index)
  38337. return item;
  38338. }
  38339. return 0;
  38340. }
  38341. int ComboBox::getNumItems() const throw()
  38342. {
  38343. int n = 0;
  38344. for (int i = items.size(); --i >= 0;)
  38345. if (items.getUnchecked(i)->isRealItem())
  38346. ++n;
  38347. return n;
  38348. }
  38349. const String ComboBox::getItemText (const int index) const
  38350. {
  38351. const ItemInfo* const item = getItemForIndex (index);
  38352. return item != 0 ? item->name : String::empty;
  38353. }
  38354. int ComboBox::getItemId (const int index) const throw()
  38355. {
  38356. const ItemInfo* const item = getItemForIndex (index);
  38357. return item != 0 ? item->itemId : 0;
  38358. }
  38359. int ComboBox::indexOfItemId (const int itemId) const throw()
  38360. {
  38361. for (int n = 0, i = 0; i < items.size(); ++i)
  38362. {
  38363. const ItemInfo* const item = items.getUnchecked(i);
  38364. if (item->isRealItem())
  38365. {
  38366. if (item->itemId == itemId)
  38367. return n;
  38368. ++n;
  38369. }
  38370. }
  38371. return -1;
  38372. }
  38373. int ComboBox::getSelectedItemIndex() const
  38374. {
  38375. int index = indexOfItemId (currentId.getValue());
  38376. if (getText() != getItemText (index))
  38377. index = -1;
  38378. return index;
  38379. }
  38380. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38381. {
  38382. setSelectedId (getItemId (index), dontSendChangeMessage);
  38383. }
  38384. int ComboBox::getSelectedId() const throw()
  38385. {
  38386. const ItemInfo* const item = getItemForId (currentId.getValue());
  38387. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38388. }
  38389. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38390. {
  38391. const ItemInfo* const item = getItemForId (newItemId);
  38392. const String newItemText (item != 0 ? item->name : String::empty);
  38393. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38394. {
  38395. if (! dontSendChangeMessage)
  38396. triggerAsyncUpdate();
  38397. label->setText (newItemText, false);
  38398. lastCurrentId = newItemId;
  38399. currentId = newItemId;
  38400. repaint(); // for the benefit of the 'none selected' text
  38401. }
  38402. }
  38403. void ComboBox::valueChanged (Value&)
  38404. {
  38405. if (lastCurrentId != (int) currentId.getValue())
  38406. setSelectedId (currentId.getValue(), false);
  38407. }
  38408. const String ComboBox::getText() const
  38409. {
  38410. return label->getText();
  38411. }
  38412. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38413. {
  38414. for (int i = items.size(); --i >= 0;)
  38415. {
  38416. const ItemInfo* const item = items.getUnchecked(i);
  38417. if (item->isRealItem()
  38418. && item->name == newText)
  38419. {
  38420. setSelectedId (item->itemId, dontSendChangeMessage);
  38421. return;
  38422. }
  38423. }
  38424. lastCurrentId = 0;
  38425. currentId = 0;
  38426. if (label->getText() != newText)
  38427. {
  38428. label->setText (newText, false);
  38429. if (! dontSendChangeMessage)
  38430. triggerAsyncUpdate();
  38431. }
  38432. repaint();
  38433. }
  38434. void ComboBox::showEditor()
  38435. {
  38436. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38437. label->showEditor();
  38438. }
  38439. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38440. {
  38441. if (textWhenNothingSelected != newMessage)
  38442. {
  38443. textWhenNothingSelected = newMessage;
  38444. repaint();
  38445. }
  38446. }
  38447. const String ComboBox::getTextWhenNothingSelected() const
  38448. {
  38449. return textWhenNothingSelected;
  38450. }
  38451. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38452. {
  38453. noChoicesMessage = newMessage;
  38454. }
  38455. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38456. {
  38457. return noChoicesMessage;
  38458. }
  38459. void ComboBox::paint (Graphics& g)
  38460. {
  38461. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38462. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38463. *this);
  38464. if (textWhenNothingSelected.isNotEmpty()
  38465. && label->getText().isEmpty()
  38466. && ! label->isBeingEdited())
  38467. {
  38468. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38469. g.setFont (label->getFont());
  38470. g.drawFittedText (textWhenNothingSelected,
  38471. label->getX() + 2, label->getY() + 1,
  38472. label->getWidth() - 4, label->getHeight() - 2,
  38473. label->getJustificationType(),
  38474. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38475. }
  38476. }
  38477. void ComboBox::resized()
  38478. {
  38479. if (getHeight() > 0 && getWidth() > 0)
  38480. getLookAndFeel().positionComboBoxText (*this, *label);
  38481. }
  38482. void ComboBox::enablementChanged()
  38483. {
  38484. repaint();
  38485. }
  38486. void ComboBox::lookAndFeelChanged()
  38487. {
  38488. repaint();
  38489. {
  38490. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38491. jassert (newLabel != 0);
  38492. if (label != 0)
  38493. {
  38494. newLabel->setEditable (label->isEditable());
  38495. newLabel->setJustificationType (label->getJustificationType());
  38496. newLabel->setTooltip (label->getTooltip());
  38497. newLabel->setText (label->getText(), false);
  38498. }
  38499. label = newLabel;
  38500. }
  38501. addAndMakeVisible (label);
  38502. label->addListener (this);
  38503. label->addMouseListener (this, false);
  38504. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38505. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38506. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38507. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38508. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38509. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38510. resized();
  38511. }
  38512. void ComboBox::colourChanged()
  38513. {
  38514. lookAndFeelChanged();
  38515. }
  38516. bool ComboBox::keyPressed (const KeyPress& key)
  38517. {
  38518. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38519. {
  38520. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38521. return true;
  38522. }
  38523. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38524. {
  38525. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38526. return true;
  38527. }
  38528. else if (key.isKeyCode (KeyPress::returnKey))
  38529. {
  38530. showPopup();
  38531. return true;
  38532. }
  38533. return false;
  38534. }
  38535. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38536. {
  38537. // only forward key events that aren't used by this component
  38538. return isKeyDown
  38539. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38540. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38541. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38542. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38543. }
  38544. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38545. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38546. void ComboBox::labelTextChanged (Label*)
  38547. {
  38548. triggerAsyncUpdate();
  38549. }
  38550. class ComboBox::Callback : public ModalComponentManager::Callback
  38551. {
  38552. public:
  38553. Callback (ComboBox* const box_)
  38554. : box (box_)
  38555. {
  38556. }
  38557. void modalStateFinished (int returnValue)
  38558. {
  38559. if (box != 0)
  38560. {
  38561. box->menuActive = false;
  38562. if (returnValue != 0)
  38563. box->setSelectedId (returnValue);
  38564. }
  38565. }
  38566. private:
  38567. Component::SafePointer<ComboBox> box;
  38568. JUCE_DECLARE_NON_COPYABLE (Callback);
  38569. };
  38570. void ComboBox::showPopup()
  38571. {
  38572. if (! menuActive)
  38573. {
  38574. const int selectedId = getSelectedId();
  38575. PopupMenu menu;
  38576. menu.setLookAndFeel (&getLookAndFeel());
  38577. for (int i = 0; i < items.size(); ++i)
  38578. {
  38579. const ItemInfo* const item = items.getUnchecked(i);
  38580. if (item->isSeparator())
  38581. menu.addSeparator();
  38582. else if (item->isHeading)
  38583. menu.addSectionHeader (item->name);
  38584. else
  38585. menu.addItem (item->itemId, item->name,
  38586. item->isEnabled, item->itemId == selectedId);
  38587. }
  38588. if (items.size() == 0)
  38589. menu.addItem (1, noChoicesMessage, false);
  38590. menuActive = true;
  38591. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38592. new Callback (this));
  38593. }
  38594. }
  38595. void ComboBox::mouseDown (const MouseEvent& e)
  38596. {
  38597. beginDragAutoRepeat (300);
  38598. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38599. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38600. showPopup();
  38601. }
  38602. void ComboBox::mouseDrag (const MouseEvent& e)
  38603. {
  38604. beginDragAutoRepeat (50);
  38605. if (isButtonDown && ! e.mouseWasClicked())
  38606. showPopup();
  38607. }
  38608. void ComboBox::mouseUp (const MouseEvent& e2)
  38609. {
  38610. if (isButtonDown)
  38611. {
  38612. isButtonDown = false;
  38613. repaint();
  38614. const MouseEvent e (e2.getEventRelativeTo (this));
  38615. if (reallyContains (e.getPosition(), true)
  38616. && (e2.eventComponent == this || ! label->isEditable()))
  38617. {
  38618. showPopup();
  38619. }
  38620. }
  38621. }
  38622. void ComboBox::addListener (ComboBoxListener* const listener)
  38623. {
  38624. listeners.add (listener);
  38625. }
  38626. void ComboBox::removeListener (ComboBoxListener* const listener)
  38627. {
  38628. listeners.remove (listener);
  38629. }
  38630. void ComboBox::handleAsyncUpdate()
  38631. {
  38632. Component::BailOutChecker checker (this);
  38633. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38634. }
  38635. END_JUCE_NAMESPACE
  38636. /*** End of inlined file: juce_ComboBox.cpp ***/
  38637. /*** Start of inlined file: juce_Label.cpp ***/
  38638. BEGIN_JUCE_NAMESPACE
  38639. Label::Label (const String& componentName,
  38640. const String& labelText)
  38641. : Component (componentName),
  38642. textValue (labelText),
  38643. lastTextValue (labelText),
  38644. font (15.0f),
  38645. justification (Justification::centredLeft),
  38646. ownerComponent (0),
  38647. horizontalBorderSize (5),
  38648. verticalBorderSize (1),
  38649. minimumHorizontalScale (0.7f),
  38650. editSingleClick (false),
  38651. editDoubleClick (false),
  38652. lossOfFocusDiscardsChanges (false)
  38653. {
  38654. setColour (TextEditor::textColourId, Colours::black);
  38655. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38656. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38657. textValue.addListener (this);
  38658. }
  38659. Label::~Label()
  38660. {
  38661. textValue.removeListener (this);
  38662. if (ownerComponent != 0)
  38663. ownerComponent->removeComponentListener (this);
  38664. editor = 0;
  38665. }
  38666. void Label::setText (const String& newText,
  38667. const bool broadcastChangeMessage)
  38668. {
  38669. hideEditor (true);
  38670. if (lastTextValue != newText)
  38671. {
  38672. lastTextValue = newText;
  38673. textValue = newText;
  38674. repaint();
  38675. textWasChanged();
  38676. if (ownerComponent != 0)
  38677. componentMovedOrResized (*ownerComponent, true, true);
  38678. if (broadcastChangeMessage)
  38679. callChangeListeners();
  38680. }
  38681. }
  38682. const String Label::getText (const bool returnActiveEditorContents) const
  38683. {
  38684. return (returnActiveEditorContents && isBeingEdited())
  38685. ? editor->getText()
  38686. : textValue.toString();
  38687. }
  38688. void Label::valueChanged (Value&)
  38689. {
  38690. if (lastTextValue != textValue.toString())
  38691. setText (textValue.toString(), true);
  38692. }
  38693. void Label::setFont (const Font& newFont)
  38694. {
  38695. if (font != newFont)
  38696. {
  38697. font = newFont;
  38698. repaint();
  38699. }
  38700. }
  38701. const Font& Label::getFont() const throw()
  38702. {
  38703. return font;
  38704. }
  38705. void Label::setEditable (const bool editOnSingleClick,
  38706. const bool editOnDoubleClick,
  38707. const bool lossOfFocusDiscardsChanges_)
  38708. {
  38709. editSingleClick = editOnSingleClick;
  38710. editDoubleClick = editOnDoubleClick;
  38711. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38712. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38713. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38714. }
  38715. void Label::setJustificationType (const Justification& newJustification)
  38716. {
  38717. if (justification != newJustification)
  38718. {
  38719. justification = newJustification;
  38720. repaint();
  38721. }
  38722. }
  38723. void Label::setBorderSize (int h, int v)
  38724. {
  38725. if (horizontalBorderSize != h || verticalBorderSize != v)
  38726. {
  38727. horizontalBorderSize = h;
  38728. verticalBorderSize = v;
  38729. repaint();
  38730. }
  38731. }
  38732. Component* Label::getAttachedComponent() const
  38733. {
  38734. return static_cast<Component*> (ownerComponent);
  38735. }
  38736. void Label::attachToComponent (Component* owner,
  38737. const bool onLeft)
  38738. {
  38739. if (ownerComponent != 0)
  38740. ownerComponent->removeComponentListener (this);
  38741. ownerComponent = owner;
  38742. leftOfOwnerComp = onLeft;
  38743. if (ownerComponent != 0)
  38744. {
  38745. setVisible (owner->isVisible());
  38746. ownerComponent->addComponentListener (this);
  38747. componentParentHierarchyChanged (*ownerComponent);
  38748. componentMovedOrResized (*ownerComponent, true, true);
  38749. }
  38750. }
  38751. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38752. {
  38753. if (leftOfOwnerComp)
  38754. {
  38755. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38756. component.getHeight());
  38757. setTopRightPosition (component.getX(), component.getY());
  38758. }
  38759. else
  38760. {
  38761. setSize (component.getWidth(),
  38762. 8 + roundToInt (getFont().getHeight()));
  38763. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38764. }
  38765. }
  38766. void Label::componentParentHierarchyChanged (Component& component)
  38767. {
  38768. if (component.getParentComponent() != 0)
  38769. component.getParentComponent()->addChildComponent (this);
  38770. }
  38771. void Label::componentVisibilityChanged (Component& component)
  38772. {
  38773. setVisible (component.isVisible());
  38774. }
  38775. void Label::textWasEdited()
  38776. {
  38777. }
  38778. void Label::textWasChanged()
  38779. {
  38780. }
  38781. void Label::showEditor()
  38782. {
  38783. if (editor == 0)
  38784. {
  38785. addAndMakeVisible (editor = createEditorComponent());
  38786. editor->setText (getText(), false);
  38787. editor->addListener (this);
  38788. editor->grabKeyboardFocus();
  38789. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38790. editor->addListener (this);
  38791. resized();
  38792. repaint();
  38793. editorShown (editor);
  38794. enterModalState (false);
  38795. editor->grabKeyboardFocus();
  38796. }
  38797. }
  38798. void Label::editorShown (TextEditor* /*editorComponent*/)
  38799. {
  38800. }
  38801. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38802. {
  38803. }
  38804. bool Label::updateFromTextEditorContents()
  38805. {
  38806. jassert (editor != 0);
  38807. const String newText (editor->getText());
  38808. if (textValue.toString() != newText)
  38809. {
  38810. lastTextValue = newText;
  38811. textValue = newText;
  38812. repaint();
  38813. textWasChanged();
  38814. if (ownerComponent != 0)
  38815. componentMovedOrResized (*ownerComponent, true, true);
  38816. return true;
  38817. }
  38818. return false;
  38819. }
  38820. void Label::hideEditor (const bool discardCurrentEditorContents)
  38821. {
  38822. if (editor != 0)
  38823. {
  38824. WeakReference<Component> deletionChecker (this);
  38825. editorAboutToBeHidden (editor);
  38826. const bool changed = (! discardCurrentEditorContents)
  38827. && updateFromTextEditorContents();
  38828. editor = 0;
  38829. repaint();
  38830. if (changed)
  38831. textWasEdited();
  38832. if (deletionChecker != 0)
  38833. exitModalState (0);
  38834. if (changed && deletionChecker != 0)
  38835. callChangeListeners();
  38836. }
  38837. }
  38838. void Label::inputAttemptWhenModal()
  38839. {
  38840. if (editor != 0)
  38841. {
  38842. if (lossOfFocusDiscardsChanges)
  38843. textEditorEscapeKeyPressed (*editor);
  38844. else
  38845. textEditorReturnKeyPressed (*editor);
  38846. }
  38847. }
  38848. bool Label::isBeingEdited() const throw()
  38849. {
  38850. return editor != 0;
  38851. }
  38852. TextEditor* Label::createEditorComponent()
  38853. {
  38854. TextEditor* const ed = new TextEditor (getName());
  38855. ed->setFont (font);
  38856. // copy these colours from our own settings..
  38857. const int cols[] = { TextEditor::backgroundColourId,
  38858. TextEditor::textColourId,
  38859. TextEditor::highlightColourId,
  38860. TextEditor::highlightedTextColourId,
  38861. TextEditor::caretColourId,
  38862. TextEditor::outlineColourId,
  38863. TextEditor::focusedOutlineColourId,
  38864. TextEditor::shadowColourId };
  38865. for (int i = 0; i < numElementsInArray (cols); ++i)
  38866. ed->setColour (cols[i], findColour (cols[i]));
  38867. return ed;
  38868. }
  38869. void Label::paint (Graphics& g)
  38870. {
  38871. getLookAndFeel().drawLabel (g, *this);
  38872. }
  38873. void Label::mouseUp (const MouseEvent& e)
  38874. {
  38875. if (editSingleClick
  38876. && e.mouseWasClicked()
  38877. && contains (e.getPosition())
  38878. && ! e.mods.isPopupMenu())
  38879. {
  38880. showEditor();
  38881. }
  38882. }
  38883. void Label::mouseDoubleClick (const MouseEvent& e)
  38884. {
  38885. if (editDoubleClick && ! e.mods.isPopupMenu())
  38886. showEditor();
  38887. }
  38888. void Label::resized()
  38889. {
  38890. if (editor != 0)
  38891. editor->setBoundsInset (BorderSize (0));
  38892. }
  38893. void Label::focusGained (FocusChangeType cause)
  38894. {
  38895. if (editSingleClick && cause == focusChangedByTabKey)
  38896. showEditor();
  38897. }
  38898. void Label::enablementChanged()
  38899. {
  38900. repaint();
  38901. }
  38902. void Label::colourChanged()
  38903. {
  38904. repaint();
  38905. }
  38906. void Label::setMinimumHorizontalScale (const float newScale)
  38907. {
  38908. if (minimumHorizontalScale != newScale)
  38909. {
  38910. minimumHorizontalScale = newScale;
  38911. repaint();
  38912. }
  38913. }
  38914. // We'll use a custom focus traverser here to make sure focus goes from the
  38915. // text editor to another component rather than back to the label itself.
  38916. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38917. {
  38918. public:
  38919. LabelKeyboardFocusTraverser() {}
  38920. Component* getNextComponent (Component* current)
  38921. {
  38922. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38923. ? current->getParentComponent() : current);
  38924. }
  38925. Component* getPreviousComponent (Component* current)
  38926. {
  38927. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38928. ? current->getParentComponent() : current);
  38929. }
  38930. };
  38931. KeyboardFocusTraverser* Label::createFocusTraverser()
  38932. {
  38933. return new LabelKeyboardFocusTraverser();
  38934. }
  38935. void Label::addListener (LabelListener* const listener)
  38936. {
  38937. listeners.add (listener);
  38938. }
  38939. void Label::removeListener (LabelListener* const listener)
  38940. {
  38941. listeners.remove (listener);
  38942. }
  38943. void Label::callChangeListeners()
  38944. {
  38945. Component::BailOutChecker checker (this);
  38946. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38947. }
  38948. void Label::textEditorTextChanged (TextEditor& ed)
  38949. {
  38950. if (editor != 0)
  38951. {
  38952. jassert (&ed == editor);
  38953. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38954. {
  38955. if (lossOfFocusDiscardsChanges)
  38956. textEditorEscapeKeyPressed (ed);
  38957. else
  38958. textEditorReturnKeyPressed (ed);
  38959. }
  38960. }
  38961. }
  38962. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38963. {
  38964. if (editor != 0)
  38965. {
  38966. jassert (&ed == editor);
  38967. (void) ed;
  38968. const bool changed = updateFromTextEditorContents();
  38969. hideEditor (true);
  38970. if (changed)
  38971. {
  38972. WeakReference<Component> deletionChecker (this);
  38973. textWasEdited();
  38974. if (deletionChecker != 0)
  38975. callChangeListeners();
  38976. }
  38977. }
  38978. }
  38979. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38980. {
  38981. if (editor != 0)
  38982. {
  38983. jassert (&ed == editor);
  38984. (void) ed;
  38985. editor->setText (textValue.toString(), false);
  38986. hideEditor (true);
  38987. }
  38988. }
  38989. void Label::textEditorFocusLost (TextEditor& ed)
  38990. {
  38991. textEditorTextChanged (ed);
  38992. }
  38993. END_JUCE_NAMESPACE
  38994. /*** End of inlined file: juce_Label.cpp ***/
  38995. /*** Start of inlined file: juce_ListBox.cpp ***/
  38996. BEGIN_JUCE_NAMESPACE
  38997. class ListBoxRowComponent : public Component,
  38998. public TooltipClient
  38999. {
  39000. public:
  39001. ListBoxRowComponent (ListBox& owner_)
  39002. : owner (owner_), row (-1),
  39003. selected (false), isDragging (false), selectRowOnMouseUp (false)
  39004. {
  39005. }
  39006. void paint (Graphics& g)
  39007. {
  39008. if (owner.getModel() != 0)
  39009. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39010. }
  39011. void update (const int row_, const bool selected_)
  39012. {
  39013. if (row != row_ || selected != selected_)
  39014. {
  39015. repaint();
  39016. row = row_;
  39017. selected = selected_;
  39018. }
  39019. if (owner.getModel() != 0)
  39020. {
  39021. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  39022. if (customComponent != 0)
  39023. {
  39024. addAndMakeVisible (customComponent);
  39025. customComponent->setBounds (getLocalBounds());
  39026. }
  39027. }
  39028. }
  39029. void mouseDown (const MouseEvent& e)
  39030. {
  39031. isDragging = false;
  39032. selectRowOnMouseUp = false;
  39033. if (isEnabled())
  39034. {
  39035. if (! selected)
  39036. {
  39037. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39038. if (owner.getModel() != 0)
  39039. owner.getModel()->listBoxItemClicked (row, e);
  39040. }
  39041. else
  39042. {
  39043. selectRowOnMouseUp = true;
  39044. }
  39045. }
  39046. }
  39047. void mouseUp (const MouseEvent& e)
  39048. {
  39049. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39050. {
  39051. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39052. if (owner.getModel() != 0)
  39053. owner.getModel()->listBoxItemClicked (row, e);
  39054. }
  39055. }
  39056. void mouseDoubleClick (const MouseEvent& e)
  39057. {
  39058. if (owner.getModel() != 0 && isEnabled())
  39059. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39060. }
  39061. void mouseDrag (const MouseEvent& e)
  39062. {
  39063. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39064. {
  39065. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39066. if (selectedRows.size() > 0)
  39067. {
  39068. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39069. if (dragDescription.isNotEmpty())
  39070. {
  39071. isDragging = true;
  39072. owner.startDragAndDrop (e, dragDescription);
  39073. }
  39074. }
  39075. }
  39076. }
  39077. void resized()
  39078. {
  39079. if (customComponent != 0)
  39080. customComponent->setBounds (getLocalBounds());
  39081. }
  39082. const String getTooltip()
  39083. {
  39084. if (owner.getModel() != 0)
  39085. return owner.getModel()->getTooltipForRow (row);
  39086. return String::empty;
  39087. }
  39088. ScopedPointer<Component> customComponent;
  39089. private:
  39090. ListBox& owner;
  39091. int row;
  39092. bool selected, isDragging, selectRowOnMouseUp;
  39093. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  39094. };
  39095. class ListViewport : public Viewport
  39096. {
  39097. public:
  39098. ListViewport (ListBox& owner_)
  39099. : owner (owner_)
  39100. {
  39101. setWantsKeyboardFocus (false);
  39102. Component* const content = new Component();
  39103. setViewedComponent (content);
  39104. content->addMouseListener (this, false);
  39105. content->setWantsKeyboardFocus (false);
  39106. }
  39107. ~ListViewport()
  39108. {
  39109. }
  39110. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39111. {
  39112. return rows [row % jmax (1, rows.size())];
  39113. }
  39114. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  39115. {
  39116. return (row >= firstIndex && row < firstIndex + rows.size())
  39117. ? getComponentForRow (row) : 0;
  39118. }
  39119. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39120. {
  39121. const int index = getIndexOfChildComponent (rowComponent);
  39122. const int num = rows.size();
  39123. for (int i = num; --i >= 0;)
  39124. if (((firstIndex + i) % jmax (1, num)) == index)
  39125. return firstIndex + i;
  39126. return -1;
  39127. }
  39128. void visibleAreaChanged (int, int, int, int)
  39129. {
  39130. updateVisibleArea (true);
  39131. if (owner.getModel() != 0)
  39132. owner.getModel()->listWasScrolled();
  39133. }
  39134. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39135. {
  39136. hasUpdated = false;
  39137. const int newX = getViewedComponent()->getX();
  39138. int newY = getViewedComponent()->getY();
  39139. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39140. const int newH = owner.totalItems * owner.getRowHeight();
  39141. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39142. newY = getMaximumVisibleHeight() - newH;
  39143. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39144. if (makeSureItUpdatesContent && ! hasUpdated)
  39145. updateContents();
  39146. }
  39147. void updateContents()
  39148. {
  39149. hasUpdated = true;
  39150. const int rowHeight = owner.getRowHeight();
  39151. if (rowHeight > 0)
  39152. {
  39153. const int y = getViewPositionY();
  39154. const int w = getViewedComponent()->getWidth();
  39155. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39156. rows.removeRange (numNeeded, rows.size());
  39157. while (numNeeded > rows.size())
  39158. {
  39159. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39160. rows.add (newRow);
  39161. getViewedComponent()->addAndMakeVisible (newRow);
  39162. }
  39163. firstIndex = y / rowHeight;
  39164. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39165. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39166. for (int i = 0; i < numNeeded; ++i)
  39167. {
  39168. const int row = i + firstIndex;
  39169. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39170. if (rowComp != 0)
  39171. {
  39172. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39173. rowComp->update (row, owner.isRowSelected (row));
  39174. }
  39175. }
  39176. }
  39177. if (owner.headerComponent != 0)
  39178. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39179. owner.outlineThickness,
  39180. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39181. getViewedComponent()->getWidth()),
  39182. owner.headerComponent->getHeight());
  39183. }
  39184. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39185. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39186. {
  39187. hasUpdated = false;
  39188. if (row < firstWholeIndex && ! dontScroll)
  39189. {
  39190. setViewPosition (getViewPositionX(), row * rowHeight);
  39191. }
  39192. else if (row >= lastWholeIndex && ! dontScroll)
  39193. {
  39194. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39195. if (row >= lastRowSelected + rowsOnScreen
  39196. && rowsOnScreen < totalItems - 1
  39197. && ! isMouseClick)
  39198. {
  39199. setViewPosition (getViewPositionX(),
  39200. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39201. }
  39202. else
  39203. {
  39204. setViewPosition (getViewPositionX(),
  39205. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39206. }
  39207. }
  39208. if (! hasUpdated)
  39209. updateContents();
  39210. }
  39211. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39212. {
  39213. if (row < firstWholeIndex)
  39214. {
  39215. setViewPosition (getViewPositionX(), row * rowHeight);
  39216. }
  39217. else if (row >= lastWholeIndex)
  39218. {
  39219. setViewPosition (getViewPositionX(),
  39220. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39221. }
  39222. }
  39223. void paint (Graphics& g)
  39224. {
  39225. if (isOpaque())
  39226. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39227. }
  39228. bool keyPressed (const KeyPress& key)
  39229. {
  39230. if (key.isKeyCode (KeyPress::upKey)
  39231. || key.isKeyCode (KeyPress::downKey)
  39232. || key.isKeyCode (KeyPress::pageUpKey)
  39233. || key.isKeyCode (KeyPress::pageDownKey)
  39234. || key.isKeyCode (KeyPress::homeKey)
  39235. || key.isKeyCode (KeyPress::endKey))
  39236. {
  39237. // we want to avoid these keypresses going to the viewport, and instead allow
  39238. // them to pass up to our listbox..
  39239. return false;
  39240. }
  39241. return Viewport::keyPressed (key);
  39242. }
  39243. private:
  39244. ListBox& owner;
  39245. OwnedArray<ListBoxRowComponent> rows;
  39246. int firstIndex, firstWholeIndex, lastWholeIndex;
  39247. bool hasUpdated;
  39248. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  39249. };
  39250. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39251. : Component (name),
  39252. model (model_),
  39253. totalItems (0),
  39254. rowHeight (22),
  39255. minimumRowWidth (0),
  39256. outlineThickness (0),
  39257. lastRowSelected (-1),
  39258. mouseMoveSelects (false),
  39259. multipleSelection (false),
  39260. hasDoneInitialUpdate (false)
  39261. {
  39262. addAndMakeVisible (viewport = new ListViewport (*this));
  39263. setWantsKeyboardFocus (true);
  39264. colourChanged();
  39265. }
  39266. ListBox::~ListBox()
  39267. {
  39268. headerComponent = 0;
  39269. viewport = 0;
  39270. }
  39271. void ListBox::setModel (ListBoxModel* const newModel)
  39272. {
  39273. if (model != newModel)
  39274. {
  39275. model = newModel;
  39276. repaint();
  39277. updateContent();
  39278. }
  39279. }
  39280. void ListBox::setMultipleSelectionEnabled (bool b)
  39281. {
  39282. multipleSelection = b;
  39283. }
  39284. void ListBox::setMouseMoveSelectsRows (bool b)
  39285. {
  39286. mouseMoveSelects = b;
  39287. if (b)
  39288. addMouseListener (this, true);
  39289. }
  39290. void ListBox::paint (Graphics& g)
  39291. {
  39292. if (! hasDoneInitialUpdate)
  39293. updateContent();
  39294. g.fillAll (findColour (backgroundColourId));
  39295. }
  39296. void ListBox::paintOverChildren (Graphics& g)
  39297. {
  39298. if (outlineThickness > 0)
  39299. {
  39300. g.setColour (findColour (outlineColourId));
  39301. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39302. }
  39303. }
  39304. void ListBox::resized()
  39305. {
  39306. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39307. outlineThickness,
  39308. outlineThickness,
  39309. outlineThickness));
  39310. viewport->setSingleStepSizes (20, getRowHeight());
  39311. viewport->updateVisibleArea (false);
  39312. }
  39313. void ListBox::visibilityChanged()
  39314. {
  39315. viewport->updateVisibleArea (true);
  39316. }
  39317. Viewport* ListBox::getViewport() const throw()
  39318. {
  39319. return viewport;
  39320. }
  39321. void ListBox::updateContent()
  39322. {
  39323. hasDoneInitialUpdate = true;
  39324. totalItems = (model != 0) ? model->getNumRows() : 0;
  39325. bool selectionChanged = false;
  39326. if (selected [selected.size() - 1] >= totalItems)
  39327. {
  39328. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39329. lastRowSelected = getSelectedRow (0);
  39330. selectionChanged = true;
  39331. }
  39332. viewport->updateVisibleArea (isVisible());
  39333. viewport->resized();
  39334. if (selectionChanged && model != 0)
  39335. model->selectedRowsChanged (lastRowSelected);
  39336. }
  39337. void ListBox::selectRow (const int row,
  39338. bool dontScroll,
  39339. bool deselectOthersFirst)
  39340. {
  39341. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39342. }
  39343. void ListBox::selectRowInternal (const int row,
  39344. bool dontScroll,
  39345. bool deselectOthersFirst,
  39346. bool isMouseClick)
  39347. {
  39348. if (! multipleSelection)
  39349. deselectOthersFirst = true;
  39350. if ((! isRowSelected (row))
  39351. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39352. {
  39353. if (isPositiveAndBelow (row, totalItems))
  39354. {
  39355. if (deselectOthersFirst)
  39356. selected.clear();
  39357. selected.addRange (Range<int> (row, row + 1));
  39358. if (getHeight() == 0 || getWidth() == 0)
  39359. dontScroll = true;
  39360. viewport->selectRow (row, getRowHeight(), dontScroll,
  39361. lastRowSelected, totalItems, isMouseClick);
  39362. lastRowSelected = row;
  39363. model->selectedRowsChanged (row);
  39364. }
  39365. else
  39366. {
  39367. if (deselectOthersFirst)
  39368. deselectAllRows();
  39369. }
  39370. }
  39371. }
  39372. void ListBox::deselectRow (const int row)
  39373. {
  39374. if (selected.contains (row))
  39375. {
  39376. selected.removeRange (Range <int> (row, row + 1));
  39377. if (row == lastRowSelected)
  39378. lastRowSelected = getSelectedRow (0);
  39379. viewport->updateContents();
  39380. model->selectedRowsChanged (lastRowSelected);
  39381. }
  39382. }
  39383. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39384. const bool sendNotificationEventToModel)
  39385. {
  39386. selected = setOfRowsToBeSelected;
  39387. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39388. if (! isRowSelected (lastRowSelected))
  39389. lastRowSelected = getSelectedRow (0);
  39390. viewport->updateContents();
  39391. if ((model != 0) && sendNotificationEventToModel)
  39392. model->selectedRowsChanged (lastRowSelected);
  39393. }
  39394. const SparseSet<int> ListBox::getSelectedRows() const
  39395. {
  39396. return selected;
  39397. }
  39398. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39399. {
  39400. if (multipleSelection && (firstRow != lastRow))
  39401. {
  39402. const int numRows = totalItems - 1;
  39403. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39404. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39405. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39406. jmax (firstRow, lastRow) + 1));
  39407. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39408. }
  39409. selectRowInternal (lastRow, false, false, true);
  39410. }
  39411. void ListBox::flipRowSelection (const int row)
  39412. {
  39413. if (isRowSelected (row))
  39414. deselectRow (row);
  39415. else
  39416. selectRowInternal (row, false, false, true);
  39417. }
  39418. void ListBox::deselectAllRows()
  39419. {
  39420. if (! selected.isEmpty())
  39421. {
  39422. selected.clear();
  39423. lastRowSelected = -1;
  39424. viewport->updateContents();
  39425. if (model != 0)
  39426. model->selectedRowsChanged (lastRowSelected);
  39427. }
  39428. }
  39429. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39430. const ModifierKeys& mods)
  39431. {
  39432. if (multipleSelection && mods.isCommandDown())
  39433. {
  39434. flipRowSelection (row);
  39435. }
  39436. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39437. {
  39438. selectRangeOfRows (lastRowSelected, row);
  39439. }
  39440. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39441. {
  39442. selectRowInternal (row, false, ! (multipleSelection && isRowSelected (row)), true);
  39443. }
  39444. }
  39445. int ListBox::getNumSelectedRows() const
  39446. {
  39447. return selected.size();
  39448. }
  39449. int ListBox::getSelectedRow (const int index) const
  39450. {
  39451. return (isPositiveAndBelow (index, selected.size()))
  39452. ? selected [index] : -1;
  39453. }
  39454. bool ListBox::isRowSelected (const int row) const
  39455. {
  39456. return selected.contains (row);
  39457. }
  39458. int ListBox::getLastRowSelected() const
  39459. {
  39460. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39461. }
  39462. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39463. {
  39464. if (isPositiveAndBelow (x, getWidth()))
  39465. {
  39466. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39467. if (isPositiveAndBelow (row, totalItems))
  39468. return row;
  39469. }
  39470. return -1;
  39471. }
  39472. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39473. {
  39474. if (isPositiveAndBelow (x, getWidth()))
  39475. {
  39476. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39477. return jlimit (0, totalItems, row);
  39478. }
  39479. return -1;
  39480. }
  39481. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39482. {
  39483. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39484. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39485. }
  39486. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39487. {
  39488. return viewport->getRowNumberOfComponent (rowComponent);
  39489. }
  39490. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39491. const bool relativeToComponentTopLeft) const throw()
  39492. {
  39493. int y = viewport->getY() + rowHeight * rowNumber;
  39494. if (relativeToComponentTopLeft)
  39495. y -= viewport->getViewPositionY();
  39496. return Rectangle<int> (viewport->getX(), y,
  39497. viewport->getViewedComponent()->getWidth(), rowHeight);
  39498. }
  39499. void ListBox::setVerticalPosition (const double proportion)
  39500. {
  39501. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39502. viewport->setViewPosition (viewport->getViewPositionX(),
  39503. jmax (0, roundToInt (proportion * offscreen)));
  39504. }
  39505. double ListBox::getVerticalPosition() const
  39506. {
  39507. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39508. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39509. : 0;
  39510. }
  39511. int ListBox::getVisibleRowWidth() const throw()
  39512. {
  39513. return viewport->getViewWidth();
  39514. }
  39515. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39516. {
  39517. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39518. }
  39519. bool ListBox::keyPressed (const KeyPress& key)
  39520. {
  39521. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39522. const bool multiple = multipleSelection
  39523. && (lastRowSelected >= 0)
  39524. && (key.getModifiers().isShiftDown()
  39525. || key.getModifiers().isCtrlDown()
  39526. || key.getModifiers().isCommandDown());
  39527. if (key.isKeyCode (KeyPress::upKey))
  39528. {
  39529. if (multiple)
  39530. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39531. else
  39532. selectRow (jmax (0, lastRowSelected - 1));
  39533. }
  39534. else if (key.isKeyCode (KeyPress::returnKey)
  39535. && isRowSelected (lastRowSelected))
  39536. {
  39537. if (model != 0)
  39538. model->returnKeyPressed (lastRowSelected);
  39539. }
  39540. else if (key.isKeyCode (KeyPress::pageUpKey))
  39541. {
  39542. if (multiple)
  39543. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39544. else
  39545. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39546. }
  39547. else if (key.isKeyCode (KeyPress::pageDownKey))
  39548. {
  39549. if (multiple)
  39550. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39551. else
  39552. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39553. }
  39554. else if (key.isKeyCode (KeyPress::homeKey))
  39555. {
  39556. if (multiple && key.getModifiers().isShiftDown())
  39557. selectRangeOfRows (lastRowSelected, 0);
  39558. else
  39559. selectRow (0);
  39560. }
  39561. else if (key.isKeyCode (KeyPress::endKey))
  39562. {
  39563. if (multiple && key.getModifiers().isShiftDown())
  39564. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39565. else
  39566. selectRow (totalItems - 1);
  39567. }
  39568. else if (key.isKeyCode (KeyPress::downKey))
  39569. {
  39570. if (multiple)
  39571. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39572. else
  39573. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39574. }
  39575. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39576. && isRowSelected (lastRowSelected))
  39577. {
  39578. if (model != 0)
  39579. model->deleteKeyPressed (lastRowSelected);
  39580. }
  39581. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39582. {
  39583. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39584. }
  39585. else
  39586. {
  39587. return false;
  39588. }
  39589. return true;
  39590. }
  39591. bool ListBox::keyStateChanged (const bool isKeyDown)
  39592. {
  39593. return isKeyDown
  39594. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39595. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39596. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39597. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39598. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39599. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39600. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39601. }
  39602. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39603. {
  39604. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39605. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39606. }
  39607. void ListBox::mouseMove (const MouseEvent& e)
  39608. {
  39609. if (mouseMoveSelects)
  39610. {
  39611. const MouseEvent e2 (e.getEventRelativeTo (this));
  39612. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39613. }
  39614. }
  39615. void ListBox::mouseExit (const MouseEvent& e)
  39616. {
  39617. mouseMove (e);
  39618. }
  39619. void ListBox::mouseUp (const MouseEvent& e)
  39620. {
  39621. if (e.mouseWasClicked() && model != 0)
  39622. model->backgroundClicked();
  39623. }
  39624. void ListBox::setRowHeight (const int newHeight)
  39625. {
  39626. rowHeight = jmax (1, newHeight);
  39627. viewport->setSingleStepSizes (20, rowHeight);
  39628. updateContent();
  39629. }
  39630. int ListBox::getNumRowsOnScreen() const throw()
  39631. {
  39632. return viewport->getMaximumVisibleHeight() / rowHeight;
  39633. }
  39634. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39635. {
  39636. minimumRowWidth = newMinimumWidth;
  39637. updateContent();
  39638. }
  39639. int ListBox::getVisibleContentWidth() const throw()
  39640. {
  39641. return viewport->getMaximumVisibleWidth();
  39642. }
  39643. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39644. {
  39645. return viewport->getVerticalScrollBar();
  39646. }
  39647. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39648. {
  39649. return viewport->getHorizontalScrollBar();
  39650. }
  39651. void ListBox::colourChanged()
  39652. {
  39653. setOpaque (findColour (backgroundColourId).isOpaque());
  39654. viewport->setOpaque (isOpaque());
  39655. repaint();
  39656. }
  39657. void ListBox::setOutlineThickness (const int outlineThickness_)
  39658. {
  39659. outlineThickness = outlineThickness_;
  39660. resized();
  39661. }
  39662. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39663. {
  39664. if (headerComponent != newHeaderComponent)
  39665. {
  39666. headerComponent = newHeaderComponent;
  39667. addAndMakeVisible (newHeaderComponent);
  39668. ListBox::resized();
  39669. }
  39670. }
  39671. void ListBox::repaintRow (const int rowNumber) throw()
  39672. {
  39673. repaint (getRowPosition (rowNumber, true));
  39674. }
  39675. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39676. {
  39677. Rectangle<int> imageArea;
  39678. const int firstRow = getRowContainingPosition (0, 0);
  39679. int i;
  39680. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39681. {
  39682. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39683. if (rowComp != 0 && isRowSelected (firstRow + i))
  39684. {
  39685. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39686. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39687. imageArea = imageArea.getUnion (rowRect);
  39688. }
  39689. }
  39690. imageArea = imageArea.getIntersection (getLocalBounds());
  39691. imageX = imageArea.getX();
  39692. imageY = imageArea.getY();
  39693. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39694. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39695. {
  39696. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39697. if (rowComp != 0 && isRowSelected (firstRow + i))
  39698. {
  39699. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39700. Graphics g (snapshot);
  39701. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39702. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39703. rowComp->paintEntireComponent (g, false);
  39704. }
  39705. }
  39706. return snapshot;
  39707. }
  39708. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39709. {
  39710. DragAndDropContainer* const dragContainer
  39711. = DragAndDropContainer::findParentDragContainerFor (this);
  39712. if (dragContainer != 0)
  39713. {
  39714. int x, y;
  39715. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39716. dragImage.multiplyAllAlphas (0.6f);
  39717. MouseEvent e2 (e.getEventRelativeTo (this));
  39718. const Point<int> p (x - e2.x, y - e2.y);
  39719. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39720. }
  39721. else
  39722. {
  39723. // to be able to do a drag-and-drop operation, the listbox needs to
  39724. // be inside a component which is also a DragAndDropContainer.
  39725. jassertfalse;
  39726. }
  39727. }
  39728. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39729. {
  39730. (void) existingComponentToUpdate;
  39731. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39732. return 0;
  39733. }
  39734. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39735. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39736. void ListBoxModel::backgroundClicked() {}
  39737. void ListBoxModel::selectedRowsChanged (int) {}
  39738. void ListBoxModel::deleteKeyPressed (int) {}
  39739. void ListBoxModel::returnKeyPressed (int) {}
  39740. void ListBoxModel::listWasScrolled() {}
  39741. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39742. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39743. END_JUCE_NAMESPACE
  39744. /*** End of inlined file: juce_ListBox.cpp ***/
  39745. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39746. BEGIN_JUCE_NAMESPACE
  39747. ProgressBar::ProgressBar (double& progress_)
  39748. : progress (progress_),
  39749. displayPercentage (true),
  39750. lastCallbackTime (0)
  39751. {
  39752. currentValue = jlimit (0.0, 1.0, progress);
  39753. }
  39754. ProgressBar::~ProgressBar()
  39755. {
  39756. }
  39757. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39758. {
  39759. displayPercentage = shouldDisplayPercentage;
  39760. repaint();
  39761. }
  39762. void ProgressBar::setTextToDisplay (const String& text)
  39763. {
  39764. displayPercentage = false;
  39765. displayedMessage = text;
  39766. }
  39767. void ProgressBar::lookAndFeelChanged()
  39768. {
  39769. setOpaque (findColour (backgroundColourId).isOpaque());
  39770. }
  39771. void ProgressBar::colourChanged()
  39772. {
  39773. lookAndFeelChanged();
  39774. }
  39775. void ProgressBar::paint (Graphics& g)
  39776. {
  39777. String text;
  39778. if (displayPercentage)
  39779. {
  39780. if (currentValue >= 0 && currentValue <= 1.0)
  39781. text << roundToInt (currentValue * 100.0) << '%';
  39782. }
  39783. else
  39784. {
  39785. text = displayedMessage;
  39786. }
  39787. getLookAndFeel().drawProgressBar (g, *this,
  39788. getWidth(), getHeight(),
  39789. currentValue, text);
  39790. }
  39791. void ProgressBar::visibilityChanged()
  39792. {
  39793. if (isVisible())
  39794. startTimer (30);
  39795. else
  39796. stopTimer();
  39797. }
  39798. void ProgressBar::timerCallback()
  39799. {
  39800. double newProgress = progress;
  39801. const uint32 now = Time::getMillisecondCounter();
  39802. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39803. lastCallbackTime = now;
  39804. if (currentValue != newProgress
  39805. || newProgress < 0 || newProgress >= 1.0
  39806. || currentMessage != displayedMessage)
  39807. {
  39808. if (currentValue < newProgress
  39809. && newProgress >= 0 && newProgress < 1.0
  39810. && currentValue >= 0 && currentValue < 1.0)
  39811. {
  39812. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39813. newProgress);
  39814. }
  39815. currentValue = newProgress;
  39816. currentMessage = displayedMessage;
  39817. repaint();
  39818. }
  39819. }
  39820. END_JUCE_NAMESPACE
  39821. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39822. /*** Start of inlined file: juce_Slider.cpp ***/
  39823. BEGIN_JUCE_NAMESPACE
  39824. class SliderPopupDisplayComponent : public BubbleComponent
  39825. {
  39826. public:
  39827. SliderPopupDisplayComponent (Slider* const owner_)
  39828. : owner (owner_),
  39829. font (15.0f, Font::bold)
  39830. {
  39831. setAlwaysOnTop (true);
  39832. }
  39833. ~SliderPopupDisplayComponent()
  39834. {
  39835. }
  39836. void paintContent (Graphics& g, int w, int h)
  39837. {
  39838. g.setFont (font);
  39839. g.setColour (Colours::black);
  39840. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39841. }
  39842. void getContentSize (int& w, int& h)
  39843. {
  39844. w = font.getStringWidth (text) + 18;
  39845. h = (int) (font.getHeight() * 1.6f);
  39846. }
  39847. void updatePosition (const String& newText)
  39848. {
  39849. if (text != newText)
  39850. {
  39851. text = newText;
  39852. repaint();
  39853. }
  39854. BubbleComponent::setPosition (owner);
  39855. }
  39856. private:
  39857. Slider* owner;
  39858. Font font;
  39859. String text;
  39860. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39861. };
  39862. Slider::Slider (const String& name)
  39863. : Component (name),
  39864. lastCurrentValue (0),
  39865. lastValueMin (0),
  39866. lastValueMax (0),
  39867. minimum (0),
  39868. maximum (10),
  39869. interval (0),
  39870. skewFactor (1.0),
  39871. velocityModeSensitivity (1.0),
  39872. velocityModeOffset (0.0),
  39873. velocityModeThreshold (1),
  39874. rotaryStart (float_Pi * 1.2f),
  39875. rotaryEnd (float_Pi * 2.8f),
  39876. numDecimalPlaces (7),
  39877. sliderRegionStart (0),
  39878. sliderRegionSize (1),
  39879. sliderBeingDragged (-1),
  39880. pixelsForFullDragExtent (250),
  39881. style (LinearHorizontal),
  39882. textBoxPos (TextBoxLeft),
  39883. textBoxWidth (80),
  39884. textBoxHeight (20),
  39885. incDecButtonMode (incDecButtonsNotDraggable),
  39886. editableText (true),
  39887. doubleClickToValue (false),
  39888. isVelocityBased (false),
  39889. userKeyOverridesVelocity (true),
  39890. rotaryStop (true),
  39891. incDecButtonsSideBySide (false),
  39892. sendChangeOnlyOnRelease (false),
  39893. popupDisplayEnabled (false),
  39894. menuEnabled (false),
  39895. menuShown (false),
  39896. scrollWheelEnabled (true),
  39897. snapsToMousePos (true),
  39898. popupDisplay (0),
  39899. parentForPopupDisplay (0)
  39900. {
  39901. setWantsKeyboardFocus (false);
  39902. setRepaintsOnMouseActivity (true);
  39903. lookAndFeelChanged();
  39904. updateText();
  39905. currentValue.addListener (this);
  39906. valueMin.addListener (this);
  39907. valueMax.addListener (this);
  39908. }
  39909. Slider::~Slider()
  39910. {
  39911. currentValue.removeListener (this);
  39912. valueMin.removeListener (this);
  39913. valueMax.removeListener (this);
  39914. popupDisplay = 0;
  39915. }
  39916. void Slider::handleAsyncUpdate()
  39917. {
  39918. cancelPendingUpdate();
  39919. Component::BailOutChecker checker (this);
  39920. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39921. }
  39922. void Slider::sendDragStart()
  39923. {
  39924. startedDragging();
  39925. Component::BailOutChecker checker (this);
  39926. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39927. }
  39928. void Slider::sendDragEnd()
  39929. {
  39930. stoppedDragging();
  39931. sliderBeingDragged = -1;
  39932. Component::BailOutChecker checker (this);
  39933. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39934. }
  39935. void Slider::addListener (SliderListener* const listener)
  39936. {
  39937. listeners.add (listener);
  39938. }
  39939. void Slider::removeListener (SliderListener* const listener)
  39940. {
  39941. listeners.remove (listener);
  39942. }
  39943. void Slider::setSliderStyle (const SliderStyle newStyle)
  39944. {
  39945. if (style != newStyle)
  39946. {
  39947. style = newStyle;
  39948. repaint();
  39949. lookAndFeelChanged();
  39950. }
  39951. }
  39952. void Slider::setRotaryParameters (const float startAngleRadians,
  39953. const float endAngleRadians,
  39954. const bool stopAtEnd)
  39955. {
  39956. // make sure the values are sensible..
  39957. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39958. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39959. jassert (rotaryStart < rotaryEnd);
  39960. rotaryStart = startAngleRadians;
  39961. rotaryEnd = endAngleRadians;
  39962. rotaryStop = stopAtEnd;
  39963. }
  39964. void Slider::setVelocityBasedMode (const bool velBased)
  39965. {
  39966. isVelocityBased = velBased;
  39967. }
  39968. void Slider::setVelocityModeParameters (const double sensitivity,
  39969. const int threshold,
  39970. const double offset,
  39971. const bool userCanPressKeyToSwapMode)
  39972. {
  39973. jassert (threshold >= 0);
  39974. jassert (sensitivity > 0);
  39975. jassert (offset >= 0);
  39976. velocityModeSensitivity = sensitivity;
  39977. velocityModeOffset = offset;
  39978. velocityModeThreshold = threshold;
  39979. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39980. }
  39981. void Slider::setSkewFactor (const double factor)
  39982. {
  39983. skewFactor = factor;
  39984. }
  39985. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39986. {
  39987. if (maximum > minimum)
  39988. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39989. / (maximum - minimum));
  39990. }
  39991. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39992. {
  39993. jassert (distanceForFullScaleDrag > 0);
  39994. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39995. }
  39996. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39997. {
  39998. if (incDecButtonMode != mode)
  39999. {
  40000. incDecButtonMode = mode;
  40001. lookAndFeelChanged();
  40002. }
  40003. }
  40004. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40005. const bool isReadOnly,
  40006. const int textEntryBoxWidth,
  40007. const int textEntryBoxHeight)
  40008. {
  40009. if (textBoxPos != newPosition
  40010. || editableText != (! isReadOnly)
  40011. || textBoxWidth != textEntryBoxWidth
  40012. || textBoxHeight != textEntryBoxHeight)
  40013. {
  40014. textBoxPos = newPosition;
  40015. editableText = ! isReadOnly;
  40016. textBoxWidth = textEntryBoxWidth;
  40017. textBoxHeight = textEntryBoxHeight;
  40018. repaint();
  40019. lookAndFeelChanged();
  40020. }
  40021. }
  40022. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40023. {
  40024. editableText = shouldBeEditable;
  40025. if (valueBox != 0)
  40026. valueBox->setEditable (shouldBeEditable && isEnabled());
  40027. }
  40028. void Slider::showTextBox()
  40029. {
  40030. jassert (editableText); // this should probably be avoided in read-only sliders.
  40031. if (valueBox != 0)
  40032. valueBox->showEditor();
  40033. }
  40034. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40035. {
  40036. if (valueBox != 0)
  40037. {
  40038. valueBox->hideEditor (discardCurrentEditorContents);
  40039. if (discardCurrentEditorContents)
  40040. updateText();
  40041. }
  40042. }
  40043. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40044. {
  40045. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40046. }
  40047. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40048. {
  40049. snapsToMousePos = shouldSnapToMouse;
  40050. }
  40051. void Slider::setPopupDisplayEnabled (const bool enabled,
  40052. Component* const parentComponentToUse)
  40053. {
  40054. popupDisplayEnabled = enabled;
  40055. parentForPopupDisplay = parentComponentToUse;
  40056. }
  40057. void Slider::colourChanged()
  40058. {
  40059. lookAndFeelChanged();
  40060. }
  40061. void Slider::lookAndFeelChanged()
  40062. {
  40063. LookAndFeel& lf = getLookAndFeel();
  40064. if (textBoxPos != NoTextBox)
  40065. {
  40066. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40067. : getTextFromValue (currentValue.getValue()));
  40068. valueBox = 0;
  40069. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40070. valueBox->setWantsKeyboardFocus (false);
  40071. valueBox->setText (previousTextBoxContent, false);
  40072. valueBox->setEditable (editableText && isEnabled());
  40073. valueBox->addListener (this);
  40074. if (style == LinearBar)
  40075. valueBox->addMouseListener (this, false);
  40076. valueBox->setTooltip (getTooltip());
  40077. }
  40078. else
  40079. {
  40080. valueBox = 0;
  40081. }
  40082. if (style == IncDecButtons)
  40083. {
  40084. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40085. incButton->addListener (this);
  40086. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40087. decButton->addListener (this);
  40088. if (incDecButtonMode != incDecButtonsNotDraggable)
  40089. {
  40090. incButton->addMouseListener (this, false);
  40091. decButton->addMouseListener (this, false);
  40092. }
  40093. else
  40094. {
  40095. incButton->setRepeatSpeed (300, 100, 20);
  40096. incButton->addMouseListener (decButton, false);
  40097. decButton->setRepeatSpeed (300, 100, 20);
  40098. decButton->addMouseListener (incButton, false);
  40099. }
  40100. incButton->setTooltip (getTooltip());
  40101. decButton->setTooltip (getTooltip());
  40102. }
  40103. else
  40104. {
  40105. incButton = 0;
  40106. decButton = 0;
  40107. }
  40108. setComponentEffect (lf.getSliderEffect());
  40109. resized();
  40110. repaint();
  40111. }
  40112. void Slider::setRange (const double newMin,
  40113. const double newMax,
  40114. const double newInt)
  40115. {
  40116. if (minimum != newMin
  40117. || maximum != newMax
  40118. || interval != newInt)
  40119. {
  40120. minimum = newMin;
  40121. maximum = newMax;
  40122. interval = newInt;
  40123. // figure out the number of DPs needed to display all values at this
  40124. // interval setting.
  40125. numDecimalPlaces = 7;
  40126. if (newInt != 0)
  40127. {
  40128. int v = abs ((int) (newInt * 10000000));
  40129. while ((v % 10) == 0)
  40130. {
  40131. --numDecimalPlaces;
  40132. v /= 10;
  40133. }
  40134. }
  40135. // keep the current values inside the new range..
  40136. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40137. {
  40138. setValue (getValue(), false, false);
  40139. }
  40140. else
  40141. {
  40142. setMinValue (getMinValue(), false, false);
  40143. setMaxValue (getMaxValue(), false, false);
  40144. }
  40145. updateText();
  40146. }
  40147. }
  40148. void Slider::triggerChangeMessage (const bool synchronous)
  40149. {
  40150. if (synchronous)
  40151. handleAsyncUpdate();
  40152. else
  40153. triggerAsyncUpdate();
  40154. valueChanged();
  40155. }
  40156. void Slider::valueChanged (Value& value)
  40157. {
  40158. if (value.refersToSameSourceAs (currentValue))
  40159. {
  40160. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40161. setValue (currentValue.getValue(), false, false);
  40162. }
  40163. else if (value.refersToSameSourceAs (valueMin))
  40164. setMinValue (valueMin.getValue(), false, false, true);
  40165. else if (value.refersToSameSourceAs (valueMax))
  40166. setMaxValue (valueMax.getValue(), false, false, true);
  40167. }
  40168. double Slider::getValue() const
  40169. {
  40170. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40171. // methods to get the two values.
  40172. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40173. return currentValue.getValue();
  40174. }
  40175. void Slider::setValue (double newValue,
  40176. const bool sendUpdateMessage,
  40177. const bool sendMessageSynchronously)
  40178. {
  40179. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40180. // methods to set the two values.
  40181. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40182. newValue = constrainedValue (newValue);
  40183. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40184. {
  40185. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40186. newValue = jlimit ((double) valueMin.getValue(),
  40187. (double) valueMax.getValue(),
  40188. newValue);
  40189. }
  40190. if (newValue != lastCurrentValue)
  40191. {
  40192. if (valueBox != 0)
  40193. valueBox->hideEditor (true);
  40194. lastCurrentValue = newValue;
  40195. currentValue = newValue;
  40196. updateText();
  40197. repaint();
  40198. if (popupDisplay != 0)
  40199. {
  40200. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40201. ->updatePosition (getTextFromValue (newValue));
  40202. popupDisplay->repaint();
  40203. }
  40204. if (sendUpdateMessage)
  40205. triggerChangeMessage (sendMessageSynchronously);
  40206. }
  40207. }
  40208. double Slider::getMinValue() const
  40209. {
  40210. // The minimum value only applies to sliders that are in two- or three-value mode.
  40211. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40212. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40213. return valueMin.getValue();
  40214. }
  40215. double Slider::getMaxValue() const
  40216. {
  40217. // The maximum value only applies to sliders that are in two- or three-value mode.
  40218. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40219. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40220. return valueMax.getValue();
  40221. }
  40222. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40223. {
  40224. // The minimum value only applies to sliders that are in two- or three-value mode.
  40225. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40226. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40227. newValue = constrainedValue (newValue);
  40228. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40229. {
  40230. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40231. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40232. newValue = jmin ((double) valueMax.getValue(), newValue);
  40233. }
  40234. else
  40235. {
  40236. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40237. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40238. newValue = jmin (lastCurrentValue, newValue);
  40239. }
  40240. if (lastValueMin != newValue)
  40241. {
  40242. lastValueMin = newValue;
  40243. valueMin = newValue;
  40244. repaint();
  40245. if (popupDisplay != 0)
  40246. {
  40247. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40248. ->updatePosition (getTextFromValue (newValue));
  40249. popupDisplay->repaint();
  40250. }
  40251. if (sendUpdateMessage)
  40252. triggerChangeMessage (sendMessageSynchronously);
  40253. }
  40254. }
  40255. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40256. {
  40257. // The maximum value only applies to sliders that are in two- or three-value mode.
  40258. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40259. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40260. newValue = constrainedValue (newValue);
  40261. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40262. {
  40263. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40264. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40265. newValue = jmax ((double) valueMin.getValue(), newValue);
  40266. }
  40267. else
  40268. {
  40269. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40270. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40271. newValue = jmax (lastCurrentValue, newValue);
  40272. }
  40273. if (lastValueMax != newValue)
  40274. {
  40275. lastValueMax = newValue;
  40276. valueMax = newValue;
  40277. repaint();
  40278. if (popupDisplay != 0)
  40279. {
  40280. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40281. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40282. popupDisplay->repaint();
  40283. }
  40284. if (sendUpdateMessage)
  40285. triggerChangeMessage (sendMessageSynchronously);
  40286. }
  40287. }
  40288. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40289. const double valueToSetOnDoubleClick)
  40290. {
  40291. doubleClickToValue = isDoubleClickEnabled;
  40292. doubleClickReturnValue = valueToSetOnDoubleClick;
  40293. }
  40294. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40295. {
  40296. isEnabled_ = doubleClickToValue;
  40297. return doubleClickReturnValue;
  40298. }
  40299. void Slider::updateText()
  40300. {
  40301. if (valueBox != 0)
  40302. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40303. }
  40304. void Slider::setTextValueSuffix (const String& suffix)
  40305. {
  40306. if (textSuffix != suffix)
  40307. {
  40308. textSuffix = suffix;
  40309. updateText();
  40310. }
  40311. }
  40312. const String Slider::getTextValueSuffix() const
  40313. {
  40314. return textSuffix;
  40315. }
  40316. const String Slider::getTextFromValue (double v)
  40317. {
  40318. if (getNumDecimalPlacesToDisplay() > 0)
  40319. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40320. else
  40321. return String (roundToInt (v)) + getTextValueSuffix();
  40322. }
  40323. double Slider::getValueFromText (const String& text)
  40324. {
  40325. String t (text.trimStart());
  40326. if (t.endsWith (textSuffix))
  40327. t = t.substring (0, t.length() - textSuffix.length());
  40328. while (t.startsWithChar ('+'))
  40329. t = t.substring (1).trimStart();
  40330. return t.initialSectionContainingOnly ("0123456789.,-")
  40331. .getDoubleValue();
  40332. }
  40333. double Slider::proportionOfLengthToValue (double proportion)
  40334. {
  40335. if (skewFactor != 1.0 && proportion > 0.0)
  40336. proportion = exp (log (proportion) / skewFactor);
  40337. return minimum + (maximum - minimum) * proportion;
  40338. }
  40339. double Slider::valueToProportionOfLength (double value)
  40340. {
  40341. const double n = (value - minimum) / (maximum - minimum);
  40342. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40343. }
  40344. double Slider::snapValue (double attemptedValue, const bool)
  40345. {
  40346. return attemptedValue;
  40347. }
  40348. void Slider::startedDragging()
  40349. {
  40350. }
  40351. void Slider::stoppedDragging()
  40352. {
  40353. }
  40354. void Slider::valueChanged()
  40355. {
  40356. }
  40357. void Slider::enablementChanged()
  40358. {
  40359. repaint();
  40360. }
  40361. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40362. {
  40363. menuEnabled = menuEnabled_;
  40364. }
  40365. void Slider::setScrollWheelEnabled (const bool enabled)
  40366. {
  40367. scrollWheelEnabled = enabled;
  40368. }
  40369. void Slider::labelTextChanged (Label* label)
  40370. {
  40371. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40372. if (newValue != (double) currentValue.getValue())
  40373. {
  40374. sendDragStart();
  40375. setValue (newValue, true, true);
  40376. sendDragEnd();
  40377. }
  40378. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40379. }
  40380. void Slider::buttonClicked (Button* button)
  40381. {
  40382. if (style == IncDecButtons)
  40383. {
  40384. sendDragStart();
  40385. if (button == incButton)
  40386. setValue (snapValue (getValue() + interval, false), true, true);
  40387. else if (button == decButton)
  40388. setValue (snapValue (getValue() - interval, false), true, true);
  40389. sendDragEnd();
  40390. }
  40391. }
  40392. double Slider::constrainedValue (double value) const
  40393. {
  40394. if (interval > 0)
  40395. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40396. if (value <= minimum || maximum <= minimum)
  40397. value = minimum;
  40398. else if (value >= maximum)
  40399. value = maximum;
  40400. return value;
  40401. }
  40402. float Slider::getLinearSliderPos (const double value)
  40403. {
  40404. double sliderPosProportional;
  40405. if (maximum > minimum)
  40406. {
  40407. if (value < minimum)
  40408. {
  40409. sliderPosProportional = 0.0;
  40410. }
  40411. else if (value > maximum)
  40412. {
  40413. sliderPosProportional = 1.0;
  40414. }
  40415. else
  40416. {
  40417. sliderPosProportional = valueToProportionOfLength (value);
  40418. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40419. }
  40420. }
  40421. else
  40422. {
  40423. sliderPosProportional = 0.5;
  40424. }
  40425. if (isVertical() || style == IncDecButtons)
  40426. sliderPosProportional = 1.0 - sliderPosProportional;
  40427. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40428. }
  40429. bool Slider::isHorizontal() const
  40430. {
  40431. return style == LinearHorizontal
  40432. || style == LinearBar
  40433. || style == TwoValueHorizontal
  40434. || style == ThreeValueHorizontal;
  40435. }
  40436. bool Slider::isVertical() const
  40437. {
  40438. return style == LinearVertical
  40439. || style == TwoValueVertical
  40440. || style == ThreeValueVertical;
  40441. }
  40442. bool Slider::incDecDragDirectionIsHorizontal() const
  40443. {
  40444. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40445. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40446. }
  40447. float Slider::getPositionOfValue (const double value)
  40448. {
  40449. if (isHorizontal() || isVertical())
  40450. {
  40451. return getLinearSliderPos (value);
  40452. }
  40453. else
  40454. {
  40455. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40456. return 0.0f;
  40457. }
  40458. }
  40459. void Slider::paint (Graphics& g)
  40460. {
  40461. if (style != IncDecButtons)
  40462. {
  40463. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40464. {
  40465. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40466. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40467. getLookAndFeel().drawRotarySlider (g,
  40468. sliderRect.getX(),
  40469. sliderRect.getY(),
  40470. sliderRect.getWidth(),
  40471. sliderRect.getHeight(),
  40472. sliderPos,
  40473. rotaryStart, rotaryEnd,
  40474. *this);
  40475. }
  40476. else
  40477. {
  40478. getLookAndFeel().drawLinearSlider (g,
  40479. sliderRect.getX(),
  40480. sliderRect.getY(),
  40481. sliderRect.getWidth(),
  40482. sliderRect.getHeight(),
  40483. getLinearSliderPos (lastCurrentValue),
  40484. getLinearSliderPos (lastValueMin),
  40485. getLinearSliderPos (lastValueMax),
  40486. style,
  40487. *this);
  40488. }
  40489. if (style == LinearBar && valueBox == 0)
  40490. {
  40491. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40492. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40493. }
  40494. }
  40495. }
  40496. void Slider::resized()
  40497. {
  40498. int minXSpace = 0;
  40499. int minYSpace = 0;
  40500. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40501. minXSpace = 30;
  40502. else
  40503. minYSpace = 15;
  40504. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40505. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40506. if (style == LinearBar)
  40507. {
  40508. if (valueBox != 0)
  40509. valueBox->setBounds (getLocalBounds());
  40510. }
  40511. else
  40512. {
  40513. if (textBoxPos == NoTextBox)
  40514. {
  40515. sliderRect = getLocalBounds();
  40516. }
  40517. else if (textBoxPos == TextBoxLeft)
  40518. {
  40519. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40520. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40521. }
  40522. else if (textBoxPos == TextBoxRight)
  40523. {
  40524. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40525. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40526. }
  40527. else if (textBoxPos == TextBoxAbove)
  40528. {
  40529. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40530. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40531. }
  40532. else if (textBoxPos == TextBoxBelow)
  40533. {
  40534. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40535. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40536. }
  40537. }
  40538. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40539. if (style == LinearBar)
  40540. {
  40541. const int barIndent = 1;
  40542. sliderRegionStart = barIndent;
  40543. sliderRegionSize = getWidth() - barIndent * 2;
  40544. sliderRect.setBounds (sliderRegionStart, barIndent,
  40545. sliderRegionSize, getHeight() - barIndent * 2);
  40546. }
  40547. else if (isHorizontal())
  40548. {
  40549. sliderRegionStart = sliderRect.getX() + indent;
  40550. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40551. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40552. sliderRegionSize, sliderRect.getHeight());
  40553. }
  40554. else if (isVertical())
  40555. {
  40556. sliderRegionStart = sliderRect.getY() + indent;
  40557. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40558. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40559. sliderRect.getWidth(), sliderRegionSize);
  40560. }
  40561. else
  40562. {
  40563. sliderRegionStart = 0;
  40564. sliderRegionSize = 100;
  40565. }
  40566. if (style == IncDecButtons)
  40567. {
  40568. Rectangle<int> buttonRect (sliderRect);
  40569. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40570. buttonRect.expand (-2, 0);
  40571. else
  40572. buttonRect.expand (0, -2);
  40573. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40574. if (incDecButtonsSideBySide)
  40575. {
  40576. decButton->setBounds (buttonRect.getX(),
  40577. buttonRect.getY(),
  40578. buttonRect.getWidth() / 2,
  40579. buttonRect.getHeight());
  40580. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40581. incButton->setBounds (buttonRect.getCentreX(),
  40582. buttonRect.getY(),
  40583. buttonRect.getWidth() / 2,
  40584. buttonRect.getHeight());
  40585. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40586. }
  40587. else
  40588. {
  40589. incButton->setBounds (buttonRect.getX(),
  40590. buttonRect.getY(),
  40591. buttonRect.getWidth(),
  40592. buttonRect.getHeight() / 2);
  40593. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40594. decButton->setBounds (buttonRect.getX(),
  40595. buttonRect.getCentreY(),
  40596. buttonRect.getWidth(),
  40597. buttonRect.getHeight() / 2);
  40598. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40599. }
  40600. }
  40601. }
  40602. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40603. {
  40604. repaint();
  40605. }
  40606. void Slider::mouseDown (const MouseEvent& e)
  40607. {
  40608. mouseWasHidden = false;
  40609. incDecDragged = false;
  40610. mouseXWhenLastDragged = e.x;
  40611. mouseYWhenLastDragged = e.y;
  40612. mouseDragStartX = e.getMouseDownX();
  40613. mouseDragStartY = e.getMouseDownY();
  40614. if (isEnabled())
  40615. {
  40616. if (e.mods.isPopupMenu() && menuEnabled)
  40617. {
  40618. menuShown = true;
  40619. PopupMenu m;
  40620. m.setLookAndFeel (&getLookAndFeel());
  40621. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40622. m.addSeparator();
  40623. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40624. {
  40625. PopupMenu rotaryMenu;
  40626. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40627. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40628. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40629. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40630. }
  40631. const int r = m.show();
  40632. if (r == 1)
  40633. {
  40634. setVelocityBasedMode (! isVelocityBased);
  40635. }
  40636. else if (r == 2)
  40637. {
  40638. setSliderStyle (Rotary);
  40639. }
  40640. else if (r == 3)
  40641. {
  40642. setSliderStyle (RotaryHorizontalDrag);
  40643. }
  40644. else if (r == 4)
  40645. {
  40646. setSliderStyle (RotaryVerticalDrag);
  40647. }
  40648. }
  40649. else if (maximum > minimum)
  40650. {
  40651. menuShown = false;
  40652. if (valueBox != 0)
  40653. valueBox->hideEditor (true);
  40654. sliderBeingDragged = 0;
  40655. if (style == TwoValueHorizontal
  40656. || style == TwoValueVertical
  40657. || style == ThreeValueHorizontal
  40658. || style == ThreeValueVertical)
  40659. {
  40660. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40661. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40662. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40663. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40664. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40665. {
  40666. if (maxPosDistance <= minPosDistance)
  40667. sliderBeingDragged = 2;
  40668. else
  40669. sliderBeingDragged = 1;
  40670. }
  40671. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40672. {
  40673. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40674. sliderBeingDragged = 1;
  40675. else if (normalPosDistance >= maxPosDistance)
  40676. sliderBeingDragged = 2;
  40677. }
  40678. }
  40679. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40680. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40681. * valueToProportionOfLength (currentValue.getValue());
  40682. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40683. : ((sliderBeingDragged == 1) ? valueMin
  40684. : currentValue)).getValue();
  40685. valueOnMouseDown = valueWhenLastDragged;
  40686. if (popupDisplayEnabled)
  40687. {
  40688. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40689. popupDisplay = popup;
  40690. if (parentForPopupDisplay != 0)
  40691. {
  40692. parentForPopupDisplay->addChildComponent (popup);
  40693. }
  40694. else
  40695. {
  40696. popup->addToDesktop (0);
  40697. }
  40698. popup->setVisible (true);
  40699. }
  40700. sendDragStart();
  40701. mouseDrag (e);
  40702. }
  40703. }
  40704. }
  40705. void Slider::mouseUp (const MouseEvent&)
  40706. {
  40707. if (isEnabled()
  40708. && (! menuShown)
  40709. && (maximum > minimum)
  40710. && (style != IncDecButtons || incDecDragged))
  40711. {
  40712. restoreMouseIfHidden();
  40713. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40714. triggerChangeMessage (false);
  40715. sendDragEnd();
  40716. popupDisplay = 0;
  40717. if (style == IncDecButtons)
  40718. {
  40719. incButton->setState (Button::buttonNormal);
  40720. decButton->setState (Button::buttonNormal);
  40721. }
  40722. }
  40723. }
  40724. void Slider::restoreMouseIfHidden()
  40725. {
  40726. if (mouseWasHidden)
  40727. {
  40728. mouseWasHidden = false;
  40729. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40730. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40731. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40732. : ((sliderBeingDragged == 1) ? getMinValue()
  40733. : (double) currentValue.getValue());
  40734. Point<int> mousePos;
  40735. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40736. {
  40737. mousePos = Desktop::getLastMouseDownPosition();
  40738. if (style == RotaryHorizontalDrag)
  40739. {
  40740. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40741. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40742. }
  40743. else
  40744. {
  40745. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40746. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40747. }
  40748. }
  40749. else
  40750. {
  40751. const int pixelPos = (int) getLinearSliderPos (pos);
  40752. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40753. isVertical() ? pixelPos : (getHeight() / 2)));
  40754. }
  40755. Desktop::setMousePosition (mousePos);
  40756. }
  40757. }
  40758. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40759. {
  40760. if (isEnabled()
  40761. && style != IncDecButtons
  40762. && style != Rotary
  40763. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40764. {
  40765. restoreMouseIfHidden();
  40766. }
  40767. }
  40768. namespace SliderHelpers
  40769. {
  40770. double smallestAngleBetween (double a1, double a2) throw()
  40771. {
  40772. return jmin (std::abs (a1 - a2),
  40773. std::abs (a1 + double_Pi * 2.0 - a2),
  40774. std::abs (a2 + double_Pi * 2.0 - a1));
  40775. }
  40776. }
  40777. void Slider::mouseDrag (const MouseEvent& e)
  40778. {
  40779. if (isEnabled()
  40780. && (! menuShown)
  40781. && (maximum > minimum))
  40782. {
  40783. if (style == Rotary)
  40784. {
  40785. int dx = e.x - sliderRect.getCentreX();
  40786. int dy = e.y - sliderRect.getCentreY();
  40787. if (dx * dx + dy * dy > 25)
  40788. {
  40789. double angle = std::atan2 ((double) dx, (double) -dy);
  40790. while (angle < 0.0)
  40791. angle += double_Pi * 2.0;
  40792. if (rotaryStop && ! e.mouseWasClicked())
  40793. {
  40794. if (std::abs (angle - lastAngle) > double_Pi)
  40795. {
  40796. if (angle >= lastAngle)
  40797. angle -= double_Pi * 2.0;
  40798. else
  40799. angle += double_Pi * 2.0;
  40800. }
  40801. if (angle >= lastAngle)
  40802. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40803. else
  40804. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40805. }
  40806. else
  40807. {
  40808. while (angle < rotaryStart)
  40809. angle += double_Pi * 2.0;
  40810. if (angle > rotaryEnd)
  40811. {
  40812. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40813. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40814. angle = rotaryStart;
  40815. else
  40816. angle = rotaryEnd;
  40817. }
  40818. }
  40819. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40820. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40821. lastAngle = angle;
  40822. }
  40823. }
  40824. else
  40825. {
  40826. if (style == LinearBar && e.mouseWasClicked()
  40827. && valueBox != 0 && valueBox->isEditable())
  40828. return;
  40829. if (style == IncDecButtons && ! incDecDragged)
  40830. {
  40831. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40832. return;
  40833. incDecDragged = true;
  40834. mouseDragStartX = e.x;
  40835. mouseDragStartY = e.y;
  40836. }
  40837. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40838. : false))
  40839. || ((maximum - minimum) / sliderRegionSize < interval))
  40840. {
  40841. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40842. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40843. if (style == RotaryHorizontalDrag
  40844. || style == RotaryVerticalDrag
  40845. || style == IncDecButtons
  40846. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40847. && ! snapsToMousePos))
  40848. {
  40849. const int mouseDiff = (style == RotaryHorizontalDrag
  40850. || style == LinearHorizontal
  40851. || style == LinearBar
  40852. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40853. ? e.x - mouseDragStartX
  40854. : mouseDragStartY - e.y;
  40855. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40856. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40857. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40858. if (style == IncDecButtons)
  40859. {
  40860. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40861. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40862. }
  40863. }
  40864. else
  40865. {
  40866. if (isVertical())
  40867. scaledMousePos = 1.0 - scaledMousePos;
  40868. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40869. }
  40870. }
  40871. else
  40872. {
  40873. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40874. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40875. ? e.x - mouseXWhenLastDragged
  40876. : e.y - mouseYWhenLastDragged;
  40877. const double maxSpeed = jmax (200, sliderRegionSize);
  40878. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40879. if (speed != 0)
  40880. {
  40881. speed = 0.2 * velocityModeSensitivity
  40882. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40883. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40884. / maxSpeed))));
  40885. if (mouseDiff < 0)
  40886. speed = -speed;
  40887. if (isVertical() || style == RotaryVerticalDrag
  40888. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40889. speed = -speed;
  40890. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40891. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40892. e.source.enableUnboundedMouseMovement (true, false);
  40893. mouseWasHidden = true;
  40894. }
  40895. }
  40896. }
  40897. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40898. if (sliderBeingDragged == 0)
  40899. {
  40900. setValue (snapValue (valueWhenLastDragged, true),
  40901. ! sendChangeOnlyOnRelease, true);
  40902. }
  40903. else if (sliderBeingDragged == 1)
  40904. {
  40905. setMinValue (snapValue (valueWhenLastDragged, true),
  40906. ! sendChangeOnlyOnRelease, false, true);
  40907. if (e.mods.isShiftDown())
  40908. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40909. else
  40910. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40911. }
  40912. else
  40913. {
  40914. jassert (sliderBeingDragged == 2);
  40915. setMaxValue (snapValue (valueWhenLastDragged, true),
  40916. ! sendChangeOnlyOnRelease, false, true);
  40917. if (e.mods.isShiftDown())
  40918. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40919. else
  40920. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40921. }
  40922. mouseXWhenLastDragged = e.x;
  40923. mouseYWhenLastDragged = e.y;
  40924. }
  40925. }
  40926. void Slider::mouseDoubleClick (const MouseEvent&)
  40927. {
  40928. if (doubleClickToValue
  40929. && isEnabled()
  40930. && style != IncDecButtons
  40931. && minimum <= doubleClickReturnValue
  40932. && maximum >= doubleClickReturnValue)
  40933. {
  40934. sendDragStart();
  40935. setValue (doubleClickReturnValue, true, true);
  40936. sendDragEnd();
  40937. }
  40938. }
  40939. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40940. {
  40941. if (scrollWheelEnabled && isEnabled()
  40942. && style != TwoValueHorizontal
  40943. && style != TwoValueVertical)
  40944. {
  40945. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40946. {
  40947. if (valueBox != 0)
  40948. valueBox->hideEditor (false);
  40949. const double value = (double) currentValue.getValue();
  40950. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40951. const double currentPos = valueToProportionOfLength (value);
  40952. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40953. double delta = (newValue != value)
  40954. ? jmax (std::abs (newValue - value), interval) : 0;
  40955. if (value > newValue)
  40956. delta = -delta;
  40957. sendDragStart();
  40958. setValue (snapValue (value + delta, false), true, true);
  40959. sendDragEnd();
  40960. }
  40961. }
  40962. else
  40963. {
  40964. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40965. }
  40966. }
  40967. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40968. {
  40969. }
  40970. void SliderListener::sliderDragEnded (Slider*)
  40971. {
  40972. }
  40973. END_JUCE_NAMESPACE
  40974. /*** End of inlined file: juce_Slider.cpp ***/
  40975. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40976. BEGIN_JUCE_NAMESPACE
  40977. class DragOverlayComp : public Component
  40978. {
  40979. public:
  40980. DragOverlayComp (const Image& image_)
  40981. : image (image_)
  40982. {
  40983. image.duplicateIfShared();
  40984. image.multiplyAllAlphas (0.8f);
  40985. setAlwaysOnTop (true);
  40986. }
  40987. void paint (Graphics& g)
  40988. {
  40989. g.drawImageAt (image, 0, 0);
  40990. }
  40991. private:
  40992. Image image;
  40993. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40994. };
  40995. TableHeaderComponent::TableHeaderComponent()
  40996. : columnsChanged (false),
  40997. columnsResized (false),
  40998. sortChanged (false),
  40999. menuActive (true),
  41000. stretchToFit (false),
  41001. columnIdBeingResized (0),
  41002. columnIdBeingDragged (0),
  41003. columnIdUnderMouse (0),
  41004. lastDeliberateWidth (0)
  41005. {
  41006. }
  41007. TableHeaderComponent::~TableHeaderComponent()
  41008. {
  41009. dragOverlayComp = 0;
  41010. }
  41011. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41012. {
  41013. menuActive = hasMenu;
  41014. }
  41015. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41016. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41017. {
  41018. if (onlyCountVisibleColumns)
  41019. {
  41020. int num = 0;
  41021. for (int i = columns.size(); --i >= 0;)
  41022. if (columns.getUnchecked(i)->isVisible())
  41023. ++num;
  41024. return num;
  41025. }
  41026. else
  41027. {
  41028. return columns.size();
  41029. }
  41030. }
  41031. const String TableHeaderComponent::getColumnName (const int columnId) const
  41032. {
  41033. const ColumnInfo* const ci = getInfoForId (columnId);
  41034. return ci != 0 ? ci->name : String::empty;
  41035. }
  41036. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41037. {
  41038. ColumnInfo* const ci = getInfoForId (columnId);
  41039. if (ci != 0 && ci->name != newName)
  41040. {
  41041. ci->name = newName;
  41042. sendColumnsChanged();
  41043. }
  41044. }
  41045. void TableHeaderComponent::addColumn (const String& columnName,
  41046. const int columnId,
  41047. const int width,
  41048. const int minimumWidth,
  41049. const int maximumWidth,
  41050. const int propertyFlags,
  41051. const int insertIndex)
  41052. {
  41053. // can't have a duplicate or null ID!
  41054. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41055. jassert (width > 0);
  41056. ColumnInfo* const ci = new ColumnInfo();
  41057. ci->name = columnName;
  41058. ci->id = columnId;
  41059. ci->width = width;
  41060. ci->lastDeliberateWidth = width;
  41061. ci->minimumWidth = minimumWidth;
  41062. ci->maximumWidth = maximumWidth;
  41063. if (ci->maximumWidth < 0)
  41064. ci->maximumWidth = std::numeric_limits<int>::max();
  41065. jassert (ci->maximumWidth >= ci->minimumWidth);
  41066. ci->propertyFlags = propertyFlags;
  41067. columns.insert (insertIndex, ci);
  41068. sendColumnsChanged();
  41069. }
  41070. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41071. {
  41072. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41073. if (index >= 0)
  41074. {
  41075. columns.remove (index);
  41076. sortChanged = true;
  41077. sendColumnsChanged();
  41078. }
  41079. }
  41080. void TableHeaderComponent::removeAllColumns()
  41081. {
  41082. if (columns.size() > 0)
  41083. {
  41084. columns.clear();
  41085. sendColumnsChanged();
  41086. }
  41087. }
  41088. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41089. {
  41090. const int currentIndex = getIndexOfColumnId (columnId, false);
  41091. newIndex = visibleIndexToTotalIndex (newIndex);
  41092. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41093. {
  41094. columns.move (currentIndex, newIndex);
  41095. sendColumnsChanged();
  41096. }
  41097. }
  41098. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41099. {
  41100. const ColumnInfo* const ci = getInfoForId (columnId);
  41101. return ci != 0 ? ci->width : 0;
  41102. }
  41103. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41104. {
  41105. ColumnInfo* const ci = getInfoForId (columnId);
  41106. if (ci != 0 && ci->width != newWidth)
  41107. {
  41108. const int numColumns = getNumColumns (true);
  41109. ci->lastDeliberateWidth = ci->width
  41110. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41111. if (stretchToFit)
  41112. {
  41113. const int index = getIndexOfColumnId (columnId, true) + 1;
  41114. if (isPositiveAndBelow (index, numColumns))
  41115. {
  41116. const int x = getColumnPosition (index).getX();
  41117. if (lastDeliberateWidth == 0)
  41118. lastDeliberateWidth = getTotalWidth();
  41119. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41120. }
  41121. }
  41122. repaint();
  41123. columnsResized = true;
  41124. triggerAsyncUpdate();
  41125. }
  41126. }
  41127. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41128. {
  41129. int n = 0;
  41130. for (int i = 0; i < columns.size(); ++i)
  41131. {
  41132. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41133. {
  41134. if (columns.getUnchecked(i)->id == columnId)
  41135. return n;
  41136. ++n;
  41137. }
  41138. }
  41139. return -1;
  41140. }
  41141. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41142. {
  41143. if (onlyCountVisibleColumns)
  41144. index = visibleIndexToTotalIndex (index);
  41145. const ColumnInfo* const ci = columns [index];
  41146. return (ci != 0) ? ci->id : 0;
  41147. }
  41148. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41149. {
  41150. int x = 0, width = 0, n = 0;
  41151. for (int i = 0; i < columns.size(); ++i)
  41152. {
  41153. x += width;
  41154. if (columns.getUnchecked(i)->isVisible())
  41155. {
  41156. width = columns.getUnchecked(i)->width;
  41157. if (n++ == index)
  41158. break;
  41159. }
  41160. else
  41161. {
  41162. width = 0;
  41163. }
  41164. }
  41165. return Rectangle<int> (x, 0, width, getHeight());
  41166. }
  41167. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41168. {
  41169. if (xToFind >= 0)
  41170. {
  41171. int x = 0;
  41172. for (int i = 0; i < columns.size(); ++i)
  41173. {
  41174. const ColumnInfo* const ci = columns.getUnchecked(i);
  41175. if (ci->isVisible())
  41176. {
  41177. x += ci->width;
  41178. if (xToFind < x)
  41179. return ci->id;
  41180. }
  41181. }
  41182. }
  41183. return 0;
  41184. }
  41185. int TableHeaderComponent::getTotalWidth() const
  41186. {
  41187. int w = 0;
  41188. for (int i = columns.size(); --i >= 0;)
  41189. if (columns.getUnchecked(i)->isVisible())
  41190. w += columns.getUnchecked(i)->width;
  41191. return w;
  41192. }
  41193. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41194. {
  41195. stretchToFit = shouldStretchToFit;
  41196. lastDeliberateWidth = getTotalWidth();
  41197. resized();
  41198. }
  41199. bool TableHeaderComponent::isStretchToFitActive() const
  41200. {
  41201. return stretchToFit;
  41202. }
  41203. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41204. {
  41205. if (stretchToFit && getWidth() > 0
  41206. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41207. {
  41208. lastDeliberateWidth = targetTotalWidth;
  41209. resizeColumnsToFit (0, targetTotalWidth);
  41210. }
  41211. }
  41212. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41213. {
  41214. targetTotalWidth = jmax (targetTotalWidth, 0);
  41215. StretchableObjectResizer sor;
  41216. int i;
  41217. for (i = firstColumnIndex; i < columns.size(); ++i)
  41218. {
  41219. ColumnInfo* const ci = columns.getUnchecked(i);
  41220. if (ci->isVisible())
  41221. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41222. }
  41223. sor.resizeToFit (targetTotalWidth);
  41224. int visIndex = 0;
  41225. for (i = firstColumnIndex; i < columns.size(); ++i)
  41226. {
  41227. ColumnInfo* const ci = columns.getUnchecked(i);
  41228. if (ci->isVisible())
  41229. {
  41230. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41231. (int) std::floor (sor.getItemSize (visIndex++)));
  41232. if (newWidth != ci->width)
  41233. {
  41234. ci->width = newWidth;
  41235. repaint();
  41236. columnsResized = true;
  41237. triggerAsyncUpdate();
  41238. }
  41239. }
  41240. }
  41241. }
  41242. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41243. {
  41244. ColumnInfo* const ci = getInfoForId (columnId);
  41245. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41246. {
  41247. if (shouldBeVisible)
  41248. ci->propertyFlags |= visible;
  41249. else
  41250. ci->propertyFlags &= ~visible;
  41251. sendColumnsChanged();
  41252. resized();
  41253. }
  41254. }
  41255. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41256. {
  41257. const ColumnInfo* const ci = getInfoForId (columnId);
  41258. return ci != 0 && ci->isVisible();
  41259. }
  41260. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41261. {
  41262. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41263. {
  41264. for (int i = columns.size(); --i >= 0;)
  41265. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41266. ColumnInfo* const ci = getInfoForId (columnId);
  41267. if (ci != 0)
  41268. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41269. reSortTable();
  41270. }
  41271. }
  41272. int TableHeaderComponent::getSortColumnId() const
  41273. {
  41274. for (int i = columns.size(); --i >= 0;)
  41275. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41276. return columns.getUnchecked(i)->id;
  41277. return 0;
  41278. }
  41279. bool TableHeaderComponent::isSortedForwards() const
  41280. {
  41281. for (int i = columns.size(); --i >= 0;)
  41282. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41283. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41284. return true;
  41285. }
  41286. void TableHeaderComponent::reSortTable()
  41287. {
  41288. sortChanged = true;
  41289. repaint();
  41290. triggerAsyncUpdate();
  41291. }
  41292. const String TableHeaderComponent::toString() const
  41293. {
  41294. String s;
  41295. XmlElement doc ("TABLELAYOUT");
  41296. doc.setAttribute ("sortedCol", getSortColumnId());
  41297. doc.setAttribute ("sortForwards", isSortedForwards());
  41298. for (int i = 0; i < columns.size(); ++i)
  41299. {
  41300. const ColumnInfo* const ci = columns.getUnchecked (i);
  41301. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41302. e->setAttribute ("id", ci->id);
  41303. e->setAttribute ("visible", ci->isVisible());
  41304. e->setAttribute ("width", ci->width);
  41305. }
  41306. return doc.createDocument (String::empty, true, false);
  41307. }
  41308. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41309. {
  41310. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41311. int index = 0;
  41312. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41313. {
  41314. forEachXmlChildElement (*storedXml, col)
  41315. {
  41316. const int tabId = col->getIntAttribute ("id");
  41317. ColumnInfo* const ci = getInfoForId (tabId);
  41318. if (ci != 0)
  41319. {
  41320. columns.move (columns.indexOf (ci), index);
  41321. ci->width = col->getIntAttribute ("width");
  41322. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41323. }
  41324. ++index;
  41325. }
  41326. columnsResized = true;
  41327. sendColumnsChanged();
  41328. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41329. storedXml->getBoolAttribute ("sortForwards", true));
  41330. }
  41331. }
  41332. void TableHeaderComponent::addListener (Listener* const newListener)
  41333. {
  41334. listeners.addIfNotAlreadyThere (newListener);
  41335. }
  41336. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41337. {
  41338. listeners.removeValue (listenerToRemove);
  41339. }
  41340. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41341. {
  41342. const ColumnInfo* const ci = getInfoForId (columnId);
  41343. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41344. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41345. }
  41346. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41347. {
  41348. for (int i = 0; i < columns.size(); ++i)
  41349. {
  41350. const ColumnInfo* const ci = columns.getUnchecked(i);
  41351. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41352. menu.addItem (ci->id, ci->name,
  41353. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41354. isColumnVisible (ci->id));
  41355. }
  41356. }
  41357. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41358. {
  41359. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41360. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41361. }
  41362. void TableHeaderComponent::paint (Graphics& g)
  41363. {
  41364. LookAndFeel& lf = getLookAndFeel();
  41365. lf.drawTableHeaderBackground (g, *this);
  41366. const Rectangle<int> clip (g.getClipBounds());
  41367. int x = 0;
  41368. for (int i = 0; i < columns.size(); ++i)
  41369. {
  41370. const ColumnInfo* const ci = columns.getUnchecked(i);
  41371. if (ci->isVisible())
  41372. {
  41373. if (x + ci->width > clip.getX()
  41374. && (ci->id != columnIdBeingDragged
  41375. || dragOverlayComp == 0
  41376. || ! dragOverlayComp->isVisible()))
  41377. {
  41378. Graphics::ScopedSaveState ss (g);
  41379. g.setOrigin (x, 0);
  41380. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41381. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41382. ci->id == columnIdUnderMouse,
  41383. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41384. ci->propertyFlags);
  41385. }
  41386. x += ci->width;
  41387. if (x >= clip.getRight())
  41388. break;
  41389. }
  41390. }
  41391. }
  41392. void TableHeaderComponent::resized()
  41393. {
  41394. }
  41395. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41396. {
  41397. updateColumnUnderMouse (e.x, e.y);
  41398. }
  41399. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41400. {
  41401. updateColumnUnderMouse (e.x, e.y);
  41402. }
  41403. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41404. {
  41405. updateColumnUnderMouse (e.x, e.y);
  41406. }
  41407. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41408. {
  41409. repaint();
  41410. columnIdBeingResized = 0;
  41411. columnIdBeingDragged = 0;
  41412. if (columnIdUnderMouse != 0)
  41413. {
  41414. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41415. if (e.mods.isPopupMenu())
  41416. columnClicked (columnIdUnderMouse, e.mods);
  41417. }
  41418. if (menuActive && e.mods.isPopupMenu())
  41419. showColumnChooserMenu (columnIdUnderMouse);
  41420. }
  41421. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41422. {
  41423. if (columnIdBeingResized == 0
  41424. && columnIdBeingDragged == 0
  41425. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41426. {
  41427. dragOverlayComp = 0;
  41428. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41429. if (columnIdBeingResized != 0)
  41430. {
  41431. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41432. initialColumnWidth = ci->width;
  41433. }
  41434. else
  41435. {
  41436. beginDrag (e);
  41437. }
  41438. }
  41439. if (columnIdBeingResized != 0)
  41440. {
  41441. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41442. if (ci != 0)
  41443. {
  41444. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41445. initialColumnWidth + e.getDistanceFromDragStartX());
  41446. if (stretchToFit)
  41447. {
  41448. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41449. int minWidthOnRight = 0;
  41450. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41451. if (columns.getUnchecked (i)->isVisible())
  41452. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41453. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41454. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41455. }
  41456. setColumnWidth (columnIdBeingResized, w);
  41457. }
  41458. }
  41459. else if (columnIdBeingDragged != 0)
  41460. {
  41461. if (e.y >= -50 && e.y < getHeight() + 50)
  41462. {
  41463. if (dragOverlayComp != 0)
  41464. {
  41465. dragOverlayComp->setVisible (true);
  41466. dragOverlayComp->setBounds (jlimit (0,
  41467. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41468. e.x - draggingColumnOffset),
  41469. 0,
  41470. dragOverlayComp->getWidth(),
  41471. getHeight());
  41472. for (int i = columns.size(); --i >= 0;)
  41473. {
  41474. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41475. int newIndex = currentIndex;
  41476. if (newIndex > 0)
  41477. {
  41478. // if the previous column isn't draggable, we can't move our column
  41479. // past it, because that'd change the undraggable column's position..
  41480. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41481. if ((previous->propertyFlags & draggable) != 0)
  41482. {
  41483. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41484. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41485. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41486. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41487. {
  41488. --newIndex;
  41489. }
  41490. }
  41491. }
  41492. if (newIndex < columns.size() - 1)
  41493. {
  41494. // if the next column isn't draggable, we can't move our column
  41495. // past it, because that'd change the undraggable column's position..
  41496. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41497. if ((nextCol->propertyFlags & draggable) != 0)
  41498. {
  41499. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41500. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41501. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41502. > abs (dragOverlayComp->getRight() - rightOfNext))
  41503. {
  41504. ++newIndex;
  41505. }
  41506. }
  41507. }
  41508. if (newIndex != currentIndex)
  41509. moveColumn (columnIdBeingDragged, newIndex);
  41510. else
  41511. break;
  41512. }
  41513. }
  41514. }
  41515. else
  41516. {
  41517. endDrag (draggingColumnOriginalIndex);
  41518. }
  41519. }
  41520. }
  41521. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41522. {
  41523. if (columnIdBeingDragged == 0)
  41524. {
  41525. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41526. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41527. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41528. {
  41529. columnIdBeingDragged = 0;
  41530. }
  41531. else
  41532. {
  41533. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41534. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41535. const int temp = columnIdBeingDragged;
  41536. columnIdBeingDragged = 0;
  41537. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41538. columnIdBeingDragged = temp;
  41539. dragOverlayComp->setBounds (columnRect);
  41540. for (int i = listeners.size(); --i >= 0;)
  41541. {
  41542. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41543. i = jmin (i, listeners.size() - 1);
  41544. }
  41545. }
  41546. }
  41547. }
  41548. void TableHeaderComponent::endDrag (const int finalIndex)
  41549. {
  41550. if (columnIdBeingDragged != 0)
  41551. {
  41552. moveColumn (columnIdBeingDragged, finalIndex);
  41553. columnIdBeingDragged = 0;
  41554. repaint();
  41555. for (int i = listeners.size(); --i >= 0;)
  41556. {
  41557. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41558. i = jmin (i, listeners.size() - 1);
  41559. }
  41560. }
  41561. }
  41562. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41563. {
  41564. mouseDrag (e);
  41565. for (int i = columns.size(); --i >= 0;)
  41566. if (columns.getUnchecked (i)->isVisible())
  41567. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41568. columnIdBeingResized = 0;
  41569. repaint();
  41570. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41571. updateColumnUnderMouse (e.x, e.y);
  41572. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41573. columnClicked (columnIdUnderMouse, e.mods);
  41574. dragOverlayComp = 0;
  41575. }
  41576. const MouseCursor TableHeaderComponent::getMouseCursor()
  41577. {
  41578. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41579. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41580. return Component::getMouseCursor();
  41581. }
  41582. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41583. {
  41584. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41585. }
  41586. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41587. {
  41588. for (int i = columns.size(); --i >= 0;)
  41589. if (columns.getUnchecked(i)->id == id)
  41590. return columns.getUnchecked(i);
  41591. return 0;
  41592. }
  41593. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41594. {
  41595. int n = 0;
  41596. for (int i = 0; i < columns.size(); ++i)
  41597. {
  41598. if (columns.getUnchecked(i)->isVisible())
  41599. {
  41600. if (n == visibleIndex)
  41601. return i;
  41602. ++n;
  41603. }
  41604. }
  41605. return -1;
  41606. }
  41607. void TableHeaderComponent::sendColumnsChanged()
  41608. {
  41609. if (stretchToFit && lastDeliberateWidth > 0)
  41610. resizeAllColumnsToFit (lastDeliberateWidth);
  41611. repaint();
  41612. columnsChanged = true;
  41613. triggerAsyncUpdate();
  41614. }
  41615. void TableHeaderComponent::handleAsyncUpdate()
  41616. {
  41617. const bool changed = columnsChanged || sortChanged;
  41618. const bool sized = columnsResized || changed;
  41619. const bool sorted = sortChanged;
  41620. columnsChanged = false;
  41621. columnsResized = false;
  41622. sortChanged = false;
  41623. if (sorted)
  41624. {
  41625. for (int i = listeners.size(); --i >= 0;)
  41626. {
  41627. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41628. i = jmin (i, listeners.size() - 1);
  41629. }
  41630. }
  41631. if (changed)
  41632. {
  41633. for (int i = listeners.size(); --i >= 0;)
  41634. {
  41635. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41636. i = jmin (i, listeners.size() - 1);
  41637. }
  41638. }
  41639. if (sized)
  41640. {
  41641. for (int i = listeners.size(); --i >= 0;)
  41642. {
  41643. listeners.getUnchecked(i)->tableColumnsResized (this);
  41644. i = jmin (i, listeners.size() - 1);
  41645. }
  41646. }
  41647. }
  41648. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41649. {
  41650. if (isPositiveAndBelow (mouseX, getWidth()))
  41651. {
  41652. const int draggableDistance = 3;
  41653. int x = 0;
  41654. for (int i = 0; i < columns.size(); ++i)
  41655. {
  41656. const ColumnInfo* const ci = columns.getUnchecked(i);
  41657. if (ci->isVisible())
  41658. {
  41659. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41660. && (ci->propertyFlags & resizable) != 0)
  41661. return ci->id;
  41662. x += ci->width;
  41663. }
  41664. }
  41665. }
  41666. return 0;
  41667. }
  41668. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41669. {
  41670. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41671. ? getColumnIdAtX (x) : 0;
  41672. if (newCol != columnIdUnderMouse)
  41673. {
  41674. columnIdUnderMouse = newCol;
  41675. repaint();
  41676. }
  41677. }
  41678. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41679. {
  41680. PopupMenu m;
  41681. addMenuItems (m, columnIdClicked);
  41682. if (m.getNumItems() > 0)
  41683. {
  41684. m.setLookAndFeel (&getLookAndFeel());
  41685. const int result = m.show();
  41686. if (result != 0)
  41687. reactToMenuItem (result, columnIdClicked);
  41688. }
  41689. }
  41690. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41691. {
  41692. }
  41693. END_JUCE_NAMESPACE
  41694. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41695. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41696. BEGIN_JUCE_NAMESPACE
  41697. class TableListRowComp : public Component,
  41698. public TooltipClient
  41699. {
  41700. public:
  41701. TableListRowComp (TableListBox& owner_)
  41702. : owner (owner_), row (-1), isSelected (false)
  41703. {
  41704. }
  41705. void paint (Graphics& g)
  41706. {
  41707. TableListBoxModel* const model = owner.getModel();
  41708. if (model != 0)
  41709. {
  41710. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41711. const TableHeaderComponent& header = owner.getHeader();
  41712. const int numColumns = header.getNumColumns (true);
  41713. for (int i = 0; i < numColumns; ++i)
  41714. {
  41715. if (columnComponents[i] == 0)
  41716. {
  41717. const int columnId = header.getColumnIdOfIndex (i, true);
  41718. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41719. Graphics::ScopedSaveState ss (g);
  41720. g.reduceClipRegion (columnRect);
  41721. g.setOrigin (columnRect.getX(), 0);
  41722. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41723. }
  41724. }
  41725. }
  41726. }
  41727. void update (const int newRow, const bool isNowSelected)
  41728. {
  41729. jassert (newRow >= 0);
  41730. if (newRow != row || isNowSelected != isSelected)
  41731. {
  41732. row = newRow;
  41733. isSelected = isNowSelected;
  41734. repaint();
  41735. }
  41736. TableListBoxModel* const model = owner.getModel();
  41737. if (model != 0 && row < owner.getNumRows())
  41738. {
  41739. const Identifier columnProperty ("_tableColumnId");
  41740. const int numColumns = owner.getHeader().getNumColumns (true);
  41741. for (int i = 0; i < numColumns; ++i)
  41742. {
  41743. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41744. Component* comp = columnComponents[i];
  41745. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41746. {
  41747. columnComponents.set (i, 0);
  41748. comp = 0;
  41749. }
  41750. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41751. columnComponents.set (i, comp, false);
  41752. if (comp != 0)
  41753. {
  41754. comp->getProperties().set (columnProperty, columnId);
  41755. addAndMakeVisible (comp);
  41756. resizeCustomComp (i);
  41757. }
  41758. }
  41759. columnComponents.removeRange (numColumns, columnComponents.size());
  41760. }
  41761. else
  41762. {
  41763. columnComponents.clear();
  41764. }
  41765. }
  41766. void resized()
  41767. {
  41768. for (int i = columnComponents.size(); --i >= 0;)
  41769. resizeCustomComp (i);
  41770. }
  41771. void resizeCustomComp (const int index)
  41772. {
  41773. Component* const c = columnComponents.getUnchecked (index);
  41774. if (c != 0)
  41775. c->setBounds (owner.getHeader().getColumnPosition (index)
  41776. .withY (0).withHeight (getHeight()));
  41777. }
  41778. void mouseDown (const MouseEvent& e)
  41779. {
  41780. isDragging = false;
  41781. selectRowOnMouseUp = false;
  41782. if (isEnabled())
  41783. {
  41784. if (! isSelected)
  41785. {
  41786. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41787. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41788. if (columnId != 0 && owner.getModel() != 0)
  41789. owner.getModel()->cellClicked (row, columnId, e);
  41790. }
  41791. else
  41792. {
  41793. selectRowOnMouseUp = true;
  41794. }
  41795. }
  41796. }
  41797. void mouseDrag (const MouseEvent& e)
  41798. {
  41799. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41800. {
  41801. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41802. if (selectedRows.size() > 0)
  41803. {
  41804. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41805. if (dragDescription.isNotEmpty())
  41806. {
  41807. isDragging = true;
  41808. owner.startDragAndDrop (e, dragDescription);
  41809. }
  41810. }
  41811. }
  41812. }
  41813. void mouseUp (const MouseEvent& e)
  41814. {
  41815. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41816. {
  41817. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41818. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41819. if (columnId != 0 && owner.getModel() != 0)
  41820. owner.getModel()->cellClicked (row, columnId, e);
  41821. }
  41822. }
  41823. void mouseDoubleClick (const MouseEvent& e)
  41824. {
  41825. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41826. if (columnId != 0 && owner.getModel() != 0)
  41827. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41828. }
  41829. const String getTooltip()
  41830. {
  41831. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41832. if (columnId != 0 && owner.getModel() != 0)
  41833. return owner.getModel()->getCellTooltip (row, columnId);
  41834. return String::empty;
  41835. }
  41836. Component* findChildComponentForColumn (const int columnId) const
  41837. {
  41838. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41839. }
  41840. private:
  41841. TableListBox& owner;
  41842. OwnedArray<Component> columnComponents;
  41843. int row;
  41844. bool isSelected, isDragging, selectRowOnMouseUp;
  41845. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41846. };
  41847. class TableListBoxHeader : public TableHeaderComponent
  41848. {
  41849. public:
  41850. TableListBoxHeader (TableListBox& owner_)
  41851. : owner (owner_)
  41852. {
  41853. }
  41854. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41855. {
  41856. if (owner.isAutoSizeMenuOptionShown())
  41857. {
  41858. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41859. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41860. menu.addSeparator();
  41861. }
  41862. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41863. }
  41864. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41865. {
  41866. switch (menuReturnId)
  41867. {
  41868. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41869. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41870. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41871. }
  41872. }
  41873. private:
  41874. TableListBox& owner;
  41875. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41876. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41877. };
  41878. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41879. : ListBox (name, 0),
  41880. model (model_),
  41881. autoSizeOptionsShown (true)
  41882. {
  41883. ListBox::model = this;
  41884. header = new TableListBoxHeader (*this);
  41885. header->setSize (100, 28);
  41886. header->addListener (this);
  41887. setHeaderComponent (header);
  41888. }
  41889. TableListBox::~TableListBox()
  41890. {
  41891. header = 0;
  41892. }
  41893. void TableListBox::setModel (TableListBoxModel* const newModel)
  41894. {
  41895. if (model != newModel)
  41896. {
  41897. model = newModel;
  41898. updateContent();
  41899. }
  41900. }
  41901. int TableListBox::getHeaderHeight() const
  41902. {
  41903. return header->getHeight();
  41904. }
  41905. void TableListBox::setHeaderHeight (const int newHeight)
  41906. {
  41907. header->setSize (header->getWidth(), newHeight);
  41908. resized();
  41909. }
  41910. void TableListBox::autoSizeColumn (const int columnId)
  41911. {
  41912. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41913. if (width > 0)
  41914. header->setColumnWidth (columnId, width);
  41915. }
  41916. void TableListBox::autoSizeAllColumns()
  41917. {
  41918. for (int i = 0; i < header->getNumColumns (true); ++i)
  41919. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41920. }
  41921. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41922. {
  41923. autoSizeOptionsShown = shouldBeShown;
  41924. }
  41925. bool TableListBox::isAutoSizeMenuOptionShown() const
  41926. {
  41927. return autoSizeOptionsShown;
  41928. }
  41929. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41930. const bool relativeToComponentTopLeft) const
  41931. {
  41932. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41933. if (relativeToComponentTopLeft)
  41934. headerCell.translate (header->getX(), 0);
  41935. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41936. .withX (headerCell.getX())
  41937. .withWidth (headerCell.getWidth());
  41938. }
  41939. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41940. {
  41941. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41942. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41943. }
  41944. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41945. {
  41946. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41947. if (scrollbar != 0)
  41948. {
  41949. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41950. double x = scrollbar->getCurrentRangeStart();
  41951. const double w = scrollbar->getCurrentRangeSize();
  41952. if (pos.getX() < x)
  41953. x = pos.getX();
  41954. else if (pos.getRight() > x + w)
  41955. x += jmax (0.0, pos.getRight() - (x + w));
  41956. scrollbar->setCurrentRangeStart (x);
  41957. }
  41958. }
  41959. int TableListBox::getNumRows()
  41960. {
  41961. return model != 0 ? model->getNumRows() : 0;
  41962. }
  41963. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41964. {
  41965. }
  41966. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41967. {
  41968. if (existingComponentToUpdate == 0)
  41969. existingComponentToUpdate = new TableListRowComp (*this);
  41970. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41971. return existingComponentToUpdate;
  41972. }
  41973. void TableListBox::selectedRowsChanged (int row)
  41974. {
  41975. if (model != 0)
  41976. model->selectedRowsChanged (row);
  41977. }
  41978. void TableListBox::deleteKeyPressed (int row)
  41979. {
  41980. if (model != 0)
  41981. model->deleteKeyPressed (row);
  41982. }
  41983. void TableListBox::returnKeyPressed (int row)
  41984. {
  41985. if (model != 0)
  41986. model->returnKeyPressed (row);
  41987. }
  41988. void TableListBox::backgroundClicked()
  41989. {
  41990. if (model != 0)
  41991. model->backgroundClicked();
  41992. }
  41993. void TableListBox::listWasScrolled()
  41994. {
  41995. if (model != 0)
  41996. model->listWasScrolled();
  41997. }
  41998. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41999. {
  42000. setMinimumContentWidth (header->getTotalWidth());
  42001. repaint();
  42002. updateColumnComponents();
  42003. }
  42004. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42005. {
  42006. setMinimumContentWidth (header->getTotalWidth());
  42007. repaint();
  42008. updateColumnComponents();
  42009. }
  42010. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42011. {
  42012. if (model != 0)
  42013. model->sortOrderChanged (header->getSortColumnId(),
  42014. header->isSortedForwards());
  42015. }
  42016. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42017. {
  42018. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42019. repaint();
  42020. }
  42021. void TableListBox::resized()
  42022. {
  42023. ListBox::resized();
  42024. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42025. setMinimumContentWidth (header->getTotalWidth());
  42026. }
  42027. void TableListBox::updateColumnComponents() const
  42028. {
  42029. const int firstRow = getRowContainingPosition (0, 0);
  42030. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42031. {
  42032. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42033. if (rowComp != 0)
  42034. rowComp->resized();
  42035. }
  42036. }
  42037. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  42038. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  42039. void TableListBoxModel::backgroundClicked() {}
  42040. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  42041. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  42042. void TableListBoxModel::selectedRowsChanged (int) {}
  42043. void TableListBoxModel::deleteKeyPressed (int) {}
  42044. void TableListBoxModel::returnKeyPressed (int) {}
  42045. void TableListBoxModel::listWasScrolled() {}
  42046. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  42047. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  42048. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42049. {
  42050. (void) existingComponentToUpdate;
  42051. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42052. return 0;
  42053. }
  42054. END_JUCE_NAMESPACE
  42055. /*** End of inlined file: juce_TableListBox.cpp ***/
  42056. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42057. BEGIN_JUCE_NAMESPACE
  42058. // a word or space that can't be broken down any further
  42059. struct TextAtom
  42060. {
  42061. String atomText;
  42062. float width;
  42063. int numChars;
  42064. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42065. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42066. const String getText (const juce_wchar passwordCharacter) const
  42067. {
  42068. if (passwordCharacter == 0)
  42069. return atomText;
  42070. else
  42071. return String::repeatedString (String::charToString (passwordCharacter),
  42072. atomText.length());
  42073. }
  42074. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42075. {
  42076. if (passwordCharacter == 0)
  42077. return atomText.substring (0, numChars);
  42078. else if (isNewLine())
  42079. return String::empty;
  42080. else
  42081. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42082. }
  42083. };
  42084. // a run of text with a single font and colour
  42085. class TextEditor::UniformTextSection
  42086. {
  42087. public:
  42088. UniformTextSection (const String& text,
  42089. const Font& font_,
  42090. const Colour& colour_,
  42091. const juce_wchar passwordCharacter)
  42092. : font (font_),
  42093. colour (colour_)
  42094. {
  42095. initialiseAtoms (text, passwordCharacter);
  42096. }
  42097. UniformTextSection (const UniformTextSection& other)
  42098. : font (other.font),
  42099. colour (other.colour)
  42100. {
  42101. atoms.ensureStorageAllocated (other.atoms.size());
  42102. for (int i = 0; i < other.atoms.size(); ++i)
  42103. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42104. }
  42105. ~UniformTextSection()
  42106. {
  42107. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42108. }
  42109. void clear()
  42110. {
  42111. for (int i = atoms.size(); --i >= 0;)
  42112. delete getAtom(i);
  42113. atoms.clear();
  42114. }
  42115. int getNumAtoms() const
  42116. {
  42117. return atoms.size();
  42118. }
  42119. TextAtom* getAtom (const int index) const throw()
  42120. {
  42121. return atoms.getUnchecked (index);
  42122. }
  42123. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42124. {
  42125. if (other.atoms.size() > 0)
  42126. {
  42127. TextAtom* const lastAtom = atoms.getLast();
  42128. int i = 0;
  42129. if (lastAtom != 0)
  42130. {
  42131. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42132. {
  42133. TextAtom* const first = other.getAtom(0);
  42134. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42135. {
  42136. lastAtom->atomText += first->atomText;
  42137. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42138. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42139. delete first;
  42140. ++i;
  42141. }
  42142. }
  42143. }
  42144. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42145. while (i < other.atoms.size())
  42146. {
  42147. atoms.add (other.getAtom(i));
  42148. ++i;
  42149. }
  42150. }
  42151. }
  42152. UniformTextSection* split (const int indexToBreakAt,
  42153. const juce_wchar passwordCharacter)
  42154. {
  42155. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42156. font, colour,
  42157. passwordCharacter);
  42158. int index = 0;
  42159. for (int i = 0; i < atoms.size(); ++i)
  42160. {
  42161. TextAtom* const atom = getAtom(i);
  42162. const int nextIndex = index + atom->numChars;
  42163. if (index == indexToBreakAt)
  42164. {
  42165. int j;
  42166. for (j = i; j < atoms.size(); ++j)
  42167. section2->atoms.add (getAtom (j));
  42168. for (j = atoms.size(); --j >= i;)
  42169. atoms.remove (j);
  42170. break;
  42171. }
  42172. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42173. {
  42174. TextAtom* const secondAtom = new TextAtom();
  42175. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42176. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42177. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42178. section2->atoms.add (secondAtom);
  42179. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42180. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42181. atom->numChars = (uint16) (indexToBreakAt - index);
  42182. int j;
  42183. for (j = i + 1; j < atoms.size(); ++j)
  42184. section2->atoms.add (getAtom (j));
  42185. for (j = atoms.size(); --j > i;)
  42186. atoms.remove (j);
  42187. break;
  42188. }
  42189. index = nextIndex;
  42190. }
  42191. return section2;
  42192. }
  42193. void appendAllText (String::Concatenator& concatenator) const
  42194. {
  42195. for (int i = 0; i < atoms.size(); ++i)
  42196. concatenator.append (getAtom(i)->atomText);
  42197. }
  42198. void appendSubstring (String::Concatenator& concatenator,
  42199. const Range<int>& range) const
  42200. {
  42201. int index = 0;
  42202. for (int i = 0; i < atoms.size(); ++i)
  42203. {
  42204. const TextAtom* const atom = getAtom (i);
  42205. const int nextIndex = index + atom->numChars;
  42206. if (range.getStart() < nextIndex)
  42207. {
  42208. if (range.getEnd() <= index)
  42209. break;
  42210. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42211. if (! r.isEmpty())
  42212. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42213. }
  42214. index = nextIndex;
  42215. }
  42216. }
  42217. int getTotalLength() const
  42218. {
  42219. int total = 0;
  42220. for (int i = atoms.size(); --i >= 0;)
  42221. total += getAtom(i)->numChars;
  42222. return total;
  42223. }
  42224. void setFont (const Font& newFont,
  42225. const juce_wchar passwordCharacter)
  42226. {
  42227. if (font != newFont)
  42228. {
  42229. font = newFont;
  42230. for (int i = atoms.size(); --i >= 0;)
  42231. {
  42232. TextAtom* const atom = atoms.getUnchecked(i);
  42233. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42234. }
  42235. }
  42236. }
  42237. Font font;
  42238. Colour colour;
  42239. private:
  42240. Array <TextAtom*> atoms;
  42241. void initialiseAtoms (const String& textToParse,
  42242. const juce_wchar passwordCharacter)
  42243. {
  42244. int i = 0;
  42245. const int len = textToParse.length();
  42246. const juce_wchar* const text = textToParse;
  42247. while (i < len)
  42248. {
  42249. int start = i;
  42250. // create a whitespace atom unless it starts with non-ws
  42251. if (CharacterFunctions::isWhitespace (text[i])
  42252. && text[i] != '\r'
  42253. && text[i] != '\n')
  42254. {
  42255. while (i < len
  42256. && CharacterFunctions::isWhitespace (text[i])
  42257. && text[i] != '\r'
  42258. && text[i] != '\n')
  42259. {
  42260. ++i;
  42261. }
  42262. }
  42263. else
  42264. {
  42265. if (text[i] == '\r')
  42266. {
  42267. ++i;
  42268. if ((i < len) && (text[i] == '\n'))
  42269. {
  42270. ++start;
  42271. ++i;
  42272. }
  42273. }
  42274. else if (text[i] == '\n')
  42275. {
  42276. ++i;
  42277. }
  42278. else
  42279. {
  42280. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42281. ++i;
  42282. }
  42283. }
  42284. TextAtom* const atom = new TextAtom();
  42285. atom->atomText = String (text + start, i - start);
  42286. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42287. atom->numChars = (uint16) (i - start);
  42288. atoms.add (atom);
  42289. }
  42290. }
  42291. UniformTextSection& operator= (const UniformTextSection& other);
  42292. JUCE_LEAK_DETECTOR (UniformTextSection);
  42293. };
  42294. class TextEditor::Iterator
  42295. {
  42296. public:
  42297. Iterator (const Array <UniformTextSection*>& sections_,
  42298. const float wordWrapWidth_,
  42299. const juce_wchar passwordCharacter_)
  42300. : indexInText (0),
  42301. lineY (0),
  42302. lineHeight (0),
  42303. maxDescent (0),
  42304. atomX (0),
  42305. atomRight (0),
  42306. atom (0),
  42307. currentSection (0),
  42308. sections (sections_),
  42309. sectionIndex (0),
  42310. atomIndex (0),
  42311. wordWrapWidth (wordWrapWidth_),
  42312. passwordCharacter (passwordCharacter_)
  42313. {
  42314. jassert (wordWrapWidth_ > 0);
  42315. if (sections.size() > 0)
  42316. {
  42317. currentSection = sections.getUnchecked (sectionIndex);
  42318. if (currentSection != 0)
  42319. beginNewLine();
  42320. }
  42321. }
  42322. Iterator (const Iterator& other)
  42323. : indexInText (other.indexInText),
  42324. lineY (other.lineY),
  42325. lineHeight (other.lineHeight),
  42326. maxDescent (other.maxDescent),
  42327. atomX (other.atomX),
  42328. atomRight (other.atomRight),
  42329. atom (other.atom),
  42330. currentSection (other.currentSection),
  42331. sections (other.sections),
  42332. sectionIndex (other.sectionIndex),
  42333. atomIndex (other.atomIndex),
  42334. wordWrapWidth (other.wordWrapWidth),
  42335. passwordCharacter (other.passwordCharacter),
  42336. tempAtom (other.tempAtom)
  42337. {
  42338. }
  42339. ~Iterator()
  42340. {
  42341. }
  42342. bool next()
  42343. {
  42344. if (atom == &tempAtom)
  42345. {
  42346. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42347. if (numRemaining > 0)
  42348. {
  42349. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42350. atomX = 0;
  42351. if (tempAtom.numChars > 0)
  42352. lineY += lineHeight;
  42353. indexInText += tempAtom.numChars;
  42354. GlyphArrangement g;
  42355. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42356. int split;
  42357. for (split = 0; split < g.getNumGlyphs(); ++split)
  42358. if (shouldWrap (g.getGlyph (split).getRight()))
  42359. break;
  42360. if (split > 0 && split <= numRemaining)
  42361. {
  42362. tempAtom.numChars = (uint16) split;
  42363. tempAtom.width = g.getGlyph (split - 1).getRight();
  42364. atomRight = atomX + tempAtom.width;
  42365. return true;
  42366. }
  42367. }
  42368. }
  42369. bool forceNewLine = false;
  42370. if (sectionIndex >= sections.size())
  42371. {
  42372. moveToEndOfLastAtom();
  42373. return false;
  42374. }
  42375. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42376. {
  42377. if (atomIndex >= currentSection->getNumAtoms())
  42378. {
  42379. if (++sectionIndex >= sections.size())
  42380. {
  42381. moveToEndOfLastAtom();
  42382. return false;
  42383. }
  42384. atomIndex = 0;
  42385. currentSection = sections.getUnchecked (sectionIndex);
  42386. }
  42387. else
  42388. {
  42389. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42390. if (! lastAtom->isWhitespace())
  42391. {
  42392. // handle the case where the last atom in a section is actually part of the same
  42393. // word as the first atom of the next section...
  42394. float right = atomRight + lastAtom->width;
  42395. float lineHeight2 = lineHeight;
  42396. float maxDescent2 = maxDescent;
  42397. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42398. {
  42399. const UniformTextSection* const s = sections.getUnchecked (section);
  42400. if (s->getNumAtoms() == 0)
  42401. break;
  42402. const TextAtom* const nextAtom = s->getAtom (0);
  42403. if (nextAtom->isWhitespace())
  42404. break;
  42405. right += nextAtom->width;
  42406. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42407. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42408. if (shouldWrap (right))
  42409. {
  42410. lineHeight = lineHeight2;
  42411. maxDescent = maxDescent2;
  42412. forceNewLine = true;
  42413. break;
  42414. }
  42415. if (s->getNumAtoms() > 1)
  42416. break;
  42417. }
  42418. }
  42419. }
  42420. }
  42421. if (atom != 0)
  42422. {
  42423. atomX = atomRight;
  42424. indexInText += atom->numChars;
  42425. if (atom->isNewLine())
  42426. beginNewLine();
  42427. }
  42428. atom = currentSection->getAtom (atomIndex);
  42429. atomRight = atomX + atom->width;
  42430. ++atomIndex;
  42431. if (shouldWrap (atomRight) || forceNewLine)
  42432. {
  42433. if (atom->isWhitespace())
  42434. {
  42435. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42436. atomRight = jmin (atomRight, wordWrapWidth);
  42437. }
  42438. else
  42439. {
  42440. atomRight = atom->width;
  42441. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42442. {
  42443. tempAtom = *atom;
  42444. tempAtom.width = 0;
  42445. tempAtom.numChars = 0;
  42446. atom = &tempAtom;
  42447. if (atomX > 0)
  42448. beginNewLine();
  42449. return next();
  42450. }
  42451. beginNewLine();
  42452. return true;
  42453. }
  42454. }
  42455. return true;
  42456. }
  42457. void beginNewLine()
  42458. {
  42459. atomX = 0;
  42460. lineY += lineHeight;
  42461. int tempSectionIndex = sectionIndex;
  42462. int tempAtomIndex = atomIndex;
  42463. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42464. lineHeight = section->font.getHeight();
  42465. maxDescent = section->font.getDescent();
  42466. float x = (atom != 0) ? atom->width : 0;
  42467. while (! shouldWrap (x))
  42468. {
  42469. if (tempSectionIndex >= sections.size())
  42470. break;
  42471. bool checkSize = false;
  42472. if (tempAtomIndex >= section->getNumAtoms())
  42473. {
  42474. if (++tempSectionIndex >= sections.size())
  42475. break;
  42476. tempAtomIndex = 0;
  42477. section = sections.getUnchecked (tempSectionIndex);
  42478. checkSize = true;
  42479. }
  42480. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42481. if (nextAtom == 0)
  42482. break;
  42483. x += nextAtom->width;
  42484. if (shouldWrap (x) || nextAtom->isNewLine())
  42485. break;
  42486. if (checkSize)
  42487. {
  42488. lineHeight = jmax (lineHeight, section->font.getHeight());
  42489. maxDescent = jmax (maxDescent, section->font.getDescent());
  42490. }
  42491. ++tempAtomIndex;
  42492. }
  42493. }
  42494. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42495. {
  42496. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42497. {
  42498. if (lastSection != currentSection)
  42499. {
  42500. lastSection = currentSection;
  42501. g.setColour (currentSection->colour);
  42502. g.setFont (currentSection->font);
  42503. }
  42504. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42505. GlyphArrangement ga;
  42506. ga.addLineOfText (currentSection->font,
  42507. atom->getTrimmedText (passwordCharacter),
  42508. atomX,
  42509. (float) roundToInt (lineY + lineHeight - maxDescent));
  42510. ga.draw (g);
  42511. }
  42512. }
  42513. void drawSelection (Graphics& g,
  42514. const Range<int>& selection) const
  42515. {
  42516. const int startX = roundToInt (indexToX (selection.getStart()));
  42517. const int endX = roundToInt (indexToX (selection.getEnd()));
  42518. const int y = roundToInt (lineY);
  42519. const int nextY = roundToInt (lineY + lineHeight);
  42520. g.fillRect (startX, y, endX - startX, nextY - y);
  42521. }
  42522. void drawSelectedText (Graphics& g,
  42523. const Range<int>& selection,
  42524. const Colour& selectedTextColour) const
  42525. {
  42526. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42527. {
  42528. GlyphArrangement ga;
  42529. ga.addLineOfText (currentSection->font,
  42530. atom->getTrimmedText (passwordCharacter),
  42531. atomX,
  42532. (float) roundToInt (lineY + lineHeight - maxDescent));
  42533. if (selection.getEnd() < indexInText + atom->numChars)
  42534. {
  42535. GlyphArrangement ga2 (ga);
  42536. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42537. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42538. g.setColour (currentSection->colour);
  42539. ga2.draw (g);
  42540. }
  42541. if (selection.getStart() > indexInText)
  42542. {
  42543. GlyphArrangement ga2 (ga);
  42544. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42545. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42546. g.setColour (currentSection->colour);
  42547. ga2.draw (g);
  42548. }
  42549. g.setColour (selectedTextColour);
  42550. ga.draw (g);
  42551. }
  42552. }
  42553. float indexToX (const int indexToFind) const
  42554. {
  42555. if (indexToFind <= indexInText)
  42556. return atomX;
  42557. if (indexToFind >= indexInText + atom->numChars)
  42558. return atomRight;
  42559. GlyphArrangement g;
  42560. g.addLineOfText (currentSection->font,
  42561. atom->getText (passwordCharacter),
  42562. atomX, 0.0f);
  42563. if (indexToFind - indexInText >= g.getNumGlyphs())
  42564. return atomRight;
  42565. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42566. }
  42567. int xToIndex (const float xToFind) const
  42568. {
  42569. if (xToFind <= atomX || atom->isNewLine())
  42570. return indexInText;
  42571. if (xToFind >= atomRight)
  42572. return indexInText + atom->numChars;
  42573. GlyphArrangement g;
  42574. g.addLineOfText (currentSection->font,
  42575. atom->getText (passwordCharacter),
  42576. atomX, 0.0f);
  42577. int j;
  42578. for (j = 0; j < g.getNumGlyphs(); ++j)
  42579. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42580. break;
  42581. return indexInText + j;
  42582. }
  42583. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42584. {
  42585. while (next())
  42586. {
  42587. if (indexInText + atom->numChars > index)
  42588. {
  42589. cx = indexToX (index);
  42590. cy = lineY;
  42591. lineHeight_ = lineHeight;
  42592. return true;
  42593. }
  42594. }
  42595. cx = atomX;
  42596. cy = lineY;
  42597. lineHeight_ = lineHeight;
  42598. return false;
  42599. }
  42600. int indexInText;
  42601. float lineY, lineHeight, maxDescent;
  42602. float atomX, atomRight;
  42603. const TextAtom* atom;
  42604. const UniformTextSection* currentSection;
  42605. private:
  42606. const Array <UniformTextSection*>& sections;
  42607. int sectionIndex, atomIndex;
  42608. const float wordWrapWidth;
  42609. const juce_wchar passwordCharacter;
  42610. TextAtom tempAtom;
  42611. Iterator& operator= (const Iterator&);
  42612. void moveToEndOfLastAtom()
  42613. {
  42614. if (atom != 0)
  42615. {
  42616. atomX = atomRight;
  42617. if (atom->isNewLine())
  42618. {
  42619. atomX = 0.0f;
  42620. lineY += lineHeight;
  42621. }
  42622. }
  42623. }
  42624. bool shouldWrap (const float x) const
  42625. {
  42626. return (x - 0.0001f) >= wordWrapWidth;
  42627. }
  42628. JUCE_LEAK_DETECTOR (Iterator);
  42629. };
  42630. class TextEditor::InsertAction : public UndoableAction
  42631. {
  42632. public:
  42633. InsertAction (TextEditor& owner_,
  42634. const String& text_,
  42635. const int insertIndex_,
  42636. const Font& font_,
  42637. const Colour& colour_,
  42638. const int oldCaretPos_,
  42639. const int newCaretPos_)
  42640. : owner (owner_),
  42641. text (text_),
  42642. insertIndex (insertIndex_),
  42643. oldCaretPos (oldCaretPos_),
  42644. newCaretPos (newCaretPos_),
  42645. font (font_),
  42646. colour (colour_)
  42647. {
  42648. }
  42649. bool perform()
  42650. {
  42651. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42652. return true;
  42653. }
  42654. bool undo()
  42655. {
  42656. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42657. return true;
  42658. }
  42659. int getSizeInUnits()
  42660. {
  42661. return text.length() + 16;
  42662. }
  42663. private:
  42664. TextEditor& owner;
  42665. const String text;
  42666. const int insertIndex, oldCaretPos, newCaretPos;
  42667. const Font font;
  42668. const Colour colour;
  42669. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42670. };
  42671. class TextEditor::RemoveAction : public UndoableAction
  42672. {
  42673. public:
  42674. RemoveAction (TextEditor& owner_,
  42675. const Range<int> range_,
  42676. const int oldCaretPos_,
  42677. const int newCaretPos_,
  42678. const Array <UniformTextSection*>& removedSections_)
  42679. : owner (owner_),
  42680. range (range_),
  42681. oldCaretPos (oldCaretPos_),
  42682. newCaretPos (newCaretPos_),
  42683. removedSections (removedSections_)
  42684. {
  42685. }
  42686. ~RemoveAction()
  42687. {
  42688. for (int i = removedSections.size(); --i >= 0;)
  42689. {
  42690. UniformTextSection* const section = removedSections.getUnchecked (i);
  42691. section->clear();
  42692. delete section;
  42693. }
  42694. }
  42695. bool perform()
  42696. {
  42697. owner.remove (range, 0, newCaretPos);
  42698. return true;
  42699. }
  42700. bool undo()
  42701. {
  42702. owner.reinsert (range.getStart(), removedSections);
  42703. owner.moveCursorTo (oldCaretPos, false);
  42704. return true;
  42705. }
  42706. int getSizeInUnits()
  42707. {
  42708. int n = 0;
  42709. for (int i = removedSections.size(); --i >= 0;)
  42710. n += removedSections.getUnchecked (i)->getTotalLength();
  42711. return n + 16;
  42712. }
  42713. private:
  42714. TextEditor& owner;
  42715. const Range<int> range;
  42716. const int oldCaretPos, newCaretPos;
  42717. Array <UniformTextSection*> removedSections;
  42718. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42719. };
  42720. class TextEditor::TextHolderComponent : public Component,
  42721. public Timer,
  42722. public ValueListener
  42723. {
  42724. public:
  42725. TextHolderComponent (TextEditor& owner_)
  42726. : owner (owner_)
  42727. {
  42728. setWantsKeyboardFocus (false);
  42729. setInterceptsMouseClicks (false, true);
  42730. owner.getTextValue().addListener (this);
  42731. }
  42732. ~TextHolderComponent()
  42733. {
  42734. owner.getTextValue().removeListener (this);
  42735. }
  42736. void paint (Graphics& g)
  42737. {
  42738. owner.drawContent (g);
  42739. }
  42740. void timerCallback()
  42741. {
  42742. owner.timerCallbackInt();
  42743. }
  42744. const MouseCursor getMouseCursor()
  42745. {
  42746. return owner.getMouseCursor();
  42747. }
  42748. void valueChanged (Value&)
  42749. {
  42750. owner.textWasChangedByValue();
  42751. }
  42752. private:
  42753. TextEditor& owner;
  42754. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42755. };
  42756. class TextEditorViewport : public Viewport
  42757. {
  42758. public:
  42759. TextEditorViewport (TextEditor* const owner_)
  42760. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42761. {
  42762. }
  42763. ~TextEditorViewport()
  42764. {
  42765. }
  42766. void visibleAreaChanged (int, int, int, int)
  42767. {
  42768. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42769. // appear and disappear, causing the wrap width to change.
  42770. {
  42771. const float wordWrapWidth = owner->getWordWrapWidth();
  42772. if (wordWrapWidth != lastWordWrapWidth)
  42773. {
  42774. lastWordWrapWidth = wordWrapWidth;
  42775. rentrant = true;
  42776. owner->updateTextHolderSize();
  42777. rentrant = false;
  42778. }
  42779. }
  42780. }
  42781. private:
  42782. TextEditor* const owner;
  42783. float lastWordWrapWidth;
  42784. bool rentrant;
  42785. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42786. };
  42787. namespace TextEditorDefs
  42788. {
  42789. const int flashSpeedIntervalMs = 380;
  42790. const int textChangeMessageId = 0x10003001;
  42791. const int returnKeyMessageId = 0x10003002;
  42792. const int escapeKeyMessageId = 0x10003003;
  42793. const int focusLossMessageId = 0x10003004;
  42794. const int maxActionsPerTransaction = 100;
  42795. int getCharacterCategory (const juce_wchar character)
  42796. {
  42797. return CharacterFunctions::isLetterOrDigit (character)
  42798. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42799. }
  42800. }
  42801. TextEditor::TextEditor (const String& name,
  42802. const juce_wchar passwordCharacter_)
  42803. : Component (name),
  42804. borderSize (1, 1, 1, 3),
  42805. readOnly (false),
  42806. multiline (false),
  42807. wordWrap (false),
  42808. returnKeyStartsNewLine (false),
  42809. caretVisible (true),
  42810. popupMenuEnabled (true),
  42811. selectAllTextWhenFocused (false),
  42812. scrollbarVisible (true),
  42813. wasFocused (false),
  42814. caretFlashState (true),
  42815. keepCursorOnScreen (true),
  42816. tabKeyUsed (false),
  42817. menuActive (false),
  42818. valueTextNeedsUpdating (false),
  42819. cursorX (0),
  42820. cursorY (0),
  42821. cursorHeight (0),
  42822. maxTextLength (0),
  42823. leftIndent (4),
  42824. topIndent (4),
  42825. lastTransactionTime (0),
  42826. currentFont (14.0f),
  42827. totalNumChars (0),
  42828. caretPosition (0),
  42829. passwordCharacter (passwordCharacter_),
  42830. dragType (notDragging)
  42831. {
  42832. setOpaque (true);
  42833. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42834. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42835. viewport->setWantsKeyboardFocus (false);
  42836. viewport->setScrollBarsShown (false, false);
  42837. setMouseCursor (MouseCursor::IBeamCursor);
  42838. setWantsKeyboardFocus (true);
  42839. }
  42840. TextEditor::~TextEditor()
  42841. {
  42842. textValue.referTo (Value());
  42843. clearInternal (0);
  42844. viewport = 0;
  42845. textHolder = 0;
  42846. }
  42847. void TextEditor::newTransaction()
  42848. {
  42849. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42850. undoManager.beginNewTransaction();
  42851. }
  42852. void TextEditor::doUndoRedo (const bool isRedo)
  42853. {
  42854. if (! isReadOnly())
  42855. {
  42856. if (isRedo ? undoManager.redo()
  42857. : undoManager.undo())
  42858. {
  42859. scrollToMakeSureCursorIsVisible();
  42860. repaint();
  42861. textChanged();
  42862. }
  42863. }
  42864. }
  42865. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42866. const bool shouldWordWrap)
  42867. {
  42868. if (multiline != shouldBeMultiLine
  42869. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42870. {
  42871. multiline = shouldBeMultiLine;
  42872. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42873. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42874. scrollbarVisible && multiline);
  42875. viewport->setViewPosition (0, 0);
  42876. resized();
  42877. scrollToMakeSureCursorIsVisible();
  42878. }
  42879. }
  42880. bool TextEditor::isMultiLine() const
  42881. {
  42882. return multiline;
  42883. }
  42884. void TextEditor::setScrollbarsShown (bool shown)
  42885. {
  42886. if (scrollbarVisible != shown)
  42887. {
  42888. scrollbarVisible = shown;
  42889. shown = shown && isMultiLine();
  42890. viewport->setScrollBarsShown (shown, shown);
  42891. }
  42892. }
  42893. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42894. {
  42895. if (readOnly != shouldBeReadOnly)
  42896. {
  42897. readOnly = shouldBeReadOnly;
  42898. enablementChanged();
  42899. }
  42900. }
  42901. bool TextEditor::isReadOnly() const
  42902. {
  42903. return readOnly || ! isEnabled();
  42904. }
  42905. bool TextEditor::isTextInputActive() const
  42906. {
  42907. return ! isReadOnly();
  42908. }
  42909. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42910. {
  42911. returnKeyStartsNewLine = shouldStartNewLine;
  42912. }
  42913. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42914. {
  42915. tabKeyUsed = shouldTabKeyBeUsed;
  42916. }
  42917. void TextEditor::setPopupMenuEnabled (const bool b)
  42918. {
  42919. popupMenuEnabled = b;
  42920. }
  42921. void TextEditor::setSelectAllWhenFocused (const bool b)
  42922. {
  42923. selectAllTextWhenFocused = b;
  42924. }
  42925. const Font TextEditor::getFont() const
  42926. {
  42927. return currentFont;
  42928. }
  42929. void TextEditor::setFont (const Font& newFont)
  42930. {
  42931. currentFont = newFont;
  42932. scrollToMakeSureCursorIsVisible();
  42933. }
  42934. void TextEditor::applyFontToAllText (const Font& newFont)
  42935. {
  42936. currentFont = newFont;
  42937. const Colour overallColour (findColour (textColourId));
  42938. for (int i = sections.size(); --i >= 0;)
  42939. {
  42940. UniformTextSection* const uts = sections.getUnchecked (i);
  42941. uts->setFont (newFont, passwordCharacter);
  42942. uts->colour = overallColour;
  42943. }
  42944. coalesceSimilarSections();
  42945. updateTextHolderSize();
  42946. scrollToMakeSureCursorIsVisible();
  42947. repaint();
  42948. }
  42949. void TextEditor::colourChanged()
  42950. {
  42951. setOpaque (findColour (backgroundColourId).isOpaque());
  42952. repaint();
  42953. }
  42954. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42955. {
  42956. caretVisible = shouldCaretBeVisible;
  42957. if (shouldCaretBeVisible)
  42958. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42959. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42960. : MouseCursor::NormalCursor);
  42961. }
  42962. void TextEditor::setInputRestrictions (const int maxLen,
  42963. const String& chars)
  42964. {
  42965. maxTextLength = jmax (0, maxLen);
  42966. allowedCharacters = chars;
  42967. }
  42968. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42969. {
  42970. textToShowWhenEmpty = text;
  42971. colourForTextWhenEmpty = colourToUse;
  42972. }
  42973. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42974. {
  42975. if (passwordCharacter != newPasswordCharacter)
  42976. {
  42977. passwordCharacter = newPasswordCharacter;
  42978. resized();
  42979. repaint();
  42980. }
  42981. }
  42982. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42983. {
  42984. viewport->setScrollBarThickness (newThicknessPixels);
  42985. }
  42986. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42987. {
  42988. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42989. }
  42990. void TextEditor::clear()
  42991. {
  42992. clearInternal (0);
  42993. updateTextHolderSize();
  42994. undoManager.clearUndoHistory();
  42995. }
  42996. void TextEditor::setText (const String& newText,
  42997. const bool sendTextChangeMessage)
  42998. {
  42999. const int newLength = newText.length();
  43000. if (newLength != getTotalNumChars() || getText() != newText)
  43001. {
  43002. const int oldCursorPos = caretPosition;
  43003. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43004. clearInternal (0);
  43005. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43006. // if you're adding text with line-feeds to a single-line text editor, it
  43007. // ain't gonna look right!
  43008. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43009. if (cursorWasAtEnd && ! isMultiLine())
  43010. moveCursorTo (getTotalNumChars(), false);
  43011. else
  43012. moveCursorTo (oldCursorPos, false);
  43013. if (sendTextChangeMessage)
  43014. textChanged();
  43015. updateTextHolderSize();
  43016. scrollToMakeSureCursorIsVisible();
  43017. undoManager.clearUndoHistory();
  43018. repaint();
  43019. }
  43020. }
  43021. Value& TextEditor::getTextValue()
  43022. {
  43023. if (valueTextNeedsUpdating)
  43024. {
  43025. valueTextNeedsUpdating = false;
  43026. textValue = getText();
  43027. }
  43028. return textValue;
  43029. }
  43030. void TextEditor::textWasChangedByValue()
  43031. {
  43032. if (textValue.getValueSource().getReferenceCount() > 1)
  43033. setText (textValue.getValue());
  43034. }
  43035. void TextEditor::textChanged()
  43036. {
  43037. updateTextHolderSize();
  43038. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43039. if (textValue.getValueSource().getReferenceCount() > 1)
  43040. {
  43041. valueTextNeedsUpdating = false;
  43042. textValue = getText();
  43043. }
  43044. }
  43045. void TextEditor::returnPressed()
  43046. {
  43047. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43048. }
  43049. void TextEditor::escapePressed()
  43050. {
  43051. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43052. }
  43053. void TextEditor::addListener (TextEditorListener* const newListener)
  43054. {
  43055. listeners.add (newListener);
  43056. }
  43057. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  43058. {
  43059. listeners.remove (listenerToRemove);
  43060. }
  43061. void TextEditor::timerCallbackInt()
  43062. {
  43063. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43064. if (caretFlashState != newState)
  43065. {
  43066. caretFlashState = newState;
  43067. if (caretFlashState)
  43068. wasFocused = true;
  43069. if (caretVisible
  43070. && hasKeyboardFocus (false)
  43071. && ! isReadOnly())
  43072. {
  43073. repaintCaret();
  43074. }
  43075. }
  43076. const unsigned int now = Time::getApproximateMillisecondCounter();
  43077. if (now > lastTransactionTime + 200)
  43078. newTransaction();
  43079. }
  43080. void TextEditor::repaintCaret()
  43081. {
  43082. if (! findColour (caretColourId).isTransparent())
  43083. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43084. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43085. 4,
  43086. roundToInt (cursorHeight) + 2);
  43087. }
  43088. void TextEditor::repaintText (const Range<int>& range)
  43089. {
  43090. if (! range.isEmpty())
  43091. {
  43092. float x = 0, y = 0, lh = currentFont.getHeight();
  43093. const float wordWrapWidth = getWordWrapWidth();
  43094. if (wordWrapWidth > 0)
  43095. {
  43096. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43097. i.getCharPosition (range.getStart(), x, y, lh);
  43098. const int y1 = (int) y;
  43099. int y2;
  43100. if (range.getEnd() >= getTotalNumChars())
  43101. {
  43102. y2 = textHolder->getHeight();
  43103. }
  43104. else
  43105. {
  43106. i.getCharPosition (range.getEnd(), x, y, lh);
  43107. y2 = (int) (y + lh * 2.0f);
  43108. }
  43109. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43110. }
  43111. }
  43112. }
  43113. void TextEditor::moveCaret (int newCaretPos)
  43114. {
  43115. if (newCaretPos < 0)
  43116. newCaretPos = 0;
  43117. else if (newCaretPos > getTotalNumChars())
  43118. newCaretPos = getTotalNumChars();
  43119. if (newCaretPos != getCaretPosition())
  43120. {
  43121. repaintCaret();
  43122. caretFlashState = true;
  43123. caretPosition = newCaretPos;
  43124. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43125. scrollToMakeSureCursorIsVisible();
  43126. repaintCaret();
  43127. }
  43128. }
  43129. void TextEditor::setCaretPosition (const int newIndex)
  43130. {
  43131. moveCursorTo (newIndex, false);
  43132. }
  43133. int TextEditor::getCaretPosition() const
  43134. {
  43135. return caretPosition;
  43136. }
  43137. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43138. const int desiredCaretY)
  43139. {
  43140. updateCaretPosition();
  43141. int vx = roundToInt (cursorX) - desiredCaretX;
  43142. int vy = roundToInt (cursorY) - desiredCaretY;
  43143. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43144. {
  43145. vx += desiredCaretX - proportionOfWidth (0.2f);
  43146. }
  43147. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43148. {
  43149. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43150. }
  43151. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43152. if (! isMultiLine())
  43153. {
  43154. vy = viewport->getViewPositionY();
  43155. }
  43156. else
  43157. {
  43158. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43159. const int curH = roundToInt (cursorHeight);
  43160. if (desiredCaretY < 0)
  43161. {
  43162. vy = jmax (0, desiredCaretY + vy);
  43163. }
  43164. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43165. {
  43166. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43167. }
  43168. }
  43169. viewport->setViewPosition (vx, vy);
  43170. }
  43171. const Rectangle<int> TextEditor::getCaretRectangle()
  43172. {
  43173. updateCaretPosition();
  43174. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43175. roundToInt (cursorY) - viewport->getY(),
  43176. 1, roundToInt (cursorHeight));
  43177. }
  43178. float TextEditor::getWordWrapWidth() const
  43179. {
  43180. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43181. : 1.0e10f;
  43182. }
  43183. void TextEditor::updateTextHolderSize()
  43184. {
  43185. const float wordWrapWidth = getWordWrapWidth();
  43186. if (wordWrapWidth > 0)
  43187. {
  43188. float maxWidth = 0.0f;
  43189. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43190. while (i.next())
  43191. maxWidth = jmax (maxWidth, i.atomRight);
  43192. const int w = leftIndent + roundToInt (maxWidth);
  43193. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43194. currentFont.getHeight()));
  43195. textHolder->setSize (w + 1, h + 1);
  43196. }
  43197. }
  43198. int TextEditor::getTextWidth() const
  43199. {
  43200. return textHolder->getWidth();
  43201. }
  43202. int TextEditor::getTextHeight() const
  43203. {
  43204. return textHolder->getHeight();
  43205. }
  43206. void TextEditor::setIndents (const int newLeftIndent,
  43207. const int newTopIndent)
  43208. {
  43209. leftIndent = newLeftIndent;
  43210. topIndent = newTopIndent;
  43211. }
  43212. void TextEditor::setBorder (const BorderSize& border)
  43213. {
  43214. borderSize = border;
  43215. resized();
  43216. }
  43217. const BorderSize TextEditor::getBorder() const
  43218. {
  43219. return borderSize;
  43220. }
  43221. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43222. {
  43223. keepCursorOnScreen = shouldScrollToShowCursor;
  43224. }
  43225. void TextEditor::updateCaretPosition()
  43226. {
  43227. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43228. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43229. }
  43230. void TextEditor::scrollToMakeSureCursorIsVisible()
  43231. {
  43232. updateCaretPosition();
  43233. if (keepCursorOnScreen)
  43234. {
  43235. int x = viewport->getViewPositionX();
  43236. int y = viewport->getViewPositionY();
  43237. const int relativeCursorX = roundToInt (cursorX) - x;
  43238. const int relativeCursorY = roundToInt (cursorY) - y;
  43239. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43240. {
  43241. x += relativeCursorX - proportionOfWidth (0.2f);
  43242. }
  43243. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43244. {
  43245. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43246. }
  43247. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43248. if (! isMultiLine())
  43249. {
  43250. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43251. }
  43252. else
  43253. {
  43254. const int curH = roundToInt (cursorHeight);
  43255. if (relativeCursorY < 0)
  43256. {
  43257. y = jmax (0, relativeCursorY + y);
  43258. }
  43259. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43260. {
  43261. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43262. }
  43263. }
  43264. viewport->setViewPosition (x, y);
  43265. }
  43266. }
  43267. void TextEditor::moveCursorTo (const int newPosition,
  43268. const bool isSelecting)
  43269. {
  43270. if (isSelecting)
  43271. {
  43272. moveCaret (newPosition);
  43273. const Range<int> oldSelection (selection);
  43274. if (dragType == notDragging)
  43275. {
  43276. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43277. dragType = draggingSelectionStart;
  43278. else
  43279. dragType = draggingSelectionEnd;
  43280. }
  43281. if (dragType == draggingSelectionStart)
  43282. {
  43283. if (getCaretPosition() >= selection.getEnd())
  43284. dragType = draggingSelectionEnd;
  43285. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43286. }
  43287. else
  43288. {
  43289. if (getCaretPosition() < selection.getStart())
  43290. dragType = draggingSelectionStart;
  43291. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43292. }
  43293. repaintText (selection.getUnionWith (oldSelection));
  43294. }
  43295. else
  43296. {
  43297. dragType = notDragging;
  43298. repaintText (selection);
  43299. moveCaret (newPosition);
  43300. selection = Range<int>::emptyRange (getCaretPosition());
  43301. }
  43302. }
  43303. int TextEditor::getTextIndexAt (const int x,
  43304. const int y)
  43305. {
  43306. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43307. (float) (y + viewport->getViewPositionY() - topIndent));
  43308. }
  43309. void TextEditor::insertTextAtCaret (const String& newText_)
  43310. {
  43311. String newText (newText_);
  43312. if (allowedCharacters.isNotEmpty())
  43313. newText = newText.retainCharacters (allowedCharacters);
  43314. if (! isMultiLine())
  43315. newText = newText.replaceCharacters ("\r\n", " ");
  43316. else
  43317. newText = newText.replace ("\r\n", "\n");
  43318. const int newCaretPos = selection.getStart() + newText.length();
  43319. const int insertIndex = selection.getStart();
  43320. remove (selection, getUndoManager(),
  43321. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43322. if (maxTextLength > 0)
  43323. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43324. if (newText.isNotEmpty())
  43325. insert (newText,
  43326. insertIndex,
  43327. currentFont,
  43328. findColour (textColourId),
  43329. getUndoManager(),
  43330. newCaretPos);
  43331. textChanged();
  43332. }
  43333. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43334. {
  43335. moveCursorTo (newSelection.getStart(), false);
  43336. moveCursorTo (newSelection.getEnd(), true);
  43337. }
  43338. void TextEditor::copy()
  43339. {
  43340. if (passwordCharacter == 0)
  43341. {
  43342. const String selectedText (getHighlightedText());
  43343. if (selectedText.isNotEmpty())
  43344. SystemClipboard::copyTextToClipboard (selectedText);
  43345. }
  43346. }
  43347. void TextEditor::paste()
  43348. {
  43349. if (! isReadOnly())
  43350. {
  43351. const String clip (SystemClipboard::getTextFromClipboard());
  43352. if (clip.isNotEmpty())
  43353. insertTextAtCaret (clip);
  43354. }
  43355. }
  43356. void TextEditor::cut()
  43357. {
  43358. if (! isReadOnly())
  43359. {
  43360. moveCaret (selection.getEnd());
  43361. insertTextAtCaret (String::empty);
  43362. }
  43363. }
  43364. void TextEditor::drawContent (Graphics& g)
  43365. {
  43366. const float wordWrapWidth = getWordWrapWidth();
  43367. if (wordWrapWidth > 0)
  43368. {
  43369. g.setOrigin (leftIndent, topIndent);
  43370. const Rectangle<int> clip (g.getClipBounds());
  43371. Colour selectedTextColour;
  43372. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43373. while (i.lineY + 200.0 < clip.getY() && i.next())
  43374. {}
  43375. if (! selection.isEmpty())
  43376. {
  43377. g.setColour (findColour (highlightColourId)
  43378. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43379. selectedTextColour = findColour (highlightedTextColourId);
  43380. Iterator i2 (i);
  43381. while (i2.next() && i2.lineY < clip.getBottom())
  43382. {
  43383. if (i2.lineY + i2.lineHeight >= clip.getY()
  43384. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43385. {
  43386. i2.drawSelection (g, selection);
  43387. }
  43388. }
  43389. }
  43390. const UniformTextSection* lastSection = 0;
  43391. while (i.next() && i.lineY < clip.getBottom())
  43392. {
  43393. if (i.lineY + i.lineHeight >= clip.getY())
  43394. {
  43395. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43396. {
  43397. i.drawSelectedText (g, selection, selectedTextColour);
  43398. lastSection = 0;
  43399. }
  43400. else
  43401. {
  43402. i.draw (g, lastSection);
  43403. }
  43404. }
  43405. }
  43406. }
  43407. }
  43408. void TextEditor::paint (Graphics& g)
  43409. {
  43410. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43411. }
  43412. void TextEditor::paintOverChildren (Graphics& g)
  43413. {
  43414. if (caretFlashState
  43415. && hasKeyboardFocus (false)
  43416. && caretVisible
  43417. && ! isReadOnly())
  43418. {
  43419. g.setColour (findColour (caretColourId));
  43420. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43421. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43422. 2.0f, cursorHeight);
  43423. }
  43424. if (textToShowWhenEmpty.isNotEmpty()
  43425. && (! hasKeyboardFocus (false))
  43426. && getTotalNumChars() == 0)
  43427. {
  43428. g.setColour (colourForTextWhenEmpty);
  43429. g.setFont (getFont());
  43430. if (isMultiLine())
  43431. {
  43432. g.drawText (textToShowWhenEmpty,
  43433. 0, 0, getWidth(), getHeight(),
  43434. Justification::centred, true);
  43435. }
  43436. else
  43437. {
  43438. g.drawText (textToShowWhenEmpty,
  43439. leftIndent, topIndent,
  43440. viewport->getWidth() - leftIndent,
  43441. viewport->getHeight() - topIndent,
  43442. Justification::centredLeft, true);
  43443. }
  43444. }
  43445. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43446. }
  43447. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43448. {
  43449. public:
  43450. TextEditorMenuPerformer (TextEditor* const editor_)
  43451. : editor (editor_)
  43452. {
  43453. }
  43454. void modalStateFinished (int returnValue)
  43455. {
  43456. if (editor != 0 && returnValue != 0)
  43457. editor->performPopupMenuAction (returnValue);
  43458. }
  43459. private:
  43460. Component::SafePointer<TextEditor> editor;
  43461. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43462. };
  43463. void TextEditor::mouseDown (const MouseEvent& e)
  43464. {
  43465. beginDragAutoRepeat (100);
  43466. newTransaction();
  43467. if (wasFocused || ! selectAllTextWhenFocused)
  43468. {
  43469. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43470. {
  43471. moveCursorTo (getTextIndexAt (e.x, e.y),
  43472. e.mods.isShiftDown());
  43473. }
  43474. else
  43475. {
  43476. PopupMenu m;
  43477. m.setLookAndFeel (&getLookAndFeel());
  43478. addPopupMenuItems (m, &e);
  43479. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43480. }
  43481. }
  43482. }
  43483. void TextEditor::mouseDrag (const MouseEvent& e)
  43484. {
  43485. if (wasFocused || ! selectAllTextWhenFocused)
  43486. {
  43487. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43488. {
  43489. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43490. }
  43491. }
  43492. }
  43493. void TextEditor::mouseUp (const MouseEvent& e)
  43494. {
  43495. newTransaction();
  43496. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43497. if (wasFocused || ! selectAllTextWhenFocused)
  43498. {
  43499. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43500. {
  43501. moveCaret (getTextIndexAt (e.x, e.y));
  43502. }
  43503. }
  43504. wasFocused = true;
  43505. }
  43506. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43507. {
  43508. int tokenEnd = getTextIndexAt (e.x, e.y);
  43509. int tokenStart = tokenEnd;
  43510. if (e.getNumberOfClicks() > 3)
  43511. {
  43512. tokenStart = 0;
  43513. tokenEnd = getTotalNumChars();
  43514. }
  43515. else
  43516. {
  43517. const String t (getText());
  43518. const int totalLength = getTotalNumChars();
  43519. while (tokenEnd < totalLength)
  43520. {
  43521. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43522. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43523. ++tokenEnd;
  43524. else
  43525. break;
  43526. }
  43527. tokenStart = tokenEnd;
  43528. while (tokenStart > 0)
  43529. {
  43530. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43531. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43532. --tokenStart;
  43533. else
  43534. break;
  43535. }
  43536. if (e.getNumberOfClicks() > 2)
  43537. {
  43538. while (tokenEnd < totalLength)
  43539. {
  43540. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43541. ++tokenEnd;
  43542. else
  43543. break;
  43544. }
  43545. while (tokenStart > 0)
  43546. {
  43547. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43548. --tokenStart;
  43549. else
  43550. break;
  43551. }
  43552. }
  43553. }
  43554. moveCursorTo (tokenEnd, false);
  43555. moveCursorTo (tokenStart, true);
  43556. }
  43557. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43558. {
  43559. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43560. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43561. }
  43562. bool TextEditor::keyPressed (const KeyPress& key)
  43563. {
  43564. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43565. return false;
  43566. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43567. if (key.isKeyCode (KeyPress::leftKey)
  43568. || key.isKeyCode (KeyPress::upKey))
  43569. {
  43570. newTransaction();
  43571. int newPos;
  43572. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43573. newPos = indexAtPosition (cursorX, cursorY - 1);
  43574. else if (moveInWholeWordSteps)
  43575. newPos = findWordBreakBefore (getCaretPosition());
  43576. else
  43577. newPos = getCaretPosition() - 1;
  43578. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43579. }
  43580. else if (key.isKeyCode (KeyPress::rightKey)
  43581. || key.isKeyCode (KeyPress::downKey))
  43582. {
  43583. newTransaction();
  43584. int newPos;
  43585. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43586. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43587. else if (moveInWholeWordSteps)
  43588. newPos = findWordBreakAfter (getCaretPosition());
  43589. else
  43590. newPos = getCaretPosition() + 1;
  43591. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43592. }
  43593. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43594. {
  43595. newTransaction();
  43596. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43597. key.getModifiers().isShiftDown());
  43598. }
  43599. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43600. {
  43601. newTransaction();
  43602. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43603. key.getModifiers().isShiftDown());
  43604. }
  43605. else if (key.isKeyCode (KeyPress::homeKey))
  43606. {
  43607. newTransaction();
  43608. if (isMultiLine() && ! moveInWholeWordSteps)
  43609. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43610. key.getModifiers().isShiftDown());
  43611. else
  43612. moveCursorTo (0, key.getModifiers().isShiftDown());
  43613. }
  43614. else if (key.isKeyCode (KeyPress::endKey))
  43615. {
  43616. newTransaction();
  43617. if (isMultiLine() && ! moveInWholeWordSteps)
  43618. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43619. key.getModifiers().isShiftDown());
  43620. else
  43621. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43622. }
  43623. else if (key.isKeyCode (KeyPress::backspaceKey))
  43624. {
  43625. if (moveInWholeWordSteps)
  43626. {
  43627. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43628. }
  43629. else
  43630. {
  43631. if (selection.isEmpty() && selection.getStart() > 0)
  43632. selection.setStart (selection.getEnd() - 1);
  43633. }
  43634. cut();
  43635. }
  43636. else if (key.isKeyCode (KeyPress::deleteKey))
  43637. {
  43638. if (key.getModifiers().isShiftDown())
  43639. copy();
  43640. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43641. selection.setEnd (selection.getStart() + 1);
  43642. cut();
  43643. }
  43644. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43645. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43646. {
  43647. newTransaction();
  43648. copy();
  43649. }
  43650. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43651. {
  43652. newTransaction();
  43653. copy();
  43654. cut();
  43655. }
  43656. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43657. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43658. {
  43659. newTransaction();
  43660. paste();
  43661. }
  43662. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43663. {
  43664. newTransaction();
  43665. doUndoRedo (false);
  43666. }
  43667. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43668. {
  43669. newTransaction();
  43670. doUndoRedo (true);
  43671. }
  43672. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43673. {
  43674. newTransaction();
  43675. moveCursorTo (getTotalNumChars(), false);
  43676. moveCursorTo (0, true);
  43677. }
  43678. else if (key == KeyPress::returnKey)
  43679. {
  43680. newTransaction();
  43681. if (returnKeyStartsNewLine)
  43682. insertTextAtCaret ("\n");
  43683. else
  43684. returnPressed();
  43685. }
  43686. else if (key.isKeyCode (KeyPress::escapeKey))
  43687. {
  43688. newTransaction();
  43689. moveCursorTo (getCaretPosition(), false);
  43690. escapePressed();
  43691. }
  43692. else if (key.getTextCharacter() >= ' '
  43693. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43694. {
  43695. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43696. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43697. }
  43698. else
  43699. {
  43700. return false;
  43701. }
  43702. return true;
  43703. }
  43704. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43705. {
  43706. if (! isKeyDown)
  43707. return false;
  43708. #if JUCE_WINDOWS
  43709. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43710. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43711. #endif
  43712. // (overridden to avoid forwarding key events to the parent)
  43713. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43714. }
  43715. const int baseMenuItemID = 0x7fff0000;
  43716. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43717. {
  43718. const bool writable = ! isReadOnly();
  43719. if (passwordCharacter == 0)
  43720. {
  43721. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43722. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43723. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43724. }
  43725. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43726. m.addSeparator();
  43727. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43728. m.addSeparator();
  43729. if (getUndoManager() != 0)
  43730. {
  43731. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43732. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43733. }
  43734. }
  43735. void TextEditor::performPopupMenuAction (const int menuItemID)
  43736. {
  43737. switch (menuItemID)
  43738. {
  43739. case baseMenuItemID + 1:
  43740. copy();
  43741. cut();
  43742. break;
  43743. case baseMenuItemID + 2:
  43744. copy();
  43745. break;
  43746. case baseMenuItemID + 3:
  43747. paste();
  43748. break;
  43749. case baseMenuItemID + 4:
  43750. cut();
  43751. break;
  43752. case baseMenuItemID + 5:
  43753. moveCursorTo (getTotalNumChars(), false);
  43754. moveCursorTo (0, true);
  43755. break;
  43756. case baseMenuItemID + 6:
  43757. doUndoRedo (false);
  43758. break;
  43759. case baseMenuItemID + 7:
  43760. doUndoRedo (true);
  43761. break;
  43762. default:
  43763. break;
  43764. }
  43765. }
  43766. void TextEditor::focusGained (FocusChangeType)
  43767. {
  43768. newTransaction();
  43769. caretFlashState = true;
  43770. if (selectAllTextWhenFocused)
  43771. {
  43772. moveCursorTo (0, false);
  43773. moveCursorTo (getTotalNumChars(), true);
  43774. }
  43775. repaint();
  43776. if (caretVisible)
  43777. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43778. ComponentPeer* const peer = getPeer();
  43779. if (peer != 0 && ! isReadOnly())
  43780. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43781. }
  43782. void TextEditor::focusLost (FocusChangeType)
  43783. {
  43784. newTransaction();
  43785. wasFocused = false;
  43786. textHolder->stopTimer();
  43787. caretFlashState = false;
  43788. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43789. repaint();
  43790. }
  43791. void TextEditor::resized()
  43792. {
  43793. viewport->setBoundsInset (borderSize);
  43794. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43795. updateTextHolderSize();
  43796. if (! isMultiLine())
  43797. {
  43798. scrollToMakeSureCursorIsVisible();
  43799. }
  43800. else
  43801. {
  43802. updateCaretPosition();
  43803. }
  43804. }
  43805. void TextEditor::handleCommandMessage (const int commandId)
  43806. {
  43807. Component::BailOutChecker checker (this);
  43808. switch (commandId)
  43809. {
  43810. case TextEditorDefs::textChangeMessageId:
  43811. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43812. break;
  43813. case TextEditorDefs::returnKeyMessageId:
  43814. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43815. break;
  43816. case TextEditorDefs::escapeKeyMessageId:
  43817. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43818. break;
  43819. case TextEditorDefs::focusLossMessageId:
  43820. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43821. break;
  43822. default:
  43823. jassertfalse;
  43824. break;
  43825. }
  43826. }
  43827. void TextEditor::enablementChanged()
  43828. {
  43829. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43830. : MouseCursor::IBeamCursor);
  43831. repaint();
  43832. }
  43833. UndoManager* TextEditor::getUndoManager() throw()
  43834. {
  43835. return isReadOnly() ? 0 : &undoManager;
  43836. }
  43837. void TextEditor::clearInternal (UndoManager* const um)
  43838. {
  43839. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43840. }
  43841. void TextEditor::insert (const String& text,
  43842. const int insertIndex,
  43843. const Font& font,
  43844. const Colour& colour,
  43845. UndoManager* const um,
  43846. const int caretPositionToMoveTo)
  43847. {
  43848. if (text.isNotEmpty())
  43849. {
  43850. if (um != 0)
  43851. {
  43852. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43853. newTransaction();
  43854. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43855. caretPosition, caretPositionToMoveTo));
  43856. }
  43857. else
  43858. {
  43859. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43860. // a line gets moved due to word wrap
  43861. int index = 0;
  43862. int nextIndex = 0;
  43863. for (int i = 0; i < sections.size(); ++i)
  43864. {
  43865. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43866. if (insertIndex == index)
  43867. {
  43868. sections.insert (i, new UniformTextSection (text,
  43869. font, colour,
  43870. passwordCharacter));
  43871. break;
  43872. }
  43873. else if (insertIndex > index && insertIndex < nextIndex)
  43874. {
  43875. splitSection (i, insertIndex - index);
  43876. sections.insert (i + 1, new UniformTextSection (text,
  43877. font, colour,
  43878. passwordCharacter));
  43879. break;
  43880. }
  43881. index = nextIndex;
  43882. }
  43883. if (nextIndex == insertIndex)
  43884. sections.add (new UniformTextSection (text,
  43885. font, colour,
  43886. passwordCharacter));
  43887. coalesceSimilarSections();
  43888. totalNumChars = -1;
  43889. valueTextNeedsUpdating = true;
  43890. moveCursorTo (caretPositionToMoveTo, false);
  43891. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43892. }
  43893. }
  43894. }
  43895. void TextEditor::reinsert (const int insertIndex,
  43896. const Array <UniformTextSection*>& sectionsToInsert)
  43897. {
  43898. int index = 0;
  43899. int nextIndex = 0;
  43900. for (int i = 0; i < sections.size(); ++i)
  43901. {
  43902. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43903. if (insertIndex == index)
  43904. {
  43905. for (int j = sectionsToInsert.size(); --j >= 0;)
  43906. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43907. break;
  43908. }
  43909. else if (insertIndex > index && insertIndex < nextIndex)
  43910. {
  43911. splitSection (i, insertIndex - index);
  43912. for (int j = sectionsToInsert.size(); --j >= 0;)
  43913. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43914. break;
  43915. }
  43916. index = nextIndex;
  43917. }
  43918. if (nextIndex == insertIndex)
  43919. {
  43920. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43921. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43922. }
  43923. coalesceSimilarSections();
  43924. totalNumChars = -1;
  43925. valueTextNeedsUpdating = true;
  43926. }
  43927. void TextEditor::remove (const Range<int>& range,
  43928. UndoManager* const um,
  43929. const int caretPositionToMoveTo)
  43930. {
  43931. if (! range.isEmpty())
  43932. {
  43933. int index = 0;
  43934. for (int i = 0; i < sections.size(); ++i)
  43935. {
  43936. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43937. if (range.getStart() > index && range.getStart() < nextIndex)
  43938. {
  43939. splitSection (i, range.getStart() - index);
  43940. --i;
  43941. }
  43942. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43943. {
  43944. splitSection (i, range.getEnd() - index);
  43945. --i;
  43946. }
  43947. else
  43948. {
  43949. index = nextIndex;
  43950. if (index > range.getEnd())
  43951. break;
  43952. }
  43953. }
  43954. index = 0;
  43955. if (um != 0)
  43956. {
  43957. Array <UniformTextSection*> removedSections;
  43958. for (int i = 0; i < sections.size(); ++i)
  43959. {
  43960. if (range.getEnd() <= range.getStart())
  43961. break;
  43962. UniformTextSection* const section = sections.getUnchecked (i);
  43963. const int nextIndex = index + section->getTotalLength();
  43964. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43965. removedSections.add (new UniformTextSection (*section));
  43966. index = nextIndex;
  43967. }
  43968. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43969. newTransaction();
  43970. um->perform (new RemoveAction (*this, range, caretPosition,
  43971. caretPositionToMoveTo, removedSections));
  43972. }
  43973. else
  43974. {
  43975. Range<int> remainingRange (range);
  43976. for (int i = 0; i < sections.size(); ++i)
  43977. {
  43978. UniformTextSection* const section = sections.getUnchecked (i);
  43979. const int nextIndex = index + section->getTotalLength();
  43980. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43981. {
  43982. sections.remove(i);
  43983. section->clear();
  43984. delete section;
  43985. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43986. if (remainingRange.isEmpty())
  43987. break;
  43988. --i;
  43989. }
  43990. else
  43991. {
  43992. index = nextIndex;
  43993. }
  43994. }
  43995. coalesceSimilarSections();
  43996. totalNumChars = -1;
  43997. valueTextNeedsUpdating = true;
  43998. moveCursorTo (caretPositionToMoveTo, false);
  43999. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44000. }
  44001. }
  44002. }
  44003. const String TextEditor::getText() const
  44004. {
  44005. String t;
  44006. t.preallocateStorage (getTotalNumChars());
  44007. String::Concatenator concatenator (t);
  44008. for (int i = 0; i < sections.size(); ++i)
  44009. sections.getUnchecked (i)->appendAllText (concatenator);
  44010. return t;
  44011. }
  44012. const String TextEditor::getTextInRange (const Range<int>& range) const
  44013. {
  44014. String t;
  44015. if (! range.isEmpty())
  44016. {
  44017. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44018. String::Concatenator concatenator (t);
  44019. int index = 0;
  44020. for (int i = 0; i < sections.size(); ++i)
  44021. {
  44022. const UniformTextSection* const s = sections.getUnchecked (i);
  44023. const int nextIndex = index + s->getTotalLength();
  44024. if (range.getStart() < nextIndex)
  44025. {
  44026. if (range.getEnd() <= index)
  44027. break;
  44028. s->appendSubstring (concatenator, range - index);
  44029. }
  44030. index = nextIndex;
  44031. }
  44032. }
  44033. return t;
  44034. }
  44035. const String TextEditor::getHighlightedText() const
  44036. {
  44037. return getTextInRange (selection);
  44038. }
  44039. int TextEditor::getTotalNumChars() const
  44040. {
  44041. if (totalNumChars < 0)
  44042. {
  44043. totalNumChars = 0;
  44044. for (int i = sections.size(); --i >= 0;)
  44045. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44046. }
  44047. return totalNumChars;
  44048. }
  44049. bool TextEditor::isEmpty() const
  44050. {
  44051. return getTotalNumChars() == 0;
  44052. }
  44053. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44054. {
  44055. const float wordWrapWidth = getWordWrapWidth();
  44056. if (wordWrapWidth > 0 && sections.size() > 0)
  44057. {
  44058. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44059. i.getCharPosition (index, cx, cy, lineHeight);
  44060. }
  44061. else
  44062. {
  44063. cx = cy = 0;
  44064. lineHeight = currentFont.getHeight();
  44065. }
  44066. }
  44067. int TextEditor::indexAtPosition (const float x, const float y)
  44068. {
  44069. const float wordWrapWidth = getWordWrapWidth();
  44070. if (wordWrapWidth > 0)
  44071. {
  44072. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44073. while (i.next())
  44074. {
  44075. if (i.lineY + i.lineHeight > y)
  44076. {
  44077. if (i.lineY > y)
  44078. return jmax (0, i.indexInText - 1);
  44079. if (i.atomX >= x)
  44080. return i.indexInText;
  44081. if (x < i.atomRight)
  44082. return i.xToIndex (x);
  44083. }
  44084. }
  44085. }
  44086. return getTotalNumChars();
  44087. }
  44088. int TextEditor::findWordBreakAfter (const int position) const
  44089. {
  44090. const String t (getTextInRange (Range<int> (position, position + 512)));
  44091. const int totalLength = t.length();
  44092. int i = 0;
  44093. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44094. ++i;
  44095. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44096. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44097. ++i;
  44098. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44099. ++i;
  44100. return position + i;
  44101. }
  44102. int TextEditor::findWordBreakBefore (const int position) const
  44103. {
  44104. if (position <= 0)
  44105. return 0;
  44106. const int startOfBuffer = jmax (0, position - 512);
  44107. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44108. int i = position - startOfBuffer;
  44109. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44110. --i;
  44111. if (i > 0)
  44112. {
  44113. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44114. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44115. --i;
  44116. }
  44117. jassert (startOfBuffer + i >= 0);
  44118. return startOfBuffer + i;
  44119. }
  44120. void TextEditor::splitSection (const int sectionIndex,
  44121. const int charToSplitAt)
  44122. {
  44123. jassert (sections[sectionIndex] != 0);
  44124. sections.insert (sectionIndex + 1,
  44125. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44126. }
  44127. void TextEditor::coalesceSimilarSections()
  44128. {
  44129. for (int i = 0; i < sections.size() - 1; ++i)
  44130. {
  44131. UniformTextSection* const s1 = sections.getUnchecked (i);
  44132. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44133. if (s1->font == s2->font
  44134. && s1->colour == s2->colour)
  44135. {
  44136. s1->append (*s2, passwordCharacter);
  44137. sections.remove (i + 1);
  44138. delete s2;
  44139. --i;
  44140. }
  44141. }
  44142. }
  44143. END_JUCE_NAMESPACE
  44144. /*** End of inlined file: juce_TextEditor.cpp ***/
  44145. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44146. BEGIN_JUCE_NAMESPACE
  44147. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44148. class ToolbarSpacerComp : public ToolbarItemComponent
  44149. {
  44150. public:
  44151. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44152. : ToolbarItemComponent (itemId_, String::empty, false),
  44153. fixedSize (fixedSize_),
  44154. drawBar (drawBar_)
  44155. {
  44156. }
  44157. ~ToolbarSpacerComp()
  44158. {
  44159. }
  44160. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44161. int& preferredSize, int& minSize, int& maxSize)
  44162. {
  44163. if (fixedSize <= 0)
  44164. {
  44165. preferredSize = toolbarThickness * 2;
  44166. minSize = 4;
  44167. maxSize = 32768;
  44168. }
  44169. else
  44170. {
  44171. maxSize = roundToInt (toolbarThickness * fixedSize);
  44172. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44173. preferredSize = maxSize;
  44174. if (getEditingMode() == editableOnPalette)
  44175. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44176. }
  44177. return true;
  44178. }
  44179. void paintButtonArea (Graphics&, int, int, bool, bool)
  44180. {
  44181. }
  44182. void contentAreaChanged (const Rectangle<int>&)
  44183. {
  44184. }
  44185. int getResizeOrder() const throw()
  44186. {
  44187. return fixedSize <= 0 ? 0 : 1;
  44188. }
  44189. void paint (Graphics& g)
  44190. {
  44191. const int w = getWidth();
  44192. const int h = getHeight();
  44193. if (drawBar)
  44194. {
  44195. g.setColour (findColour (Toolbar::separatorColourId, true));
  44196. const float thickness = 0.2f;
  44197. if (isToolbarVertical())
  44198. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44199. else
  44200. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44201. }
  44202. if (getEditingMode() != normalMode && ! drawBar)
  44203. {
  44204. g.setColour (findColour (Toolbar::separatorColourId, true));
  44205. const int indentX = jmin (2, (w - 3) / 2);
  44206. const int indentY = jmin (2, (h - 3) / 2);
  44207. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44208. if (fixedSize <= 0)
  44209. {
  44210. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44211. if (isToolbarVertical())
  44212. {
  44213. x1 = w * 0.5f;
  44214. y1 = h * 0.4f;
  44215. x2 = x1;
  44216. y2 = indentX * 2.0f;
  44217. x3 = x1;
  44218. y3 = h * 0.6f;
  44219. x4 = x1;
  44220. y4 = h - y2;
  44221. hw = w * 0.15f;
  44222. hl = w * 0.2f;
  44223. }
  44224. else
  44225. {
  44226. x1 = w * 0.4f;
  44227. y1 = h * 0.5f;
  44228. x2 = indentX * 2.0f;
  44229. y2 = y1;
  44230. x3 = w * 0.6f;
  44231. y3 = y1;
  44232. x4 = w - x2;
  44233. y4 = y1;
  44234. hw = h * 0.15f;
  44235. hl = h * 0.2f;
  44236. }
  44237. Path p;
  44238. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44239. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44240. g.fillPath (p);
  44241. }
  44242. }
  44243. }
  44244. private:
  44245. const float fixedSize;
  44246. const bool drawBar;
  44247. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  44248. };
  44249. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44250. {
  44251. public:
  44252. MissingItemsComponent (Toolbar& owner_, const int height_)
  44253. : PopupMenuCustomComponent (true),
  44254. owner (&owner_),
  44255. height (height_)
  44256. {
  44257. for (int i = owner_.items.size(); --i >= 0;)
  44258. {
  44259. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44260. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44261. {
  44262. oldIndexes.insert (0, i);
  44263. addAndMakeVisible (tc, 0);
  44264. }
  44265. }
  44266. layout (400);
  44267. }
  44268. ~MissingItemsComponent()
  44269. {
  44270. if (owner != 0)
  44271. {
  44272. for (int i = 0; i < getNumChildComponents(); ++i)
  44273. {
  44274. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44275. if (tc != 0)
  44276. {
  44277. tc->setVisible (false);
  44278. const int index = oldIndexes.remove (i);
  44279. owner->addChildComponent (tc, index);
  44280. --i;
  44281. }
  44282. }
  44283. owner->resized();
  44284. }
  44285. }
  44286. void layout (const int preferredWidth)
  44287. {
  44288. const int indent = 8;
  44289. int x = indent;
  44290. int y = indent;
  44291. int maxX = 0;
  44292. for (int i = 0; i < getNumChildComponents(); ++i)
  44293. {
  44294. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44295. if (tc != 0)
  44296. {
  44297. int preferredSize = 1, minSize = 1, maxSize = 1;
  44298. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44299. {
  44300. if (x + preferredSize > preferredWidth && x > indent)
  44301. {
  44302. x = indent;
  44303. y += height;
  44304. }
  44305. tc->setBounds (x, y, preferredSize, height);
  44306. x += preferredSize;
  44307. maxX = jmax (maxX, x);
  44308. }
  44309. }
  44310. }
  44311. setSize (maxX + 8, y + height + 8);
  44312. }
  44313. void getIdealSize (int& idealWidth, int& idealHeight)
  44314. {
  44315. idealWidth = getWidth();
  44316. idealHeight = getHeight();
  44317. }
  44318. private:
  44319. Component::SafePointer<Toolbar> owner;
  44320. const int height;
  44321. Array <int> oldIndexes;
  44322. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44323. };
  44324. Toolbar::Toolbar()
  44325. : vertical (false),
  44326. isEditingActive (false),
  44327. toolbarStyle (Toolbar::iconsOnly)
  44328. {
  44329. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44330. missingItemsButton->setAlwaysOnTop (true);
  44331. missingItemsButton->addListener (this);
  44332. }
  44333. Toolbar::~Toolbar()
  44334. {
  44335. items.clear();
  44336. }
  44337. void Toolbar::setVertical (const bool shouldBeVertical)
  44338. {
  44339. if (vertical != shouldBeVertical)
  44340. {
  44341. vertical = shouldBeVertical;
  44342. resized();
  44343. }
  44344. }
  44345. void Toolbar::clear()
  44346. {
  44347. items.clear();
  44348. resized();
  44349. }
  44350. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44351. {
  44352. if (itemId == ToolbarItemFactory::separatorBarId)
  44353. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44354. else if (itemId == ToolbarItemFactory::spacerId)
  44355. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44356. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44357. return new ToolbarSpacerComp (itemId, 0, false);
  44358. return factory.createItem (itemId);
  44359. }
  44360. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44361. const int itemId,
  44362. const int insertIndex)
  44363. {
  44364. // An ID can't be zero - this might indicate a mistake somewhere?
  44365. jassert (itemId != 0);
  44366. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44367. if (tc != 0)
  44368. {
  44369. #if JUCE_DEBUG
  44370. Array <int> allowedIds;
  44371. factory.getAllToolbarItemIds (allowedIds);
  44372. // If your factory can create an item for a given ID, it must also return
  44373. // that ID from its getAllToolbarItemIds() method!
  44374. jassert (allowedIds.contains (itemId));
  44375. #endif
  44376. items.insert (insertIndex, tc);
  44377. addAndMakeVisible (tc, insertIndex);
  44378. }
  44379. }
  44380. void Toolbar::addItem (ToolbarItemFactory& factory,
  44381. const int itemId,
  44382. const int insertIndex)
  44383. {
  44384. addItemInternal (factory, itemId, insertIndex);
  44385. resized();
  44386. }
  44387. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44388. {
  44389. Array <int> ids;
  44390. factoryToUse.getDefaultItemSet (ids);
  44391. clear();
  44392. for (int i = 0; i < ids.size(); ++i)
  44393. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44394. resized();
  44395. }
  44396. void Toolbar::removeToolbarItem (const int itemIndex)
  44397. {
  44398. items.remove (itemIndex);
  44399. resized();
  44400. }
  44401. int Toolbar::getNumItems() const throw()
  44402. {
  44403. return items.size();
  44404. }
  44405. int Toolbar::getItemId (const int itemIndex) const throw()
  44406. {
  44407. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44408. return tc != 0 ? tc->getItemId() : 0;
  44409. }
  44410. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44411. {
  44412. return items [itemIndex];
  44413. }
  44414. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44415. {
  44416. for (;;)
  44417. {
  44418. index += delta;
  44419. ToolbarItemComponent* const tc = getItemComponent (index);
  44420. if (tc == 0)
  44421. break;
  44422. if (tc->isActive)
  44423. return tc;
  44424. }
  44425. return 0;
  44426. }
  44427. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44428. {
  44429. if (toolbarStyle != newStyle)
  44430. {
  44431. toolbarStyle = newStyle;
  44432. updateAllItemPositions (false);
  44433. }
  44434. }
  44435. const String Toolbar::toString() const
  44436. {
  44437. String s ("TB:");
  44438. for (int i = 0; i < getNumItems(); ++i)
  44439. s << getItemId(i) << ' ';
  44440. return s.trimEnd();
  44441. }
  44442. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44443. const String& savedVersion)
  44444. {
  44445. if (! savedVersion.startsWith ("TB:"))
  44446. return false;
  44447. StringArray tokens;
  44448. tokens.addTokens (savedVersion.substring (3), false);
  44449. clear();
  44450. for (int i = 0; i < tokens.size(); ++i)
  44451. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44452. resized();
  44453. return true;
  44454. }
  44455. void Toolbar::paint (Graphics& g)
  44456. {
  44457. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44458. }
  44459. int Toolbar::getThickness() const throw()
  44460. {
  44461. return vertical ? getWidth() : getHeight();
  44462. }
  44463. int Toolbar::getLength() const throw()
  44464. {
  44465. return vertical ? getHeight() : getWidth();
  44466. }
  44467. void Toolbar::setEditingActive (const bool active)
  44468. {
  44469. if (isEditingActive != active)
  44470. {
  44471. isEditingActive = active;
  44472. updateAllItemPositions (false);
  44473. }
  44474. }
  44475. void Toolbar::resized()
  44476. {
  44477. updateAllItemPositions (false);
  44478. }
  44479. void Toolbar::updateAllItemPositions (const bool animate)
  44480. {
  44481. if (getWidth() > 0 && getHeight() > 0)
  44482. {
  44483. StretchableObjectResizer resizer;
  44484. int i;
  44485. for (i = 0; i < items.size(); ++i)
  44486. {
  44487. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44488. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44489. : ToolbarItemComponent::normalMode);
  44490. tc->setStyle (toolbarStyle);
  44491. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44492. int preferredSize = 1, minSize = 1, maxSize = 1;
  44493. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44494. preferredSize, minSize, maxSize))
  44495. {
  44496. tc->isActive = true;
  44497. resizer.addItem (preferredSize, minSize, maxSize,
  44498. spacer != 0 ? spacer->getResizeOrder() : 2);
  44499. }
  44500. else
  44501. {
  44502. tc->isActive = false;
  44503. tc->setVisible (false);
  44504. }
  44505. }
  44506. resizer.resizeToFit (getLength());
  44507. int totalLength = 0;
  44508. for (i = 0; i < resizer.getNumItems(); ++i)
  44509. totalLength += (int) resizer.getItemSize (i);
  44510. const bool itemsOffTheEnd = totalLength > getLength();
  44511. const int extrasButtonSize = getThickness() / 2;
  44512. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44513. missingItemsButton->setVisible (itemsOffTheEnd);
  44514. missingItemsButton->setEnabled (! isEditingActive);
  44515. if (vertical)
  44516. missingItemsButton->setCentrePosition (getWidth() / 2,
  44517. getHeight() - 4 - extrasButtonSize / 2);
  44518. else
  44519. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44520. getHeight() / 2);
  44521. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44522. : missingItemsButton->getX()) - 4
  44523. : getLength();
  44524. int pos = 0, activeIndex = 0;
  44525. for (i = 0; i < items.size(); ++i)
  44526. {
  44527. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44528. if (tc->isActive)
  44529. {
  44530. const int size = (int) resizer.getItemSize (activeIndex++);
  44531. Rectangle<int> newBounds;
  44532. if (vertical)
  44533. newBounds.setBounds (0, pos, getWidth(), size);
  44534. else
  44535. newBounds.setBounds (pos, 0, size, getHeight());
  44536. if (animate)
  44537. {
  44538. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44539. }
  44540. else
  44541. {
  44542. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44543. tc->setBounds (newBounds);
  44544. }
  44545. pos += size;
  44546. tc->setVisible (pos <= maxLength
  44547. && ((! tc->isBeingDragged)
  44548. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44549. }
  44550. }
  44551. }
  44552. }
  44553. void Toolbar::buttonClicked (Button*)
  44554. {
  44555. jassert (missingItemsButton->isShowing());
  44556. if (missingItemsButton->isShowing())
  44557. {
  44558. PopupMenu m;
  44559. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44560. m.showAt (missingItemsButton);
  44561. }
  44562. }
  44563. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44564. Component* /*sourceComponent*/)
  44565. {
  44566. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44567. }
  44568. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44569. {
  44570. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44571. if (tc != 0)
  44572. {
  44573. if (! items.contains (tc))
  44574. {
  44575. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44576. {
  44577. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44578. if (palette != 0)
  44579. palette->replaceComponent (tc);
  44580. }
  44581. else
  44582. {
  44583. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44584. }
  44585. items.add (tc);
  44586. addChildComponent (tc);
  44587. updateAllItemPositions (true);
  44588. }
  44589. for (int i = getNumItems(); --i >= 0;)
  44590. {
  44591. const int currentIndex = items.indexOf (tc);
  44592. int newIndex = currentIndex;
  44593. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44594. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44595. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44596. .getComponentDestination (getChildComponent (newIndex)));
  44597. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44598. if (prev != 0)
  44599. {
  44600. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44601. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44602. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44603. {
  44604. newIndex = getIndexOfChildComponent (prev);
  44605. }
  44606. }
  44607. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44608. if (next != 0)
  44609. {
  44610. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44611. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44612. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44613. {
  44614. newIndex = getIndexOfChildComponent (next) + 1;
  44615. }
  44616. }
  44617. if (newIndex == currentIndex)
  44618. break;
  44619. items.removeObject (tc, false);
  44620. removeChildComponent (tc);
  44621. addChildComponent (tc, newIndex);
  44622. items.insert (newIndex, tc);
  44623. updateAllItemPositions (true);
  44624. }
  44625. }
  44626. }
  44627. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44628. {
  44629. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44630. if (tc != 0 && isParentOf (tc))
  44631. {
  44632. items.removeObject (tc, false);
  44633. removeChildComponent (tc);
  44634. updateAllItemPositions (true);
  44635. }
  44636. }
  44637. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44638. {
  44639. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44640. if (tc != 0)
  44641. tc->setState (Button::buttonNormal);
  44642. }
  44643. void Toolbar::mouseDown (const MouseEvent&)
  44644. {
  44645. }
  44646. class ToolbarCustomisationDialog : public DialogWindow
  44647. {
  44648. public:
  44649. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44650. Toolbar* const toolbar_,
  44651. const int optionFlags)
  44652. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44653. toolbar (toolbar_)
  44654. {
  44655. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44656. setResizable (true, true);
  44657. setResizeLimits (400, 300, 1500, 1000);
  44658. positionNearBar();
  44659. }
  44660. ~ToolbarCustomisationDialog()
  44661. {
  44662. setContentComponent (0, true);
  44663. }
  44664. void closeButtonPressed()
  44665. {
  44666. setVisible (false);
  44667. }
  44668. bool canModalEventBeSentToComponent (const Component* comp)
  44669. {
  44670. return toolbar->isParentOf (comp);
  44671. }
  44672. void positionNearBar()
  44673. {
  44674. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44675. const int tbx = toolbar->getScreenX();
  44676. const int tby = toolbar->getScreenY();
  44677. const int gap = 8;
  44678. int x, y;
  44679. if (toolbar->isVertical())
  44680. {
  44681. y = tby;
  44682. if (tbx > screenSize.getCentreX())
  44683. x = tbx - getWidth() - gap;
  44684. else
  44685. x = tbx + toolbar->getWidth() + gap;
  44686. }
  44687. else
  44688. {
  44689. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44690. if (tby > screenSize.getCentreY())
  44691. y = tby - getHeight() - gap;
  44692. else
  44693. y = tby + toolbar->getHeight() + gap;
  44694. }
  44695. setTopLeftPosition (x, y);
  44696. }
  44697. private:
  44698. Toolbar* const toolbar;
  44699. class CustomiserPanel : public Component,
  44700. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44701. private ButtonListener
  44702. {
  44703. public:
  44704. CustomiserPanel (ToolbarItemFactory& factory_,
  44705. Toolbar* const toolbar_,
  44706. const int optionFlags)
  44707. : factory (factory_),
  44708. toolbar (toolbar_),
  44709. palette (factory_, toolbar_),
  44710. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44711. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44712. defaultButton (TRANS ("Restore to default set of items"))
  44713. {
  44714. addAndMakeVisible (&palette);
  44715. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44716. | Toolbar::allowIconsWithTextChoice
  44717. | Toolbar::allowTextOnlyChoice)) != 0)
  44718. {
  44719. addAndMakeVisible (&styleBox);
  44720. styleBox.setEditableText (false);
  44721. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44722. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44723. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44724. int selectedStyle = 0;
  44725. switch (toolbar_->getStyle())
  44726. {
  44727. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44728. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44729. case Toolbar::textOnly: selectedStyle = 3; break;
  44730. }
  44731. styleBox.setSelectedId (selectedStyle);
  44732. styleBox.addListener (this);
  44733. }
  44734. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44735. {
  44736. addAndMakeVisible (&defaultButton);
  44737. defaultButton.addListener (this);
  44738. }
  44739. addAndMakeVisible (&instructions);
  44740. instructions.setFont (Font (13.0f));
  44741. setSize (500, 300);
  44742. }
  44743. void comboBoxChanged (ComboBox*)
  44744. {
  44745. switch (styleBox.getSelectedId())
  44746. {
  44747. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44748. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44749. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44750. }
  44751. palette.resized(); // to make it update the styles
  44752. }
  44753. void buttonClicked (Button*)
  44754. {
  44755. toolbar->addDefaultItems (factory);
  44756. }
  44757. void paint (Graphics& g)
  44758. {
  44759. Colour background;
  44760. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44761. if (dw != 0)
  44762. background = dw->getBackgroundColour();
  44763. g.setColour (background.contrasting().withAlpha (0.3f));
  44764. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44765. }
  44766. void resized()
  44767. {
  44768. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44769. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44770. defaultButton.changeWidthToFitText (22);
  44771. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44772. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44773. }
  44774. private:
  44775. ToolbarItemFactory& factory;
  44776. Toolbar* const toolbar;
  44777. ToolbarItemPalette palette;
  44778. Label instructions;
  44779. ComboBox styleBox;
  44780. TextButton defaultButton;
  44781. };
  44782. };
  44783. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44784. {
  44785. setEditingActive (true);
  44786. #if JUCE_DEBUG
  44787. WeakReference<Component> checker (this);
  44788. #endif
  44789. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44790. dw.runModalLoop();
  44791. #if JUCE_DEBUG
  44792. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44793. #endif
  44794. setEditingActive (false);
  44795. }
  44796. END_JUCE_NAMESPACE
  44797. /*** End of inlined file: juce_Toolbar.cpp ***/
  44798. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44799. BEGIN_JUCE_NAMESPACE
  44800. ToolbarItemFactory::ToolbarItemFactory()
  44801. {
  44802. }
  44803. ToolbarItemFactory::~ToolbarItemFactory()
  44804. {
  44805. }
  44806. class ItemDragAndDropOverlayComponent : public Component
  44807. {
  44808. public:
  44809. ItemDragAndDropOverlayComponent()
  44810. : isDragging (false)
  44811. {
  44812. setAlwaysOnTop (true);
  44813. setRepaintsOnMouseActivity (true);
  44814. setMouseCursor (MouseCursor::DraggingHandCursor);
  44815. }
  44816. void paint (Graphics& g)
  44817. {
  44818. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44819. if (isMouseOverOrDragging()
  44820. && tc != 0
  44821. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44822. {
  44823. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44824. g.drawRect (0, 0, getWidth(), getHeight(),
  44825. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44826. }
  44827. }
  44828. void mouseDown (const MouseEvent& e)
  44829. {
  44830. isDragging = false;
  44831. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44832. if (tc != 0)
  44833. {
  44834. tc->dragOffsetX = e.x;
  44835. tc->dragOffsetY = e.y;
  44836. }
  44837. }
  44838. void mouseDrag (const MouseEvent& e)
  44839. {
  44840. if (! (isDragging || e.mouseWasClicked()))
  44841. {
  44842. isDragging = true;
  44843. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44844. if (dnd != 0)
  44845. {
  44846. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44847. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44848. if (tc != 0)
  44849. {
  44850. tc->isBeingDragged = true;
  44851. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44852. tc->setVisible (false);
  44853. }
  44854. }
  44855. }
  44856. }
  44857. void mouseUp (const MouseEvent&)
  44858. {
  44859. isDragging = false;
  44860. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44861. if (tc != 0)
  44862. {
  44863. tc->isBeingDragged = false;
  44864. Toolbar* const tb = tc->getToolbar();
  44865. if (tb != 0)
  44866. tb->updateAllItemPositions (true);
  44867. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44868. delete tc;
  44869. }
  44870. }
  44871. void parentSizeChanged()
  44872. {
  44873. setBounds (0, 0, getParentWidth(), getParentHeight());
  44874. }
  44875. private:
  44876. bool isDragging;
  44877. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44878. };
  44879. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44880. const String& labelText,
  44881. const bool isBeingUsedAsAButton_)
  44882. : Button (labelText),
  44883. itemId (itemId_),
  44884. mode (normalMode),
  44885. toolbarStyle (Toolbar::iconsOnly),
  44886. dragOffsetX (0),
  44887. dragOffsetY (0),
  44888. isActive (true),
  44889. isBeingDragged (false),
  44890. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44891. {
  44892. // Your item ID can't be 0!
  44893. jassert (itemId_ != 0);
  44894. }
  44895. ToolbarItemComponent::~ToolbarItemComponent()
  44896. {
  44897. overlayComp = 0;
  44898. }
  44899. Toolbar* ToolbarItemComponent::getToolbar() const
  44900. {
  44901. return dynamic_cast <Toolbar*> (getParentComponent());
  44902. }
  44903. bool ToolbarItemComponent::isToolbarVertical() const
  44904. {
  44905. const Toolbar* const t = getToolbar();
  44906. return t != 0 && t->isVertical();
  44907. }
  44908. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44909. {
  44910. if (toolbarStyle != newStyle)
  44911. {
  44912. toolbarStyle = newStyle;
  44913. repaint();
  44914. resized();
  44915. }
  44916. }
  44917. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44918. {
  44919. if (isBeingUsedAsAButton)
  44920. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44921. over, down, *this);
  44922. if (toolbarStyle != Toolbar::iconsOnly)
  44923. {
  44924. const int indent = contentArea.getX();
  44925. int y = indent;
  44926. int h = getHeight() - indent * 2;
  44927. if (toolbarStyle == Toolbar::iconsWithText)
  44928. {
  44929. y = contentArea.getBottom() + indent / 2;
  44930. h -= contentArea.getHeight();
  44931. }
  44932. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44933. getButtonText(), *this);
  44934. }
  44935. if (! contentArea.isEmpty())
  44936. {
  44937. Graphics::ScopedSaveState ss (g);
  44938. g.reduceClipRegion (contentArea);
  44939. g.setOrigin (contentArea.getX(), contentArea.getY());
  44940. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44941. }
  44942. }
  44943. void ToolbarItemComponent::resized()
  44944. {
  44945. if (toolbarStyle != Toolbar::textOnly)
  44946. {
  44947. const int indent = jmin (proportionOfWidth (0.08f),
  44948. proportionOfHeight (0.08f));
  44949. contentArea = Rectangle<int> (indent, indent,
  44950. getWidth() - indent * 2,
  44951. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44952. : (getHeight() - indent * 2));
  44953. }
  44954. else
  44955. {
  44956. contentArea = Rectangle<int>();
  44957. }
  44958. contentAreaChanged (contentArea);
  44959. }
  44960. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44961. {
  44962. if (mode != newMode)
  44963. {
  44964. mode = newMode;
  44965. repaint();
  44966. if (mode == normalMode)
  44967. {
  44968. overlayComp = 0;
  44969. }
  44970. else if (overlayComp == 0)
  44971. {
  44972. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44973. overlayComp->parentSizeChanged();
  44974. }
  44975. resized();
  44976. }
  44977. }
  44978. END_JUCE_NAMESPACE
  44979. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44980. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44981. BEGIN_JUCE_NAMESPACE
  44982. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44983. Toolbar* const toolbar_)
  44984. : factory (factory_),
  44985. toolbar (toolbar_)
  44986. {
  44987. Component* const itemHolder = new Component();
  44988. viewport.setViewedComponent (itemHolder);
  44989. Array <int> allIds;
  44990. factory.getAllToolbarItemIds (allIds);
  44991. for (int i = 0; i < allIds.size(); ++i)
  44992. addComponent (allIds.getUnchecked (i), -1);
  44993. addAndMakeVisible (&viewport);
  44994. }
  44995. ToolbarItemPalette::~ToolbarItemPalette()
  44996. {
  44997. }
  44998. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44999. {
  45000. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  45001. jassert (tc != 0);
  45002. if (tc != 0)
  45003. {
  45004. items.insert (index, tc);
  45005. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  45006. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45007. }
  45008. }
  45009. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45010. {
  45011. const int index = items.indexOf (comp);
  45012. jassert (index >= 0);
  45013. items.removeObject (comp, false);
  45014. addComponent (comp->getItemId(), index);
  45015. resized();
  45016. }
  45017. void ToolbarItemPalette::resized()
  45018. {
  45019. viewport.setBoundsInset (BorderSize (1));
  45020. Component* const itemHolder = viewport.getViewedComponent();
  45021. const int indent = 8;
  45022. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  45023. const int height = toolbar->getThickness();
  45024. int x = indent;
  45025. int y = indent;
  45026. int maxX = 0;
  45027. for (int i = 0; i < items.size(); ++i)
  45028. {
  45029. ToolbarItemComponent* const tc = items.getUnchecked(i);
  45030. tc->setStyle (toolbar->getStyle());
  45031. int preferredSize = 1, minSize = 1, maxSize = 1;
  45032. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45033. {
  45034. if (x + preferredSize > preferredWidth && x > indent)
  45035. {
  45036. x = indent;
  45037. y += height;
  45038. }
  45039. tc->setBounds (x, y, preferredSize, height);
  45040. x += preferredSize + 8;
  45041. maxX = jmax (maxX, x);
  45042. }
  45043. }
  45044. itemHolder->setSize (maxX, y + height + 8);
  45045. }
  45046. END_JUCE_NAMESPACE
  45047. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45048. /*** Start of inlined file: juce_TreeView.cpp ***/
  45049. BEGIN_JUCE_NAMESPACE
  45050. class TreeViewContentComponent : public Component,
  45051. public TooltipClient
  45052. {
  45053. public:
  45054. TreeViewContentComponent (TreeView& owner_)
  45055. : owner (owner_),
  45056. buttonUnderMouse (0),
  45057. isDragging (false)
  45058. {
  45059. }
  45060. ~TreeViewContentComponent()
  45061. {
  45062. }
  45063. void mouseDown (const MouseEvent& e)
  45064. {
  45065. updateButtonUnderMouse (e);
  45066. isDragging = false;
  45067. needSelectionOnMouseUp = false;
  45068. Rectangle<int> pos;
  45069. TreeViewItem* const item = findItemAt (e.y, pos);
  45070. if (item == 0)
  45071. return;
  45072. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45073. // as selection clicks)
  45074. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45075. {
  45076. if (e.x >= pos.getX() - owner.getIndentSize())
  45077. item->setOpen (! item->isOpen());
  45078. // (clicks to the left of an open/close button are ignored)
  45079. }
  45080. else
  45081. {
  45082. // mouse-down inside the body of the item..
  45083. if (! owner.isMultiSelectEnabled())
  45084. item->setSelected (true, true);
  45085. else if (item->isSelected())
  45086. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45087. else
  45088. selectBasedOnModifiers (item, e.mods);
  45089. if (e.x >= pos.getX())
  45090. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45091. }
  45092. }
  45093. void mouseUp (const MouseEvent& e)
  45094. {
  45095. updateButtonUnderMouse (e);
  45096. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45097. {
  45098. Rectangle<int> pos;
  45099. TreeViewItem* const item = findItemAt (e.y, pos);
  45100. if (item != 0)
  45101. selectBasedOnModifiers (item, e.mods);
  45102. }
  45103. }
  45104. void mouseDoubleClick (const MouseEvent& e)
  45105. {
  45106. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45107. {
  45108. Rectangle<int> pos;
  45109. TreeViewItem* const item = findItemAt (e.y, pos);
  45110. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45111. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45112. }
  45113. }
  45114. void mouseDrag (const MouseEvent& e)
  45115. {
  45116. if (isEnabled()
  45117. && ! (isDragging || e.mouseWasClicked()
  45118. || e.getDistanceFromDragStart() < 5
  45119. || e.mods.isPopupMenu()))
  45120. {
  45121. isDragging = true;
  45122. Rectangle<int> pos;
  45123. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45124. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45125. {
  45126. const String dragDescription (item->getDragSourceDescription());
  45127. if (dragDescription.isNotEmpty())
  45128. {
  45129. DragAndDropContainer* const dragContainer
  45130. = DragAndDropContainer::findParentDragContainerFor (this);
  45131. if (dragContainer != 0)
  45132. {
  45133. pos.setSize (pos.getWidth(), item->itemHeight);
  45134. Image dragImage (Component::createComponentSnapshot (pos, true));
  45135. dragImage.multiplyAllAlphas (0.6f);
  45136. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45137. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45138. }
  45139. else
  45140. {
  45141. // to be able to do a drag-and-drop operation, the treeview needs to
  45142. // be inside a component which is also a DragAndDropContainer.
  45143. jassertfalse;
  45144. }
  45145. }
  45146. }
  45147. }
  45148. }
  45149. void mouseMove (const MouseEvent& e)
  45150. {
  45151. updateButtonUnderMouse (e);
  45152. }
  45153. void mouseExit (const MouseEvent& e)
  45154. {
  45155. updateButtonUnderMouse (e);
  45156. }
  45157. void paint (Graphics& g)
  45158. {
  45159. if (owner.rootItem != 0)
  45160. {
  45161. owner.handleAsyncUpdate();
  45162. if (! owner.rootItemVisible)
  45163. g.setOrigin (0, -owner.rootItem->itemHeight);
  45164. owner.rootItem->paintRecursively (g, getWidth());
  45165. }
  45166. }
  45167. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45168. {
  45169. if (owner.rootItem != 0)
  45170. {
  45171. owner.handleAsyncUpdate();
  45172. if (! owner.rootItemVisible)
  45173. y += owner.rootItem->itemHeight;
  45174. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45175. if (ti != 0)
  45176. itemPosition = ti->getItemPosition (false);
  45177. return ti;
  45178. }
  45179. return 0;
  45180. }
  45181. void updateComponents()
  45182. {
  45183. const int visibleTop = -getY();
  45184. const int visibleBottom = visibleTop + getParentHeight();
  45185. {
  45186. for (int i = items.size(); --i >= 0;)
  45187. items.getUnchecked(i)->shouldKeep = false;
  45188. }
  45189. {
  45190. TreeViewItem* item = owner.rootItem;
  45191. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45192. while (item != 0 && y < visibleBottom)
  45193. {
  45194. y += item->itemHeight;
  45195. if (y >= visibleTop)
  45196. {
  45197. RowItem* const ri = findItem (item->uid);
  45198. if (ri != 0)
  45199. {
  45200. ri->shouldKeep = true;
  45201. }
  45202. else
  45203. {
  45204. Component* const comp = item->createItemComponent();
  45205. if (comp != 0)
  45206. {
  45207. items.add (new RowItem (item, comp, item->uid));
  45208. addAndMakeVisible (comp);
  45209. }
  45210. }
  45211. }
  45212. item = item->getNextVisibleItem (true);
  45213. }
  45214. }
  45215. for (int i = items.size(); --i >= 0;)
  45216. {
  45217. RowItem* const ri = items.getUnchecked(i);
  45218. bool keep = false;
  45219. if (isParentOf (ri->component))
  45220. {
  45221. if (ri->shouldKeep)
  45222. {
  45223. Rectangle<int> pos (ri->item->getItemPosition (false));
  45224. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45225. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45226. {
  45227. keep = true;
  45228. ri->component->setBounds (pos);
  45229. }
  45230. }
  45231. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45232. {
  45233. keep = true;
  45234. ri->component->setSize (0, 0);
  45235. }
  45236. }
  45237. if (! keep)
  45238. items.remove (i);
  45239. }
  45240. }
  45241. void updateButtonUnderMouse (const MouseEvent& e)
  45242. {
  45243. TreeViewItem* newItem = 0;
  45244. if (owner.openCloseButtonsVisible)
  45245. {
  45246. Rectangle<int> pos;
  45247. TreeViewItem* item = findItemAt (e.y, pos);
  45248. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45249. {
  45250. newItem = item;
  45251. if (! newItem->mightContainSubItems())
  45252. newItem = 0;
  45253. }
  45254. }
  45255. if (buttonUnderMouse != newItem)
  45256. {
  45257. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45258. {
  45259. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45260. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45261. }
  45262. buttonUnderMouse = newItem;
  45263. if (buttonUnderMouse != 0)
  45264. {
  45265. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45266. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45267. }
  45268. }
  45269. }
  45270. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45271. {
  45272. return item == buttonUnderMouse;
  45273. }
  45274. void resized()
  45275. {
  45276. owner.itemsChanged();
  45277. }
  45278. const String getTooltip()
  45279. {
  45280. Rectangle<int> pos;
  45281. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45282. if (item != 0)
  45283. return item->getTooltip();
  45284. return owner.getTooltip();
  45285. }
  45286. private:
  45287. TreeView& owner;
  45288. struct RowItem
  45289. {
  45290. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45291. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45292. {
  45293. }
  45294. ~RowItem()
  45295. {
  45296. delete component.get();
  45297. }
  45298. WeakReference<Component> component;
  45299. TreeViewItem* item;
  45300. int uid;
  45301. bool shouldKeep;
  45302. };
  45303. OwnedArray <RowItem> items;
  45304. TreeViewItem* buttonUnderMouse;
  45305. bool isDragging, needSelectionOnMouseUp;
  45306. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45307. {
  45308. TreeViewItem* firstSelected = 0;
  45309. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45310. {
  45311. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45312. jassert (lastSelected != 0);
  45313. int rowStart = firstSelected->getRowNumberInTree();
  45314. int rowEnd = lastSelected->getRowNumberInTree();
  45315. if (rowStart > rowEnd)
  45316. swapVariables (rowStart, rowEnd);
  45317. int ourRow = item->getRowNumberInTree();
  45318. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45319. if (ourRow > otherEnd)
  45320. swapVariables (ourRow, otherEnd);
  45321. for (int i = ourRow; i <= otherEnd; ++i)
  45322. owner.getItemOnRow (i)->setSelected (true, false);
  45323. }
  45324. else
  45325. {
  45326. const bool cmd = modifiers.isCommandDown();
  45327. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45328. }
  45329. }
  45330. bool containsItem (TreeViewItem* const item) const throw()
  45331. {
  45332. for (int i = items.size(); --i >= 0;)
  45333. if (items.getUnchecked(i)->item == item)
  45334. return true;
  45335. return false;
  45336. }
  45337. RowItem* findItem (const int uid) const throw()
  45338. {
  45339. for (int i = items.size(); --i >= 0;)
  45340. {
  45341. RowItem* const ri = items.getUnchecked(i);
  45342. if (ri->uid == uid)
  45343. return ri;
  45344. }
  45345. return 0;
  45346. }
  45347. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45348. {
  45349. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45350. {
  45351. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45352. if (source->isDragging())
  45353. {
  45354. Component* const underMouse = source->getComponentUnderMouse();
  45355. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45356. return true;
  45357. }
  45358. }
  45359. return false;
  45360. }
  45361. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45362. };
  45363. class TreeView::TreeViewport : public Viewport
  45364. {
  45365. public:
  45366. TreeViewport() throw() : lastX (-1) {}
  45367. ~TreeViewport() throw() {}
  45368. void updateComponents (const bool triggerResize = false)
  45369. {
  45370. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45371. if (tvc != 0)
  45372. {
  45373. if (triggerResize)
  45374. tvc->resized();
  45375. else
  45376. tvc->updateComponents();
  45377. }
  45378. repaint();
  45379. }
  45380. void visibleAreaChanged (int x, int, int, int)
  45381. {
  45382. const bool hasScrolledSideways = (x != lastX);
  45383. lastX = x;
  45384. updateComponents (hasScrolledSideways);
  45385. }
  45386. private:
  45387. int lastX;
  45388. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45389. };
  45390. TreeView::TreeView (const String& componentName)
  45391. : Component (componentName),
  45392. rootItem (0),
  45393. indentSize (24),
  45394. defaultOpenness (false),
  45395. needsRecalculating (true),
  45396. rootItemVisible (true),
  45397. multiSelectEnabled (false),
  45398. openCloseButtonsVisible (true)
  45399. {
  45400. addAndMakeVisible (viewport = new TreeViewport());
  45401. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45402. viewport->setWantsKeyboardFocus (false);
  45403. setWantsKeyboardFocus (true);
  45404. }
  45405. TreeView::~TreeView()
  45406. {
  45407. if (rootItem != 0)
  45408. rootItem->setOwnerView (0);
  45409. }
  45410. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45411. {
  45412. if (rootItem != newRootItem)
  45413. {
  45414. if (newRootItem != 0)
  45415. {
  45416. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45417. if (newRootItem->ownerView != 0)
  45418. newRootItem->ownerView->setRootItem (0);
  45419. }
  45420. if (rootItem != 0)
  45421. rootItem->setOwnerView (0);
  45422. rootItem = newRootItem;
  45423. if (newRootItem != 0)
  45424. newRootItem->setOwnerView (this);
  45425. needsRecalculating = true;
  45426. handleAsyncUpdate();
  45427. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45428. {
  45429. rootItem->setOpen (false); // force a re-open
  45430. rootItem->setOpen (true);
  45431. }
  45432. }
  45433. }
  45434. void TreeView::deleteRootItem()
  45435. {
  45436. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45437. setRootItem (0);
  45438. }
  45439. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45440. {
  45441. rootItemVisible = shouldBeVisible;
  45442. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45443. {
  45444. rootItem->setOpen (false); // force a re-open
  45445. rootItem->setOpen (true);
  45446. }
  45447. itemsChanged();
  45448. }
  45449. void TreeView::colourChanged()
  45450. {
  45451. setOpaque (findColour (backgroundColourId).isOpaque());
  45452. repaint();
  45453. }
  45454. void TreeView::setIndentSize (const int newIndentSize)
  45455. {
  45456. if (indentSize != newIndentSize)
  45457. {
  45458. indentSize = newIndentSize;
  45459. resized();
  45460. }
  45461. }
  45462. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45463. {
  45464. if (defaultOpenness != isOpenByDefault)
  45465. {
  45466. defaultOpenness = isOpenByDefault;
  45467. itemsChanged();
  45468. }
  45469. }
  45470. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45471. {
  45472. multiSelectEnabled = canMultiSelect;
  45473. }
  45474. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45475. {
  45476. if (openCloseButtonsVisible != shouldBeVisible)
  45477. {
  45478. openCloseButtonsVisible = shouldBeVisible;
  45479. itemsChanged();
  45480. }
  45481. }
  45482. Viewport* TreeView::getViewport() const throw()
  45483. {
  45484. return viewport;
  45485. }
  45486. void TreeView::clearSelectedItems()
  45487. {
  45488. if (rootItem != 0)
  45489. rootItem->deselectAllRecursively();
  45490. }
  45491. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45492. {
  45493. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45494. }
  45495. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45496. {
  45497. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45498. }
  45499. int TreeView::getNumRowsInTree() const
  45500. {
  45501. if (rootItem != 0)
  45502. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45503. return 0;
  45504. }
  45505. TreeViewItem* TreeView::getItemOnRow (int index) const
  45506. {
  45507. if (! rootItemVisible)
  45508. ++index;
  45509. if (rootItem != 0 && index >= 0)
  45510. return rootItem->getItemOnRow (index);
  45511. return 0;
  45512. }
  45513. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45514. {
  45515. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45516. Rectangle<int> pos;
  45517. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45518. }
  45519. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45520. {
  45521. if (rootItem == 0)
  45522. return 0;
  45523. return rootItem->findItemFromIdentifierString (identifierString);
  45524. }
  45525. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45526. {
  45527. XmlElement* e = 0;
  45528. if (rootItem != 0)
  45529. {
  45530. e = rootItem->getOpennessState();
  45531. if (e != 0 && alsoIncludeScrollPosition)
  45532. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45533. }
  45534. return e;
  45535. }
  45536. void TreeView::restoreOpennessState (const XmlElement& newState)
  45537. {
  45538. if (rootItem != 0)
  45539. {
  45540. rootItem->restoreOpennessState (newState);
  45541. if (newState.hasAttribute ("scrollPos"))
  45542. viewport->setViewPosition (viewport->getViewPositionX(),
  45543. newState.getIntAttribute ("scrollPos"));
  45544. }
  45545. }
  45546. void TreeView::paint (Graphics& g)
  45547. {
  45548. g.fillAll (findColour (backgroundColourId));
  45549. }
  45550. void TreeView::resized()
  45551. {
  45552. viewport->setBounds (getLocalBounds());
  45553. itemsChanged();
  45554. handleAsyncUpdate();
  45555. }
  45556. void TreeView::enablementChanged()
  45557. {
  45558. repaint();
  45559. }
  45560. void TreeView::moveSelectedRow (int delta)
  45561. {
  45562. if (delta == 0)
  45563. return;
  45564. int rowSelected = 0;
  45565. TreeViewItem* const firstSelected = getSelectedItem (0);
  45566. if (firstSelected != 0)
  45567. rowSelected = firstSelected->getRowNumberInTree();
  45568. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45569. for (;;)
  45570. {
  45571. TreeViewItem* item = getItemOnRow (rowSelected);
  45572. if (item != 0)
  45573. {
  45574. if (! item->canBeSelected())
  45575. {
  45576. // if the row we want to highlight doesn't allow it, try skipping
  45577. // to the next item..
  45578. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45579. rowSelected + (delta < 0 ? -1 : 1));
  45580. if (rowSelected != nextRowToTry)
  45581. {
  45582. rowSelected = nextRowToTry;
  45583. continue;
  45584. }
  45585. else
  45586. {
  45587. break;
  45588. }
  45589. }
  45590. item->setSelected (true, true);
  45591. scrollToKeepItemVisible (item);
  45592. }
  45593. break;
  45594. }
  45595. }
  45596. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45597. {
  45598. if (item != 0 && item->ownerView == this)
  45599. {
  45600. handleAsyncUpdate();
  45601. item = item->getDeepestOpenParentItem();
  45602. int y = item->y;
  45603. int viewTop = viewport->getViewPositionY();
  45604. if (y < viewTop)
  45605. {
  45606. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45607. }
  45608. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45609. {
  45610. viewport->setViewPosition (viewport->getViewPositionX(),
  45611. (y + item->itemHeight) - viewport->getViewHeight());
  45612. }
  45613. }
  45614. }
  45615. bool TreeView::keyPressed (const KeyPress& key)
  45616. {
  45617. if (key.isKeyCode (KeyPress::upKey))
  45618. {
  45619. moveSelectedRow (-1);
  45620. }
  45621. else if (key.isKeyCode (KeyPress::downKey))
  45622. {
  45623. moveSelectedRow (1);
  45624. }
  45625. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45626. {
  45627. if (rootItem != 0)
  45628. {
  45629. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45630. if (key.isKeyCode (KeyPress::pageUpKey))
  45631. rowsOnScreen = -rowsOnScreen;
  45632. moveSelectedRow (rowsOnScreen);
  45633. }
  45634. }
  45635. else if (key.isKeyCode (KeyPress::homeKey))
  45636. {
  45637. moveSelectedRow (-0x3fffffff);
  45638. }
  45639. else if (key.isKeyCode (KeyPress::endKey))
  45640. {
  45641. moveSelectedRow (0x3fffffff);
  45642. }
  45643. else if (key.isKeyCode (KeyPress::returnKey))
  45644. {
  45645. TreeViewItem* const firstSelected = getSelectedItem (0);
  45646. if (firstSelected != 0)
  45647. firstSelected->setOpen (! firstSelected->isOpen());
  45648. }
  45649. else if (key.isKeyCode (KeyPress::leftKey))
  45650. {
  45651. TreeViewItem* const firstSelected = getSelectedItem (0);
  45652. if (firstSelected != 0)
  45653. {
  45654. if (firstSelected->isOpen())
  45655. {
  45656. firstSelected->setOpen (false);
  45657. }
  45658. else
  45659. {
  45660. TreeViewItem* parent = firstSelected->parentItem;
  45661. if ((! rootItemVisible) && parent == rootItem)
  45662. parent = 0;
  45663. if (parent != 0)
  45664. {
  45665. parent->setSelected (true, true);
  45666. scrollToKeepItemVisible (parent);
  45667. }
  45668. }
  45669. }
  45670. }
  45671. else if (key.isKeyCode (KeyPress::rightKey))
  45672. {
  45673. TreeViewItem* const firstSelected = getSelectedItem (0);
  45674. if (firstSelected != 0)
  45675. {
  45676. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45677. moveSelectedRow (1);
  45678. else
  45679. firstSelected->setOpen (true);
  45680. }
  45681. }
  45682. else
  45683. {
  45684. return false;
  45685. }
  45686. return true;
  45687. }
  45688. void TreeView::itemsChanged() throw()
  45689. {
  45690. needsRecalculating = true;
  45691. repaint();
  45692. triggerAsyncUpdate();
  45693. }
  45694. void TreeView::handleAsyncUpdate()
  45695. {
  45696. if (needsRecalculating)
  45697. {
  45698. needsRecalculating = false;
  45699. const ScopedLock sl (nodeAlterationLock);
  45700. if (rootItem != 0)
  45701. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45702. viewport->updateComponents();
  45703. if (rootItem != 0)
  45704. {
  45705. viewport->getViewedComponent()
  45706. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45707. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45708. }
  45709. else
  45710. {
  45711. viewport->getViewedComponent()->setSize (0, 0);
  45712. }
  45713. }
  45714. }
  45715. class TreeView::InsertPointHighlight : public Component
  45716. {
  45717. public:
  45718. InsertPointHighlight()
  45719. : lastItem (0)
  45720. {
  45721. setSize (100, 12);
  45722. setAlwaysOnTop (true);
  45723. setInterceptsMouseClicks (false, false);
  45724. }
  45725. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45726. {
  45727. lastItem = item;
  45728. lastIndex = insertIndex;
  45729. const int offset = getHeight() / 2;
  45730. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45731. }
  45732. void paint (Graphics& g)
  45733. {
  45734. Path p;
  45735. const float h = (float) getHeight();
  45736. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45737. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45738. p.lineTo ((float) getWidth(), h / 2.0f);
  45739. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45740. g.strokePath (p, PathStrokeType (2.0f));
  45741. }
  45742. TreeViewItem* lastItem;
  45743. int lastIndex;
  45744. private:
  45745. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45746. };
  45747. class TreeView::TargetGroupHighlight : public Component
  45748. {
  45749. public:
  45750. TargetGroupHighlight()
  45751. {
  45752. setAlwaysOnTop (true);
  45753. setInterceptsMouseClicks (false, false);
  45754. }
  45755. void setTargetPosition (TreeViewItem* const item) throw()
  45756. {
  45757. Rectangle<int> r (item->getItemPosition (true));
  45758. r.setHeight (item->getItemHeight());
  45759. setBounds (r);
  45760. }
  45761. void paint (Graphics& g)
  45762. {
  45763. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45764. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45765. }
  45766. private:
  45767. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45768. };
  45769. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45770. {
  45771. beginDragAutoRepeat (100);
  45772. if (dragInsertPointHighlight == 0)
  45773. {
  45774. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45775. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45776. }
  45777. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45778. dragTargetGroupHighlight->setTargetPosition (item);
  45779. }
  45780. void TreeView::hideDragHighlight() throw()
  45781. {
  45782. dragInsertPointHighlight = 0;
  45783. dragTargetGroupHighlight = 0;
  45784. }
  45785. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45786. const StringArray& files, const String& sourceDescription,
  45787. Component* sourceComponent) const throw()
  45788. {
  45789. insertIndex = 0;
  45790. TreeViewItem* item = getItemAt (y);
  45791. if (item == 0)
  45792. return 0;
  45793. Rectangle<int> itemPos (item->getItemPosition (true));
  45794. insertIndex = item->getIndexInParent();
  45795. const int oldY = y;
  45796. y = itemPos.getY();
  45797. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45798. {
  45799. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45800. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45801. {
  45802. // Check if we're trying to drag into an empty group item..
  45803. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45804. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45805. {
  45806. insertIndex = 0;
  45807. x = itemPos.getX() + getIndentSize();
  45808. y = itemPos.getBottom();
  45809. return item;
  45810. }
  45811. }
  45812. }
  45813. if (oldY > itemPos.getCentreY())
  45814. {
  45815. y += item->getItemHeight();
  45816. while (item->isLastOfSiblings() && item->parentItem != 0
  45817. && item->parentItem->parentItem != 0)
  45818. {
  45819. if (x > itemPos.getX())
  45820. break;
  45821. item = item->parentItem;
  45822. itemPos = item->getItemPosition (true);
  45823. insertIndex = item->getIndexInParent();
  45824. }
  45825. ++insertIndex;
  45826. }
  45827. x = itemPos.getX();
  45828. return item->parentItem;
  45829. }
  45830. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45831. {
  45832. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45833. int insertIndex;
  45834. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45835. if (item != 0)
  45836. {
  45837. if (scrolled || dragInsertPointHighlight == 0
  45838. || dragInsertPointHighlight->lastItem != item
  45839. || dragInsertPointHighlight->lastIndex != insertIndex)
  45840. {
  45841. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45842. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45843. showDragHighlight (item, insertIndex, x, y);
  45844. else
  45845. hideDragHighlight();
  45846. }
  45847. }
  45848. else
  45849. {
  45850. hideDragHighlight();
  45851. }
  45852. }
  45853. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45854. {
  45855. hideDragHighlight();
  45856. int insertIndex;
  45857. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45858. if (item != 0)
  45859. {
  45860. if (files.size() > 0)
  45861. {
  45862. if (item->isInterestedInFileDrag (files))
  45863. item->filesDropped (files, insertIndex);
  45864. }
  45865. else
  45866. {
  45867. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45868. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45869. }
  45870. }
  45871. }
  45872. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45873. {
  45874. return true;
  45875. }
  45876. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45877. {
  45878. fileDragMove (files, x, y);
  45879. }
  45880. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45881. {
  45882. handleDrag (files, String::empty, 0, x, y);
  45883. }
  45884. void TreeView::fileDragExit (const StringArray&)
  45885. {
  45886. hideDragHighlight();
  45887. }
  45888. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45889. {
  45890. handleDrop (files, String::empty, 0, x, y);
  45891. }
  45892. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45893. {
  45894. return true;
  45895. }
  45896. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45897. {
  45898. itemDragMove (sourceDescription, sourceComponent, x, y);
  45899. }
  45900. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45901. {
  45902. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45903. }
  45904. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45905. {
  45906. hideDragHighlight();
  45907. }
  45908. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45909. {
  45910. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45911. }
  45912. enum TreeViewOpenness
  45913. {
  45914. opennessDefault = 0,
  45915. opennessClosed = 1,
  45916. opennessOpen = 2
  45917. };
  45918. TreeViewItem::TreeViewItem()
  45919. : ownerView (0),
  45920. parentItem (0),
  45921. y (0),
  45922. itemHeight (0),
  45923. totalHeight (0),
  45924. selected (false),
  45925. redrawNeeded (true),
  45926. drawLinesInside (true),
  45927. drawsInLeftMargin (false),
  45928. openness (opennessDefault)
  45929. {
  45930. static int nextUID = 0;
  45931. uid = nextUID++;
  45932. }
  45933. TreeViewItem::~TreeViewItem()
  45934. {
  45935. }
  45936. const String TreeViewItem::getUniqueName() const
  45937. {
  45938. return String::empty;
  45939. }
  45940. void TreeViewItem::itemOpennessChanged (bool)
  45941. {
  45942. }
  45943. int TreeViewItem::getNumSubItems() const throw()
  45944. {
  45945. return subItems.size();
  45946. }
  45947. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45948. {
  45949. return subItems [index];
  45950. }
  45951. void TreeViewItem::clearSubItems()
  45952. {
  45953. if (subItems.size() > 0)
  45954. {
  45955. if (ownerView != 0)
  45956. {
  45957. const ScopedLock sl (ownerView->nodeAlterationLock);
  45958. subItems.clear();
  45959. treeHasChanged();
  45960. }
  45961. else
  45962. {
  45963. subItems.clear();
  45964. }
  45965. }
  45966. }
  45967. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45968. {
  45969. if (newItem != 0)
  45970. {
  45971. newItem->parentItem = this;
  45972. newItem->setOwnerView (ownerView);
  45973. newItem->y = 0;
  45974. newItem->itemHeight = newItem->getItemHeight();
  45975. newItem->totalHeight = 0;
  45976. newItem->itemWidth = newItem->getItemWidth();
  45977. newItem->totalWidth = 0;
  45978. if (ownerView != 0)
  45979. {
  45980. const ScopedLock sl (ownerView->nodeAlterationLock);
  45981. subItems.insert (insertPosition, newItem);
  45982. treeHasChanged();
  45983. if (newItem->isOpen())
  45984. newItem->itemOpennessChanged (true);
  45985. }
  45986. else
  45987. {
  45988. subItems.insert (insertPosition, newItem);
  45989. if (newItem->isOpen())
  45990. newItem->itemOpennessChanged (true);
  45991. }
  45992. }
  45993. }
  45994. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45995. {
  45996. if (ownerView != 0)
  45997. {
  45998. const ScopedLock sl (ownerView->nodeAlterationLock);
  45999. if (isPositiveAndBelow (index, subItems.size()))
  46000. {
  46001. subItems.remove (index, deleteItem);
  46002. treeHasChanged();
  46003. }
  46004. }
  46005. else
  46006. {
  46007. subItems.remove (index, deleteItem);
  46008. }
  46009. }
  46010. bool TreeViewItem::isOpen() const throw()
  46011. {
  46012. if (openness == opennessDefault)
  46013. return ownerView != 0 && ownerView->defaultOpenness;
  46014. else
  46015. return openness == opennessOpen;
  46016. }
  46017. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46018. {
  46019. if (isOpen() != shouldBeOpen)
  46020. {
  46021. openness = shouldBeOpen ? opennessOpen
  46022. : opennessClosed;
  46023. treeHasChanged();
  46024. itemOpennessChanged (isOpen());
  46025. }
  46026. }
  46027. bool TreeViewItem::isSelected() const throw()
  46028. {
  46029. return selected;
  46030. }
  46031. void TreeViewItem::deselectAllRecursively()
  46032. {
  46033. setSelected (false, false);
  46034. for (int i = 0; i < subItems.size(); ++i)
  46035. subItems.getUnchecked(i)->deselectAllRecursively();
  46036. }
  46037. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46038. const bool deselectOtherItemsFirst)
  46039. {
  46040. if (shouldBeSelected && ! canBeSelected())
  46041. return;
  46042. if (deselectOtherItemsFirst)
  46043. getTopLevelItem()->deselectAllRecursively();
  46044. if (shouldBeSelected != selected)
  46045. {
  46046. selected = shouldBeSelected;
  46047. if (ownerView != 0)
  46048. ownerView->repaint();
  46049. itemSelectionChanged (shouldBeSelected);
  46050. }
  46051. }
  46052. void TreeViewItem::paintItem (Graphics&, int, int)
  46053. {
  46054. }
  46055. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46056. {
  46057. ownerView->getLookAndFeel()
  46058. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46059. }
  46060. void TreeViewItem::itemClicked (const MouseEvent&)
  46061. {
  46062. }
  46063. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46064. {
  46065. if (mightContainSubItems())
  46066. setOpen (! isOpen());
  46067. }
  46068. void TreeViewItem::itemSelectionChanged (bool)
  46069. {
  46070. }
  46071. const String TreeViewItem::getTooltip()
  46072. {
  46073. return String::empty;
  46074. }
  46075. const String TreeViewItem::getDragSourceDescription()
  46076. {
  46077. return String::empty;
  46078. }
  46079. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46080. {
  46081. return false;
  46082. }
  46083. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46084. {
  46085. }
  46086. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46087. {
  46088. return false;
  46089. }
  46090. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46091. {
  46092. }
  46093. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46094. {
  46095. const int indentX = getIndentX();
  46096. int width = itemWidth;
  46097. if (ownerView != 0 && width < 0)
  46098. width = ownerView->viewport->getViewWidth() - indentX;
  46099. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46100. if (relativeToTreeViewTopLeft)
  46101. r -= ownerView->viewport->getViewPosition();
  46102. return r;
  46103. }
  46104. void TreeViewItem::treeHasChanged() const throw()
  46105. {
  46106. if (ownerView != 0)
  46107. ownerView->itemsChanged();
  46108. }
  46109. void TreeViewItem::repaintItem() const
  46110. {
  46111. if (ownerView != 0 && areAllParentsOpen())
  46112. {
  46113. Rectangle<int> r (getItemPosition (true));
  46114. r.setLeft (0);
  46115. ownerView->viewport->repaint (r);
  46116. }
  46117. }
  46118. bool TreeViewItem::areAllParentsOpen() const throw()
  46119. {
  46120. return parentItem == 0
  46121. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46122. }
  46123. void TreeViewItem::updatePositions (int newY)
  46124. {
  46125. y = newY;
  46126. itemHeight = getItemHeight();
  46127. totalHeight = itemHeight;
  46128. itemWidth = getItemWidth();
  46129. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46130. if (isOpen())
  46131. {
  46132. newY += totalHeight;
  46133. for (int i = 0; i < subItems.size(); ++i)
  46134. {
  46135. TreeViewItem* const ti = subItems.getUnchecked(i);
  46136. ti->updatePositions (newY);
  46137. newY += ti->totalHeight;
  46138. totalHeight += ti->totalHeight;
  46139. totalWidth = jmax (totalWidth, ti->totalWidth);
  46140. }
  46141. }
  46142. }
  46143. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46144. {
  46145. TreeViewItem* result = this;
  46146. TreeViewItem* item = this;
  46147. while (item->parentItem != 0)
  46148. {
  46149. item = item->parentItem;
  46150. if (! item->isOpen())
  46151. result = item;
  46152. }
  46153. return result;
  46154. }
  46155. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46156. {
  46157. ownerView = newOwner;
  46158. for (int i = subItems.size(); --i >= 0;)
  46159. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46160. }
  46161. int TreeViewItem::getIndentX() const throw()
  46162. {
  46163. const int indentWidth = ownerView->getIndentSize();
  46164. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46165. if (! ownerView->openCloseButtonsVisible)
  46166. x -= indentWidth;
  46167. TreeViewItem* p = parentItem;
  46168. while (p != 0)
  46169. {
  46170. x += indentWidth;
  46171. p = p->parentItem;
  46172. }
  46173. return x;
  46174. }
  46175. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46176. {
  46177. drawsInLeftMargin = canDrawInLeftMargin;
  46178. }
  46179. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46180. {
  46181. jassert (ownerView != 0);
  46182. if (ownerView == 0)
  46183. return;
  46184. const int indent = getIndentX();
  46185. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46186. {
  46187. Graphics::ScopedSaveState ss (g);
  46188. g.setOrigin (indent, 0);
  46189. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46190. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46191. paintItem (g, itemW, itemHeight);
  46192. }
  46193. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46194. const float halfH = itemHeight * 0.5f;
  46195. int depth = 0;
  46196. TreeViewItem* p = parentItem;
  46197. while (p != 0)
  46198. {
  46199. ++depth;
  46200. p = p->parentItem;
  46201. }
  46202. if (! ownerView->rootItemVisible)
  46203. --depth;
  46204. const int indentWidth = ownerView->getIndentSize();
  46205. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46206. {
  46207. float x = (depth + 0.5f) * indentWidth;
  46208. if (depth >= 0)
  46209. {
  46210. if (parentItem != 0 && parentItem->drawLinesInside)
  46211. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46212. if ((parentItem != 0 && parentItem->drawLinesInside)
  46213. || (parentItem == 0 && drawLinesInside))
  46214. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46215. }
  46216. p = parentItem;
  46217. int d = depth;
  46218. while (p != 0 && --d >= 0)
  46219. {
  46220. x -= (float) indentWidth;
  46221. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46222. && ! p->isLastOfSiblings())
  46223. {
  46224. g.drawLine (x, 0, x, (float) itemHeight);
  46225. }
  46226. p = p->parentItem;
  46227. }
  46228. if (mightContainSubItems())
  46229. {
  46230. Graphics::ScopedSaveState ss (g);
  46231. g.setOrigin (depth * indentWidth, 0);
  46232. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46233. paintOpenCloseButton (g, indentWidth, itemHeight,
  46234. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46235. ->isMouseOverButton (this));
  46236. }
  46237. }
  46238. if (isOpen())
  46239. {
  46240. const Rectangle<int> clip (g.getClipBounds());
  46241. for (int i = 0; i < subItems.size(); ++i)
  46242. {
  46243. TreeViewItem* const ti = subItems.getUnchecked(i);
  46244. const int relY = ti->y - y;
  46245. if (relY >= clip.getBottom())
  46246. break;
  46247. if (relY + ti->totalHeight >= clip.getY())
  46248. {
  46249. Graphics::ScopedSaveState ss (g);
  46250. g.setOrigin (0, relY);
  46251. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46252. ti->paintRecursively (g, width);
  46253. }
  46254. }
  46255. }
  46256. }
  46257. bool TreeViewItem::isLastOfSiblings() const throw()
  46258. {
  46259. return parentItem == 0
  46260. || parentItem->subItems.getLast() == this;
  46261. }
  46262. int TreeViewItem::getIndexInParent() const throw()
  46263. {
  46264. return parentItem == 0 ? 0
  46265. : parentItem->subItems.indexOf (this);
  46266. }
  46267. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46268. {
  46269. return parentItem == 0 ? this
  46270. : parentItem->getTopLevelItem();
  46271. }
  46272. int TreeViewItem::getNumRows() const throw()
  46273. {
  46274. int num = 1;
  46275. if (isOpen())
  46276. {
  46277. for (int i = subItems.size(); --i >= 0;)
  46278. num += subItems.getUnchecked(i)->getNumRows();
  46279. }
  46280. return num;
  46281. }
  46282. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46283. {
  46284. if (index == 0)
  46285. return this;
  46286. if (index > 0 && isOpen())
  46287. {
  46288. --index;
  46289. for (int i = 0; i < subItems.size(); ++i)
  46290. {
  46291. TreeViewItem* const item = subItems.getUnchecked(i);
  46292. if (index == 0)
  46293. return item;
  46294. const int numRows = item->getNumRows();
  46295. if (numRows > index)
  46296. return item->getItemOnRow (index);
  46297. index -= numRows;
  46298. }
  46299. }
  46300. return 0;
  46301. }
  46302. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46303. {
  46304. if (isPositiveAndBelow (targetY, totalHeight))
  46305. {
  46306. const int h = itemHeight;
  46307. if (targetY < h)
  46308. return this;
  46309. if (isOpen())
  46310. {
  46311. targetY -= h;
  46312. for (int i = 0; i < subItems.size(); ++i)
  46313. {
  46314. TreeViewItem* const ti = subItems.getUnchecked(i);
  46315. if (targetY < ti->totalHeight)
  46316. return ti->findItemRecursively (targetY);
  46317. targetY -= ti->totalHeight;
  46318. }
  46319. }
  46320. }
  46321. return 0;
  46322. }
  46323. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46324. {
  46325. int total = isSelected() ? 1 : 0;
  46326. if (depth != 0)
  46327. for (int i = subItems.size(); --i >= 0;)
  46328. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46329. return total;
  46330. }
  46331. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46332. {
  46333. if (isSelected())
  46334. {
  46335. if (index == 0)
  46336. return this;
  46337. --index;
  46338. }
  46339. if (index >= 0)
  46340. {
  46341. for (int i = 0; i < subItems.size(); ++i)
  46342. {
  46343. TreeViewItem* const item = subItems.getUnchecked(i);
  46344. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46345. if (found != 0)
  46346. return found;
  46347. index -= item->countSelectedItemsRecursively (-1);
  46348. }
  46349. }
  46350. return 0;
  46351. }
  46352. int TreeViewItem::getRowNumberInTree() const throw()
  46353. {
  46354. if (parentItem != 0 && ownerView != 0)
  46355. {
  46356. int n = 1 + parentItem->getRowNumberInTree();
  46357. int ourIndex = parentItem->subItems.indexOf (this);
  46358. jassert (ourIndex >= 0);
  46359. while (--ourIndex >= 0)
  46360. n += parentItem->subItems [ourIndex]->getNumRows();
  46361. if (parentItem->parentItem == 0
  46362. && ! ownerView->rootItemVisible)
  46363. --n;
  46364. return n;
  46365. }
  46366. else
  46367. {
  46368. return 0;
  46369. }
  46370. }
  46371. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46372. {
  46373. drawLinesInside = drawLines;
  46374. }
  46375. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46376. {
  46377. if (recurse && isOpen() && subItems.size() > 0)
  46378. return subItems [0];
  46379. if (parentItem != 0)
  46380. {
  46381. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46382. if (nextIndex >= parentItem->subItems.size())
  46383. return parentItem->getNextVisibleItem (false);
  46384. return parentItem->subItems [nextIndex];
  46385. }
  46386. return 0;
  46387. }
  46388. const String TreeViewItem::getItemIdentifierString() const
  46389. {
  46390. String s;
  46391. if (parentItem != 0)
  46392. s = parentItem->getItemIdentifierString();
  46393. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46394. }
  46395. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46396. {
  46397. const String thisId (getUniqueName());
  46398. if (thisId == identifierString)
  46399. return this;
  46400. if (identifierString.startsWith (thisId + "/"))
  46401. {
  46402. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46403. bool wasOpen = isOpen();
  46404. setOpen (true);
  46405. for (int i = subItems.size(); --i >= 0;)
  46406. {
  46407. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46408. if (item != 0)
  46409. return item;
  46410. }
  46411. setOpen (wasOpen);
  46412. }
  46413. return 0;
  46414. }
  46415. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46416. {
  46417. if (e.hasTagName ("CLOSED"))
  46418. {
  46419. setOpen (false);
  46420. }
  46421. else if (e.hasTagName ("OPEN"))
  46422. {
  46423. setOpen (true);
  46424. forEachXmlChildElement (e, n)
  46425. {
  46426. const String id (n->getStringAttribute ("id"));
  46427. for (int i = 0; i < subItems.size(); ++i)
  46428. {
  46429. TreeViewItem* const ti = subItems.getUnchecked(i);
  46430. if (ti->getUniqueName() == id)
  46431. {
  46432. ti->restoreOpennessState (*n);
  46433. break;
  46434. }
  46435. }
  46436. }
  46437. }
  46438. }
  46439. XmlElement* TreeViewItem::getOpennessState() const throw()
  46440. {
  46441. const String name (getUniqueName());
  46442. if (name.isNotEmpty())
  46443. {
  46444. XmlElement* e;
  46445. if (isOpen())
  46446. {
  46447. e = new XmlElement ("OPEN");
  46448. for (int i = 0; i < subItems.size(); ++i)
  46449. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46450. }
  46451. else
  46452. {
  46453. e = new XmlElement ("CLOSED");
  46454. }
  46455. e->setAttribute ("id", name);
  46456. return e;
  46457. }
  46458. else
  46459. {
  46460. // trying to save the openness for an element that has no name - this won't
  46461. // work because it needs the names to identify what to open.
  46462. jassertfalse;
  46463. }
  46464. return 0;
  46465. }
  46466. END_JUCE_NAMESPACE
  46467. /*** End of inlined file: juce_TreeView.cpp ***/
  46468. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46469. BEGIN_JUCE_NAMESPACE
  46470. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46471. : fileList (listToShow)
  46472. {
  46473. }
  46474. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46475. {
  46476. }
  46477. FileBrowserListener::~FileBrowserListener()
  46478. {
  46479. }
  46480. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46481. {
  46482. listeners.add (listener);
  46483. }
  46484. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46485. {
  46486. listeners.remove (listener);
  46487. }
  46488. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46489. {
  46490. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46491. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46492. }
  46493. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46494. {
  46495. if (fileList.getDirectory().exists())
  46496. {
  46497. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46498. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46499. }
  46500. }
  46501. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46502. {
  46503. if (fileList.getDirectory().exists())
  46504. {
  46505. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46506. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46507. }
  46508. }
  46509. END_JUCE_NAMESPACE
  46510. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46511. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46512. BEGIN_JUCE_NAMESPACE
  46513. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46514. TimeSliceThread& thread_)
  46515. : fileFilter (fileFilter_),
  46516. thread (thread_),
  46517. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46518. fileFindHandle (0),
  46519. shouldStop (true)
  46520. {
  46521. }
  46522. DirectoryContentsList::~DirectoryContentsList()
  46523. {
  46524. clear();
  46525. }
  46526. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46527. {
  46528. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46529. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46530. }
  46531. bool DirectoryContentsList::ignoresHiddenFiles() const
  46532. {
  46533. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46534. }
  46535. const File& DirectoryContentsList::getDirectory() const
  46536. {
  46537. return root;
  46538. }
  46539. void DirectoryContentsList::setDirectory (const File& directory,
  46540. const bool includeDirectories,
  46541. const bool includeFiles)
  46542. {
  46543. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46544. if (directory != root)
  46545. {
  46546. clear();
  46547. root = directory;
  46548. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46549. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46550. }
  46551. int newFlags = fileTypeFlags;
  46552. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46553. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46554. setTypeFlags (newFlags);
  46555. }
  46556. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46557. {
  46558. if (fileTypeFlags != newFlags)
  46559. {
  46560. fileTypeFlags = newFlags;
  46561. refresh();
  46562. }
  46563. }
  46564. void DirectoryContentsList::clear()
  46565. {
  46566. shouldStop = true;
  46567. thread.removeTimeSliceClient (this);
  46568. fileFindHandle = 0;
  46569. if (files.size() > 0)
  46570. {
  46571. files.clear();
  46572. changed();
  46573. }
  46574. }
  46575. void DirectoryContentsList::refresh()
  46576. {
  46577. clear();
  46578. if (root.isDirectory())
  46579. {
  46580. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46581. shouldStop = false;
  46582. thread.addTimeSliceClient (this);
  46583. }
  46584. }
  46585. int DirectoryContentsList::getNumFiles() const
  46586. {
  46587. return files.size();
  46588. }
  46589. bool DirectoryContentsList::getFileInfo (const int index,
  46590. FileInfo& result) const
  46591. {
  46592. const ScopedLock sl (fileListLock);
  46593. const FileInfo* const info = files [index];
  46594. if (info != 0)
  46595. {
  46596. result = *info;
  46597. return true;
  46598. }
  46599. return false;
  46600. }
  46601. const File DirectoryContentsList::getFile (const int index) const
  46602. {
  46603. const ScopedLock sl (fileListLock);
  46604. const FileInfo* const info = files [index];
  46605. if (info != 0)
  46606. return root.getChildFile (info->filename);
  46607. return File::nonexistent;
  46608. }
  46609. bool DirectoryContentsList::isStillLoading() const
  46610. {
  46611. return fileFindHandle != 0;
  46612. }
  46613. void DirectoryContentsList::changed()
  46614. {
  46615. sendChangeMessage();
  46616. }
  46617. bool DirectoryContentsList::useTimeSlice()
  46618. {
  46619. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46620. bool hasChanged = false;
  46621. for (int i = 100; --i >= 0;)
  46622. {
  46623. if (! checkNextFile (hasChanged))
  46624. {
  46625. if (hasChanged)
  46626. changed();
  46627. return false;
  46628. }
  46629. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46630. break;
  46631. }
  46632. if (hasChanged)
  46633. changed();
  46634. return true;
  46635. }
  46636. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46637. {
  46638. if (fileFindHandle != 0)
  46639. {
  46640. bool fileFoundIsDir, isHidden, isReadOnly;
  46641. int64 fileSize;
  46642. Time modTime, creationTime;
  46643. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46644. &modTime, &creationTime, &isReadOnly))
  46645. {
  46646. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46647. fileSize, modTime, creationTime, isReadOnly))
  46648. {
  46649. hasChanged = true;
  46650. }
  46651. return true;
  46652. }
  46653. else
  46654. {
  46655. fileFindHandle = 0;
  46656. }
  46657. }
  46658. return false;
  46659. }
  46660. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46661. const DirectoryContentsList::FileInfo* const second)
  46662. {
  46663. #if JUCE_WINDOWS
  46664. if (first->isDirectory != second->isDirectory)
  46665. return first->isDirectory ? -1 : 1;
  46666. #endif
  46667. return first->filename.compareIgnoreCase (second->filename);
  46668. }
  46669. bool DirectoryContentsList::addFile (const File& file,
  46670. const bool isDir,
  46671. const int64 fileSize,
  46672. const Time& modTime,
  46673. const Time& creationTime,
  46674. const bool isReadOnly)
  46675. {
  46676. if (fileFilter == 0
  46677. || ((! isDir) && fileFilter->isFileSuitable (file))
  46678. || (isDir && fileFilter->isDirectorySuitable (file)))
  46679. {
  46680. ScopedPointer <FileInfo> info (new FileInfo());
  46681. info->filename = file.getFileName();
  46682. info->fileSize = fileSize;
  46683. info->modificationTime = modTime;
  46684. info->creationTime = creationTime;
  46685. info->isDirectory = isDir;
  46686. info->isReadOnly = isReadOnly;
  46687. const ScopedLock sl (fileListLock);
  46688. for (int i = files.size(); --i >= 0;)
  46689. if (files.getUnchecked(i)->filename == info->filename)
  46690. return false;
  46691. files.addSorted (*this, info.release());
  46692. return true;
  46693. }
  46694. return false;
  46695. }
  46696. END_JUCE_NAMESPACE
  46697. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46698. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46699. BEGIN_JUCE_NAMESPACE
  46700. FileBrowserComponent::FileBrowserComponent (int flags_,
  46701. const File& initialFileOrDirectory,
  46702. const FileFilter* fileFilter_,
  46703. FilePreviewComponent* previewComp_)
  46704. : FileFilter (String::empty),
  46705. fileFilter (fileFilter_),
  46706. flags (flags_),
  46707. previewComp (previewComp_),
  46708. currentPathBox ("path"),
  46709. fileLabel ("f", TRANS ("file:")),
  46710. thread ("Juce FileBrowser")
  46711. {
  46712. // You need to specify one or other of the open/save flags..
  46713. jassert ((flags & (saveMode | openMode)) != 0);
  46714. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46715. // You need to specify at least one of these flags..
  46716. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46717. String filename;
  46718. if (initialFileOrDirectory == File::nonexistent)
  46719. {
  46720. currentRoot = File::getCurrentWorkingDirectory();
  46721. }
  46722. else if (initialFileOrDirectory.isDirectory())
  46723. {
  46724. currentRoot = initialFileOrDirectory;
  46725. }
  46726. else
  46727. {
  46728. chosenFiles.add (initialFileOrDirectory);
  46729. currentRoot = initialFileOrDirectory.getParentDirectory();
  46730. filename = initialFileOrDirectory.getFileName();
  46731. }
  46732. fileList = new DirectoryContentsList (this, thread);
  46733. if ((flags & useTreeView) != 0)
  46734. {
  46735. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46736. fileListComponent = tree;
  46737. if ((flags & canSelectMultipleItems) != 0)
  46738. tree->setMultiSelectEnabled (true);
  46739. addAndMakeVisible (tree);
  46740. }
  46741. else
  46742. {
  46743. FileListComponent* const list = new FileListComponent (*fileList);
  46744. fileListComponent = list;
  46745. list->setOutlineThickness (1);
  46746. if ((flags & canSelectMultipleItems) != 0)
  46747. list->setMultipleSelectionEnabled (true);
  46748. addAndMakeVisible (list);
  46749. }
  46750. fileListComponent->addListener (this);
  46751. addAndMakeVisible (&currentPathBox);
  46752. currentPathBox.setEditableText (true);
  46753. StringArray rootNames, rootPaths;
  46754. const BigInteger separators (getRoots (rootNames, rootPaths));
  46755. for (int i = 0; i < rootNames.size(); ++i)
  46756. {
  46757. if (separators [i])
  46758. currentPathBox.addSeparator();
  46759. currentPathBox.addItem (rootNames[i], i + 1);
  46760. }
  46761. currentPathBox.addSeparator();
  46762. currentPathBox.addListener (this);
  46763. addAndMakeVisible (&filenameBox);
  46764. filenameBox.setMultiLine (false);
  46765. filenameBox.setSelectAllWhenFocused (true);
  46766. filenameBox.setText (filename, false);
  46767. filenameBox.addListener (this);
  46768. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46769. addAndMakeVisible (&fileLabel);
  46770. fileLabel.attachToComponent (&filenameBox, true);
  46771. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46772. goUpButton->addListener (this);
  46773. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46774. if (previewComp != 0)
  46775. addAndMakeVisible (previewComp);
  46776. setRoot (currentRoot);
  46777. thread.startThread (4);
  46778. }
  46779. FileBrowserComponent::~FileBrowserComponent()
  46780. {
  46781. fileListComponent = 0;
  46782. fileList = 0;
  46783. thread.stopThread (10000);
  46784. }
  46785. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46786. {
  46787. listeners.add (newListener);
  46788. }
  46789. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46790. {
  46791. listeners.remove (listener);
  46792. }
  46793. bool FileBrowserComponent::isSaveMode() const throw()
  46794. {
  46795. return (flags & saveMode) != 0;
  46796. }
  46797. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46798. {
  46799. if (chosenFiles.size() == 0 && currentFileIsValid())
  46800. return 1;
  46801. return chosenFiles.size();
  46802. }
  46803. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46804. {
  46805. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46806. return currentRoot;
  46807. if (! filenameBox.isReadOnly())
  46808. return currentRoot.getChildFile (filenameBox.getText());
  46809. return chosenFiles[index];
  46810. }
  46811. bool FileBrowserComponent::currentFileIsValid() const
  46812. {
  46813. if (isSaveMode())
  46814. return ! getSelectedFile (0).isDirectory();
  46815. else
  46816. return getSelectedFile (0).exists();
  46817. }
  46818. const File FileBrowserComponent::getHighlightedFile() const throw()
  46819. {
  46820. return fileListComponent->getSelectedFile (0);
  46821. }
  46822. void FileBrowserComponent::deselectAllFiles()
  46823. {
  46824. fileListComponent->deselectAllFiles();
  46825. }
  46826. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46827. {
  46828. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46829. }
  46830. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46831. {
  46832. return true;
  46833. }
  46834. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46835. {
  46836. if (f.isDirectory())
  46837. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46838. return (flags & canSelectFiles) != 0 && f.exists()
  46839. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46840. }
  46841. const File FileBrowserComponent::getRoot() const
  46842. {
  46843. return currentRoot;
  46844. }
  46845. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46846. {
  46847. if (currentRoot != newRootDirectory)
  46848. {
  46849. fileListComponent->scrollToTop();
  46850. String path (newRootDirectory.getFullPathName());
  46851. if (path.isEmpty())
  46852. path = File::separatorString;
  46853. StringArray rootNames, rootPaths;
  46854. getRoots (rootNames, rootPaths);
  46855. if (! rootPaths.contains (path, true))
  46856. {
  46857. bool alreadyListed = false;
  46858. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46859. {
  46860. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46861. {
  46862. alreadyListed = true;
  46863. break;
  46864. }
  46865. }
  46866. if (! alreadyListed)
  46867. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46868. }
  46869. }
  46870. currentRoot = newRootDirectory;
  46871. fileList->setDirectory (currentRoot, true, true);
  46872. String currentRootName (currentRoot.getFullPathName());
  46873. if (currentRootName.isEmpty())
  46874. currentRootName = File::separatorString;
  46875. currentPathBox.setText (currentRootName, true);
  46876. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46877. && currentRoot.getParentDirectory() != currentRoot);
  46878. }
  46879. void FileBrowserComponent::goUp()
  46880. {
  46881. setRoot (getRoot().getParentDirectory());
  46882. }
  46883. void FileBrowserComponent::refresh()
  46884. {
  46885. fileList->refresh();
  46886. }
  46887. const String FileBrowserComponent::getActionVerb() const
  46888. {
  46889. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46890. }
  46891. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46892. {
  46893. return previewComp;
  46894. }
  46895. void FileBrowserComponent::resized()
  46896. {
  46897. getLookAndFeel()
  46898. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46899. &currentPathBox, &filenameBox, goUpButton);
  46900. }
  46901. void FileBrowserComponent::sendListenerChangeMessage()
  46902. {
  46903. Component::BailOutChecker checker (this);
  46904. if (previewComp != 0)
  46905. previewComp->selectedFileChanged (getSelectedFile (0));
  46906. // You shouldn't delete the browser when the file gets changed!
  46907. jassert (! checker.shouldBailOut());
  46908. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46909. }
  46910. void FileBrowserComponent::selectionChanged()
  46911. {
  46912. StringArray newFilenames;
  46913. bool resetChosenFiles = true;
  46914. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46915. {
  46916. const File f (fileListComponent->getSelectedFile (i));
  46917. if (isFileOrDirSuitable (f))
  46918. {
  46919. if (resetChosenFiles)
  46920. {
  46921. chosenFiles.clear();
  46922. resetChosenFiles = false;
  46923. }
  46924. chosenFiles.add (f);
  46925. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46926. }
  46927. }
  46928. if (newFilenames.size() > 0)
  46929. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46930. sendListenerChangeMessage();
  46931. }
  46932. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46933. {
  46934. Component::BailOutChecker checker (this);
  46935. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46936. }
  46937. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46938. {
  46939. if (f.isDirectory())
  46940. {
  46941. setRoot (f);
  46942. if ((flags & canSelectDirectories) != 0)
  46943. filenameBox.setText (String::empty);
  46944. }
  46945. else
  46946. {
  46947. Component::BailOutChecker checker (this);
  46948. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46949. }
  46950. }
  46951. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46952. {
  46953. (void) key;
  46954. #if JUCE_LINUX || JUCE_WINDOWS
  46955. if (key.getModifiers().isCommandDown()
  46956. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46957. {
  46958. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46959. fileList->refresh();
  46960. return true;
  46961. }
  46962. #endif
  46963. return false;
  46964. }
  46965. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46966. {
  46967. sendListenerChangeMessage();
  46968. }
  46969. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46970. {
  46971. if (filenameBox.getText().containsChar (File::separator))
  46972. {
  46973. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46974. if (f.isDirectory())
  46975. {
  46976. setRoot (f);
  46977. chosenFiles.clear();
  46978. filenameBox.setText (String::empty);
  46979. }
  46980. else
  46981. {
  46982. setRoot (f.getParentDirectory());
  46983. chosenFiles.clear();
  46984. chosenFiles.add (f);
  46985. filenameBox.setText (f.getFileName());
  46986. }
  46987. }
  46988. else
  46989. {
  46990. fileDoubleClicked (getSelectedFile (0));
  46991. }
  46992. }
  46993. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46994. {
  46995. }
  46996. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46997. {
  46998. if (! isSaveMode())
  46999. selectionChanged();
  47000. }
  47001. void FileBrowserComponent::buttonClicked (Button*)
  47002. {
  47003. goUp();
  47004. }
  47005. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47006. {
  47007. const String newText (currentPathBox.getText().trim().unquoted());
  47008. if (newText.isNotEmpty())
  47009. {
  47010. const int index = currentPathBox.getSelectedId() - 1;
  47011. StringArray rootNames, rootPaths;
  47012. getRoots (rootNames, rootPaths);
  47013. if (rootPaths [index].isNotEmpty())
  47014. {
  47015. setRoot (File (rootPaths [index]));
  47016. }
  47017. else
  47018. {
  47019. File f (newText);
  47020. for (;;)
  47021. {
  47022. if (f.isDirectory())
  47023. {
  47024. setRoot (f);
  47025. break;
  47026. }
  47027. if (f.getParentDirectory() == f)
  47028. break;
  47029. f = f.getParentDirectory();
  47030. }
  47031. }
  47032. }
  47033. }
  47034. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47035. {
  47036. BigInteger separators;
  47037. #if JUCE_WINDOWS
  47038. Array<File> roots;
  47039. File::findFileSystemRoots (roots);
  47040. rootPaths.clear();
  47041. for (int i = 0; i < roots.size(); ++i)
  47042. {
  47043. const File& drive = roots.getReference(i);
  47044. String name (drive.getFullPathName());
  47045. rootPaths.add (name);
  47046. if (drive.isOnHardDisk())
  47047. {
  47048. String volume (drive.getVolumeLabel());
  47049. if (volume.isEmpty())
  47050. volume = TRANS("Hard Drive");
  47051. name << " [" << volume << ']';
  47052. }
  47053. else if (drive.isOnCDRomDrive())
  47054. {
  47055. name << TRANS(" [CD/DVD drive]");
  47056. }
  47057. rootNames.add (name);
  47058. }
  47059. separators.setBit (rootPaths.size());
  47060. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47061. rootNames.add ("Documents");
  47062. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47063. rootNames.add ("Desktop");
  47064. #endif
  47065. #if JUCE_MAC
  47066. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47067. rootNames.add ("Home folder");
  47068. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47069. rootNames.add ("Documents");
  47070. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47071. rootNames.add ("Desktop");
  47072. separators.setBit (rootPaths.size());
  47073. Array <File> volumes;
  47074. File vol ("/Volumes");
  47075. vol.findChildFiles (volumes, File::findDirectories, false);
  47076. for (int i = 0; i < volumes.size(); ++i)
  47077. {
  47078. const File& volume = volumes.getReference(i);
  47079. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47080. {
  47081. rootPaths.add (volume.getFullPathName());
  47082. rootNames.add (volume.getFileName());
  47083. }
  47084. }
  47085. #endif
  47086. #if JUCE_LINUX
  47087. rootPaths.add ("/");
  47088. rootNames.add ("/");
  47089. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47090. rootNames.add ("Home folder");
  47091. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47092. rootNames.add ("Desktop");
  47093. #endif
  47094. return separators;
  47095. }
  47096. END_JUCE_NAMESPACE
  47097. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47098. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47099. BEGIN_JUCE_NAMESPACE
  47100. FileChooser::FileChooser (const String& chooserBoxTitle,
  47101. const File& currentFileOrDirectory,
  47102. const String& fileFilters,
  47103. const bool useNativeDialogBox_)
  47104. : title (chooserBoxTitle),
  47105. filters (fileFilters),
  47106. startingFile (currentFileOrDirectory),
  47107. useNativeDialogBox (useNativeDialogBox_)
  47108. {
  47109. #if JUCE_LINUX
  47110. useNativeDialogBox = false;
  47111. #endif
  47112. if (! fileFilters.containsNonWhitespaceChars())
  47113. filters = "*";
  47114. }
  47115. FileChooser::~FileChooser()
  47116. {
  47117. }
  47118. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47119. {
  47120. return showDialog (false, true, false, false, false, previewComponent);
  47121. }
  47122. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47123. {
  47124. return showDialog (false, true, false, false, true, previewComponent);
  47125. }
  47126. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47127. {
  47128. return showDialog (true, true, false, false, true, previewComponent);
  47129. }
  47130. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47131. {
  47132. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47133. }
  47134. bool FileChooser::browseForDirectory()
  47135. {
  47136. return showDialog (true, false, false, false, false, 0);
  47137. }
  47138. const File FileChooser::getResult() const
  47139. {
  47140. // if you've used a multiple-file select, you should use the getResults() method
  47141. // to retrieve all the files that were chosen.
  47142. jassert (results.size() <= 1);
  47143. return results.getFirst();
  47144. }
  47145. const Array<File>& FileChooser::getResults() const
  47146. {
  47147. return results;
  47148. }
  47149. bool FileChooser::showDialog (const bool selectsDirectories,
  47150. const bool selectsFiles,
  47151. const bool isSave,
  47152. const bool warnAboutOverwritingExistingFiles,
  47153. const bool selectMultipleFiles,
  47154. FilePreviewComponent* const previewComponent)
  47155. {
  47156. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47157. results.clear();
  47158. // the preview component needs to be the right size before you pass it in here..
  47159. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47160. && previewComponent->getHeight() > 10));
  47161. #if JUCE_WINDOWS
  47162. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47163. #elif JUCE_MAC
  47164. if (useNativeDialogBox && (previewComponent == 0))
  47165. #else
  47166. if (false)
  47167. #endif
  47168. {
  47169. showPlatformDialog (results, title, startingFile, filters,
  47170. selectsDirectories, selectsFiles, isSave,
  47171. warnAboutOverwritingExistingFiles,
  47172. selectMultipleFiles,
  47173. previewComponent);
  47174. }
  47175. else
  47176. {
  47177. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47178. selectsDirectories ? "*" : String::empty,
  47179. String::empty);
  47180. int flags = isSave ? FileBrowserComponent::saveMode
  47181. : FileBrowserComponent::openMode;
  47182. if (selectsFiles)
  47183. flags |= FileBrowserComponent::canSelectFiles;
  47184. if (selectsDirectories)
  47185. {
  47186. flags |= FileBrowserComponent::canSelectDirectories;
  47187. if (! isSave)
  47188. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47189. }
  47190. if (selectMultipleFiles)
  47191. flags |= FileBrowserComponent::canSelectMultipleItems;
  47192. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47193. FileChooserDialogBox box (title, String::empty,
  47194. browserComponent,
  47195. warnAboutOverwritingExistingFiles,
  47196. browserComponent.findColour (AlertWindow::backgroundColourId));
  47197. if (box.show())
  47198. {
  47199. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47200. results.add (browserComponent.getSelectedFile (i));
  47201. }
  47202. }
  47203. if (previouslyFocused != 0)
  47204. previouslyFocused->grabKeyboardFocus();
  47205. return results.size() > 0;
  47206. }
  47207. FilePreviewComponent::FilePreviewComponent()
  47208. {
  47209. }
  47210. FilePreviewComponent::~FilePreviewComponent()
  47211. {
  47212. }
  47213. END_JUCE_NAMESPACE
  47214. /*** End of inlined file: juce_FileChooser.cpp ***/
  47215. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47216. BEGIN_JUCE_NAMESPACE
  47217. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47218. const String& instructions,
  47219. FileBrowserComponent& chooserComponent,
  47220. const bool warnAboutOverwritingExistingFiles_,
  47221. const Colour& backgroundColour)
  47222. : ResizableWindow (name, backgroundColour, true),
  47223. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47224. {
  47225. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47226. setResizable (true, true);
  47227. setResizeLimits (300, 300, 1200, 1000);
  47228. content->okButton.addListener (this);
  47229. content->cancelButton.addListener (this);
  47230. content->newFolderButton.addListener (this);
  47231. content->chooserComponent.addListener (this);
  47232. selectionChanged();
  47233. }
  47234. FileChooserDialogBox::~FileChooserDialogBox()
  47235. {
  47236. content->chooserComponent.removeListener (this);
  47237. }
  47238. bool FileChooserDialogBox::show (int w, int h)
  47239. {
  47240. return showAt (-1, -1, w, h);
  47241. }
  47242. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47243. {
  47244. if (w <= 0)
  47245. {
  47246. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47247. if (previewComp != 0)
  47248. w = 400 + previewComp->getWidth();
  47249. else
  47250. w = 600;
  47251. }
  47252. if (h <= 0)
  47253. h = 500;
  47254. if (x < 0 || y < 0)
  47255. centreWithSize (w, h);
  47256. else
  47257. setBounds (x, y, w, h);
  47258. const bool ok = (runModalLoop() != 0);
  47259. setVisible (false);
  47260. return ok;
  47261. }
  47262. void FileChooserDialogBox::buttonClicked (Button* button)
  47263. {
  47264. if (button == &(content->okButton))
  47265. {
  47266. okButtonPressed();
  47267. }
  47268. else if (button == &(content->cancelButton))
  47269. {
  47270. closeButtonPressed();
  47271. }
  47272. else if (button == &(content->newFolderButton))
  47273. {
  47274. createNewFolder();
  47275. }
  47276. }
  47277. void FileChooserDialogBox::closeButtonPressed()
  47278. {
  47279. setVisible (false);
  47280. }
  47281. void FileChooserDialogBox::selectionChanged()
  47282. {
  47283. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47284. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47285. && content->chooserComponent.getRoot().isDirectory());
  47286. }
  47287. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47288. {
  47289. }
  47290. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47291. {
  47292. selectionChanged();
  47293. content->okButton.triggerClick();
  47294. }
  47295. void FileChooserDialogBox::okButtonPressed()
  47296. {
  47297. if ((! (warnAboutOverwritingExistingFiles
  47298. && content->chooserComponent.isSaveMode()
  47299. && content->chooserComponent.getSelectedFile(0).exists()))
  47300. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47301. TRANS("File already exists"),
  47302. TRANS("There's already a file called:")
  47303. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47304. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47305. TRANS("overwrite"),
  47306. TRANS("cancel")))
  47307. {
  47308. exitModalState (1);
  47309. }
  47310. }
  47311. void FileChooserDialogBox::createNewFolder()
  47312. {
  47313. File parent (content->chooserComponent.getRoot());
  47314. if (parent.isDirectory())
  47315. {
  47316. AlertWindow aw (TRANS("New Folder"),
  47317. TRANS("Please enter the name for the folder"),
  47318. AlertWindow::NoIcon, this);
  47319. aw.addTextEditor ("name", String::empty, String::empty, false);
  47320. aw.addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47321. aw.addButton (TRANS("cancel"), KeyPress::escapeKey);
  47322. if (aw.runModalLoop() != 0)
  47323. {
  47324. aw.setVisible (false);
  47325. const String name (File::createLegalFileName (aw.getTextEditorContents ("name")));
  47326. if (! name.isEmpty())
  47327. {
  47328. if (! parent.getChildFile (name).createDirectory())
  47329. {
  47330. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  47331. TRANS ("New Folder"),
  47332. TRANS ("Couldn't create the folder!"));
  47333. }
  47334. content->chooserComponent.refresh();
  47335. }
  47336. }
  47337. }
  47338. }
  47339. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47340. : Component (name), instructions (instructions_),
  47341. chooserComponent (chooserComponent_),
  47342. okButton (chooserComponent_.getActionVerb()),
  47343. cancelButton (TRANS ("Cancel")),
  47344. newFolderButton (TRANS ("New Folder"))
  47345. {
  47346. addAndMakeVisible (&chooserComponent);
  47347. addAndMakeVisible (&okButton);
  47348. okButton.addShortcut (KeyPress::returnKey);
  47349. addAndMakeVisible (&cancelButton);
  47350. cancelButton.addShortcut (KeyPress::escapeKey);
  47351. addChildComponent (&newFolderButton);
  47352. setInterceptsMouseClicks (false, true);
  47353. }
  47354. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47355. {
  47356. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47357. text.draw (g);
  47358. }
  47359. void FileChooserDialogBox::ContentComponent::resized()
  47360. {
  47361. const int buttonHeight = 26;
  47362. Rectangle<int> area (getLocalBounds());
  47363. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47364. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47365. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47366. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47367. Rectangle<int> buttonArea (area.reduced (16, 10));
  47368. okButton.changeWidthToFitText (buttonHeight);
  47369. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47370. buttonArea.removeFromRight (16);
  47371. cancelButton.changeWidthToFitText (buttonHeight);
  47372. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47373. newFolderButton.changeWidthToFitText (buttonHeight);
  47374. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47375. }
  47376. END_JUCE_NAMESPACE
  47377. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47378. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47379. BEGIN_JUCE_NAMESPACE
  47380. FileFilter::FileFilter (const String& filterDescription)
  47381. : description (filterDescription)
  47382. {
  47383. }
  47384. FileFilter::~FileFilter()
  47385. {
  47386. }
  47387. const String& FileFilter::getDescription() const throw()
  47388. {
  47389. return description;
  47390. }
  47391. END_JUCE_NAMESPACE
  47392. /*** End of inlined file: juce_FileFilter.cpp ***/
  47393. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47394. BEGIN_JUCE_NAMESPACE
  47395. const Image juce_createIconForFile (const File& file);
  47396. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47397. : ListBox (String::empty, 0),
  47398. DirectoryContentsDisplayComponent (listToShow)
  47399. {
  47400. setModel (this);
  47401. fileList.addChangeListener (this);
  47402. }
  47403. FileListComponent::~FileListComponent()
  47404. {
  47405. fileList.removeChangeListener (this);
  47406. }
  47407. int FileListComponent::getNumSelectedFiles() const
  47408. {
  47409. return getNumSelectedRows();
  47410. }
  47411. const File FileListComponent::getSelectedFile (int index) const
  47412. {
  47413. return fileList.getFile (getSelectedRow (index));
  47414. }
  47415. void FileListComponent::deselectAllFiles()
  47416. {
  47417. deselectAllRows();
  47418. }
  47419. void FileListComponent::scrollToTop()
  47420. {
  47421. getVerticalScrollBar()->setCurrentRangeStart (0);
  47422. }
  47423. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47424. {
  47425. updateContent();
  47426. if (lastDirectory != fileList.getDirectory())
  47427. {
  47428. lastDirectory = fileList.getDirectory();
  47429. deselectAllRows();
  47430. }
  47431. }
  47432. class FileListItemComponent : public Component,
  47433. public TimeSliceClient,
  47434. public AsyncUpdater
  47435. {
  47436. public:
  47437. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47438. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47439. {
  47440. }
  47441. ~FileListItemComponent()
  47442. {
  47443. thread.removeTimeSliceClient (this);
  47444. }
  47445. void paint (Graphics& g)
  47446. {
  47447. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47448. file.getFileName(),
  47449. &icon, fileSize, modTime,
  47450. isDirectory, highlighted,
  47451. index, owner);
  47452. }
  47453. void mouseDown (const MouseEvent& e)
  47454. {
  47455. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47456. owner.sendMouseClickMessage (file, e);
  47457. }
  47458. void mouseDoubleClick (const MouseEvent&)
  47459. {
  47460. owner.sendDoubleClickMessage (file);
  47461. }
  47462. void update (const File& root,
  47463. const DirectoryContentsList::FileInfo* const fileInfo,
  47464. const int index_,
  47465. const bool highlighted_)
  47466. {
  47467. thread.removeTimeSliceClient (this);
  47468. if (highlighted_ != highlighted || index_ != index)
  47469. {
  47470. index = index_;
  47471. highlighted = highlighted_;
  47472. repaint();
  47473. }
  47474. File newFile;
  47475. String newFileSize, newModTime;
  47476. if (fileInfo != 0)
  47477. {
  47478. newFile = root.getChildFile (fileInfo->filename);
  47479. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47480. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47481. }
  47482. if (newFile != file
  47483. || fileSize != newFileSize
  47484. || modTime != newModTime)
  47485. {
  47486. file = newFile;
  47487. fileSize = newFileSize;
  47488. modTime = newModTime;
  47489. icon = Image::null;
  47490. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47491. repaint();
  47492. }
  47493. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47494. {
  47495. updateIcon (true);
  47496. if (! icon.isValid())
  47497. thread.addTimeSliceClient (this);
  47498. }
  47499. }
  47500. bool useTimeSlice()
  47501. {
  47502. updateIcon (false);
  47503. return false;
  47504. }
  47505. void handleAsyncUpdate()
  47506. {
  47507. repaint();
  47508. }
  47509. private:
  47510. FileListComponent& owner;
  47511. TimeSliceThread& thread;
  47512. File file;
  47513. String fileSize, modTime;
  47514. Image icon;
  47515. int index;
  47516. bool highlighted, isDirectory;
  47517. void updateIcon (const bool onlyUpdateIfCached)
  47518. {
  47519. if (icon.isNull())
  47520. {
  47521. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47522. Image im (ImageCache::getFromHashCode (hashCode));
  47523. if (im.isNull() && ! onlyUpdateIfCached)
  47524. {
  47525. im = juce_createIconForFile (file);
  47526. if (im.isValid())
  47527. ImageCache::addImageToCache (im, hashCode);
  47528. }
  47529. if (im.isValid())
  47530. {
  47531. icon = im;
  47532. triggerAsyncUpdate();
  47533. }
  47534. }
  47535. }
  47536. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47537. };
  47538. int FileListComponent::getNumRows()
  47539. {
  47540. return fileList.getNumFiles();
  47541. }
  47542. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47543. {
  47544. }
  47545. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47546. {
  47547. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47548. if (comp == 0)
  47549. {
  47550. delete existingComponentToUpdate;
  47551. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47552. }
  47553. DirectoryContentsList::FileInfo fileInfo;
  47554. if (fileList.getFileInfo (row, fileInfo))
  47555. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47556. else
  47557. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47558. return comp;
  47559. }
  47560. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47561. {
  47562. sendSelectionChangeMessage();
  47563. }
  47564. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47565. {
  47566. }
  47567. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47568. {
  47569. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47570. }
  47571. END_JUCE_NAMESPACE
  47572. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47573. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47574. BEGIN_JUCE_NAMESPACE
  47575. FilenameComponent::FilenameComponent (const String& name,
  47576. const File& currentFile,
  47577. const bool canEditFilename,
  47578. const bool isDirectory,
  47579. const bool isForSaving,
  47580. const String& fileBrowserWildcard,
  47581. const String& enforcedSuffix_,
  47582. const String& textWhenNothingSelected)
  47583. : Component (name),
  47584. maxRecentFiles (30),
  47585. isDir (isDirectory),
  47586. isSaving (isForSaving),
  47587. isFileDragOver (false),
  47588. wildcard (fileBrowserWildcard),
  47589. enforcedSuffix (enforcedSuffix_)
  47590. {
  47591. addAndMakeVisible (&filenameBox);
  47592. filenameBox.setEditableText (canEditFilename);
  47593. filenameBox.addListener (this);
  47594. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47595. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47596. setBrowseButtonText ("...");
  47597. setCurrentFile (currentFile, true);
  47598. }
  47599. FilenameComponent::~FilenameComponent()
  47600. {
  47601. }
  47602. void FilenameComponent::paintOverChildren (Graphics& g)
  47603. {
  47604. if (isFileDragOver)
  47605. {
  47606. g.setColour (Colours::red.withAlpha (0.2f));
  47607. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47608. }
  47609. }
  47610. void FilenameComponent::resized()
  47611. {
  47612. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47613. }
  47614. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47615. {
  47616. browseButtonText = newBrowseButtonText;
  47617. lookAndFeelChanged();
  47618. }
  47619. void FilenameComponent::lookAndFeelChanged()
  47620. {
  47621. browseButton = 0;
  47622. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47623. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47624. resized();
  47625. browseButton->addListener (this);
  47626. }
  47627. void FilenameComponent::setTooltip (const String& newTooltip)
  47628. {
  47629. SettableTooltipClient::setTooltip (newTooltip);
  47630. filenameBox.setTooltip (newTooltip);
  47631. }
  47632. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47633. {
  47634. defaultBrowseFile = newDefaultDirectory;
  47635. }
  47636. void FilenameComponent::buttonClicked (Button*)
  47637. {
  47638. FileChooser fc (TRANS("Choose a new file"),
  47639. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47640. : getCurrentFile(),
  47641. wildcard);
  47642. if (isDir ? fc.browseForDirectory()
  47643. : (isSaving ? fc.browseForFileToSave (false)
  47644. : fc.browseForFileToOpen()))
  47645. {
  47646. setCurrentFile (fc.getResult(), true);
  47647. }
  47648. }
  47649. void FilenameComponent::comboBoxChanged (ComboBox*)
  47650. {
  47651. setCurrentFile (getCurrentFile(), true);
  47652. }
  47653. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47654. {
  47655. return true;
  47656. }
  47657. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47658. {
  47659. isFileDragOver = false;
  47660. repaint();
  47661. const File f (filenames[0]);
  47662. if (f.exists() && (f.isDirectory() == isDir))
  47663. setCurrentFile (f, true);
  47664. }
  47665. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47666. {
  47667. isFileDragOver = true;
  47668. repaint();
  47669. }
  47670. void FilenameComponent::fileDragExit (const StringArray&)
  47671. {
  47672. isFileDragOver = false;
  47673. repaint();
  47674. }
  47675. const File FilenameComponent::getCurrentFile() const
  47676. {
  47677. File f (filenameBox.getText());
  47678. if (enforcedSuffix.isNotEmpty())
  47679. f = f.withFileExtension (enforcedSuffix);
  47680. return f;
  47681. }
  47682. void FilenameComponent::setCurrentFile (File newFile,
  47683. const bool addToRecentlyUsedList,
  47684. const bool sendChangeNotification)
  47685. {
  47686. if (enforcedSuffix.isNotEmpty())
  47687. newFile = newFile.withFileExtension (enforcedSuffix);
  47688. if (newFile.getFullPathName() != lastFilename)
  47689. {
  47690. lastFilename = newFile.getFullPathName();
  47691. if (addToRecentlyUsedList)
  47692. addRecentlyUsedFile (newFile);
  47693. filenameBox.setText (lastFilename, true);
  47694. if (sendChangeNotification)
  47695. triggerAsyncUpdate();
  47696. }
  47697. }
  47698. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47699. {
  47700. filenameBox.setEditableText (shouldBeEditable);
  47701. }
  47702. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47703. {
  47704. StringArray names;
  47705. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47706. names.add (filenameBox.getItemText (i));
  47707. return names;
  47708. }
  47709. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47710. {
  47711. if (filenames != getRecentlyUsedFilenames())
  47712. {
  47713. filenameBox.clear();
  47714. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47715. filenameBox.addItem (filenames[i], i + 1);
  47716. }
  47717. }
  47718. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47719. {
  47720. maxRecentFiles = jmax (1, newMaximum);
  47721. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47722. }
  47723. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47724. {
  47725. StringArray files (getRecentlyUsedFilenames());
  47726. if (file.getFullPathName().isNotEmpty())
  47727. {
  47728. files.removeString (file.getFullPathName(), true);
  47729. files.insert (0, file.getFullPathName());
  47730. setRecentlyUsedFilenames (files);
  47731. }
  47732. }
  47733. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47734. {
  47735. listeners.add (listener);
  47736. }
  47737. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47738. {
  47739. listeners.remove (listener);
  47740. }
  47741. void FilenameComponent::handleAsyncUpdate()
  47742. {
  47743. Component::BailOutChecker checker (this);
  47744. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47745. }
  47746. END_JUCE_NAMESPACE
  47747. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47748. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47749. BEGIN_JUCE_NAMESPACE
  47750. FileSearchPathListComponent::FileSearchPathListComponent()
  47751. : addButton ("+"),
  47752. removeButton ("-"),
  47753. changeButton (TRANS ("change...")),
  47754. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47755. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47756. {
  47757. listBox.setModel (this);
  47758. addAndMakeVisible (&listBox);
  47759. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47760. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47761. listBox.setOutlineThickness (1);
  47762. addAndMakeVisible (&addButton);
  47763. addButton.addListener (this);
  47764. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47765. addAndMakeVisible (&removeButton);
  47766. removeButton.addListener (this);
  47767. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47768. addAndMakeVisible (&changeButton);
  47769. changeButton.addListener (this);
  47770. addAndMakeVisible (&upButton);
  47771. upButton.addListener (this);
  47772. {
  47773. Path arrowPath;
  47774. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47775. DrawablePath arrowImage;
  47776. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47777. arrowImage.setPath (arrowPath);
  47778. upButton.setImages (&arrowImage);
  47779. }
  47780. addAndMakeVisible (&downButton);
  47781. downButton.addListener (this);
  47782. {
  47783. Path arrowPath;
  47784. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47785. DrawablePath arrowImage;
  47786. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47787. arrowImage.setPath (arrowPath);
  47788. downButton.setImages (&arrowImage);
  47789. }
  47790. updateButtons();
  47791. }
  47792. FileSearchPathListComponent::~FileSearchPathListComponent()
  47793. {
  47794. }
  47795. void FileSearchPathListComponent::updateButtons()
  47796. {
  47797. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47798. removeButton.setEnabled (anythingSelected);
  47799. changeButton.setEnabled (anythingSelected);
  47800. upButton.setEnabled (anythingSelected);
  47801. downButton.setEnabled (anythingSelected);
  47802. }
  47803. void FileSearchPathListComponent::changed()
  47804. {
  47805. listBox.updateContent();
  47806. listBox.repaint();
  47807. updateButtons();
  47808. }
  47809. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47810. {
  47811. if (newPath.toString() != path.toString())
  47812. {
  47813. path = newPath;
  47814. changed();
  47815. }
  47816. }
  47817. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47818. {
  47819. defaultBrowseTarget = newDefaultDirectory;
  47820. }
  47821. int FileSearchPathListComponent::getNumRows()
  47822. {
  47823. return path.getNumPaths();
  47824. }
  47825. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47826. {
  47827. if (rowIsSelected)
  47828. g.fillAll (findColour (TextEditor::highlightColourId));
  47829. g.setColour (findColour (ListBox::textColourId));
  47830. Font f (height * 0.7f);
  47831. f.setHorizontalScale (0.9f);
  47832. g.setFont (f);
  47833. g.drawText (path [rowNumber].getFullPathName(),
  47834. 4, 0, width - 6, height,
  47835. Justification::centredLeft, true);
  47836. }
  47837. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47838. {
  47839. if (isPositiveAndBelow (row, path.getNumPaths()))
  47840. {
  47841. path.remove (row);
  47842. changed();
  47843. }
  47844. }
  47845. void FileSearchPathListComponent::returnKeyPressed (int row)
  47846. {
  47847. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47848. if (chooser.browseForDirectory())
  47849. {
  47850. path.remove (row);
  47851. path.add (chooser.getResult(), row);
  47852. changed();
  47853. }
  47854. }
  47855. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47856. {
  47857. returnKeyPressed (row);
  47858. }
  47859. void FileSearchPathListComponent::selectedRowsChanged (int)
  47860. {
  47861. updateButtons();
  47862. }
  47863. void FileSearchPathListComponent::paint (Graphics& g)
  47864. {
  47865. g.fillAll (findColour (backgroundColourId));
  47866. }
  47867. void FileSearchPathListComponent::resized()
  47868. {
  47869. const int buttonH = 22;
  47870. const int buttonY = getHeight() - buttonH - 4;
  47871. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47872. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47873. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47874. changeButton.changeWidthToFitText (buttonH);
  47875. downButton.setSize (buttonH * 2, buttonH);
  47876. upButton.setSize (buttonH * 2, buttonH);
  47877. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47878. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47879. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47880. }
  47881. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47882. {
  47883. return true;
  47884. }
  47885. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47886. {
  47887. for (int i = filenames.size(); --i >= 0;)
  47888. {
  47889. const File f (filenames[i]);
  47890. if (f.isDirectory())
  47891. {
  47892. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47893. path.add (f, row);
  47894. changed();
  47895. }
  47896. }
  47897. }
  47898. void FileSearchPathListComponent::buttonClicked (Button* button)
  47899. {
  47900. const int currentRow = listBox.getSelectedRow();
  47901. if (button == &removeButton)
  47902. {
  47903. deleteKeyPressed (currentRow);
  47904. }
  47905. else if (button == &addButton)
  47906. {
  47907. File start (defaultBrowseTarget);
  47908. if (start == File::nonexistent)
  47909. start = path [0];
  47910. if (start == File::nonexistent)
  47911. start = File::getCurrentWorkingDirectory();
  47912. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47913. if (chooser.browseForDirectory())
  47914. {
  47915. path.add (chooser.getResult(), currentRow);
  47916. }
  47917. }
  47918. else if (button == &changeButton)
  47919. {
  47920. returnKeyPressed (currentRow);
  47921. }
  47922. else if (button == &upButton)
  47923. {
  47924. if (currentRow > 0 && currentRow < path.getNumPaths())
  47925. {
  47926. const File f (path[currentRow]);
  47927. path.remove (currentRow);
  47928. path.add (f, currentRow - 1);
  47929. listBox.selectRow (currentRow - 1);
  47930. }
  47931. }
  47932. else if (button == &downButton)
  47933. {
  47934. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47935. {
  47936. const File f (path[currentRow]);
  47937. path.remove (currentRow);
  47938. path.add (f, currentRow + 1);
  47939. listBox.selectRow (currentRow + 1);
  47940. }
  47941. }
  47942. changed();
  47943. }
  47944. END_JUCE_NAMESPACE
  47945. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47946. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47947. BEGIN_JUCE_NAMESPACE
  47948. const Image juce_createIconForFile (const File& file);
  47949. class FileListTreeItem : public TreeViewItem,
  47950. public TimeSliceClient,
  47951. public AsyncUpdater,
  47952. public ChangeListener
  47953. {
  47954. public:
  47955. FileListTreeItem (FileTreeComponent& owner_,
  47956. DirectoryContentsList* const parentContentsList_,
  47957. const int indexInContentsList_,
  47958. const File& file_,
  47959. TimeSliceThread& thread_)
  47960. : file (file_),
  47961. owner (owner_),
  47962. parentContentsList (parentContentsList_),
  47963. indexInContentsList (indexInContentsList_),
  47964. subContentsList (0),
  47965. canDeleteSubContentsList (false),
  47966. thread (thread_),
  47967. icon (0)
  47968. {
  47969. DirectoryContentsList::FileInfo fileInfo;
  47970. if (parentContentsList_ != 0
  47971. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47972. {
  47973. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47974. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47975. isDirectory = fileInfo.isDirectory;
  47976. }
  47977. else
  47978. {
  47979. isDirectory = true;
  47980. }
  47981. }
  47982. ~FileListTreeItem()
  47983. {
  47984. thread.removeTimeSliceClient (this);
  47985. clearSubItems();
  47986. if (canDeleteSubContentsList)
  47987. delete subContentsList;
  47988. }
  47989. bool mightContainSubItems() { return isDirectory; }
  47990. const String getUniqueName() const { return file.getFullPathName(); }
  47991. int getItemHeight() const { return 22; }
  47992. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47993. void itemOpennessChanged (bool isNowOpen)
  47994. {
  47995. if (isNowOpen)
  47996. {
  47997. clearSubItems();
  47998. isDirectory = file.isDirectory();
  47999. if (isDirectory)
  48000. {
  48001. if (subContentsList == 0)
  48002. {
  48003. jassert (parentContentsList != 0);
  48004. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48005. l->setDirectory (file, true, true);
  48006. setSubContentsList (l);
  48007. canDeleteSubContentsList = true;
  48008. }
  48009. changeListenerCallback (0);
  48010. }
  48011. }
  48012. }
  48013. void setSubContentsList (DirectoryContentsList* newList)
  48014. {
  48015. jassert (subContentsList == 0);
  48016. subContentsList = newList;
  48017. newList->addChangeListener (this);
  48018. }
  48019. void changeListenerCallback (ChangeBroadcaster*)
  48020. {
  48021. clearSubItems();
  48022. if (isOpen() && subContentsList != 0)
  48023. {
  48024. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48025. {
  48026. FileListTreeItem* const item
  48027. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48028. addSubItem (item);
  48029. }
  48030. }
  48031. }
  48032. void paintItem (Graphics& g, int width, int height)
  48033. {
  48034. if (file != File::nonexistent)
  48035. {
  48036. updateIcon (true);
  48037. if (icon.isNull())
  48038. thread.addTimeSliceClient (this);
  48039. }
  48040. owner.getLookAndFeel()
  48041. .drawFileBrowserRow (g, width, height,
  48042. file.getFileName(),
  48043. &icon, fileSize, modTime,
  48044. isDirectory, isSelected(),
  48045. indexInContentsList, owner);
  48046. }
  48047. void itemClicked (const MouseEvent& e)
  48048. {
  48049. owner.sendMouseClickMessage (file, e);
  48050. }
  48051. void itemDoubleClicked (const MouseEvent& e)
  48052. {
  48053. TreeViewItem::itemDoubleClicked (e);
  48054. owner.sendDoubleClickMessage (file);
  48055. }
  48056. void itemSelectionChanged (bool)
  48057. {
  48058. owner.sendSelectionChangeMessage();
  48059. }
  48060. bool useTimeSlice()
  48061. {
  48062. updateIcon (false);
  48063. thread.removeTimeSliceClient (this);
  48064. return false;
  48065. }
  48066. void handleAsyncUpdate()
  48067. {
  48068. owner.repaint();
  48069. }
  48070. const File file;
  48071. private:
  48072. FileTreeComponent& owner;
  48073. DirectoryContentsList* parentContentsList;
  48074. int indexInContentsList;
  48075. DirectoryContentsList* subContentsList;
  48076. bool isDirectory, canDeleteSubContentsList;
  48077. TimeSliceThread& thread;
  48078. Image icon;
  48079. String fileSize;
  48080. String modTime;
  48081. void updateIcon (const bool onlyUpdateIfCached)
  48082. {
  48083. if (icon.isNull())
  48084. {
  48085. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48086. Image im (ImageCache::getFromHashCode (hashCode));
  48087. if (im.isNull() && ! onlyUpdateIfCached)
  48088. {
  48089. im = juce_createIconForFile (file);
  48090. if (im.isValid())
  48091. ImageCache::addImageToCache (im, hashCode);
  48092. }
  48093. if (im.isValid())
  48094. {
  48095. icon = im;
  48096. triggerAsyncUpdate();
  48097. }
  48098. }
  48099. }
  48100. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  48101. };
  48102. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48103. : DirectoryContentsDisplayComponent (listToShow)
  48104. {
  48105. FileListTreeItem* const root
  48106. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48107. listToShow.getTimeSliceThread());
  48108. root->setSubContentsList (&listToShow);
  48109. setRootItemVisible (false);
  48110. setRootItem (root);
  48111. }
  48112. FileTreeComponent::~FileTreeComponent()
  48113. {
  48114. deleteRootItem();
  48115. }
  48116. const File FileTreeComponent::getSelectedFile (const int index) const
  48117. {
  48118. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48119. return item != 0 ? item->file
  48120. : File::nonexistent;
  48121. }
  48122. void FileTreeComponent::deselectAllFiles()
  48123. {
  48124. clearSelectedItems();
  48125. }
  48126. void FileTreeComponent::scrollToTop()
  48127. {
  48128. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48129. }
  48130. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48131. {
  48132. dragAndDropDescription = description;
  48133. }
  48134. END_JUCE_NAMESPACE
  48135. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48136. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48137. BEGIN_JUCE_NAMESPACE
  48138. ImagePreviewComponent::ImagePreviewComponent()
  48139. {
  48140. }
  48141. ImagePreviewComponent::~ImagePreviewComponent()
  48142. {
  48143. }
  48144. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48145. {
  48146. const int availableW = proportionOfWidth (0.97f);
  48147. const int availableH = getHeight() - 13 * 4;
  48148. const double scale = jmin (1.0,
  48149. availableW / (double) w,
  48150. availableH / (double) h);
  48151. w = roundToInt (scale * w);
  48152. h = roundToInt (scale * h);
  48153. }
  48154. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48155. {
  48156. if (fileToLoad != file)
  48157. {
  48158. fileToLoad = file;
  48159. startTimer (100);
  48160. }
  48161. }
  48162. void ImagePreviewComponent::timerCallback()
  48163. {
  48164. stopTimer();
  48165. currentThumbnail = Image::null;
  48166. currentDetails = String::empty;
  48167. repaint();
  48168. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48169. if (in != 0)
  48170. {
  48171. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48172. if (format != 0)
  48173. {
  48174. currentThumbnail = format->decodeImage (*in);
  48175. if (currentThumbnail.isValid())
  48176. {
  48177. int w = currentThumbnail.getWidth();
  48178. int h = currentThumbnail.getHeight();
  48179. currentDetails
  48180. << fileToLoad.getFileName() << "\n"
  48181. << format->getFormatName() << "\n"
  48182. << w << " x " << h << " pixels\n"
  48183. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48184. getThumbSize (w, h);
  48185. currentThumbnail = currentThumbnail.rescaled (w, h);
  48186. }
  48187. }
  48188. }
  48189. }
  48190. void ImagePreviewComponent::paint (Graphics& g)
  48191. {
  48192. if (currentThumbnail.isValid())
  48193. {
  48194. g.setFont (13.0f);
  48195. int w = currentThumbnail.getWidth();
  48196. int h = currentThumbnail.getHeight();
  48197. getThumbSize (w, h);
  48198. const int numLines = 4;
  48199. const int totalH = 13 * numLines + h + 4;
  48200. const int y = (getHeight() - totalH) / 2;
  48201. g.drawImageWithin (currentThumbnail,
  48202. (getWidth() - w) / 2, y, w, h,
  48203. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48204. false);
  48205. g.drawFittedText (currentDetails,
  48206. 0, y + h + 4, getWidth(), 100,
  48207. Justification::centredTop, numLines);
  48208. }
  48209. }
  48210. END_JUCE_NAMESPACE
  48211. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48212. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48213. BEGIN_JUCE_NAMESPACE
  48214. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48215. const String& directoryWildcardPatterns,
  48216. const String& description_)
  48217. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48218. : (description_ + " (" + fileWildcardPatterns + ")"))
  48219. {
  48220. parse (fileWildcardPatterns, fileWildcards);
  48221. parse (directoryWildcardPatterns, directoryWildcards);
  48222. }
  48223. WildcardFileFilter::~WildcardFileFilter()
  48224. {
  48225. }
  48226. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48227. {
  48228. return match (file, fileWildcards);
  48229. }
  48230. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48231. {
  48232. return match (file, directoryWildcards);
  48233. }
  48234. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48235. {
  48236. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48237. result.trim();
  48238. result.removeEmptyStrings();
  48239. // special case for *.*, because people use it to mean "any file", but it
  48240. // would actually ignore files with no extension.
  48241. for (int i = result.size(); --i >= 0;)
  48242. if (result[i] == "*.*")
  48243. result.set (i, "*");
  48244. }
  48245. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48246. {
  48247. const String filename (file.getFileName());
  48248. for (int i = wildcards.size(); --i >= 0;)
  48249. if (filename.matchesWildcard (wildcards[i], true))
  48250. return true;
  48251. return false;
  48252. }
  48253. END_JUCE_NAMESPACE
  48254. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48255. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48256. BEGIN_JUCE_NAMESPACE
  48257. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48258. {
  48259. }
  48260. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48261. {
  48262. }
  48263. namespace KeyboardFocusHelpers
  48264. {
  48265. // This will sort a set of components, so that they are ordered in terms of
  48266. // left-to-right and then top-to-bottom.
  48267. class ScreenPositionComparator
  48268. {
  48269. public:
  48270. ScreenPositionComparator() {}
  48271. static int compareElements (const Component* const first, const Component* const second)
  48272. {
  48273. int explicitOrder1 = first->getExplicitFocusOrder();
  48274. if (explicitOrder1 <= 0)
  48275. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48276. int explicitOrder2 = second->getExplicitFocusOrder();
  48277. if (explicitOrder2 <= 0)
  48278. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48279. if (explicitOrder1 != explicitOrder2)
  48280. return explicitOrder1 - explicitOrder2;
  48281. const int diff = first->getY() - second->getY();
  48282. return (diff == 0) ? first->getX() - second->getX()
  48283. : diff;
  48284. }
  48285. };
  48286. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48287. {
  48288. if (parent->getNumChildComponents() > 0)
  48289. {
  48290. Array <Component*> localComps;
  48291. ScreenPositionComparator comparator;
  48292. int i;
  48293. for (i = parent->getNumChildComponents(); --i >= 0;)
  48294. {
  48295. Component* const c = parent->getChildComponent (i);
  48296. if (c->isVisible() && c->isEnabled())
  48297. localComps.addSorted (comparator, c);
  48298. }
  48299. for (i = 0; i < localComps.size(); ++i)
  48300. {
  48301. Component* const c = localComps.getUnchecked (i);
  48302. if (c->getWantsKeyboardFocus())
  48303. comps.add (c);
  48304. if (! c->isFocusContainer())
  48305. findAllFocusableComponents (c, comps);
  48306. }
  48307. }
  48308. }
  48309. }
  48310. namespace KeyboardFocusHelpers
  48311. {
  48312. Component* getIncrementedComponent (Component* const current, const int delta)
  48313. {
  48314. Component* focusContainer = current->getParentComponent();
  48315. if (focusContainer != 0)
  48316. {
  48317. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48318. focusContainer = focusContainer->getParentComponent();
  48319. if (focusContainer != 0)
  48320. {
  48321. Array <Component*> comps;
  48322. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48323. if (comps.size() > 0)
  48324. {
  48325. const int index = comps.indexOf (current);
  48326. return comps [(index + comps.size() + delta) % comps.size()];
  48327. }
  48328. }
  48329. }
  48330. return 0;
  48331. }
  48332. }
  48333. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48334. {
  48335. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48336. }
  48337. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48338. {
  48339. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48340. }
  48341. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48342. {
  48343. Array <Component*> comps;
  48344. if (parentComponent != 0)
  48345. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48346. return comps.getFirst();
  48347. }
  48348. END_JUCE_NAMESPACE
  48349. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48350. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48351. BEGIN_JUCE_NAMESPACE
  48352. bool KeyListener::keyStateChanged (const bool, Component*)
  48353. {
  48354. return false;
  48355. }
  48356. END_JUCE_NAMESPACE
  48357. /*** End of inlined file: juce_KeyListener.cpp ***/
  48358. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48359. BEGIN_JUCE_NAMESPACE
  48360. // N.B. these two includes are put here deliberately to avoid problems with
  48361. // old GCCs failing on long include paths
  48362. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48363. {
  48364. public:
  48365. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48366. const CommandID commandID_,
  48367. const String& keyName,
  48368. const int keyNum_)
  48369. : Button (keyName),
  48370. owner (owner_),
  48371. commandID (commandID_),
  48372. keyNum (keyNum_)
  48373. {
  48374. setWantsKeyboardFocus (false);
  48375. setTriggeredOnMouseDown (keyNum >= 0);
  48376. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48377. : TRANS("click to change this key-mapping"));
  48378. }
  48379. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48380. {
  48381. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48382. keyNum >= 0 ? getName() : String::empty);
  48383. }
  48384. void clicked()
  48385. {
  48386. if (keyNum >= 0)
  48387. {
  48388. // existing key clicked..
  48389. PopupMenu m;
  48390. m.addItem (1, TRANS("change this key-mapping"));
  48391. m.addSeparator();
  48392. m.addItem (2, TRANS("remove this key-mapping"));
  48393. switch (m.show())
  48394. {
  48395. case 1: assignNewKey(); break;
  48396. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48397. default: break;
  48398. }
  48399. }
  48400. else
  48401. {
  48402. assignNewKey(); // + button pressed..
  48403. }
  48404. }
  48405. void fitToContent (const int h) throw()
  48406. {
  48407. if (keyNum < 0)
  48408. {
  48409. setSize (h, h);
  48410. }
  48411. else
  48412. {
  48413. Font f (h * 0.6f);
  48414. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48415. }
  48416. }
  48417. class KeyEntryWindow : public AlertWindow
  48418. {
  48419. public:
  48420. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48421. : AlertWindow (TRANS("New key-mapping"),
  48422. TRANS("Please press a key combination now..."),
  48423. AlertWindow::NoIcon),
  48424. owner (owner_)
  48425. {
  48426. addButton (TRANS("Ok"), 1);
  48427. addButton (TRANS("Cancel"), 0);
  48428. // (avoid return + escape keys getting processed by the buttons..)
  48429. for (int i = getNumChildComponents(); --i >= 0;)
  48430. getChildComponent (i)->setWantsKeyboardFocus (false);
  48431. setWantsKeyboardFocus (true);
  48432. grabKeyboardFocus();
  48433. }
  48434. bool keyPressed (const KeyPress& key)
  48435. {
  48436. lastPress = key;
  48437. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48438. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48439. if (previousCommand != 0)
  48440. message << "\n\n" << TRANS("(Currently assigned to \"")
  48441. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48442. setMessage (message);
  48443. return true;
  48444. }
  48445. bool keyStateChanged (bool)
  48446. {
  48447. return true;
  48448. }
  48449. KeyPress lastPress;
  48450. private:
  48451. KeyMappingEditorComponent& owner;
  48452. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48453. };
  48454. void assignNewKey()
  48455. {
  48456. KeyEntryWindow entryWindow (owner);
  48457. if (entryWindow.runModalLoop() != 0)
  48458. {
  48459. entryWindow.setVisible (false);
  48460. if (entryWindow.lastPress.isValid())
  48461. {
  48462. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48463. if (previousCommand == 0
  48464. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48465. TRANS("Change key-mapping"),
  48466. TRANS("This key is already assigned to the command \"")
  48467. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48468. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48469. TRANS("Re-assign"),
  48470. TRANS("Cancel")))
  48471. {
  48472. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48473. if (keyNum >= 0)
  48474. owner.getMappings().removeKeyPress (commandID, keyNum);
  48475. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48476. }
  48477. }
  48478. }
  48479. }
  48480. private:
  48481. KeyMappingEditorComponent& owner;
  48482. const CommandID commandID;
  48483. const int keyNum;
  48484. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48485. };
  48486. class KeyMappingEditorComponent::ItemComponent : public Component
  48487. {
  48488. public:
  48489. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48490. : owner (owner_), commandID (commandID_)
  48491. {
  48492. setInterceptsMouseClicks (false, true);
  48493. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48494. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48495. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48496. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48497. addKeyPressButton (String::empty, -1, isReadOnly);
  48498. }
  48499. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48500. {
  48501. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48502. keyChangeButtons.add (b);
  48503. b->setEnabled (! isReadOnly);
  48504. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48505. addChildComponent (b);
  48506. }
  48507. void paint (Graphics& g)
  48508. {
  48509. g.setFont (getHeight() * 0.7f);
  48510. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48511. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48512. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48513. Justification::centredLeft, true);
  48514. }
  48515. void resized()
  48516. {
  48517. int x = getWidth() - 4;
  48518. for (int i = keyChangeButtons.size(); --i >= 0;)
  48519. {
  48520. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48521. b->fitToContent (getHeight() - 2);
  48522. b->setTopRightPosition (x, 1);
  48523. x = b->getX() - 5;
  48524. }
  48525. }
  48526. private:
  48527. KeyMappingEditorComponent& owner;
  48528. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48529. const CommandID commandID;
  48530. enum { maxNumAssignments = 3 };
  48531. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48532. };
  48533. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48534. {
  48535. public:
  48536. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48537. : owner (owner_), commandID (commandID_)
  48538. {
  48539. }
  48540. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48541. bool mightContainSubItems() { return false; }
  48542. int getItemHeight() const { return 20; }
  48543. Component* createItemComponent()
  48544. {
  48545. return new ItemComponent (owner, commandID);
  48546. }
  48547. private:
  48548. KeyMappingEditorComponent& owner;
  48549. const CommandID commandID;
  48550. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48551. };
  48552. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48553. {
  48554. public:
  48555. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48556. : owner (owner_), categoryName (name)
  48557. {
  48558. }
  48559. const String getUniqueName() const { return categoryName + "_cat"; }
  48560. bool mightContainSubItems() { return true; }
  48561. int getItemHeight() const { return 28; }
  48562. void paintItem (Graphics& g, int width, int height)
  48563. {
  48564. g.setFont (height * 0.6f, Font::bold);
  48565. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48566. g.drawText (categoryName,
  48567. 2, 0, width - 2, height,
  48568. Justification::centredLeft, true);
  48569. }
  48570. void itemOpennessChanged (bool isNowOpen)
  48571. {
  48572. if (isNowOpen)
  48573. {
  48574. if (getNumSubItems() == 0)
  48575. {
  48576. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48577. for (int i = 0; i < commands.size(); ++i)
  48578. {
  48579. if (owner.shouldCommandBeIncluded (commands[i]))
  48580. addSubItem (new MappingItem (owner, commands[i]));
  48581. }
  48582. }
  48583. }
  48584. else
  48585. {
  48586. clearSubItems();
  48587. }
  48588. }
  48589. private:
  48590. KeyMappingEditorComponent& owner;
  48591. String categoryName;
  48592. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48593. };
  48594. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48595. public ChangeListener,
  48596. public ButtonListener
  48597. {
  48598. public:
  48599. TopLevelItem (KeyMappingEditorComponent& owner_)
  48600. : owner (owner_)
  48601. {
  48602. setLinesDrawnForSubItems (false);
  48603. owner.getMappings().addChangeListener (this);
  48604. }
  48605. ~TopLevelItem()
  48606. {
  48607. owner.getMappings().removeChangeListener (this);
  48608. }
  48609. bool mightContainSubItems() { return true; }
  48610. const String getUniqueName() const { return "keys"; }
  48611. void changeListenerCallback (ChangeBroadcaster*)
  48612. {
  48613. const ScopedPointer <XmlElement> oldOpenness (owner.tree.getOpennessState (true));
  48614. clearSubItems();
  48615. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48616. for (int i = 0; i < categories.size(); ++i)
  48617. {
  48618. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48619. int count = 0;
  48620. for (int j = 0; j < commands.size(); ++j)
  48621. if (owner.shouldCommandBeIncluded (commands[j]))
  48622. ++count;
  48623. if (count > 0)
  48624. addSubItem (new CategoryItem (owner, categories[i]));
  48625. }
  48626. if (oldOpenness != 0)
  48627. owner.tree.restoreOpennessState (*oldOpenness);
  48628. }
  48629. void buttonClicked (Button*)
  48630. {
  48631. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48632. TRANS("Reset to defaults"),
  48633. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48634. TRANS("Reset")))
  48635. {
  48636. owner.getMappings().resetToDefaultMappings();
  48637. }
  48638. }
  48639. private:
  48640. KeyMappingEditorComponent& owner;
  48641. };
  48642. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48643. const bool showResetToDefaultButton)
  48644. : mappings (mappingManager),
  48645. resetButton (TRANS ("reset to defaults"))
  48646. {
  48647. treeItem = new TopLevelItem (*this);
  48648. if (showResetToDefaultButton)
  48649. {
  48650. addAndMakeVisible (&resetButton);
  48651. resetButton.addListener (treeItem);
  48652. }
  48653. addAndMakeVisible (&tree);
  48654. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48655. tree.setRootItemVisible (false);
  48656. tree.setDefaultOpenness (true);
  48657. tree.setRootItem (treeItem);
  48658. }
  48659. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48660. {
  48661. tree.setRootItem (0);
  48662. }
  48663. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48664. const Colour& textColour)
  48665. {
  48666. setColour (backgroundColourId, mainBackground);
  48667. setColour (textColourId, textColour);
  48668. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48669. }
  48670. void KeyMappingEditorComponent::parentHierarchyChanged()
  48671. {
  48672. treeItem->changeListenerCallback (0);
  48673. }
  48674. void KeyMappingEditorComponent::resized()
  48675. {
  48676. int h = getHeight();
  48677. if (resetButton.isVisible())
  48678. {
  48679. const int buttonHeight = 20;
  48680. h -= buttonHeight + 8;
  48681. int x = getWidth() - 8;
  48682. resetButton.changeWidthToFitText (buttonHeight);
  48683. resetButton.setTopRightPosition (x, h + 6);
  48684. }
  48685. tree.setBounds (0, 0, getWidth(), h);
  48686. }
  48687. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48688. {
  48689. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48690. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48691. }
  48692. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48693. {
  48694. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48695. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48696. }
  48697. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48698. {
  48699. return key.getTextDescription();
  48700. }
  48701. END_JUCE_NAMESPACE
  48702. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48703. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48704. BEGIN_JUCE_NAMESPACE
  48705. KeyPress::KeyPress() throw()
  48706. : keyCode (0),
  48707. mods (0),
  48708. textCharacter (0)
  48709. {
  48710. }
  48711. KeyPress::KeyPress (const int keyCode_,
  48712. const ModifierKeys& mods_,
  48713. const juce_wchar textCharacter_) throw()
  48714. : keyCode (keyCode_),
  48715. mods (mods_),
  48716. textCharacter (textCharacter_)
  48717. {
  48718. }
  48719. KeyPress::KeyPress (const int keyCode_) throw()
  48720. : keyCode (keyCode_),
  48721. textCharacter (0)
  48722. {
  48723. }
  48724. KeyPress::KeyPress (const KeyPress& other) throw()
  48725. : keyCode (other.keyCode),
  48726. mods (other.mods),
  48727. textCharacter (other.textCharacter)
  48728. {
  48729. }
  48730. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48731. {
  48732. keyCode = other.keyCode;
  48733. mods = other.mods;
  48734. textCharacter = other.textCharacter;
  48735. return *this;
  48736. }
  48737. bool KeyPress::operator== (const KeyPress& other) const throw()
  48738. {
  48739. return mods.getRawFlags() == other.mods.getRawFlags()
  48740. && (textCharacter == other.textCharacter
  48741. || textCharacter == 0
  48742. || other.textCharacter == 0)
  48743. && (keyCode == other.keyCode
  48744. || (keyCode < 256
  48745. && other.keyCode < 256
  48746. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48747. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48748. }
  48749. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48750. {
  48751. return ! operator== (other);
  48752. }
  48753. bool KeyPress::isCurrentlyDown() const
  48754. {
  48755. return isKeyCurrentlyDown (keyCode)
  48756. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48757. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48758. }
  48759. namespace KeyPressHelpers
  48760. {
  48761. struct KeyNameAndCode
  48762. {
  48763. const char* name;
  48764. int code;
  48765. };
  48766. const KeyNameAndCode translations[] =
  48767. {
  48768. { "spacebar", KeyPress::spaceKey },
  48769. { "return", KeyPress::returnKey },
  48770. { "escape", KeyPress::escapeKey },
  48771. { "backspace", KeyPress::backspaceKey },
  48772. { "cursor left", KeyPress::leftKey },
  48773. { "cursor right", KeyPress::rightKey },
  48774. { "cursor up", KeyPress::upKey },
  48775. { "cursor down", KeyPress::downKey },
  48776. { "page up", KeyPress::pageUpKey },
  48777. { "page down", KeyPress::pageDownKey },
  48778. { "home", KeyPress::homeKey },
  48779. { "end", KeyPress::endKey },
  48780. { "delete", KeyPress::deleteKey },
  48781. { "insert", KeyPress::insertKey },
  48782. { "tab", KeyPress::tabKey },
  48783. { "play", KeyPress::playKey },
  48784. { "stop", KeyPress::stopKey },
  48785. { "fast forward", KeyPress::fastForwardKey },
  48786. { "rewind", KeyPress::rewindKey }
  48787. };
  48788. const String numberPadPrefix() { return "numpad "; }
  48789. }
  48790. const KeyPress KeyPress::createFromDescription (const String& desc)
  48791. {
  48792. int modifiers = 0;
  48793. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48794. || desc.containsWholeWordIgnoreCase ("control")
  48795. || desc.containsWholeWordIgnoreCase ("ctl"))
  48796. modifiers |= ModifierKeys::ctrlModifier;
  48797. if (desc.containsWholeWordIgnoreCase ("shift")
  48798. || desc.containsWholeWordIgnoreCase ("shft"))
  48799. modifiers |= ModifierKeys::shiftModifier;
  48800. if (desc.containsWholeWordIgnoreCase ("alt")
  48801. || desc.containsWholeWordIgnoreCase ("option"))
  48802. modifiers |= ModifierKeys::altModifier;
  48803. if (desc.containsWholeWordIgnoreCase ("command")
  48804. || desc.containsWholeWordIgnoreCase ("cmd"))
  48805. modifiers |= ModifierKeys::commandModifier;
  48806. int key = 0;
  48807. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48808. {
  48809. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48810. {
  48811. key = KeyPressHelpers::translations[i].code;
  48812. break;
  48813. }
  48814. }
  48815. if (key == 0)
  48816. {
  48817. // see if it's a numpad key..
  48818. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48819. {
  48820. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48821. if (lastChar >= '0' && lastChar <= '9')
  48822. key = numberPad0 + lastChar - '0';
  48823. else if (lastChar == '+')
  48824. key = numberPadAdd;
  48825. else if (lastChar == '-')
  48826. key = numberPadSubtract;
  48827. else if (lastChar == '*')
  48828. key = numberPadMultiply;
  48829. else if (lastChar == '/')
  48830. key = numberPadDivide;
  48831. else if (lastChar == '.')
  48832. key = numberPadDecimalPoint;
  48833. else if (lastChar == '=')
  48834. key = numberPadEquals;
  48835. else if (desc.endsWith ("separator"))
  48836. key = numberPadSeparator;
  48837. else if (desc.endsWith ("delete"))
  48838. key = numberPadDelete;
  48839. }
  48840. if (key == 0)
  48841. {
  48842. // see if it's a function key..
  48843. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48844. for (int i = 1; i <= 12; ++i)
  48845. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48846. key = F1Key + i - 1;
  48847. if (key == 0)
  48848. {
  48849. // give up and use the hex code..
  48850. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48851. .toLowerCase()
  48852. .retainCharacters ("0123456789abcdef")
  48853. .getHexValue32();
  48854. if (hexCode > 0)
  48855. key = hexCode;
  48856. else
  48857. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48858. }
  48859. }
  48860. }
  48861. return KeyPress (key, ModifierKeys (modifiers), 0);
  48862. }
  48863. const String KeyPress::getTextDescription() const
  48864. {
  48865. String desc;
  48866. if (keyCode > 0)
  48867. {
  48868. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48869. // want to store it as being a slash, not shift+whatever.
  48870. if (textCharacter == '/')
  48871. return "/";
  48872. if (mods.isCtrlDown())
  48873. desc << "ctrl + ";
  48874. if (mods.isShiftDown())
  48875. desc << "shift + ";
  48876. #if JUCE_MAC
  48877. // only do this on the mac, because on Windows ctrl and command are the same,
  48878. // and this would get confusing
  48879. if (mods.isCommandDown())
  48880. desc << "command + ";
  48881. if (mods.isAltDown())
  48882. desc << "option + ";
  48883. #else
  48884. if (mods.isAltDown())
  48885. desc << "alt + ";
  48886. #endif
  48887. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48888. if (keyCode == KeyPressHelpers::translations[i].code)
  48889. return desc + KeyPressHelpers::translations[i].name;
  48890. if (keyCode >= F1Key && keyCode <= F16Key)
  48891. desc << 'F' << (1 + keyCode - F1Key);
  48892. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48893. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48894. else if (keyCode >= 33 && keyCode < 176)
  48895. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48896. else if (keyCode == numberPadAdd)
  48897. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48898. else if (keyCode == numberPadSubtract)
  48899. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48900. else if (keyCode == numberPadMultiply)
  48901. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48902. else if (keyCode == numberPadDivide)
  48903. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48904. else if (keyCode == numberPadSeparator)
  48905. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48906. else if (keyCode == numberPadDecimalPoint)
  48907. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48908. else if (keyCode == numberPadDelete)
  48909. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48910. else
  48911. desc << '#' << String::toHexString (keyCode);
  48912. }
  48913. return desc;
  48914. }
  48915. END_JUCE_NAMESPACE
  48916. /*** End of inlined file: juce_KeyPress.cpp ***/
  48917. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48918. BEGIN_JUCE_NAMESPACE
  48919. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48920. : commandManager (commandManager_)
  48921. {
  48922. // A manager is needed to get the descriptions of commands, and will be called when
  48923. // a command is invoked. So you can't leave this null..
  48924. jassert (commandManager_ != 0);
  48925. Desktop::getInstance().addFocusChangeListener (this);
  48926. }
  48927. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48928. : commandManager (other.commandManager)
  48929. {
  48930. Desktop::getInstance().addFocusChangeListener (this);
  48931. }
  48932. KeyPressMappingSet::~KeyPressMappingSet()
  48933. {
  48934. Desktop::getInstance().removeFocusChangeListener (this);
  48935. }
  48936. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48937. {
  48938. for (int i = 0; i < mappings.size(); ++i)
  48939. if (mappings.getUnchecked(i)->commandID == commandID)
  48940. return mappings.getUnchecked (i)->keypresses;
  48941. return Array <KeyPress> ();
  48942. }
  48943. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48944. const KeyPress& newKeyPress,
  48945. int insertIndex)
  48946. {
  48947. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48948. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48949. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48950. && ! newKeyPress.getModifiers().isShiftDown()));
  48951. if (findCommandForKeyPress (newKeyPress) != commandID)
  48952. {
  48953. removeKeyPress (newKeyPress);
  48954. if (newKeyPress.isValid())
  48955. {
  48956. for (int i = mappings.size(); --i >= 0;)
  48957. {
  48958. if (mappings.getUnchecked(i)->commandID == commandID)
  48959. {
  48960. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48961. sendChangeMessage();
  48962. return;
  48963. }
  48964. }
  48965. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48966. if (ci != 0)
  48967. {
  48968. CommandMapping* const cm = new CommandMapping();
  48969. cm->commandID = commandID;
  48970. cm->keypresses.add (newKeyPress);
  48971. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48972. mappings.add (cm);
  48973. sendChangeMessage();
  48974. }
  48975. }
  48976. }
  48977. }
  48978. void KeyPressMappingSet::resetToDefaultMappings()
  48979. {
  48980. mappings.clear();
  48981. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48982. {
  48983. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48984. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48985. {
  48986. addKeyPress (ci->commandID,
  48987. ci->defaultKeypresses.getReference (j));
  48988. }
  48989. }
  48990. sendChangeMessage();
  48991. }
  48992. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48993. {
  48994. clearAllKeyPresses (commandID);
  48995. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48996. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48997. {
  48998. addKeyPress (ci->commandID,
  48999. ci->defaultKeypresses.getReference (j));
  49000. }
  49001. }
  49002. void KeyPressMappingSet::clearAllKeyPresses()
  49003. {
  49004. if (mappings.size() > 0)
  49005. {
  49006. sendChangeMessage();
  49007. mappings.clear();
  49008. }
  49009. }
  49010. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49011. {
  49012. for (int i = mappings.size(); --i >= 0;)
  49013. {
  49014. if (mappings.getUnchecked(i)->commandID == commandID)
  49015. {
  49016. mappings.remove (i);
  49017. sendChangeMessage();
  49018. }
  49019. }
  49020. }
  49021. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49022. {
  49023. if (keypress.isValid())
  49024. {
  49025. for (int i = mappings.size(); --i >= 0;)
  49026. {
  49027. CommandMapping* const cm = mappings.getUnchecked(i);
  49028. for (int j = cm->keypresses.size(); --j >= 0;)
  49029. {
  49030. if (keypress == cm->keypresses [j])
  49031. {
  49032. cm->keypresses.remove (j);
  49033. sendChangeMessage();
  49034. }
  49035. }
  49036. }
  49037. }
  49038. }
  49039. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49040. {
  49041. for (int i = mappings.size(); --i >= 0;)
  49042. {
  49043. if (mappings.getUnchecked(i)->commandID == commandID)
  49044. {
  49045. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49046. sendChangeMessage();
  49047. break;
  49048. }
  49049. }
  49050. }
  49051. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49052. {
  49053. for (int i = 0; i < mappings.size(); ++i)
  49054. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49055. return mappings.getUnchecked(i)->commandID;
  49056. return 0;
  49057. }
  49058. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49059. {
  49060. for (int i = mappings.size(); --i >= 0;)
  49061. if (mappings.getUnchecked(i)->commandID == commandID)
  49062. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49063. return false;
  49064. }
  49065. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49066. const KeyPress& key,
  49067. const bool isKeyDown,
  49068. const int millisecsSinceKeyPressed,
  49069. Component* const originatingComponent) const
  49070. {
  49071. ApplicationCommandTarget::InvocationInfo info (commandID);
  49072. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49073. info.isKeyDown = isKeyDown;
  49074. info.keyPress = key;
  49075. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49076. info.originatingComponent = originatingComponent;
  49077. commandManager->invoke (info, false);
  49078. }
  49079. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49080. {
  49081. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49082. {
  49083. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49084. {
  49085. // if the XML was created as a set of differences from the default mappings,
  49086. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49087. resetToDefaultMappings();
  49088. }
  49089. else
  49090. {
  49091. // if the XML was created calling createXml (false), then we need to clear all
  49092. // the keys and treat the xml as describing the entire set of mappings.
  49093. clearAllKeyPresses();
  49094. }
  49095. forEachXmlChildElement (xmlVersion, map)
  49096. {
  49097. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49098. if (commandId != 0)
  49099. {
  49100. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49101. if (map->hasTagName ("MAPPING"))
  49102. {
  49103. addKeyPress (commandId, key);
  49104. }
  49105. else if (map->hasTagName ("UNMAPPING"))
  49106. {
  49107. if (containsMapping (commandId, key))
  49108. removeKeyPress (key);
  49109. }
  49110. }
  49111. }
  49112. return true;
  49113. }
  49114. return false;
  49115. }
  49116. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49117. {
  49118. ScopedPointer <KeyPressMappingSet> defaultSet;
  49119. if (saveDifferencesFromDefaultSet)
  49120. {
  49121. defaultSet = new KeyPressMappingSet (commandManager);
  49122. defaultSet->resetToDefaultMappings();
  49123. }
  49124. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49125. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49126. int i;
  49127. for (i = 0; i < mappings.size(); ++i)
  49128. {
  49129. const CommandMapping* const cm = mappings.getUnchecked(i);
  49130. for (int j = 0; j < cm->keypresses.size(); ++j)
  49131. {
  49132. if (defaultSet == 0
  49133. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49134. {
  49135. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49136. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49137. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49138. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49139. }
  49140. }
  49141. }
  49142. if (defaultSet != 0)
  49143. {
  49144. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49145. {
  49146. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49147. for (int j = 0; j < cm->keypresses.size(); ++j)
  49148. {
  49149. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49150. {
  49151. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49152. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49153. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49154. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49155. }
  49156. }
  49157. }
  49158. }
  49159. return doc;
  49160. }
  49161. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49162. Component* originatingComponent)
  49163. {
  49164. bool used = false;
  49165. const CommandID commandID = findCommandForKeyPress (key);
  49166. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49167. if (ci != 0
  49168. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49169. {
  49170. ApplicationCommandInfo info (0);
  49171. if (commandManager->getTargetForCommand (commandID, info) != 0
  49172. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49173. {
  49174. invokeCommand (commandID, key, true, 0, originatingComponent);
  49175. used = true;
  49176. }
  49177. else
  49178. {
  49179. if (originatingComponent != 0)
  49180. originatingComponent->getLookAndFeel().playAlertSound();
  49181. }
  49182. }
  49183. return used;
  49184. }
  49185. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49186. {
  49187. bool used = false;
  49188. const uint32 now = Time::getMillisecondCounter();
  49189. for (int i = mappings.size(); --i >= 0;)
  49190. {
  49191. CommandMapping* const cm = mappings.getUnchecked(i);
  49192. if (cm->wantsKeyUpDownCallbacks)
  49193. {
  49194. for (int j = cm->keypresses.size(); --j >= 0;)
  49195. {
  49196. const KeyPress key (cm->keypresses.getReference (j));
  49197. const bool isDown = key.isCurrentlyDown();
  49198. int keyPressEntryIndex = 0;
  49199. bool wasDown = false;
  49200. for (int k = keysDown.size(); --k >= 0;)
  49201. {
  49202. if (key == keysDown.getUnchecked(k)->key)
  49203. {
  49204. keyPressEntryIndex = k;
  49205. wasDown = true;
  49206. used = true;
  49207. break;
  49208. }
  49209. }
  49210. if (isDown != wasDown)
  49211. {
  49212. int millisecs = 0;
  49213. if (isDown)
  49214. {
  49215. KeyPressTime* const k = new KeyPressTime();
  49216. k->key = key;
  49217. k->timeWhenPressed = now;
  49218. keysDown.add (k);
  49219. }
  49220. else
  49221. {
  49222. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49223. if (now > pressTime)
  49224. millisecs = now - pressTime;
  49225. keysDown.remove (keyPressEntryIndex);
  49226. }
  49227. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49228. used = true;
  49229. }
  49230. }
  49231. }
  49232. }
  49233. return used;
  49234. }
  49235. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49236. {
  49237. if (focusedComponent != 0)
  49238. focusedComponent->keyStateChanged (false);
  49239. }
  49240. END_JUCE_NAMESPACE
  49241. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49242. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49243. BEGIN_JUCE_NAMESPACE
  49244. ModifierKeys::ModifierKeys (const int flags_) throw()
  49245. : flags (flags_)
  49246. {
  49247. }
  49248. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49249. : flags (other.flags)
  49250. {
  49251. }
  49252. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49253. {
  49254. flags = other.flags;
  49255. return *this;
  49256. }
  49257. ModifierKeys ModifierKeys::currentModifiers;
  49258. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49259. {
  49260. return currentModifiers;
  49261. }
  49262. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49263. {
  49264. int num = 0;
  49265. if (isLeftButtonDown()) ++num;
  49266. if (isRightButtonDown()) ++num;
  49267. if (isMiddleButtonDown()) ++num;
  49268. return num;
  49269. }
  49270. END_JUCE_NAMESPACE
  49271. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49272. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49273. BEGIN_JUCE_NAMESPACE
  49274. class ComponentAnimator::AnimationTask
  49275. {
  49276. public:
  49277. AnimationTask (Component* const comp)
  49278. : component (comp)
  49279. {
  49280. }
  49281. void reset (const Rectangle<int>& finalBounds,
  49282. float finalAlpha,
  49283. int millisecondsToSpendMoving,
  49284. bool useProxyComponent,
  49285. double startSpeed_, double endSpeed_)
  49286. {
  49287. msElapsed = 0;
  49288. msTotal = jmax (1, millisecondsToSpendMoving);
  49289. lastProgress = 0;
  49290. destination = finalBounds;
  49291. destAlpha = finalAlpha;
  49292. isMoving = (finalBounds != component->getBounds());
  49293. isChangingAlpha = (finalAlpha != component->getAlpha());
  49294. left = component->getX();
  49295. top = component->getY();
  49296. right = component->getRight();
  49297. bottom = component->getBottom();
  49298. alpha = component->getAlpha();
  49299. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49300. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49301. midSpeed = invTotalDistance;
  49302. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49303. if (useProxyComponent)
  49304. proxy = new ProxyComponent (*component);
  49305. else
  49306. proxy = 0;
  49307. component->setVisible (! useProxyComponent);
  49308. }
  49309. bool useTimeslice (const int elapsed)
  49310. {
  49311. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49312. : static_cast <Component*> (component);
  49313. if (c != 0)
  49314. {
  49315. msElapsed += elapsed;
  49316. double newProgress = msElapsed / (double) msTotal;
  49317. if (newProgress >= 0 && newProgress < 1.0)
  49318. {
  49319. newProgress = timeToDistance (newProgress);
  49320. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49321. jassert (newProgress >= lastProgress);
  49322. lastProgress = newProgress;
  49323. if (delta < 1.0)
  49324. {
  49325. bool stillBusy = false;
  49326. if (isMoving)
  49327. {
  49328. left += (destination.getX() - left) * delta;
  49329. top += (destination.getY() - top) * delta;
  49330. right += (destination.getRight() - right) * delta;
  49331. bottom += (destination.getBottom() - bottom) * delta;
  49332. const Rectangle<int> newBounds (roundToInt (left),
  49333. roundToInt (top),
  49334. roundToInt (right - left),
  49335. roundToInt (bottom - top));
  49336. if (newBounds != destination)
  49337. {
  49338. c->setBounds (newBounds);
  49339. stillBusy = true;
  49340. }
  49341. }
  49342. if (isChangingAlpha)
  49343. {
  49344. alpha += (destAlpha - alpha) * delta;
  49345. c->setAlpha ((float) alpha);
  49346. stillBusy = true;
  49347. }
  49348. if (stillBusy)
  49349. return true;
  49350. }
  49351. }
  49352. }
  49353. moveToFinalDestination();
  49354. return false;
  49355. }
  49356. void moveToFinalDestination()
  49357. {
  49358. if (component != 0)
  49359. {
  49360. component->setAlpha ((float) destAlpha);
  49361. component->setBounds (destination);
  49362. }
  49363. }
  49364. class ProxyComponent : public Component
  49365. {
  49366. public:
  49367. ProxyComponent (Component& component)
  49368. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49369. {
  49370. setBounds (component.getBounds());
  49371. setAlpha (component.getAlpha());
  49372. setInterceptsMouseClicks (false, false);
  49373. Component* const parent = component.getParentComponent();
  49374. if (parent != 0)
  49375. parent->addAndMakeVisible (this);
  49376. else if (component.isOnDesktop() && component.getPeer() != 0)
  49377. addToDesktop (component.getPeer()->getStyleFlags());
  49378. else
  49379. jassertfalse; // seem to be trying to animate a component that's not visible..
  49380. setVisible (true);
  49381. toBehind (&component);
  49382. }
  49383. void paint (Graphics& g)
  49384. {
  49385. g.setOpacity (1.0f);
  49386. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49387. 0, 0, image.getWidth(), image.getHeight());
  49388. }
  49389. private:
  49390. Image image;
  49391. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49392. };
  49393. WeakReference<Component> component;
  49394. ScopedPointer<Component> proxy;
  49395. Rectangle<int> destination;
  49396. double destAlpha;
  49397. int msElapsed, msTotal;
  49398. double startSpeed, midSpeed, endSpeed, lastProgress;
  49399. double left, top, right, bottom, alpha;
  49400. bool isMoving, isChangingAlpha;
  49401. private:
  49402. double timeToDistance (const double time) const throw()
  49403. {
  49404. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49405. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49406. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49407. }
  49408. };
  49409. ComponentAnimator::ComponentAnimator()
  49410. : lastTime (0)
  49411. {
  49412. }
  49413. ComponentAnimator::~ComponentAnimator()
  49414. {
  49415. }
  49416. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49417. {
  49418. for (int i = tasks.size(); --i >= 0;)
  49419. if (component == tasks.getUnchecked(i)->component.get())
  49420. return tasks.getUnchecked(i);
  49421. return 0;
  49422. }
  49423. void ComponentAnimator::animateComponent (Component* const component,
  49424. const Rectangle<int>& finalBounds,
  49425. const float finalAlpha,
  49426. const int millisecondsToSpendMoving,
  49427. const bool useProxyComponent,
  49428. const double startSpeed,
  49429. const double endSpeed)
  49430. {
  49431. // the speeds must be 0 or greater!
  49432. jassert (startSpeed >= 0 && endSpeed >= 0)
  49433. if (component != 0)
  49434. {
  49435. AnimationTask* at = findTaskFor (component);
  49436. if (at == 0)
  49437. {
  49438. at = new AnimationTask (component);
  49439. tasks.add (at);
  49440. sendChangeMessage();
  49441. }
  49442. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49443. useProxyComponent, startSpeed, endSpeed);
  49444. if (! isTimerRunning())
  49445. {
  49446. lastTime = Time::getMillisecondCounter();
  49447. startTimer (1000 / 50);
  49448. }
  49449. }
  49450. }
  49451. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49452. {
  49453. if (component != 0)
  49454. {
  49455. if (component->isShowing() && millisecondsToTake > 0)
  49456. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49457. component->setVisible (false);
  49458. }
  49459. }
  49460. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49461. {
  49462. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49463. {
  49464. component->setAlpha (0.0f);
  49465. component->setVisible (true);
  49466. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49467. }
  49468. }
  49469. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49470. {
  49471. if (tasks.size() > 0)
  49472. {
  49473. if (moveComponentsToTheirFinalPositions)
  49474. for (int i = tasks.size(); --i >= 0;)
  49475. tasks.getUnchecked(i)->moveToFinalDestination();
  49476. tasks.clear();
  49477. sendChangeMessage();
  49478. }
  49479. }
  49480. void ComponentAnimator::cancelAnimation (Component* const component,
  49481. const bool moveComponentToItsFinalPosition)
  49482. {
  49483. AnimationTask* const at = findTaskFor (component);
  49484. if (at != 0)
  49485. {
  49486. if (moveComponentToItsFinalPosition)
  49487. at->moveToFinalDestination();
  49488. tasks.removeObject (at);
  49489. sendChangeMessage();
  49490. }
  49491. }
  49492. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49493. {
  49494. jassert (component != 0);
  49495. AnimationTask* const at = findTaskFor (component);
  49496. if (at != 0)
  49497. return at->destination;
  49498. return component->getBounds();
  49499. }
  49500. bool ComponentAnimator::isAnimating (Component* component) const
  49501. {
  49502. return findTaskFor (component) != 0;
  49503. }
  49504. void ComponentAnimator::timerCallback()
  49505. {
  49506. const uint32 timeNow = Time::getMillisecondCounter();
  49507. if (lastTime == 0 || lastTime == timeNow)
  49508. lastTime = timeNow;
  49509. const int elapsed = timeNow - lastTime;
  49510. for (int i = tasks.size(); --i >= 0;)
  49511. {
  49512. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49513. {
  49514. tasks.remove (i);
  49515. sendChangeMessage();
  49516. }
  49517. }
  49518. lastTime = timeNow;
  49519. if (tasks.size() == 0)
  49520. stopTimer();
  49521. }
  49522. END_JUCE_NAMESPACE
  49523. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49524. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49525. BEGIN_JUCE_NAMESPACE
  49526. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49527. : minW (0),
  49528. maxW (0x3fffffff),
  49529. minH (0),
  49530. maxH (0x3fffffff),
  49531. minOffTop (0),
  49532. minOffLeft (0),
  49533. minOffBottom (0),
  49534. minOffRight (0),
  49535. aspectRatio (0.0)
  49536. {
  49537. }
  49538. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49539. {
  49540. }
  49541. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49542. {
  49543. minW = minimumWidth;
  49544. }
  49545. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49546. {
  49547. maxW = maximumWidth;
  49548. }
  49549. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49550. {
  49551. minH = minimumHeight;
  49552. }
  49553. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49554. {
  49555. maxH = maximumHeight;
  49556. }
  49557. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49558. {
  49559. jassert (maxW >= minimumWidth);
  49560. jassert (maxH >= minimumHeight);
  49561. jassert (minimumWidth > 0 && minimumHeight > 0);
  49562. minW = minimumWidth;
  49563. minH = minimumHeight;
  49564. if (minW > maxW)
  49565. maxW = minW;
  49566. if (minH > maxH)
  49567. maxH = minH;
  49568. }
  49569. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49570. {
  49571. jassert (maximumWidth >= minW);
  49572. jassert (maximumHeight >= minH);
  49573. jassert (maximumWidth > 0 && maximumHeight > 0);
  49574. maxW = jmax (minW, maximumWidth);
  49575. maxH = jmax (minH, maximumHeight);
  49576. }
  49577. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49578. const int minimumHeight,
  49579. const int maximumWidth,
  49580. const int maximumHeight) throw()
  49581. {
  49582. jassert (maximumWidth >= minimumWidth);
  49583. jassert (maximumHeight >= minimumHeight);
  49584. jassert (maximumWidth > 0 && maximumHeight > 0);
  49585. jassert (minimumWidth > 0 && minimumHeight > 0);
  49586. minW = jmax (0, minimumWidth);
  49587. minH = jmax (0, minimumHeight);
  49588. maxW = jmax (minW, maximumWidth);
  49589. maxH = jmax (minH, maximumHeight);
  49590. }
  49591. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49592. const int minimumWhenOffTheLeft,
  49593. const int minimumWhenOffTheBottom,
  49594. const int minimumWhenOffTheRight) throw()
  49595. {
  49596. minOffTop = minimumWhenOffTheTop;
  49597. minOffLeft = minimumWhenOffTheLeft;
  49598. minOffBottom = minimumWhenOffTheBottom;
  49599. minOffRight = minimumWhenOffTheRight;
  49600. }
  49601. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49602. {
  49603. aspectRatio = jmax (0.0, widthOverHeight);
  49604. }
  49605. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49606. {
  49607. return aspectRatio;
  49608. }
  49609. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49610. const Rectangle<int>& targetBounds,
  49611. const bool isStretchingTop,
  49612. const bool isStretchingLeft,
  49613. const bool isStretchingBottom,
  49614. const bool isStretchingRight)
  49615. {
  49616. jassert (component != 0);
  49617. Rectangle<int> limits, bounds (targetBounds);
  49618. BorderSize border;
  49619. Component* const parent = component->getParentComponent();
  49620. if (parent == 0)
  49621. {
  49622. ComponentPeer* peer = component->getPeer();
  49623. if (peer != 0)
  49624. border = peer->getFrameSize();
  49625. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49626. }
  49627. else
  49628. {
  49629. limits.setSize (parent->getWidth(), parent->getHeight());
  49630. }
  49631. border.addTo (bounds);
  49632. checkBounds (bounds,
  49633. border.addedTo (component->getBounds()), limits,
  49634. isStretchingTop, isStretchingLeft,
  49635. isStretchingBottom, isStretchingRight);
  49636. border.subtractFrom (bounds);
  49637. applyBoundsToComponent (component, bounds);
  49638. }
  49639. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49640. {
  49641. setBoundsForComponent (component, component->getBounds(),
  49642. false, false, false, false);
  49643. }
  49644. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49645. const Rectangle<int>& bounds)
  49646. {
  49647. component->setBounds (bounds);
  49648. }
  49649. void ComponentBoundsConstrainer::resizeStart()
  49650. {
  49651. }
  49652. void ComponentBoundsConstrainer::resizeEnd()
  49653. {
  49654. }
  49655. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49656. const Rectangle<int>& old,
  49657. const Rectangle<int>& limits,
  49658. const bool isStretchingTop,
  49659. const bool isStretchingLeft,
  49660. const bool isStretchingBottom,
  49661. const bool isStretchingRight)
  49662. {
  49663. // constrain the size if it's being stretched..
  49664. if (isStretchingLeft)
  49665. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49666. if (isStretchingRight)
  49667. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49668. if (isStretchingTop)
  49669. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49670. if (isStretchingBottom)
  49671. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49672. if (bounds.isEmpty())
  49673. return;
  49674. if (minOffTop > 0)
  49675. {
  49676. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49677. if (bounds.getY() < limit)
  49678. {
  49679. if (isStretchingTop)
  49680. bounds.setTop (limits.getY());
  49681. else
  49682. bounds.setY (limit);
  49683. }
  49684. }
  49685. if (minOffLeft > 0)
  49686. {
  49687. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49688. if (bounds.getX() < limit)
  49689. {
  49690. if (isStretchingLeft)
  49691. bounds.setLeft (limits.getX());
  49692. else
  49693. bounds.setX (limit);
  49694. }
  49695. }
  49696. if (minOffBottom > 0)
  49697. {
  49698. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49699. if (bounds.getY() > limit)
  49700. {
  49701. if (isStretchingBottom)
  49702. bounds.setBottom (limits.getBottom());
  49703. else
  49704. bounds.setY (limit);
  49705. }
  49706. }
  49707. if (minOffRight > 0)
  49708. {
  49709. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49710. if (bounds.getX() > limit)
  49711. {
  49712. if (isStretchingRight)
  49713. bounds.setRight (limits.getRight());
  49714. else
  49715. bounds.setX (limit);
  49716. }
  49717. }
  49718. // constrain the aspect ratio if one has been specified..
  49719. if (aspectRatio > 0.0)
  49720. {
  49721. bool adjustWidth;
  49722. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49723. {
  49724. adjustWidth = true;
  49725. }
  49726. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49727. {
  49728. adjustWidth = false;
  49729. }
  49730. else
  49731. {
  49732. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49733. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49734. adjustWidth = (oldRatio > newRatio);
  49735. }
  49736. if (adjustWidth)
  49737. {
  49738. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49739. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49740. {
  49741. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49742. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49743. }
  49744. }
  49745. else
  49746. {
  49747. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49748. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49749. {
  49750. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49751. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49752. }
  49753. }
  49754. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49755. {
  49756. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49757. }
  49758. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49759. {
  49760. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49761. }
  49762. else
  49763. {
  49764. if (isStretchingLeft)
  49765. bounds.setX (old.getRight() - bounds.getWidth());
  49766. if (isStretchingTop)
  49767. bounds.setY (old.getBottom() - bounds.getHeight());
  49768. }
  49769. }
  49770. jassert (! bounds.isEmpty());
  49771. }
  49772. END_JUCE_NAMESPACE
  49773. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49774. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49775. BEGIN_JUCE_NAMESPACE
  49776. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49777. : component (component_),
  49778. lastPeer (0),
  49779. reentrant (false)
  49780. {
  49781. jassert (component != 0); // can't use this with a null pointer..
  49782. component->addComponentListener (this);
  49783. registerWithParentComps();
  49784. }
  49785. ComponentMovementWatcher::~ComponentMovementWatcher()
  49786. {
  49787. component->removeComponentListener (this);
  49788. unregister();
  49789. }
  49790. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49791. {
  49792. // agh! don't delete the target component without deleting this object first!
  49793. jassert (component != 0);
  49794. if (! reentrant)
  49795. {
  49796. reentrant = true;
  49797. ComponentPeer* const peer = component->getPeer();
  49798. if (peer != lastPeer)
  49799. {
  49800. componentPeerChanged();
  49801. if (component == 0)
  49802. return;
  49803. lastPeer = peer;
  49804. }
  49805. unregister();
  49806. registerWithParentComps();
  49807. reentrant = false;
  49808. componentMovedOrResized (*component, true, true);
  49809. }
  49810. }
  49811. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49812. {
  49813. // agh! don't delete the target component without deleting this object first!
  49814. jassert (component != 0);
  49815. if (wasMoved)
  49816. {
  49817. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49818. wasMoved = lastBounds.getPosition() != pos;
  49819. lastBounds.setPosition (pos);
  49820. }
  49821. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49822. lastBounds.setSize (component->getWidth(), component->getHeight());
  49823. if (wasMoved || wasResized)
  49824. componentMovedOrResized (wasMoved, wasResized);
  49825. }
  49826. void ComponentMovementWatcher::registerWithParentComps()
  49827. {
  49828. Component* p = component->getParentComponent();
  49829. while (p != 0)
  49830. {
  49831. p->addComponentListener (this);
  49832. registeredParentComps.add (p);
  49833. p = p->getParentComponent();
  49834. }
  49835. }
  49836. void ComponentMovementWatcher::unregister()
  49837. {
  49838. for (int i = registeredParentComps.size(); --i >= 0;)
  49839. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49840. registeredParentComps.clear();
  49841. }
  49842. END_JUCE_NAMESPACE
  49843. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49844. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49845. BEGIN_JUCE_NAMESPACE
  49846. GroupComponent::GroupComponent (const String& componentName,
  49847. const String& labelText)
  49848. : Component (componentName),
  49849. text (labelText),
  49850. justification (Justification::left)
  49851. {
  49852. setInterceptsMouseClicks (false, true);
  49853. }
  49854. GroupComponent::~GroupComponent()
  49855. {
  49856. }
  49857. void GroupComponent::setText (const String& newText)
  49858. {
  49859. if (text != newText)
  49860. {
  49861. text = newText;
  49862. repaint();
  49863. }
  49864. }
  49865. const String GroupComponent::getText() const
  49866. {
  49867. return text;
  49868. }
  49869. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49870. {
  49871. if (justification != newJustification)
  49872. {
  49873. justification = newJustification;
  49874. repaint();
  49875. }
  49876. }
  49877. void GroupComponent::paint (Graphics& g)
  49878. {
  49879. getLookAndFeel()
  49880. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49881. text, justification,
  49882. *this);
  49883. }
  49884. void GroupComponent::enablementChanged()
  49885. {
  49886. repaint();
  49887. }
  49888. void GroupComponent::colourChanged()
  49889. {
  49890. repaint();
  49891. }
  49892. END_JUCE_NAMESPACE
  49893. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49894. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49895. BEGIN_JUCE_NAMESPACE
  49896. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49897. : DocumentWindow (String::empty, backgroundColour,
  49898. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49899. {
  49900. }
  49901. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49902. {
  49903. }
  49904. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49905. {
  49906. MultiDocumentPanel* const owner = getOwner();
  49907. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49908. if (owner != 0)
  49909. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49910. }
  49911. void MultiDocumentPanelWindow::closeButtonPressed()
  49912. {
  49913. MultiDocumentPanel* const owner = getOwner();
  49914. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49915. if (owner != 0)
  49916. owner->closeDocument (getContentComponent(), true);
  49917. }
  49918. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49919. {
  49920. DocumentWindow::activeWindowStatusChanged();
  49921. updateOrder();
  49922. }
  49923. void MultiDocumentPanelWindow::broughtToFront()
  49924. {
  49925. DocumentWindow::broughtToFront();
  49926. updateOrder();
  49927. }
  49928. void MultiDocumentPanelWindow::updateOrder()
  49929. {
  49930. MultiDocumentPanel* const owner = getOwner();
  49931. if (owner != 0)
  49932. owner->updateOrder();
  49933. }
  49934. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49935. {
  49936. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49937. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49938. }
  49939. class MDITabbedComponentInternal : public TabbedComponent
  49940. {
  49941. public:
  49942. MDITabbedComponentInternal()
  49943. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49944. {
  49945. }
  49946. ~MDITabbedComponentInternal()
  49947. {
  49948. }
  49949. void currentTabChanged (int, const String&)
  49950. {
  49951. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49952. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49953. if (owner != 0)
  49954. owner->updateOrder();
  49955. }
  49956. };
  49957. MultiDocumentPanel::MultiDocumentPanel()
  49958. : mode (MaximisedWindowsWithTabs),
  49959. backgroundColour (Colours::lightblue),
  49960. maximumNumDocuments (0),
  49961. numDocsBeforeTabsUsed (0)
  49962. {
  49963. setOpaque (true);
  49964. }
  49965. MultiDocumentPanel::~MultiDocumentPanel()
  49966. {
  49967. closeAllDocuments (false);
  49968. }
  49969. namespace MultiDocHelpers
  49970. {
  49971. bool shouldDeleteComp (Component* const c)
  49972. {
  49973. return c->getProperties() ["mdiDocumentDelete_"];
  49974. }
  49975. }
  49976. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49977. {
  49978. while (components.size() > 0)
  49979. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49980. return false;
  49981. return true;
  49982. }
  49983. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49984. {
  49985. return new MultiDocumentPanelWindow (backgroundColour);
  49986. }
  49987. void MultiDocumentPanel::addWindow (Component* component)
  49988. {
  49989. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49990. dw->setResizable (true, false);
  49991. dw->setContentComponent (component, false, true);
  49992. dw->setName (component->getName());
  49993. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49994. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49995. int x = 4;
  49996. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49997. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49998. x += 16;
  49999. dw->setTopLeftPosition (x, x);
  50000. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50001. if (pos.toString().isNotEmpty())
  50002. dw->restoreWindowStateFromString (pos.toString());
  50003. addAndMakeVisible (dw);
  50004. dw->toFront (true);
  50005. }
  50006. bool MultiDocumentPanel::addDocument (Component* const component,
  50007. const Colour& docColour,
  50008. const bool deleteWhenRemoved)
  50009. {
  50010. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50011. // with a frame-within-a-frame! Just pass in the bare content component.
  50012. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50013. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50014. return false;
  50015. components.add (component);
  50016. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50017. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50018. component->addComponentListener (this);
  50019. if (mode == FloatingWindows)
  50020. {
  50021. if (isFullscreenWhenOneDocument())
  50022. {
  50023. if (components.size() == 1)
  50024. {
  50025. addAndMakeVisible (component);
  50026. }
  50027. else
  50028. {
  50029. if (components.size() == 2)
  50030. addWindow (components.getFirst());
  50031. addWindow (component);
  50032. }
  50033. }
  50034. else
  50035. {
  50036. addWindow (component);
  50037. }
  50038. }
  50039. else
  50040. {
  50041. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50042. {
  50043. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50044. Array <Component*> temp (components);
  50045. for (int i = 0; i < temp.size(); ++i)
  50046. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50047. resized();
  50048. }
  50049. else
  50050. {
  50051. if (tabComponent != 0)
  50052. tabComponent->addTab (component->getName(), docColour, component, false);
  50053. else
  50054. addAndMakeVisible (component);
  50055. }
  50056. setActiveDocument (component);
  50057. }
  50058. resized();
  50059. activeDocumentChanged();
  50060. return true;
  50061. }
  50062. bool MultiDocumentPanel::closeDocument (Component* component,
  50063. const bool checkItsOkToCloseFirst)
  50064. {
  50065. if (components.contains (component))
  50066. {
  50067. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50068. return false;
  50069. component->removeComponentListener (this);
  50070. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50071. component->getProperties().remove ("mdiDocumentDelete_");
  50072. component->getProperties().remove ("mdiDocumentBkg_");
  50073. if (mode == FloatingWindows)
  50074. {
  50075. for (int i = getNumChildComponents(); --i >= 0;)
  50076. {
  50077. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50078. if (dw != 0 && dw->getContentComponent() == component)
  50079. {
  50080. dw->setContentComponent (0, false);
  50081. delete dw;
  50082. break;
  50083. }
  50084. }
  50085. if (shouldDelete)
  50086. delete component;
  50087. components.removeValue (component);
  50088. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50089. {
  50090. for (int i = getNumChildComponents(); --i >= 0;)
  50091. {
  50092. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50093. if (dw != 0)
  50094. {
  50095. dw->setContentComponent (0, false);
  50096. delete dw;
  50097. }
  50098. }
  50099. addAndMakeVisible (components.getFirst());
  50100. }
  50101. }
  50102. else
  50103. {
  50104. jassert (components.indexOf (component) >= 0);
  50105. if (tabComponent != 0)
  50106. {
  50107. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50108. if (tabComponent->getTabContentComponent (i) == component)
  50109. tabComponent->removeTab (i);
  50110. }
  50111. else
  50112. {
  50113. removeChildComponent (component);
  50114. }
  50115. if (shouldDelete)
  50116. delete component;
  50117. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50118. tabComponent = 0;
  50119. components.removeValue (component);
  50120. if (components.size() > 0 && tabComponent == 0)
  50121. addAndMakeVisible (components.getFirst());
  50122. }
  50123. resized();
  50124. activeDocumentChanged();
  50125. }
  50126. else
  50127. {
  50128. jassertfalse;
  50129. }
  50130. return true;
  50131. }
  50132. int MultiDocumentPanel::getNumDocuments() const throw()
  50133. {
  50134. return components.size();
  50135. }
  50136. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50137. {
  50138. return components [index];
  50139. }
  50140. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50141. {
  50142. if (mode == FloatingWindows)
  50143. {
  50144. for (int i = getNumChildComponents(); --i >= 0;)
  50145. {
  50146. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50147. if (dw != 0 && dw->isActiveWindow())
  50148. return dw->getContentComponent();
  50149. }
  50150. }
  50151. return components.getLast();
  50152. }
  50153. void MultiDocumentPanel::setActiveDocument (Component* component)
  50154. {
  50155. if (mode == FloatingWindows)
  50156. {
  50157. component = getContainerComp (component);
  50158. if (component != 0)
  50159. component->toFront (true);
  50160. }
  50161. else if (tabComponent != 0)
  50162. {
  50163. jassert (components.indexOf (component) >= 0);
  50164. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50165. {
  50166. if (tabComponent->getTabContentComponent (i) == component)
  50167. {
  50168. tabComponent->setCurrentTabIndex (i);
  50169. break;
  50170. }
  50171. }
  50172. }
  50173. else
  50174. {
  50175. component->grabKeyboardFocus();
  50176. }
  50177. }
  50178. void MultiDocumentPanel::activeDocumentChanged()
  50179. {
  50180. }
  50181. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50182. {
  50183. maximumNumDocuments = newNumber;
  50184. }
  50185. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50186. {
  50187. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50188. }
  50189. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50190. {
  50191. return numDocsBeforeTabsUsed != 0;
  50192. }
  50193. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50194. {
  50195. if (mode != newLayoutMode)
  50196. {
  50197. mode = newLayoutMode;
  50198. if (mode == FloatingWindows)
  50199. {
  50200. tabComponent = 0;
  50201. }
  50202. else
  50203. {
  50204. for (int i = getNumChildComponents(); --i >= 0;)
  50205. {
  50206. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50207. if (dw != 0)
  50208. {
  50209. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50210. dw->setContentComponent (0, false);
  50211. delete dw;
  50212. }
  50213. }
  50214. }
  50215. resized();
  50216. const Array <Component*> tempComps (components);
  50217. components.clear();
  50218. for (int i = 0; i < tempComps.size(); ++i)
  50219. {
  50220. Component* const c = tempComps.getUnchecked(i);
  50221. addDocument (c,
  50222. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50223. MultiDocHelpers::shouldDeleteComp (c));
  50224. }
  50225. }
  50226. }
  50227. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50228. {
  50229. if (backgroundColour != newBackgroundColour)
  50230. {
  50231. backgroundColour = newBackgroundColour;
  50232. setOpaque (newBackgroundColour.isOpaque());
  50233. repaint();
  50234. }
  50235. }
  50236. void MultiDocumentPanel::paint (Graphics& g)
  50237. {
  50238. g.fillAll (backgroundColour);
  50239. }
  50240. void MultiDocumentPanel::resized()
  50241. {
  50242. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50243. {
  50244. for (int i = getNumChildComponents(); --i >= 0;)
  50245. getChildComponent (i)->setBounds (getLocalBounds());
  50246. }
  50247. setWantsKeyboardFocus (components.size() == 0);
  50248. }
  50249. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50250. {
  50251. if (mode == FloatingWindows)
  50252. {
  50253. for (int i = 0; i < getNumChildComponents(); ++i)
  50254. {
  50255. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50256. if (dw != 0 && dw->getContentComponent() == c)
  50257. {
  50258. c = dw;
  50259. break;
  50260. }
  50261. }
  50262. }
  50263. return c;
  50264. }
  50265. void MultiDocumentPanel::componentNameChanged (Component&)
  50266. {
  50267. if (mode == FloatingWindows)
  50268. {
  50269. for (int i = 0; i < getNumChildComponents(); ++i)
  50270. {
  50271. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50272. if (dw != 0)
  50273. dw->setName (dw->getContentComponent()->getName());
  50274. }
  50275. }
  50276. else if (tabComponent != 0)
  50277. {
  50278. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50279. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50280. }
  50281. }
  50282. void MultiDocumentPanel::updateOrder()
  50283. {
  50284. const Array <Component*> oldList (components);
  50285. if (mode == FloatingWindows)
  50286. {
  50287. components.clear();
  50288. for (int i = 0; i < getNumChildComponents(); ++i)
  50289. {
  50290. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50291. if (dw != 0)
  50292. components.add (dw->getContentComponent());
  50293. }
  50294. }
  50295. else
  50296. {
  50297. if (tabComponent != 0)
  50298. {
  50299. Component* const current = tabComponent->getCurrentContentComponent();
  50300. if (current != 0)
  50301. {
  50302. components.removeValue (current);
  50303. components.add (current);
  50304. }
  50305. }
  50306. }
  50307. if (components != oldList)
  50308. activeDocumentChanged();
  50309. }
  50310. END_JUCE_NAMESPACE
  50311. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50312. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50313. BEGIN_JUCE_NAMESPACE
  50314. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50315. : zone (zoneFlags)
  50316. {}
  50317. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50318. : zone (other.zone)
  50319. {}
  50320. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50321. {
  50322. zone = other.zone;
  50323. return *this;
  50324. }
  50325. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50326. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50327. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50328. const BorderSize& border,
  50329. const Point<int>& position)
  50330. {
  50331. int z = 0;
  50332. if (totalSize.contains (position)
  50333. && ! border.subtractedFrom (totalSize).contains (position))
  50334. {
  50335. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50336. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50337. z |= left;
  50338. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50339. z |= right;
  50340. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50341. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50342. z |= top;
  50343. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50344. z |= bottom;
  50345. }
  50346. return Zone (z);
  50347. }
  50348. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50349. {
  50350. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50351. switch (zone)
  50352. {
  50353. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50354. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50355. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50356. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50357. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50358. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50359. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50360. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50361. default: break;
  50362. }
  50363. return mc;
  50364. }
  50365. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50366. ComponentBoundsConstrainer* const constrainer_)
  50367. : component (componentToResize),
  50368. constrainer (constrainer_),
  50369. borderSize (5),
  50370. mouseZone (0)
  50371. {
  50372. }
  50373. ResizableBorderComponent::~ResizableBorderComponent()
  50374. {
  50375. }
  50376. void ResizableBorderComponent::paint (Graphics& g)
  50377. {
  50378. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50379. }
  50380. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50381. {
  50382. updateMouseZone (e);
  50383. }
  50384. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50385. {
  50386. updateMouseZone (e);
  50387. }
  50388. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50389. {
  50390. if (component == 0)
  50391. {
  50392. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50393. return;
  50394. }
  50395. updateMouseZone (e);
  50396. originalBounds = component->getBounds();
  50397. if (constrainer != 0)
  50398. constrainer->resizeStart();
  50399. }
  50400. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50401. {
  50402. if (component == 0)
  50403. {
  50404. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50405. return;
  50406. }
  50407. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50408. if (constrainer != 0)
  50409. constrainer->setBoundsForComponent (component, bounds,
  50410. mouseZone.isDraggingTopEdge(),
  50411. mouseZone.isDraggingLeftEdge(),
  50412. mouseZone.isDraggingBottomEdge(),
  50413. mouseZone.isDraggingRightEdge());
  50414. else
  50415. component->setBounds (bounds);
  50416. }
  50417. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50418. {
  50419. if (constrainer != 0)
  50420. constrainer->resizeEnd();
  50421. }
  50422. bool ResizableBorderComponent::hitTest (int x, int y)
  50423. {
  50424. return x < borderSize.getLeft()
  50425. || x >= getWidth() - borderSize.getRight()
  50426. || y < borderSize.getTop()
  50427. || y >= getHeight() - borderSize.getBottom();
  50428. }
  50429. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50430. {
  50431. if (borderSize != newBorderSize)
  50432. {
  50433. borderSize = newBorderSize;
  50434. repaint();
  50435. }
  50436. }
  50437. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50438. {
  50439. return borderSize;
  50440. }
  50441. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50442. {
  50443. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50444. if (mouseZone != newZone)
  50445. {
  50446. mouseZone = newZone;
  50447. setMouseCursor (newZone.getMouseCursor());
  50448. }
  50449. }
  50450. END_JUCE_NAMESPACE
  50451. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50452. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50453. BEGIN_JUCE_NAMESPACE
  50454. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50455. ComponentBoundsConstrainer* const constrainer_)
  50456. : component (componentToResize),
  50457. constrainer (constrainer_)
  50458. {
  50459. setRepaintsOnMouseActivity (true);
  50460. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50461. }
  50462. ResizableCornerComponent::~ResizableCornerComponent()
  50463. {
  50464. }
  50465. void ResizableCornerComponent::paint (Graphics& g)
  50466. {
  50467. getLookAndFeel()
  50468. .drawCornerResizer (g, getWidth(), getHeight(),
  50469. isMouseOverOrDragging(),
  50470. isMouseButtonDown());
  50471. }
  50472. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50473. {
  50474. if (component == 0)
  50475. {
  50476. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50477. return;
  50478. }
  50479. originalBounds = component->getBounds();
  50480. if (constrainer != 0)
  50481. constrainer->resizeStart();
  50482. }
  50483. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50484. {
  50485. if (component == 0)
  50486. {
  50487. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50488. return;
  50489. }
  50490. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50491. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50492. if (constrainer != 0)
  50493. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50494. else
  50495. component->setBounds (r);
  50496. }
  50497. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50498. {
  50499. if (constrainer != 0)
  50500. constrainer->resizeStart();
  50501. }
  50502. bool ResizableCornerComponent::hitTest (int x, int y)
  50503. {
  50504. if (getWidth() <= 0)
  50505. return false;
  50506. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50507. return y >= yAtX - getHeight() / 4;
  50508. }
  50509. END_JUCE_NAMESPACE
  50510. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50511. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50512. BEGIN_JUCE_NAMESPACE
  50513. class ScrollBar::ScrollbarButton : public Button
  50514. {
  50515. public:
  50516. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50517. : Button (String::empty),
  50518. direction (direction_),
  50519. owner (owner_)
  50520. {
  50521. setWantsKeyboardFocus (false);
  50522. }
  50523. void paintButton (Graphics& g, bool over, bool down)
  50524. {
  50525. getLookAndFeel()
  50526. .drawScrollbarButton (g, owner,
  50527. getWidth(), getHeight(),
  50528. direction,
  50529. owner.isVertical(),
  50530. over, down);
  50531. }
  50532. void clicked()
  50533. {
  50534. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50535. }
  50536. int direction;
  50537. private:
  50538. ScrollBar& owner;
  50539. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50540. };
  50541. ScrollBar::ScrollBar (const bool vertical_,
  50542. const bool buttonsAreVisible)
  50543. : totalRange (0.0, 1.0),
  50544. visibleRange (0.0, 0.1),
  50545. singleStepSize (0.1),
  50546. thumbAreaStart (0),
  50547. thumbAreaSize (0),
  50548. thumbStart (0),
  50549. thumbSize (0),
  50550. initialDelayInMillisecs (100),
  50551. repeatDelayInMillisecs (50),
  50552. minimumDelayInMillisecs (10),
  50553. vertical (vertical_),
  50554. isDraggingThumb (false),
  50555. autohides (true)
  50556. {
  50557. setButtonVisibility (buttonsAreVisible);
  50558. setRepaintsOnMouseActivity (true);
  50559. setFocusContainer (true);
  50560. }
  50561. ScrollBar::~ScrollBar()
  50562. {
  50563. upButton = 0;
  50564. downButton = 0;
  50565. }
  50566. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50567. {
  50568. if (totalRange != newRangeLimit)
  50569. {
  50570. totalRange = newRangeLimit;
  50571. setCurrentRange (visibleRange);
  50572. updateThumbPosition();
  50573. }
  50574. }
  50575. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50576. {
  50577. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50578. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50579. }
  50580. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50581. {
  50582. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50583. if (visibleRange != constrainedRange)
  50584. {
  50585. visibleRange = constrainedRange;
  50586. updateThumbPosition();
  50587. triggerAsyncUpdate();
  50588. }
  50589. }
  50590. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50591. {
  50592. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50593. }
  50594. void ScrollBar::setCurrentRangeStart (const double newStart)
  50595. {
  50596. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50597. }
  50598. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50599. {
  50600. singleStepSize = newSingleStepSize;
  50601. }
  50602. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50603. {
  50604. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50605. }
  50606. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50607. {
  50608. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50609. }
  50610. void ScrollBar::scrollToTop()
  50611. {
  50612. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50613. }
  50614. void ScrollBar::scrollToBottom()
  50615. {
  50616. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50617. }
  50618. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50619. const int repeatDelayInMillisecs_,
  50620. const int minimumDelayInMillisecs_)
  50621. {
  50622. initialDelayInMillisecs = initialDelayInMillisecs_;
  50623. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50624. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50625. if (upButton != 0)
  50626. {
  50627. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50628. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50629. }
  50630. }
  50631. void ScrollBar::addListener (Listener* const listener)
  50632. {
  50633. listeners.add (listener);
  50634. }
  50635. void ScrollBar::removeListener (Listener* const listener)
  50636. {
  50637. listeners.remove (listener);
  50638. }
  50639. void ScrollBar::handleAsyncUpdate()
  50640. {
  50641. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50642. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50643. }
  50644. void ScrollBar::updateThumbPosition()
  50645. {
  50646. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50647. : thumbAreaSize);
  50648. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50649. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50650. if (newThumbSize > thumbAreaSize)
  50651. newThumbSize = thumbAreaSize;
  50652. int newThumbStart = thumbAreaStart;
  50653. if (totalRange.getLength() > visibleRange.getLength())
  50654. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50655. / (totalRange.getLength() - visibleRange.getLength()));
  50656. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50657. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50658. {
  50659. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50660. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50661. if (vertical)
  50662. repaint (0, repaintStart, getWidth(), repaintSize);
  50663. else
  50664. repaint (repaintStart, 0, repaintSize, getHeight());
  50665. thumbStart = newThumbStart;
  50666. thumbSize = newThumbSize;
  50667. }
  50668. }
  50669. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50670. {
  50671. if (vertical != shouldBeVertical)
  50672. {
  50673. vertical = shouldBeVertical;
  50674. if (upButton != 0)
  50675. {
  50676. upButton->direction = vertical ? 0 : 3;
  50677. downButton->direction = vertical ? 2 : 1;
  50678. }
  50679. updateThumbPosition();
  50680. }
  50681. }
  50682. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50683. {
  50684. upButton = 0;
  50685. downButton = 0;
  50686. if (buttonsAreVisible)
  50687. {
  50688. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50689. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50690. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50691. }
  50692. updateThumbPosition();
  50693. }
  50694. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50695. {
  50696. autohides = shouldHideWhenFullRange;
  50697. updateThumbPosition();
  50698. }
  50699. bool ScrollBar::autoHides() const throw()
  50700. {
  50701. return autohides;
  50702. }
  50703. void ScrollBar::paint (Graphics& g)
  50704. {
  50705. if (thumbAreaSize > 0)
  50706. {
  50707. LookAndFeel& lf = getLookAndFeel();
  50708. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50709. ? thumbSize : 0;
  50710. if (vertical)
  50711. {
  50712. lf.drawScrollbar (g, *this,
  50713. 0, thumbAreaStart,
  50714. getWidth(), thumbAreaSize,
  50715. vertical,
  50716. thumbStart, thumb,
  50717. isMouseOver(), isMouseButtonDown());
  50718. }
  50719. else
  50720. {
  50721. lf.drawScrollbar (g, *this,
  50722. thumbAreaStart, 0,
  50723. thumbAreaSize, getHeight(),
  50724. vertical,
  50725. thumbStart, thumb,
  50726. isMouseOver(), isMouseButtonDown());
  50727. }
  50728. }
  50729. }
  50730. void ScrollBar::lookAndFeelChanged()
  50731. {
  50732. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50733. }
  50734. void ScrollBar::resized()
  50735. {
  50736. const int length = ((vertical) ? getHeight() : getWidth());
  50737. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50738. : 0;
  50739. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50740. {
  50741. thumbAreaStart = length >> 1;
  50742. thumbAreaSize = 0;
  50743. }
  50744. else
  50745. {
  50746. thumbAreaStart = buttonSize;
  50747. thumbAreaSize = length - (buttonSize << 1);
  50748. }
  50749. if (upButton != 0)
  50750. {
  50751. if (vertical)
  50752. {
  50753. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50754. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50755. }
  50756. else
  50757. {
  50758. upButton->setBounds (0, 0, buttonSize, getHeight());
  50759. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50760. }
  50761. }
  50762. updateThumbPosition();
  50763. }
  50764. void ScrollBar::mouseDown (const MouseEvent& e)
  50765. {
  50766. isDraggingThumb = false;
  50767. lastMousePos = vertical ? e.y : e.x;
  50768. dragStartMousePos = lastMousePos;
  50769. dragStartRange = visibleRange.getStart();
  50770. if (dragStartMousePos < thumbStart)
  50771. {
  50772. moveScrollbarInPages (-1);
  50773. startTimer (400);
  50774. }
  50775. else if (dragStartMousePos >= thumbStart + thumbSize)
  50776. {
  50777. moveScrollbarInPages (1);
  50778. startTimer (400);
  50779. }
  50780. else
  50781. {
  50782. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50783. && (thumbAreaSize > thumbSize);
  50784. }
  50785. }
  50786. void ScrollBar::mouseDrag (const MouseEvent& e)
  50787. {
  50788. const int mousePos = vertical ? e.y : e.x;
  50789. if (isDraggingThumb && lastMousePos != mousePos)
  50790. {
  50791. const int deltaPixels = mousePos - dragStartMousePos;
  50792. setCurrentRangeStart (dragStartRange
  50793. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50794. / (thumbAreaSize - thumbSize));
  50795. }
  50796. lastMousePos = mousePos;
  50797. }
  50798. void ScrollBar::mouseUp (const MouseEvent&)
  50799. {
  50800. isDraggingThumb = false;
  50801. stopTimer();
  50802. repaint();
  50803. }
  50804. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50805. float wheelIncrementX,
  50806. float wheelIncrementY)
  50807. {
  50808. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50809. if (increment < 0)
  50810. increment = jmin (increment * 10.0f, -1.0f);
  50811. else if (increment > 0)
  50812. increment = jmax (increment * 10.0f, 1.0f);
  50813. setCurrentRange (visibleRange - singleStepSize * increment);
  50814. }
  50815. void ScrollBar::timerCallback()
  50816. {
  50817. if (isMouseButtonDown())
  50818. {
  50819. startTimer (40);
  50820. if (lastMousePos < thumbStart)
  50821. setCurrentRange (visibleRange - visibleRange.getLength());
  50822. else if (lastMousePos > thumbStart + thumbSize)
  50823. setCurrentRangeStart (visibleRange.getEnd());
  50824. }
  50825. else
  50826. {
  50827. stopTimer();
  50828. }
  50829. }
  50830. bool ScrollBar::keyPressed (const KeyPress& key)
  50831. {
  50832. if (! isVisible())
  50833. return false;
  50834. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50835. moveScrollbarInSteps (-1);
  50836. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50837. moveScrollbarInSteps (1);
  50838. else if (key.isKeyCode (KeyPress::pageUpKey))
  50839. moveScrollbarInPages (-1);
  50840. else if (key.isKeyCode (KeyPress::pageDownKey))
  50841. moveScrollbarInPages (1);
  50842. else if (key.isKeyCode (KeyPress::homeKey))
  50843. scrollToTop();
  50844. else if (key.isKeyCode (KeyPress::endKey))
  50845. scrollToBottom();
  50846. else
  50847. return false;
  50848. return true;
  50849. }
  50850. END_JUCE_NAMESPACE
  50851. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50852. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50853. BEGIN_JUCE_NAMESPACE
  50854. StretchableLayoutManager::StretchableLayoutManager()
  50855. : totalSize (0)
  50856. {
  50857. }
  50858. StretchableLayoutManager::~StretchableLayoutManager()
  50859. {
  50860. }
  50861. void StretchableLayoutManager::clearAllItems()
  50862. {
  50863. items.clear();
  50864. totalSize = 0;
  50865. }
  50866. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50867. const double minimumSize,
  50868. const double maximumSize,
  50869. const double preferredSize)
  50870. {
  50871. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50872. if (layout == 0)
  50873. {
  50874. layout = new ItemLayoutProperties();
  50875. layout->itemIndex = itemIndex;
  50876. int i;
  50877. for (i = 0; i < items.size(); ++i)
  50878. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50879. break;
  50880. items.insert (i, layout);
  50881. }
  50882. layout->minSize = minimumSize;
  50883. layout->maxSize = maximumSize;
  50884. layout->preferredSize = preferredSize;
  50885. layout->currentSize = 0;
  50886. }
  50887. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50888. double& minimumSize,
  50889. double& maximumSize,
  50890. double& preferredSize) const
  50891. {
  50892. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50893. if (layout != 0)
  50894. {
  50895. minimumSize = layout->minSize;
  50896. maximumSize = layout->maxSize;
  50897. preferredSize = layout->preferredSize;
  50898. return true;
  50899. }
  50900. return false;
  50901. }
  50902. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50903. {
  50904. totalSize = newTotalSize;
  50905. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50906. }
  50907. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50908. {
  50909. int pos = 0;
  50910. for (int i = 0; i < itemIndex; ++i)
  50911. {
  50912. const ItemLayoutProperties* const layout = getInfoFor (i);
  50913. if (layout != 0)
  50914. pos += layout->currentSize;
  50915. }
  50916. return pos;
  50917. }
  50918. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50919. {
  50920. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50921. if (layout != 0)
  50922. return layout->currentSize;
  50923. return 0;
  50924. }
  50925. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50926. {
  50927. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50928. if (layout != 0)
  50929. return -layout->currentSize / (double) totalSize;
  50930. return 0;
  50931. }
  50932. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50933. int newPosition)
  50934. {
  50935. for (int i = items.size(); --i >= 0;)
  50936. {
  50937. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50938. if (layout->itemIndex == itemIndex)
  50939. {
  50940. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50941. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50942. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50943. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50944. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50945. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50946. endPos += layout->currentSize;
  50947. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50948. updatePrefSizesToMatchCurrentPositions();
  50949. break;
  50950. }
  50951. }
  50952. }
  50953. void StretchableLayoutManager::layOutComponents (Component** const components,
  50954. int numComponents,
  50955. int x, int y, int w, int h,
  50956. const bool vertically,
  50957. const bool resizeOtherDimension)
  50958. {
  50959. setTotalSize (vertically ? h : w);
  50960. int pos = vertically ? y : x;
  50961. for (int i = 0; i < numComponents; ++i)
  50962. {
  50963. const ItemLayoutProperties* const layout = getInfoFor (i);
  50964. if (layout != 0)
  50965. {
  50966. Component* const c = components[i];
  50967. if (c != 0)
  50968. {
  50969. if (i == numComponents - 1)
  50970. {
  50971. // if it's the last item, crop it to exactly fit the available space..
  50972. if (resizeOtherDimension)
  50973. {
  50974. if (vertically)
  50975. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50976. else
  50977. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50978. }
  50979. else
  50980. {
  50981. if (vertically)
  50982. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50983. else
  50984. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50985. }
  50986. }
  50987. else
  50988. {
  50989. if (resizeOtherDimension)
  50990. {
  50991. if (vertically)
  50992. c->setBounds (x, pos, w, layout->currentSize);
  50993. else
  50994. c->setBounds (pos, y, layout->currentSize, h);
  50995. }
  50996. else
  50997. {
  50998. if (vertically)
  50999. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51000. else
  51001. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51002. }
  51003. }
  51004. }
  51005. pos += layout->currentSize;
  51006. }
  51007. }
  51008. }
  51009. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51010. {
  51011. for (int i = items.size(); --i >= 0;)
  51012. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51013. return items.getUnchecked(i);
  51014. return 0;
  51015. }
  51016. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51017. const int endIndex,
  51018. const int availableSpace,
  51019. int startPos)
  51020. {
  51021. // calculate the total sizes
  51022. int i;
  51023. double totalIdealSize = 0.0;
  51024. int totalMinimums = 0;
  51025. for (i = startIndex; i < endIndex; ++i)
  51026. {
  51027. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51028. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51029. totalMinimums += layout->currentSize;
  51030. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51031. }
  51032. if (totalIdealSize <= 0)
  51033. totalIdealSize = 1.0;
  51034. // now calc the best sizes..
  51035. int extraSpace = availableSpace - totalMinimums;
  51036. while (extraSpace > 0)
  51037. {
  51038. int numWantingMoreSpace = 0;
  51039. int numHavingTakenExtraSpace = 0;
  51040. // first figure out how many comps want a slice of the extra space..
  51041. for (i = startIndex; i < endIndex; ++i)
  51042. {
  51043. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51044. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51045. const int bestSize = jlimit (layout->currentSize,
  51046. jmax (layout->currentSize,
  51047. sizeToRealSize (layout->maxSize, totalSize)),
  51048. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51049. if (bestSize > layout->currentSize)
  51050. ++numWantingMoreSpace;
  51051. }
  51052. // ..share out the extra space..
  51053. for (i = startIndex; i < endIndex; ++i)
  51054. {
  51055. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51056. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51057. int bestSize = jlimit (layout->currentSize,
  51058. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51059. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51060. const int extraWanted = bestSize - layout->currentSize;
  51061. if (extraWanted > 0)
  51062. {
  51063. const int extraAllowed = jmin (extraWanted,
  51064. extraSpace / jmax (1, numWantingMoreSpace));
  51065. if (extraAllowed > 0)
  51066. {
  51067. ++numHavingTakenExtraSpace;
  51068. --numWantingMoreSpace;
  51069. layout->currentSize += extraAllowed;
  51070. extraSpace -= extraAllowed;
  51071. }
  51072. }
  51073. }
  51074. if (numHavingTakenExtraSpace <= 0)
  51075. break;
  51076. }
  51077. // ..and calculate the end position
  51078. for (i = startIndex; i < endIndex; ++i)
  51079. {
  51080. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51081. startPos += layout->currentSize;
  51082. }
  51083. return startPos;
  51084. }
  51085. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51086. const int endIndex) const
  51087. {
  51088. int totalMinimums = 0;
  51089. for (int i = startIndex; i < endIndex; ++i)
  51090. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51091. return totalMinimums;
  51092. }
  51093. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51094. {
  51095. int totalMaximums = 0;
  51096. for (int i = startIndex; i < endIndex; ++i)
  51097. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51098. return totalMaximums;
  51099. }
  51100. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51101. {
  51102. for (int i = 0; i < items.size(); ++i)
  51103. {
  51104. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51105. layout->preferredSize
  51106. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51107. : getItemCurrentAbsoluteSize (i);
  51108. }
  51109. }
  51110. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51111. {
  51112. if (size < 0)
  51113. size *= -totalSpace;
  51114. return roundToInt (size);
  51115. }
  51116. END_JUCE_NAMESPACE
  51117. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51118. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51119. BEGIN_JUCE_NAMESPACE
  51120. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51121. const int itemIndex_,
  51122. const bool isVertical_)
  51123. : layout (layout_),
  51124. itemIndex (itemIndex_),
  51125. isVertical (isVertical_)
  51126. {
  51127. setRepaintsOnMouseActivity (true);
  51128. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51129. : MouseCursor::UpDownResizeCursor));
  51130. }
  51131. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51132. {
  51133. }
  51134. void StretchableLayoutResizerBar::paint (Graphics& g)
  51135. {
  51136. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51137. getWidth(), getHeight(),
  51138. isVertical,
  51139. isMouseOver(),
  51140. isMouseButtonDown());
  51141. }
  51142. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51143. {
  51144. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51145. }
  51146. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51147. {
  51148. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51149. : e.getDistanceFromDragStartY());
  51150. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51151. {
  51152. layout->setItemPosition (itemIndex, desiredPos);
  51153. hasBeenMoved();
  51154. }
  51155. }
  51156. void StretchableLayoutResizerBar::hasBeenMoved()
  51157. {
  51158. if (getParentComponent() != 0)
  51159. getParentComponent()->resized();
  51160. }
  51161. END_JUCE_NAMESPACE
  51162. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51163. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51164. BEGIN_JUCE_NAMESPACE
  51165. StretchableObjectResizer::StretchableObjectResizer()
  51166. {
  51167. }
  51168. StretchableObjectResizer::~StretchableObjectResizer()
  51169. {
  51170. }
  51171. void StretchableObjectResizer::addItem (const double size,
  51172. const double minSize, const double maxSize,
  51173. const int order)
  51174. {
  51175. // the order must be >= 0 but less than the maximum integer value.
  51176. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51177. Item* const item = new Item();
  51178. item->size = size;
  51179. item->minSize = minSize;
  51180. item->maxSize = maxSize;
  51181. item->order = order;
  51182. items.add (item);
  51183. }
  51184. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51185. {
  51186. const Item* const it = items [index];
  51187. return it != 0 ? it->size : 0;
  51188. }
  51189. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51190. {
  51191. int order = 0;
  51192. for (;;)
  51193. {
  51194. double currentSize = 0;
  51195. double minSize = 0;
  51196. double maxSize = 0;
  51197. int nextHighestOrder = std::numeric_limits<int>::max();
  51198. for (int i = 0; i < items.size(); ++i)
  51199. {
  51200. const Item* const it = items.getUnchecked(i);
  51201. currentSize += it->size;
  51202. if (it->order <= order)
  51203. {
  51204. minSize += it->minSize;
  51205. maxSize += it->maxSize;
  51206. }
  51207. else
  51208. {
  51209. minSize += it->size;
  51210. maxSize += it->size;
  51211. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51212. }
  51213. }
  51214. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51215. if (thisIterationTarget >= currentSize)
  51216. {
  51217. const double availableExtraSpace = maxSize - currentSize;
  51218. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51219. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51220. for (int i = 0; i < items.size(); ++i)
  51221. {
  51222. Item* const it = items.getUnchecked(i);
  51223. if (it->order <= order)
  51224. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51225. }
  51226. }
  51227. else
  51228. {
  51229. const double amountOfSlack = currentSize - minSize;
  51230. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51231. const double scale = targetAmountOfSlack / amountOfSlack;
  51232. for (int i = 0; i < items.size(); ++i)
  51233. {
  51234. Item* const it = items.getUnchecked(i);
  51235. if (it->order <= order)
  51236. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51237. }
  51238. }
  51239. if (nextHighestOrder < std::numeric_limits<int>::max())
  51240. order = nextHighestOrder;
  51241. else
  51242. break;
  51243. }
  51244. }
  51245. END_JUCE_NAMESPACE
  51246. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51247. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51248. BEGIN_JUCE_NAMESPACE
  51249. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51250. : Button (name),
  51251. owner (owner_),
  51252. overlapPixels (0)
  51253. {
  51254. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51255. setComponentEffect (&shadow);
  51256. setWantsKeyboardFocus (false);
  51257. }
  51258. TabBarButton::~TabBarButton()
  51259. {
  51260. }
  51261. int TabBarButton::getIndex() const
  51262. {
  51263. return owner.indexOfTabButton (this);
  51264. }
  51265. void TabBarButton::paintButton (Graphics& g,
  51266. bool isMouseOverButton,
  51267. bool isButtonDown)
  51268. {
  51269. const Rectangle<int> area (getActiveArea());
  51270. g.setOrigin (area.getX(), area.getY());
  51271. getLookAndFeel()
  51272. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51273. owner.getTabBackgroundColour (getIndex()),
  51274. getIndex(), getButtonText(), *this,
  51275. owner.getOrientation(),
  51276. isMouseOverButton, isButtonDown,
  51277. getToggleState());
  51278. }
  51279. void TabBarButton::clicked (const ModifierKeys& mods)
  51280. {
  51281. if (mods.isPopupMenu())
  51282. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51283. else
  51284. owner.setCurrentTabIndex (getIndex());
  51285. }
  51286. bool TabBarButton::hitTest (int mx, int my)
  51287. {
  51288. const Rectangle<int> area (getActiveArea());
  51289. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51290. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51291. {
  51292. if (isPositiveAndBelow (mx, getWidth())
  51293. && my >= area.getY() + overlapPixels
  51294. && my < area.getBottom() - overlapPixels)
  51295. return true;
  51296. }
  51297. else
  51298. {
  51299. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51300. && isPositiveAndBelow (my, getHeight()))
  51301. return true;
  51302. }
  51303. Path p;
  51304. getLookAndFeel()
  51305. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51306. owner.getOrientation(), false, false, getToggleState());
  51307. return p.contains ((float) (mx - area.getX()),
  51308. (float) (my - area.getY()));
  51309. }
  51310. int TabBarButton::getBestTabLength (const int depth)
  51311. {
  51312. return jlimit (depth * 2,
  51313. depth * 7,
  51314. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51315. }
  51316. const Rectangle<int> TabBarButton::getActiveArea()
  51317. {
  51318. Rectangle<int> r (getLocalBounds());
  51319. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51320. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51321. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51322. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51323. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51324. return r;
  51325. }
  51326. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51327. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51328. {
  51329. public:
  51330. BehindFrontTabComp (TabbedButtonBar& owner_)
  51331. : owner (owner_)
  51332. {
  51333. setInterceptsMouseClicks (false, false);
  51334. }
  51335. void paint (Graphics& g)
  51336. {
  51337. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51338. owner, owner.getOrientation());
  51339. }
  51340. void enablementChanged()
  51341. {
  51342. repaint();
  51343. }
  51344. void buttonClicked (Button*)
  51345. {
  51346. owner.showExtraItemsMenu();
  51347. }
  51348. private:
  51349. TabbedButtonBar& owner;
  51350. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51351. };
  51352. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51353. : orientation (orientation_),
  51354. minimumScale (0.7),
  51355. currentTabIndex (-1)
  51356. {
  51357. setInterceptsMouseClicks (false, true);
  51358. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51359. setFocusContainer (true);
  51360. }
  51361. TabbedButtonBar::~TabbedButtonBar()
  51362. {
  51363. tabs.clear();
  51364. extraTabsButton = 0;
  51365. }
  51366. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51367. {
  51368. orientation = newOrientation;
  51369. for (int i = getNumChildComponents(); --i >= 0;)
  51370. getChildComponent (i)->resized();
  51371. resized();
  51372. }
  51373. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51374. {
  51375. return new TabBarButton (name, *this);
  51376. }
  51377. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51378. {
  51379. minimumScale = newMinimumScale;
  51380. resized();
  51381. }
  51382. void TabbedButtonBar::clearTabs()
  51383. {
  51384. tabs.clear();
  51385. extraTabsButton = 0;
  51386. setCurrentTabIndex (-1);
  51387. }
  51388. void TabbedButtonBar::addTab (const String& tabName,
  51389. const Colour& tabBackgroundColour,
  51390. int insertIndex)
  51391. {
  51392. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51393. if (tabName.isNotEmpty())
  51394. {
  51395. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51396. insertIndex = tabs.size();
  51397. TabInfo* newTab = new TabInfo();
  51398. newTab->name = tabName;
  51399. newTab->colour = tabBackgroundColour;
  51400. newTab->component = createTabButton (tabName, insertIndex);
  51401. jassert (newTab->component != 0);
  51402. tabs.insert (insertIndex, newTab);
  51403. addAndMakeVisible (newTab->component, insertIndex);
  51404. resized();
  51405. if (currentTabIndex < 0)
  51406. setCurrentTabIndex (0);
  51407. }
  51408. }
  51409. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51410. {
  51411. TabInfo* const tab = tabs [tabIndex];
  51412. if (tab != 0 && tab->name != newName)
  51413. {
  51414. tab->name = newName;
  51415. tab->component->setButtonText (newName);
  51416. resized();
  51417. }
  51418. }
  51419. void TabbedButtonBar::removeTab (const int tabIndex)
  51420. {
  51421. if (tabs [tabIndex] != 0)
  51422. {
  51423. const int oldTabIndex = currentTabIndex;
  51424. if (currentTabIndex == tabIndex)
  51425. currentTabIndex = -1;
  51426. tabs.remove (tabIndex);
  51427. resized();
  51428. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51429. }
  51430. }
  51431. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51432. {
  51433. tabs.move (currentIndex, newIndex);
  51434. resized();
  51435. }
  51436. int TabbedButtonBar::getNumTabs() const
  51437. {
  51438. return tabs.size();
  51439. }
  51440. const String TabbedButtonBar::getCurrentTabName() const
  51441. {
  51442. TabInfo* tab = tabs [currentTabIndex];
  51443. return tab == 0 ? String::empty : tab->name;
  51444. }
  51445. const StringArray TabbedButtonBar::getTabNames() const
  51446. {
  51447. StringArray names;
  51448. for (int i = 0; i < tabs.size(); ++i)
  51449. names.add (tabs.getUnchecked(i)->name);
  51450. return names;
  51451. }
  51452. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51453. {
  51454. if (currentTabIndex != newIndex)
  51455. {
  51456. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51457. newIndex = -1;
  51458. currentTabIndex = newIndex;
  51459. for (int i = 0; i < tabs.size(); ++i)
  51460. {
  51461. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51462. tb->setToggleState (i == newIndex, false);
  51463. }
  51464. resized();
  51465. if (sendChangeMessage_)
  51466. sendChangeMessage();
  51467. currentTabChanged (newIndex, getCurrentTabName());
  51468. }
  51469. }
  51470. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51471. {
  51472. TabInfo* const tab = tabs[index];
  51473. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51474. }
  51475. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51476. {
  51477. for (int i = tabs.size(); --i >= 0;)
  51478. if (tabs.getUnchecked(i)->component == button)
  51479. return i;
  51480. return -1;
  51481. }
  51482. void TabbedButtonBar::lookAndFeelChanged()
  51483. {
  51484. extraTabsButton = 0;
  51485. resized();
  51486. }
  51487. void TabbedButtonBar::resized()
  51488. {
  51489. int depth = getWidth();
  51490. int length = getHeight();
  51491. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51492. swapVariables (depth, length);
  51493. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51494. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51495. int i, totalLength = overlap;
  51496. int numVisibleButtons = tabs.size();
  51497. for (i = 0; i < tabs.size(); ++i)
  51498. {
  51499. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51500. totalLength += tb->getBestTabLength (depth) - overlap;
  51501. tb->overlapPixels = overlap / 2;
  51502. }
  51503. double scale = 1.0;
  51504. if (totalLength > length)
  51505. scale = jmax (minimumScale, length / (double) totalLength);
  51506. const bool isTooBig = totalLength * scale > length;
  51507. int tabsButtonPos = 0;
  51508. if (isTooBig)
  51509. {
  51510. if (extraTabsButton == 0)
  51511. {
  51512. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51513. extraTabsButton->addListener (behindFrontTab);
  51514. extraTabsButton->setAlwaysOnTop (true);
  51515. extraTabsButton->setTriggeredOnMouseDown (true);
  51516. }
  51517. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51518. extraTabsButton->setSize (buttonSize, buttonSize);
  51519. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51520. {
  51521. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51522. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51523. }
  51524. else
  51525. {
  51526. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51527. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51528. }
  51529. totalLength = 0;
  51530. for (i = 0; i < tabs.size(); ++i)
  51531. {
  51532. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51533. const int newLength = totalLength + tb->getBestTabLength (depth);
  51534. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51535. {
  51536. totalLength += overlap;
  51537. break;
  51538. }
  51539. numVisibleButtons = i + 1;
  51540. totalLength = newLength - overlap;
  51541. }
  51542. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51543. }
  51544. else
  51545. {
  51546. extraTabsButton = 0;
  51547. }
  51548. int pos = 0;
  51549. TabBarButton* frontTab = 0;
  51550. for (i = 0; i < tabs.size(); ++i)
  51551. {
  51552. TabBarButton* const tb = getTabButton (i);
  51553. if (tb != 0)
  51554. {
  51555. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51556. if (i < numVisibleButtons)
  51557. {
  51558. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51559. tb->setBounds (pos, 0, bestLength, getHeight());
  51560. else
  51561. tb->setBounds (0, pos, getWidth(), bestLength);
  51562. tb->toBack();
  51563. if (i == currentTabIndex)
  51564. frontTab = tb;
  51565. tb->setVisible (true);
  51566. }
  51567. else
  51568. {
  51569. tb->setVisible (false);
  51570. }
  51571. pos += bestLength - overlap;
  51572. }
  51573. }
  51574. behindFrontTab->setBounds (getLocalBounds());
  51575. if (frontTab != 0)
  51576. {
  51577. frontTab->toFront (false);
  51578. behindFrontTab->toBehind (frontTab);
  51579. }
  51580. }
  51581. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51582. {
  51583. TabInfo* const tab = tabs [tabIndex];
  51584. return tab == 0 ? Colours::white : tab->colour;
  51585. }
  51586. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51587. {
  51588. TabInfo* const tab = tabs [tabIndex];
  51589. if (tab != 0 && tab->colour != newColour)
  51590. {
  51591. tab->colour = newColour;
  51592. repaint();
  51593. }
  51594. }
  51595. void TabbedButtonBar::showExtraItemsMenu()
  51596. {
  51597. PopupMenu m;
  51598. for (int i = 0; i < tabs.size(); ++i)
  51599. {
  51600. const TabInfo* const tab = tabs.getUnchecked(i);
  51601. if (! tab->component->isVisible())
  51602. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51603. }
  51604. const int res = m.showAt (extraTabsButton);
  51605. if (res != 0)
  51606. setCurrentTabIndex (res - 1);
  51607. }
  51608. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51609. {
  51610. }
  51611. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51612. {
  51613. }
  51614. END_JUCE_NAMESPACE
  51615. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51616. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51617. BEGIN_JUCE_NAMESPACE
  51618. class TabCompButtonBar : public TabbedButtonBar
  51619. {
  51620. public:
  51621. TabCompButtonBar (TabbedComponent& owner_,
  51622. const TabbedButtonBar::Orientation orientation_)
  51623. : TabbedButtonBar (orientation_),
  51624. owner (owner_)
  51625. {
  51626. }
  51627. ~TabCompButtonBar()
  51628. {
  51629. }
  51630. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51631. {
  51632. owner.changeCallback (newCurrentTabIndex, newTabName);
  51633. }
  51634. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51635. {
  51636. owner.popupMenuClickOnTab (tabIndex, tabName);
  51637. }
  51638. const Colour getTabBackgroundColour (const int tabIndex)
  51639. {
  51640. return owner.tabs->getTabBackgroundColour (tabIndex);
  51641. }
  51642. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51643. {
  51644. return owner.createTabButton (tabName, tabIndex);
  51645. }
  51646. private:
  51647. TabbedComponent& owner;
  51648. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabCompButtonBar);
  51649. };
  51650. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51651. : tabDepth (30),
  51652. outlineThickness (1),
  51653. edgeIndent (0)
  51654. {
  51655. addAndMakeVisible (tabs = new TabCompButtonBar (*this, orientation));
  51656. }
  51657. TabbedComponent::~TabbedComponent()
  51658. {
  51659. clearTabs();
  51660. tabs = 0;
  51661. }
  51662. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51663. {
  51664. tabs->setOrientation (orientation);
  51665. resized();
  51666. }
  51667. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51668. {
  51669. return tabs->getOrientation();
  51670. }
  51671. void TabbedComponent::setTabBarDepth (const int newDepth)
  51672. {
  51673. if (tabDepth != newDepth)
  51674. {
  51675. tabDepth = newDepth;
  51676. resized();
  51677. }
  51678. }
  51679. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51680. {
  51681. return new TabBarButton (tabName, *tabs);
  51682. }
  51683. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51684. void TabbedComponent::clearTabs()
  51685. {
  51686. if (panelComponent != 0)
  51687. {
  51688. panelComponent->setVisible (false);
  51689. removeChildComponent (panelComponent);
  51690. panelComponent = 0;
  51691. }
  51692. tabs->clearTabs();
  51693. for (int i = contentComponents.size(); --i >= 0;)
  51694. {
  51695. WeakReference<Component>& c = *contentComponents.getUnchecked (i);
  51696. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51697. delete c.get();
  51698. }
  51699. contentComponents.clear();
  51700. }
  51701. void TabbedComponent::addTab (const String& tabName,
  51702. const Colour& tabBackgroundColour,
  51703. Component* const contentComponent,
  51704. const bool deleteComponentWhenNotNeeded,
  51705. const int insertIndex)
  51706. {
  51707. contentComponents.insert (insertIndex, new WeakReference<Component> (contentComponent));
  51708. if (contentComponent != 0)
  51709. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51710. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51711. }
  51712. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51713. {
  51714. tabs->setTabName (tabIndex, newName);
  51715. }
  51716. void TabbedComponent::removeTab (const int tabIndex)
  51717. {
  51718. WeakReference<Component>* c = contentComponents [tabIndex];
  51719. if (c != 0)
  51720. {
  51721. if ((bool) ((*c)->getProperties() [deleteComponentId]))
  51722. delete c->get();
  51723. contentComponents.remove (tabIndex);
  51724. tabs->removeTab (tabIndex);
  51725. }
  51726. }
  51727. int TabbedComponent::getNumTabs() const
  51728. {
  51729. return tabs->getNumTabs();
  51730. }
  51731. const StringArray TabbedComponent::getTabNames() const
  51732. {
  51733. return tabs->getTabNames();
  51734. }
  51735. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51736. {
  51737. WeakReference<Component>* const c = contentComponents [tabIndex];
  51738. return c != 0 ? *c : 0;
  51739. }
  51740. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51741. {
  51742. return tabs->getTabBackgroundColour (tabIndex);
  51743. }
  51744. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51745. {
  51746. tabs->setTabBackgroundColour (tabIndex, newColour);
  51747. if (getCurrentTabIndex() == tabIndex)
  51748. repaint();
  51749. }
  51750. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51751. {
  51752. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51753. }
  51754. int TabbedComponent::getCurrentTabIndex() const
  51755. {
  51756. return tabs->getCurrentTabIndex();
  51757. }
  51758. const String TabbedComponent::getCurrentTabName() const
  51759. {
  51760. return tabs->getCurrentTabName();
  51761. }
  51762. void TabbedComponent::setOutline (int thickness)
  51763. {
  51764. outlineThickness = thickness;
  51765. repaint();
  51766. }
  51767. void TabbedComponent::setIndent (const int indentThickness)
  51768. {
  51769. edgeIndent = indentThickness;
  51770. }
  51771. void TabbedComponent::paint (Graphics& g)
  51772. {
  51773. g.fillAll (findColour (backgroundColourId));
  51774. const TabbedButtonBar::Orientation o = getOrientation();
  51775. int x = 0;
  51776. int y = 0;
  51777. int r = getWidth();
  51778. int b = getHeight();
  51779. if (o == TabbedButtonBar::TabsAtTop)
  51780. y += tabDepth;
  51781. else if (o == TabbedButtonBar::TabsAtBottom)
  51782. b -= tabDepth;
  51783. else if (o == TabbedButtonBar::TabsAtLeft)
  51784. x += tabDepth;
  51785. else if (o == TabbedButtonBar::TabsAtRight)
  51786. r -= tabDepth;
  51787. g.reduceClipRegion (x, y, r - x, b - y);
  51788. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51789. if (outlineThickness > 0)
  51790. {
  51791. if (o == TabbedButtonBar::TabsAtTop)
  51792. --y;
  51793. else if (o == TabbedButtonBar::TabsAtBottom)
  51794. ++b;
  51795. else if (o == TabbedButtonBar::TabsAtLeft)
  51796. --x;
  51797. else if (o == TabbedButtonBar::TabsAtRight)
  51798. ++r;
  51799. g.setColour (findColour (outlineColourId));
  51800. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51801. }
  51802. }
  51803. void TabbedComponent::resized()
  51804. {
  51805. const TabbedButtonBar::Orientation o = getOrientation();
  51806. const int indent = edgeIndent + outlineThickness;
  51807. BorderSize indents (indent);
  51808. if (o == TabbedButtonBar::TabsAtTop)
  51809. {
  51810. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51811. indents.setTop (tabDepth + edgeIndent);
  51812. }
  51813. else if (o == TabbedButtonBar::TabsAtBottom)
  51814. {
  51815. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51816. indents.setBottom (tabDepth + edgeIndent);
  51817. }
  51818. else if (o == TabbedButtonBar::TabsAtLeft)
  51819. {
  51820. tabs->setBounds (0, 0, tabDepth, getHeight());
  51821. indents.setLeft (tabDepth + edgeIndent);
  51822. }
  51823. else if (o == TabbedButtonBar::TabsAtRight)
  51824. {
  51825. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51826. indents.setRight (tabDepth + edgeIndent);
  51827. }
  51828. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51829. for (int i = contentComponents.size(); --i >= 0;)
  51830. if (*contentComponents.getUnchecked (i) != 0)
  51831. (*contentComponents.getUnchecked (i))->setBounds (bounds);
  51832. }
  51833. void TabbedComponent::lookAndFeelChanged()
  51834. {
  51835. for (int i = contentComponents.size(); --i >= 0;)
  51836. if (*contentComponents.getUnchecked (i) != 0)
  51837. (*contentComponents.getUnchecked (i))->lookAndFeelChanged();
  51838. }
  51839. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51840. const String& newTabName)
  51841. {
  51842. if (panelComponent != 0)
  51843. {
  51844. panelComponent->setVisible (false);
  51845. removeChildComponent (panelComponent);
  51846. panelComponent = 0;
  51847. }
  51848. if (getCurrentTabIndex() >= 0)
  51849. {
  51850. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51851. if (panelComponent != 0)
  51852. {
  51853. // do these ops as two stages instead of addAndMakeVisible() so that the
  51854. // component has always got a parent when it gets the visibilityChanged() callback
  51855. addChildComponent (panelComponent);
  51856. panelComponent->setVisible (true);
  51857. panelComponent->toFront (true);
  51858. }
  51859. repaint();
  51860. }
  51861. resized();
  51862. currentTabChanged (newCurrentTabIndex, newTabName);
  51863. }
  51864. void TabbedComponent::currentTabChanged (const int, const String&)
  51865. {
  51866. }
  51867. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51868. {
  51869. }
  51870. END_JUCE_NAMESPACE
  51871. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51872. /*** Start of inlined file: juce_Viewport.cpp ***/
  51873. BEGIN_JUCE_NAMESPACE
  51874. Viewport::Viewport (const String& componentName)
  51875. : Component (componentName),
  51876. scrollBarThickness (0),
  51877. singleStepX (16),
  51878. singleStepY (16),
  51879. showHScrollbar (true),
  51880. showVScrollbar (true),
  51881. verticalScrollBar (true),
  51882. horizontalScrollBar (false)
  51883. {
  51884. // content holder is used to clip the contents so they don't overlap the scrollbars
  51885. addAndMakeVisible (&contentHolder);
  51886. contentHolder.setInterceptsMouseClicks (false, true);
  51887. addChildComponent (&verticalScrollBar);
  51888. addChildComponent (&horizontalScrollBar);
  51889. verticalScrollBar.addListener (this);
  51890. horizontalScrollBar.addListener (this);
  51891. setInterceptsMouseClicks (false, true);
  51892. setWantsKeyboardFocus (true);
  51893. }
  51894. Viewport::~Viewport()
  51895. {
  51896. deleteContentComp();
  51897. }
  51898. void Viewport::visibleAreaChanged (int, int, int, int)
  51899. {
  51900. }
  51901. void Viewport::deleteContentComp()
  51902. {
  51903. // This sets the content comp to a null pointer before deleting the old one, in case
  51904. // anything tries to use the old one while it's in mid-deletion..
  51905. ScopedPointer<Component> oldCompDeleter (contentComp);
  51906. contentComp = 0;
  51907. }
  51908. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51909. {
  51910. if (contentComp.get() != newViewedComponent)
  51911. {
  51912. deleteContentComp();
  51913. contentComp = newViewedComponent;
  51914. if (contentComp != 0)
  51915. {
  51916. contentComp->setTopLeftPosition (0, 0);
  51917. contentHolder.addAndMakeVisible (contentComp);
  51918. contentComp->addComponentListener (this);
  51919. }
  51920. updateVisibleArea();
  51921. }
  51922. }
  51923. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51924. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51925. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51926. {
  51927. if (contentComp != 0)
  51928. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51929. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51930. }
  51931. void Viewport::setViewPosition (const Point<int>& newPosition)
  51932. {
  51933. setViewPosition (newPosition.getX(), newPosition.getY());
  51934. }
  51935. void Viewport::setViewPositionProportionately (const double x, const double y)
  51936. {
  51937. if (contentComp != 0)
  51938. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51939. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51940. }
  51941. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51942. {
  51943. if (contentComp != 0)
  51944. {
  51945. int dx = 0, dy = 0;
  51946. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51947. {
  51948. if (mouseX < activeBorderThickness)
  51949. dx = activeBorderThickness - mouseX;
  51950. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51951. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51952. if (dx < 0)
  51953. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51954. else
  51955. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51956. }
  51957. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51958. {
  51959. if (mouseY < activeBorderThickness)
  51960. dy = activeBorderThickness - mouseY;
  51961. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51962. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51963. if (dy < 0)
  51964. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51965. else
  51966. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51967. }
  51968. if (dx != 0 || dy != 0)
  51969. {
  51970. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51971. contentComp->getY() + dy);
  51972. return true;
  51973. }
  51974. }
  51975. return false;
  51976. }
  51977. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51978. {
  51979. updateVisibleArea();
  51980. }
  51981. void Viewport::resized()
  51982. {
  51983. updateVisibleArea();
  51984. }
  51985. void Viewport::updateVisibleArea()
  51986. {
  51987. const int scrollbarWidth = getScrollBarThickness();
  51988. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51989. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51990. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51991. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51992. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51993. Rectangle<int> contentArea (getLocalBounds());
  51994. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51995. {
  51996. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51997. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51998. if (vBarVisible)
  51999. contentArea.setWidth (getWidth() - scrollbarWidth);
  52000. if (hBarVisible)
  52001. contentArea.setHeight (getHeight() - scrollbarWidth);
  52002. if (! contentArea.contains (contentComp->getBounds()))
  52003. {
  52004. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52005. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52006. }
  52007. }
  52008. if (vBarVisible)
  52009. contentArea.setWidth (getWidth() - scrollbarWidth);
  52010. if (hBarVisible)
  52011. contentArea.setHeight (getHeight() - scrollbarWidth);
  52012. contentHolder.setBounds (contentArea);
  52013. Rectangle<int> contentBounds;
  52014. if (contentComp != 0)
  52015. contentBounds = contentComp->getBounds();
  52016. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52017. if (hBarVisible)
  52018. {
  52019. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52020. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52021. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52022. horizontalScrollBar.setSingleStepSize (singleStepX);
  52023. horizontalScrollBar.cancelPendingUpdate();
  52024. }
  52025. if (vBarVisible)
  52026. {
  52027. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52028. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52029. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52030. verticalScrollBar.setSingleStepSize (singleStepY);
  52031. verticalScrollBar.cancelPendingUpdate();
  52032. }
  52033. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52034. horizontalScrollBar.setVisible (hBarVisible);
  52035. verticalScrollBar.setVisible (vBarVisible);
  52036. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52037. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52038. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52039. if (lastVisibleArea != visibleArea)
  52040. {
  52041. lastVisibleArea = visibleArea;
  52042. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52043. }
  52044. horizontalScrollBar.handleUpdateNowIfNeeded();
  52045. verticalScrollBar.handleUpdateNowIfNeeded();
  52046. }
  52047. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52048. {
  52049. if (singleStepX != stepX || singleStepY != stepY)
  52050. {
  52051. singleStepX = stepX;
  52052. singleStepY = stepY;
  52053. updateVisibleArea();
  52054. }
  52055. }
  52056. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52057. const bool showHorizontalScrollbarIfNeeded)
  52058. {
  52059. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52060. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52061. {
  52062. showVScrollbar = showVerticalScrollbarIfNeeded;
  52063. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52064. updateVisibleArea();
  52065. }
  52066. }
  52067. void Viewport::setScrollBarThickness (const int thickness)
  52068. {
  52069. if (scrollBarThickness != thickness)
  52070. {
  52071. scrollBarThickness = thickness;
  52072. updateVisibleArea();
  52073. }
  52074. }
  52075. int Viewport::getScrollBarThickness() const
  52076. {
  52077. return scrollBarThickness > 0 ? scrollBarThickness
  52078. : getLookAndFeel().getDefaultScrollbarWidth();
  52079. }
  52080. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52081. {
  52082. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52083. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52084. }
  52085. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52086. {
  52087. const int newRangeStartInt = roundToInt (newRangeStart);
  52088. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52089. {
  52090. setViewPosition (newRangeStartInt, getViewPositionY());
  52091. }
  52092. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52093. {
  52094. setViewPosition (getViewPositionX(), newRangeStartInt);
  52095. }
  52096. }
  52097. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52098. {
  52099. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52100. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52101. }
  52102. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52103. {
  52104. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52105. {
  52106. const bool hasVertBar = verticalScrollBar.isVisible();
  52107. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52108. if (hasHorzBar || hasVertBar)
  52109. {
  52110. if (wheelIncrementX != 0)
  52111. {
  52112. wheelIncrementX *= 14.0f * singleStepX;
  52113. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52114. : jmax (wheelIncrementX, 1.0f);
  52115. }
  52116. if (wheelIncrementY != 0)
  52117. {
  52118. wheelIncrementY *= 14.0f * singleStepY;
  52119. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52120. : jmax (wheelIncrementY, 1.0f);
  52121. }
  52122. Point<int> pos (getViewPosition());
  52123. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52124. {
  52125. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52126. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52127. }
  52128. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52129. {
  52130. if (wheelIncrementX == 0 && ! hasVertBar)
  52131. wheelIncrementX = wheelIncrementY;
  52132. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52133. }
  52134. else if (hasVertBar && wheelIncrementY != 0)
  52135. {
  52136. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52137. }
  52138. if (pos != getViewPosition())
  52139. {
  52140. setViewPosition (pos);
  52141. return true;
  52142. }
  52143. }
  52144. }
  52145. return false;
  52146. }
  52147. bool Viewport::keyPressed (const KeyPress& key)
  52148. {
  52149. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52150. || key.isKeyCode (KeyPress::downKey)
  52151. || key.isKeyCode (KeyPress::pageUpKey)
  52152. || key.isKeyCode (KeyPress::pageDownKey)
  52153. || key.isKeyCode (KeyPress::homeKey)
  52154. || key.isKeyCode (KeyPress::endKey);
  52155. if (verticalScrollBar.isVisible() && isUpDownKey)
  52156. return verticalScrollBar.keyPressed (key);
  52157. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52158. || key.isKeyCode (KeyPress::rightKey);
  52159. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52160. return horizontalScrollBar.keyPressed (key);
  52161. return false;
  52162. }
  52163. END_JUCE_NAMESPACE
  52164. /*** End of inlined file: juce_Viewport.cpp ***/
  52165. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52166. BEGIN_JUCE_NAMESPACE
  52167. namespace LookAndFeelHelpers
  52168. {
  52169. void createRoundedPath (Path& p,
  52170. const float x, const float y,
  52171. const float w, const float h,
  52172. const float cs,
  52173. const bool curveTopLeft, const bool curveTopRight,
  52174. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52175. {
  52176. const float cs2 = 2.0f * cs;
  52177. if (curveTopLeft)
  52178. {
  52179. p.startNewSubPath (x, y + cs);
  52180. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52181. }
  52182. else
  52183. {
  52184. p.startNewSubPath (x, y);
  52185. }
  52186. if (curveTopRight)
  52187. {
  52188. p.lineTo (x + w - cs, y);
  52189. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52190. }
  52191. else
  52192. {
  52193. p.lineTo (x + w, y);
  52194. }
  52195. if (curveBottomRight)
  52196. {
  52197. p.lineTo (x + w, y + h - cs);
  52198. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52199. }
  52200. else
  52201. {
  52202. p.lineTo (x + w, y + h);
  52203. }
  52204. if (curveBottomLeft)
  52205. {
  52206. p.lineTo (x + cs, y + h);
  52207. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52208. }
  52209. else
  52210. {
  52211. p.lineTo (x, y + h);
  52212. }
  52213. p.closeSubPath();
  52214. }
  52215. const Colour createBaseColour (const Colour& buttonColour,
  52216. const bool hasKeyboardFocus,
  52217. const bool isMouseOverButton,
  52218. const bool isButtonDown) throw()
  52219. {
  52220. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52221. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52222. if (isButtonDown)
  52223. return baseColour.contrasting (0.2f);
  52224. else if (isMouseOverButton)
  52225. return baseColour.contrasting (0.1f);
  52226. return baseColour;
  52227. }
  52228. const TextLayout layoutTooltipText (const String& text) throw()
  52229. {
  52230. const float tooltipFontSize = 12.0f;
  52231. const int maxToolTipWidth = 400;
  52232. const Font f (tooltipFontSize, Font::bold);
  52233. TextLayout tl (text, f);
  52234. tl.layout (maxToolTipWidth, Justification::left, true);
  52235. return tl;
  52236. }
  52237. LookAndFeel* defaultLF = 0;
  52238. LookAndFeel* currentDefaultLF = 0;
  52239. }
  52240. LookAndFeel::LookAndFeel()
  52241. {
  52242. /* if this fails it means you're trying to create a LookAndFeel object before
  52243. the static Colours have been initialised. That ain't gonna work. It probably
  52244. means that you're using a static LookAndFeel object and that your compiler has
  52245. decided to intialise it before the Colours class.
  52246. */
  52247. jassert (Colours::white == Colour (0xffffffff));
  52248. // set up the standard set of colours..
  52249. const int textButtonColour = 0xffbbbbff;
  52250. const int textHighlightColour = 0x401111ee;
  52251. const int standardOutlineColour = 0xb2808080;
  52252. static const int standardColours[] =
  52253. {
  52254. TextButton::buttonColourId, textButtonColour,
  52255. TextButton::buttonOnColourId, 0xff4444ff,
  52256. TextButton::textColourOnId, 0xff000000,
  52257. TextButton::textColourOffId, 0xff000000,
  52258. ComboBox::buttonColourId, 0xffbbbbff,
  52259. ComboBox::outlineColourId, standardOutlineColour,
  52260. ToggleButton::textColourId, 0xff000000,
  52261. TextEditor::backgroundColourId, 0xffffffff,
  52262. TextEditor::textColourId, 0xff000000,
  52263. TextEditor::highlightColourId, textHighlightColour,
  52264. TextEditor::highlightedTextColourId, 0xff000000,
  52265. TextEditor::caretColourId, 0xff000000,
  52266. TextEditor::outlineColourId, 0x00000000,
  52267. TextEditor::focusedOutlineColourId, textButtonColour,
  52268. TextEditor::shadowColourId, 0x38000000,
  52269. Label::backgroundColourId, 0x00000000,
  52270. Label::textColourId, 0xff000000,
  52271. Label::outlineColourId, 0x00000000,
  52272. ScrollBar::backgroundColourId, 0x00000000,
  52273. ScrollBar::thumbColourId, 0xffffffff,
  52274. TreeView::linesColourId, 0x4c000000,
  52275. TreeView::backgroundColourId, 0x00000000,
  52276. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52277. PopupMenu::backgroundColourId, 0xffffffff,
  52278. PopupMenu::textColourId, 0xff000000,
  52279. PopupMenu::headerTextColourId, 0xff000000,
  52280. PopupMenu::highlightedTextColourId, 0xffffffff,
  52281. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52282. ComboBox::textColourId, 0xff000000,
  52283. ComboBox::backgroundColourId, 0xffffffff,
  52284. ComboBox::arrowColourId, 0x99000000,
  52285. ListBox::backgroundColourId, 0xffffffff,
  52286. ListBox::outlineColourId, standardOutlineColour,
  52287. ListBox::textColourId, 0xff000000,
  52288. Slider::backgroundColourId, 0x00000000,
  52289. Slider::thumbColourId, textButtonColour,
  52290. Slider::trackColourId, 0x7fffffff,
  52291. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52292. Slider::rotarySliderOutlineColourId, 0x66000000,
  52293. Slider::textBoxTextColourId, 0xff000000,
  52294. Slider::textBoxBackgroundColourId, 0xffffffff,
  52295. Slider::textBoxHighlightColourId, textHighlightColour,
  52296. Slider::textBoxOutlineColourId, standardOutlineColour,
  52297. ResizableWindow::backgroundColourId, 0xff777777,
  52298. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52299. AlertWindow::backgroundColourId, 0xffededed,
  52300. AlertWindow::textColourId, 0xff000000,
  52301. AlertWindow::outlineColourId, 0xff666666,
  52302. ProgressBar::backgroundColourId, 0xffeeeeee,
  52303. ProgressBar::foregroundColourId, 0xffaaaaee,
  52304. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52305. TooltipWindow::textColourId, 0xff000000,
  52306. TooltipWindow::outlineColourId, 0x4c000000,
  52307. TabbedComponent::backgroundColourId, 0x00000000,
  52308. TabbedComponent::outlineColourId, 0xff777777,
  52309. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52310. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52311. Toolbar::backgroundColourId, 0xfff6f8f9,
  52312. Toolbar::separatorColourId, 0x4c000000,
  52313. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52314. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52315. Toolbar::labelTextColourId, 0xff000000,
  52316. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52317. HyperlinkButton::textColourId, 0xcc1111ee,
  52318. GroupComponent::outlineColourId, 0x66000000,
  52319. GroupComponent::textColourId, 0xff000000,
  52320. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52321. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52322. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52323. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52324. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52325. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52326. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52327. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52328. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52329. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52330. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52331. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52332. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52333. CodeEditorComponent::caretColourId, 0xff000000,
  52334. CodeEditorComponent::highlightColourId, textHighlightColour,
  52335. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52336. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52337. ColourSelector::labelTextColourId, 0xff000000,
  52338. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52339. KeyMappingEditorComponent::textColourId, 0xff000000,
  52340. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52341. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52342. DrawableButton::textColourId, 0xff000000,
  52343. };
  52344. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52345. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52346. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52347. if (defaultSansName.isEmpty())
  52348. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52349. defaultSans = defaultSansName;
  52350. defaultSerif = defaultSerifName;
  52351. defaultFixed = defaultFixedName;
  52352. Font::setFallbackFontName (defaultFallback);
  52353. }
  52354. LookAndFeel::~LookAndFeel()
  52355. {
  52356. if (this == LookAndFeelHelpers::currentDefaultLF)
  52357. setDefaultLookAndFeel (0);
  52358. }
  52359. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52360. {
  52361. const int index = colourIds.indexOf (colourId);
  52362. if (index >= 0)
  52363. return colours [index];
  52364. jassertfalse;
  52365. return Colours::black;
  52366. }
  52367. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52368. {
  52369. const int index = colourIds.indexOf (colourId);
  52370. if (index >= 0)
  52371. {
  52372. colours.set (index, colour);
  52373. }
  52374. else
  52375. {
  52376. colourIds.add (colourId);
  52377. colours.add (colour);
  52378. }
  52379. }
  52380. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52381. {
  52382. return colourIds.contains (colourId);
  52383. }
  52384. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52385. {
  52386. // if this happens, your app hasn't initialised itself properly.. if you're
  52387. // trying to hack your own main() function, have a look at
  52388. // JUCEApplication::initialiseForGUI()
  52389. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52390. return *LookAndFeelHelpers::currentDefaultLF;
  52391. }
  52392. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52393. {
  52394. using namespace LookAndFeelHelpers;
  52395. if (newDefaultLookAndFeel == 0)
  52396. {
  52397. if (defaultLF == 0)
  52398. defaultLF = new LookAndFeel();
  52399. newDefaultLookAndFeel = defaultLF;
  52400. }
  52401. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52402. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52403. {
  52404. Component* const c = Desktop::getInstance().getComponent (i);
  52405. if (c != 0)
  52406. c->sendLookAndFeelChange();
  52407. }
  52408. }
  52409. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52410. {
  52411. using namespace LookAndFeelHelpers;
  52412. if (currentDefaultLF == defaultLF)
  52413. currentDefaultLF = 0;
  52414. deleteAndZero (defaultLF);
  52415. }
  52416. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52417. {
  52418. String faceName (font.getTypefaceName());
  52419. if (faceName == Font::getDefaultSansSerifFontName())
  52420. faceName = defaultSans;
  52421. else if (faceName == Font::getDefaultSerifFontName())
  52422. faceName = defaultSerif;
  52423. else if (faceName == Font::getDefaultMonospacedFontName())
  52424. faceName = defaultFixed;
  52425. Font f (font);
  52426. f.setTypefaceName (faceName);
  52427. return Typeface::createSystemTypefaceFor (f);
  52428. }
  52429. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52430. {
  52431. defaultSans = newName;
  52432. }
  52433. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52434. {
  52435. return component.getMouseCursor();
  52436. }
  52437. void LookAndFeel::drawButtonBackground (Graphics& g,
  52438. Button& button,
  52439. const Colour& backgroundColour,
  52440. bool isMouseOverButton,
  52441. bool isButtonDown)
  52442. {
  52443. const int width = button.getWidth();
  52444. const int height = button.getHeight();
  52445. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52446. const float halfThickness = outlineThickness * 0.5f;
  52447. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52448. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52449. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52450. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52451. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52452. button.hasKeyboardFocus (true),
  52453. isMouseOverButton, isButtonDown)
  52454. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52455. drawGlassLozenge (g,
  52456. indentL,
  52457. indentT,
  52458. width - indentL - indentR,
  52459. height - indentT - indentB,
  52460. baseColour, outlineThickness, -1.0f,
  52461. button.isConnectedOnLeft(),
  52462. button.isConnectedOnRight(),
  52463. button.isConnectedOnTop(),
  52464. button.isConnectedOnBottom());
  52465. }
  52466. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52467. {
  52468. return button.getFont();
  52469. }
  52470. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52471. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52472. {
  52473. Font font (getFontForTextButton (button));
  52474. g.setFont (font);
  52475. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52476. : TextButton::textColourOffId)
  52477. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52478. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52479. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52480. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52481. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52482. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52483. g.drawFittedText (button.getButtonText(),
  52484. leftIndent,
  52485. yIndent,
  52486. button.getWidth() - leftIndent - rightIndent,
  52487. button.getHeight() - yIndent * 2,
  52488. Justification::centred, 2);
  52489. }
  52490. void LookAndFeel::drawTickBox (Graphics& g,
  52491. Component& component,
  52492. float x, float y, float w, float h,
  52493. const bool ticked,
  52494. const bool isEnabled,
  52495. const bool isMouseOverButton,
  52496. const bool isButtonDown)
  52497. {
  52498. const float boxSize = w * 0.7f;
  52499. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52500. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52501. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52502. true, isMouseOverButton, isButtonDown),
  52503. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52504. if (ticked)
  52505. {
  52506. Path tick;
  52507. tick.startNewSubPath (1.5f, 3.0f);
  52508. tick.lineTo (3.0f, 6.0f);
  52509. tick.lineTo (6.0f, 0.0f);
  52510. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52511. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52512. .translated (x, y));
  52513. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52514. }
  52515. }
  52516. void LookAndFeel::drawToggleButton (Graphics& g,
  52517. ToggleButton& button,
  52518. bool isMouseOverButton,
  52519. bool isButtonDown)
  52520. {
  52521. if (button.hasKeyboardFocus (true))
  52522. {
  52523. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52524. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52525. }
  52526. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52527. const float tickWidth = fontSize * 1.1f;
  52528. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52529. tickWidth, tickWidth,
  52530. button.getToggleState(),
  52531. button.isEnabled(),
  52532. isMouseOverButton,
  52533. isButtonDown);
  52534. g.setColour (button.findColour (ToggleButton::textColourId));
  52535. g.setFont (fontSize);
  52536. if (! button.isEnabled())
  52537. g.setOpacity (0.5f);
  52538. const int textX = (int) tickWidth + 5;
  52539. g.drawFittedText (button.getButtonText(),
  52540. textX, 0,
  52541. button.getWidth() - textX - 2, button.getHeight(),
  52542. Justification::centredLeft, 10);
  52543. }
  52544. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52545. {
  52546. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52547. const int tickWidth = jmin (24, button.getHeight());
  52548. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52549. button.getHeight());
  52550. }
  52551. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52552. const String& message,
  52553. const String& button1,
  52554. const String& button2,
  52555. const String& button3,
  52556. AlertWindow::AlertIconType iconType,
  52557. int numButtons,
  52558. Component* associatedComponent)
  52559. {
  52560. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52561. if (numButtons == 1)
  52562. {
  52563. aw->addButton (button1, 0,
  52564. KeyPress (KeyPress::escapeKey, 0, 0),
  52565. KeyPress (KeyPress::returnKey, 0, 0));
  52566. }
  52567. else
  52568. {
  52569. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52570. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52571. if (button1ShortCut == button2ShortCut)
  52572. button2ShortCut = KeyPress();
  52573. if (numButtons == 2)
  52574. {
  52575. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52576. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52577. }
  52578. else if (numButtons == 3)
  52579. {
  52580. aw->addButton (button1, 1, button1ShortCut);
  52581. aw->addButton (button2, 2, button2ShortCut);
  52582. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52583. }
  52584. }
  52585. return aw;
  52586. }
  52587. void LookAndFeel::drawAlertBox (Graphics& g,
  52588. AlertWindow& alert,
  52589. const Rectangle<int>& textArea,
  52590. TextLayout& textLayout)
  52591. {
  52592. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52593. int iconSpaceUsed = 0;
  52594. Justification alignment (Justification::horizontallyCentred);
  52595. const int iconWidth = 80;
  52596. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52597. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52598. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52599. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52600. iconSize, iconSize);
  52601. if (alert.getAlertType() != AlertWindow::NoIcon)
  52602. {
  52603. Path icon;
  52604. uint32 colour;
  52605. char character;
  52606. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52607. {
  52608. colour = 0x55ff5555;
  52609. character = '!';
  52610. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52611. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52612. (float) iconRect.getX(), (float) iconRect.getBottom());
  52613. icon = icon.createPathWithRoundedCorners (5.0f);
  52614. }
  52615. else
  52616. {
  52617. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52618. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52619. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52620. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52621. }
  52622. GlyphArrangement ga;
  52623. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52624. String::charToString (character),
  52625. (float) iconRect.getX(), (float) iconRect.getY(),
  52626. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52627. Justification::centred, false);
  52628. ga.createPath (icon);
  52629. icon.setUsingNonZeroWinding (false);
  52630. g.setColour (Colour (colour));
  52631. g.fillPath (icon);
  52632. iconSpaceUsed = iconWidth;
  52633. alignment = Justification::left;
  52634. }
  52635. g.setColour (alert.findColour (AlertWindow::textColourId));
  52636. textLayout.drawWithin (g,
  52637. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52638. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52639. alignment.getFlags() | Justification::top);
  52640. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52641. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52642. }
  52643. int LookAndFeel::getAlertBoxWindowFlags()
  52644. {
  52645. return ComponentPeer::windowAppearsOnTaskbar
  52646. | ComponentPeer::windowHasDropShadow;
  52647. }
  52648. int LookAndFeel::getAlertWindowButtonHeight()
  52649. {
  52650. return 28;
  52651. }
  52652. const Font LookAndFeel::getAlertWindowFont()
  52653. {
  52654. return Font (12.0f);
  52655. }
  52656. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52657. int width, int height,
  52658. double progress, const String& textToShow)
  52659. {
  52660. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52661. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52662. g.fillAll (background);
  52663. if (progress >= 0.0f && progress < 1.0f)
  52664. {
  52665. drawGlassLozenge (g, 1.0f, 1.0f,
  52666. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52667. (float) (height - 2),
  52668. foreground,
  52669. 0.5f, 0.0f,
  52670. true, true, true, true);
  52671. }
  52672. else
  52673. {
  52674. // spinning bar..
  52675. g.setColour (foreground);
  52676. const int stripeWidth = height * 2;
  52677. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52678. Path p;
  52679. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52680. p.addQuadrilateral (x, 0.0f,
  52681. x + stripeWidth * 0.5f, 0.0f,
  52682. x, (float) height,
  52683. x - stripeWidth * 0.5f, (float) height);
  52684. Image im (Image::ARGB, width, height, true);
  52685. {
  52686. Graphics g2 (im);
  52687. drawGlassLozenge (g2, 1.0f, 1.0f,
  52688. (float) (width - 2),
  52689. (float) (height - 2),
  52690. foreground,
  52691. 0.5f, 0.0f,
  52692. true, true, true, true);
  52693. }
  52694. g.setTiledImageFill (im, 0, 0, 0.85f);
  52695. g.fillPath (p);
  52696. }
  52697. if (textToShow.isNotEmpty())
  52698. {
  52699. g.setColour (Colour::contrasting (background, foreground));
  52700. g.setFont (height * 0.6f);
  52701. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52702. }
  52703. }
  52704. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52705. {
  52706. const float radius = jmin (w, h) * 0.4f;
  52707. const float thickness = radius * 0.15f;
  52708. Path p;
  52709. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52710. radius * 0.6f, thickness,
  52711. thickness * 0.5f);
  52712. const float cx = x + w * 0.5f;
  52713. const float cy = y + h * 0.5f;
  52714. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52715. for (int i = 0; i < 12; ++i)
  52716. {
  52717. const int n = (i + 12 - animationIndex) % 12;
  52718. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52719. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52720. .translated (cx, cy));
  52721. }
  52722. }
  52723. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52724. ScrollBar& scrollbar,
  52725. int width, int height,
  52726. int buttonDirection,
  52727. bool /*isScrollbarVertical*/,
  52728. bool /*isMouseOverButton*/,
  52729. bool isButtonDown)
  52730. {
  52731. Path p;
  52732. if (buttonDirection == 0)
  52733. p.addTriangle (width * 0.5f, height * 0.2f,
  52734. width * 0.1f, height * 0.7f,
  52735. width * 0.9f, height * 0.7f);
  52736. else if (buttonDirection == 1)
  52737. p.addTriangle (width * 0.8f, height * 0.5f,
  52738. width * 0.3f, height * 0.1f,
  52739. width * 0.3f, height * 0.9f);
  52740. else if (buttonDirection == 2)
  52741. p.addTriangle (width * 0.5f, height * 0.8f,
  52742. width * 0.1f, height * 0.3f,
  52743. width * 0.9f, height * 0.3f);
  52744. else if (buttonDirection == 3)
  52745. p.addTriangle (width * 0.2f, height * 0.5f,
  52746. width * 0.7f, height * 0.1f,
  52747. width * 0.7f, height * 0.9f);
  52748. if (isButtonDown)
  52749. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52750. else
  52751. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52752. g.fillPath (p);
  52753. g.setColour (Colour (0x80000000));
  52754. g.strokePath (p, PathStrokeType (0.5f));
  52755. }
  52756. void LookAndFeel::drawScrollbar (Graphics& g,
  52757. ScrollBar& scrollbar,
  52758. int x, int y,
  52759. int width, int height,
  52760. bool isScrollbarVertical,
  52761. int thumbStartPosition,
  52762. int thumbSize,
  52763. bool /*isMouseOver*/,
  52764. bool /*isMouseDown*/)
  52765. {
  52766. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52767. Path slotPath, thumbPath;
  52768. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52769. const float slotIndentx2 = slotIndent * 2.0f;
  52770. const float thumbIndent = slotIndent + 1.0f;
  52771. const float thumbIndentx2 = thumbIndent * 2.0f;
  52772. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52773. if (isScrollbarVertical)
  52774. {
  52775. slotPath.addRoundedRectangle (x + slotIndent,
  52776. y + slotIndent,
  52777. width - slotIndentx2,
  52778. height - slotIndentx2,
  52779. (width - slotIndentx2) * 0.5f);
  52780. if (thumbSize > 0)
  52781. thumbPath.addRoundedRectangle (x + thumbIndent,
  52782. thumbStartPosition + thumbIndent,
  52783. width - thumbIndentx2,
  52784. thumbSize - thumbIndentx2,
  52785. (width - thumbIndentx2) * 0.5f);
  52786. gx1 = (float) x;
  52787. gx2 = x + width * 0.7f;
  52788. }
  52789. else
  52790. {
  52791. slotPath.addRoundedRectangle (x + slotIndent,
  52792. y + slotIndent,
  52793. width - slotIndentx2,
  52794. height - slotIndentx2,
  52795. (height - slotIndentx2) * 0.5f);
  52796. if (thumbSize > 0)
  52797. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52798. y + thumbIndent,
  52799. thumbSize - thumbIndentx2,
  52800. height - thumbIndentx2,
  52801. (height - thumbIndentx2) * 0.5f);
  52802. gy1 = (float) y;
  52803. gy2 = y + height * 0.7f;
  52804. }
  52805. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52806. Colour trackColour1, trackColour2;
  52807. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  52808. {
  52809. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  52810. }
  52811. else
  52812. {
  52813. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  52814. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  52815. }
  52816. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  52817. trackColour2, gx2, gy2, false));
  52818. g.fillPath (slotPath);
  52819. if (isScrollbarVertical)
  52820. {
  52821. gx1 = x + width * 0.6f;
  52822. gx2 = (float) x + width;
  52823. }
  52824. else
  52825. {
  52826. gy1 = y + height * 0.6f;
  52827. gy2 = (float) y + height;
  52828. }
  52829. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52830. Colour (0x19000000), gx2, gy2, false));
  52831. g.fillPath (slotPath);
  52832. g.setColour (thumbColour);
  52833. g.fillPath (thumbPath);
  52834. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52835. Colours::transparentBlack, gx2, gy2, false));
  52836. g.saveState();
  52837. if (isScrollbarVertical)
  52838. g.reduceClipRegion (x + width / 2, y, width, height);
  52839. else
  52840. g.reduceClipRegion (x, y + height / 2, width, height);
  52841. g.fillPath (thumbPath);
  52842. g.restoreState();
  52843. g.setColour (Colour (0x4c000000));
  52844. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52845. }
  52846. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52847. {
  52848. return 0;
  52849. }
  52850. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52851. {
  52852. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52853. }
  52854. int LookAndFeel::getDefaultScrollbarWidth()
  52855. {
  52856. return 18;
  52857. }
  52858. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52859. {
  52860. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52861. : scrollbar.getHeight());
  52862. }
  52863. const Path LookAndFeel::getTickShape (const float height)
  52864. {
  52865. static const unsigned char tickShapeData[] =
  52866. {
  52867. 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,
  52868. 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,
  52869. 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,
  52870. 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,
  52871. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52872. };
  52873. Path p;
  52874. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52875. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52876. return p;
  52877. }
  52878. const Path LookAndFeel::getCrossShape (const float height)
  52879. {
  52880. static const unsigned char crossShapeData[] =
  52881. {
  52882. 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,
  52883. 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,
  52884. 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,
  52885. 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,
  52886. 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,
  52887. 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,
  52888. 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
  52889. };
  52890. Path p;
  52891. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52892. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52893. return p;
  52894. }
  52895. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52896. {
  52897. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52898. x += (w - boxSize) >> 1;
  52899. y += (h - boxSize) >> 1;
  52900. w = boxSize;
  52901. h = boxSize;
  52902. g.setColour (Colour (0xe5ffffff));
  52903. g.fillRect (x, y, w, h);
  52904. g.setColour (Colour (0x80000000));
  52905. g.drawRect (x, y, w, h);
  52906. const float size = boxSize / 2 + 1.0f;
  52907. const float centre = (float) (boxSize / 2);
  52908. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52909. if (isPlus)
  52910. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52911. }
  52912. void LookAndFeel::drawBubble (Graphics& g,
  52913. float tipX, float tipY,
  52914. float boxX, float boxY,
  52915. float boxW, float boxH)
  52916. {
  52917. int side = 0;
  52918. if (tipX < boxX)
  52919. side = 1;
  52920. else if (tipX > boxX + boxW)
  52921. side = 3;
  52922. else if (tipY > boxY + boxH)
  52923. side = 2;
  52924. const float indent = 2.0f;
  52925. Path p;
  52926. p.addBubble (boxX + indent,
  52927. boxY + indent,
  52928. boxW - indent * 2.0f,
  52929. boxH - indent * 2.0f,
  52930. 5.0f,
  52931. tipX, tipY,
  52932. side,
  52933. 0.5f,
  52934. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52935. //xxx need to take comp as param for colour
  52936. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52937. g.fillPath (p);
  52938. //xxx as above
  52939. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52940. g.strokePath (p, PathStrokeType (1.33f));
  52941. }
  52942. const Font LookAndFeel::getPopupMenuFont()
  52943. {
  52944. return Font (17.0f);
  52945. }
  52946. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52947. const bool isSeparator,
  52948. int standardMenuItemHeight,
  52949. int& idealWidth,
  52950. int& idealHeight)
  52951. {
  52952. if (isSeparator)
  52953. {
  52954. idealWidth = 50;
  52955. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52956. }
  52957. else
  52958. {
  52959. Font font (getPopupMenuFont());
  52960. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52961. font.setHeight (standardMenuItemHeight / 1.3f);
  52962. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52963. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52964. }
  52965. }
  52966. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52967. {
  52968. const Colour background (findColour (PopupMenu::backgroundColourId));
  52969. g.fillAll (background);
  52970. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52971. for (int i = 0; i < height; i += 3)
  52972. g.fillRect (0, i, width, 1);
  52973. #if ! JUCE_MAC
  52974. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52975. g.drawRect (0, 0, width, height);
  52976. #endif
  52977. }
  52978. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52979. int width, int height,
  52980. bool isScrollUpArrow)
  52981. {
  52982. const Colour background (findColour (PopupMenu::backgroundColourId));
  52983. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52984. background.withAlpha (0.0f),
  52985. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52986. false));
  52987. g.fillRect (1, 1, width - 2, height - 2);
  52988. const float hw = width * 0.5f;
  52989. const float arrowW = height * 0.3f;
  52990. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52991. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52992. Path p;
  52993. p.addTriangle (hw - arrowW, y1,
  52994. hw + arrowW, y1,
  52995. hw, y2);
  52996. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52997. g.fillPath (p);
  52998. }
  52999. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53000. int width, int height,
  53001. const bool isSeparator,
  53002. const bool isActive,
  53003. const bool isHighlighted,
  53004. const bool isTicked,
  53005. const bool hasSubMenu,
  53006. const String& text,
  53007. const String& shortcutKeyText,
  53008. Image* image,
  53009. const Colour* const textColourToUse)
  53010. {
  53011. const float halfH = height * 0.5f;
  53012. if (isSeparator)
  53013. {
  53014. const float separatorIndent = 5.5f;
  53015. g.setColour (Colour (0x33000000));
  53016. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53017. g.setColour (Colour (0x66ffffff));
  53018. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53019. }
  53020. else
  53021. {
  53022. Colour textColour (findColour (PopupMenu::textColourId));
  53023. if (textColourToUse != 0)
  53024. textColour = *textColourToUse;
  53025. if (isHighlighted)
  53026. {
  53027. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53028. g.fillRect (1, 1, width - 2, height - 2);
  53029. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53030. }
  53031. else
  53032. {
  53033. g.setColour (textColour);
  53034. }
  53035. if (! isActive)
  53036. g.setOpacity (0.3f);
  53037. Font font (getPopupMenuFont());
  53038. if (font.getHeight() > height / 1.3f)
  53039. font.setHeight (height / 1.3f);
  53040. g.setFont (font);
  53041. const int leftBorder = (height * 5) / 4;
  53042. const int rightBorder = 4;
  53043. if (image != 0)
  53044. {
  53045. g.drawImageWithin (*image,
  53046. 2, 1, leftBorder - 4, height - 2,
  53047. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53048. }
  53049. else if (isTicked)
  53050. {
  53051. const Path tick (getTickShape (1.0f));
  53052. const float th = font.getAscent();
  53053. const float ty = halfH - th * 0.5f;
  53054. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53055. th, true));
  53056. }
  53057. g.drawFittedText (text,
  53058. leftBorder, 0,
  53059. width - (leftBorder + rightBorder), height,
  53060. Justification::centredLeft, 1);
  53061. if (shortcutKeyText.isNotEmpty())
  53062. {
  53063. Font f2 (font);
  53064. f2.setHeight (f2.getHeight() * 0.75f);
  53065. f2.setHorizontalScale (0.95f);
  53066. g.setFont (f2);
  53067. g.drawText (shortcutKeyText,
  53068. leftBorder,
  53069. 0,
  53070. width - (leftBorder + rightBorder + 4),
  53071. height,
  53072. Justification::centredRight,
  53073. true);
  53074. }
  53075. if (hasSubMenu)
  53076. {
  53077. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53078. const float x = width - height * 0.6f;
  53079. Path p;
  53080. p.addTriangle (x, halfH - arrowH * 0.5f,
  53081. x, halfH + arrowH * 0.5f,
  53082. x + arrowH * 0.6f, halfH);
  53083. g.fillPath (p);
  53084. }
  53085. }
  53086. }
  53087. int LookAndFeel::getMenuWindowFlags()
  53088. {
  53089. return ComponentPeer::windowHasDropShadow;
  53090. }
  53091. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53092. bool, MenuBarComponent& menuBar)
  53093. {
  53094. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53095. if (menuBar.isEnabled())
  53096. {
  53097. drawShinyButtonShape (g,
  53098. -4.0f, 0.0f,
  53099. width + 8.0f, (float) height,
  53100. 0.0f,
  53101. baseColour,
  53102. 0.4f,
  53103. true, true, true, true);
  53104. }
  53105. else
  53106. {
  53107. g.fillAll (baseColour);
  53108. }
  53109. }
  53110. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53111. {
  53112. return Font (menuBar.getHeight() * 0.7f);
  53113. }
  53114. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53115. {
  53116. return getMenuBarFont (menuBar, itemIndex, itemText)
  53117. .getStringWidth (itemText) + menuBar.getHeight();
  53118. }
  53119. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53120. int width, int height,
  53121. int itemIndex,
  53122. const String& itemText,
  53123. bool isMouseOverItem,
  53124. bool isMenuOpen,
  53125. bool /*isMouseOverBar*/,
  53126. MenuBarComponent& menuBar)
  53127. {
  53128. if (! menuBar.isEnabled())
  53129. {
  53130. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53131. .withMultipliedAlpha (0.5f));
  53132. }
  53133. else if (isMenuOpen || isMouseOverItem)
  53134. {
  53135. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53136. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53137. }
  53138. else
  53139. {
  53140. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53141. }
  53142. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53143. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53144. }
  53145. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53146. TextEditor& textEditor)
  53147. {
  53148. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53149. }
  53150. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53151. {
  53152. if (textEditor.isEnabled())
  53153. {
  53154. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53155. {
  53156. const int border = 2;
  53157. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53158. g.drawRect (0, 0, width, height, border);
  53159. g.setOpacity (1.0f);
  53160. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53161. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53162. }
  53163. else
  53164. {
  53165. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53166. g.drawRect (0, 0, width, height);
  53167. g.setOpacity (1.0f);
  53168. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53169. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53170. }
  53171. }
  53172. }
  53173. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53174. const bool isButtonDown,
  53175. int buttonX, int buttonY,
  53176. int buttonW, int buttonH,
  53177. ComboBox& box)
  53178. {
  53179. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53180. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53181. {
  53182. g.setColour (box.findColour (TextButton::buttonColourId));
  53183. g.drawRect (0, 0, width, height, 2);
  53184. }
  53185. else
  53186. {
  53187. g.setColour (box.findColour (ComboBox::outlineColourId));
  53188. g.drawRect (0, 0, width, height);
  53189. }
  53190. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53191. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53192. box.hasKeyboardFocus (true),
  53193. false, isButtonDown)
  53194. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53195. drawGlassLozenge (g,
  53196. buttonX + outlineThickness, buttonY + outlineThickness,
  53197. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53198. baseColour, outlineThickness, -1.0f,
  53199. true, true, true, true);
  53200. if (box.isEnabled())
  53201. {
  53202. const float arrowX = 0.3f;
  53203. const float arrowH = 0.2f;
  53204. Path p;
  53205. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53206. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53207. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53208. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53209. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53210. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53211. g.setColour (box.findColour (ComboBox::arrowColourId));
  53212. g.fillPath (p);
  53213. }
  53214. }
  53215. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53216. {
  53217. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53218. }
  53219. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53220. {
  53221. return new Label (String::empty, String::empty);
  53222. }
  53223. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53224. {
  53225. label.setBounds (1, 1,
  53226. box.getWidth() + 3 - box.getHeight(),
  53227. box.getHeight() - 2);
  53228. label.setFont (getComboBoxFont (box));
  53229. }
  53230. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53231. {
  53232. g.fillAll (label.findColour (Label::backgroundColourId));
  53233. if (! label.isBeingEdited())
  53234. {
  53235. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53236. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53237. g.setFont (label.getFont());
  53238. g.drawFittedText (label.getText(),
  53239. label.getHorizontalBorderSize(),
  53240. label.getVerticalBorderSize(),
  53241. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53242. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53243. label.getJustificationType(),
  53244. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53245. label.getMinimumHorizontalScale());
  53246. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53247. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53248. }
  53249. else if (label.isEnabled())
  53250. {
  53251. g.setColour (label.findColour (Label::outlineColourId));
  53252. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53253. }
  53254. }
  53255. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53256. int x, int y,
  53257. int width, int height,
  53258. float /*sliderPos*/,
  53259. float /*minSliderPos*/,
  53260. float /*maxSliderPos*/,
  53261. const Slider::SliderStyle /*style*/,
  53262. Slider& slider)
  53263. {
  53264. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53265. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53266. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53267. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53268. Path indent;
  53269. if (slider.isHorizontal())
  53270. {
  53271. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53272. const float ih = sliderRadius;
  53273. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53274. gradCol2, 0.0f, iy + ih, false));
  53275. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53276. width + sliderRadius, ih,
  53277. 5.0f);
  53278. g.fillPath (indent);
  53279. }
  53280. else
  53281. {
  53282. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53283. const float iw = sliderRadius;
  53284. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53285. gradCol2, ix + iw, 0.0f, false));
  53286. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53287. iw, height + sliderRadius,
  53288. 5.0f);
  53289. g.fillPath (indent);
  53290. }
  53291. g.setColour (Colour (0x4c000000));
  53292. g.strokePath (indent, PathStrokeType (0.5f));
  53293. }
  53294. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53295. int x, int y,
  53296. int width, int height,
  53297. float sliderPos,
  53298. float minSliderPos,
  53299. float maxSliderPos,
  53300. const Slider::SliderStyle style,
  53301. Slider& slider)
  53302. {
  53303. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53304. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53305. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53306. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53307. slider.isMouseButtonDown() && slider.isEnabled()));
  53308. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53309. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53310. {
  53311. float kx, ky;
  53312. if (style == Slider::LinearVertical)
  53313. {
  53314. kx = x + width * 0.5f;
  53315. ky = sliderPos;
  53316. }
  53317. else
  53318. {
  53319. kx = sliderPos;
  53320. ky = y + height * 0.5f;
  53321. }
  53322. drawGlassSphere (g,
  53323. kx - sliderRadius,
  53324. ky - sliderRadius,
  53325. sliderRadius * 2.0f,
  53326. knobColour, outlineThickness);
  53327. }
  53328. else
  53329. {
  53330. if (style == Slider::ThreeValueVertical)
  53331. {
  53332. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53333. sliderPos - sliderRadius,
  53334. sliderRadius * 2.0f,
  53335. knobColour, outlineThickness);
  53336. }
  53337. else if (style == Slider::ThreeValueHorizontal)
  53338. {
  53339. drawGlassSphere (g,sliderPos - sliderRadius,
  53340. y + height * 0.5f - sliderRadius,
  53341. sliderRadius * 2.0f,
  53342. knobColour, outlineThickness);
  53343. }
  53344. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53345. {
  53346. const float sr = jmin (sliderRadius, width * 0.4f);
  53347. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53348. minSliderPos - sliderRadius,
  53349. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53350. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53351. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53352. }
  53353. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53354. {
  53355. const float sr = jmin (sliderRadius, height * 0.4f);
  53356. drawGlassPointer (g, minSliderPos - sr,
  53357. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53358. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53359. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53360. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53361. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53362. }
  53363. }
  53364. }
  53365. void LookAndFeel::drawLinearSlider (Graphics& g,
  53366. int x, int y,
  53367. int width, int height,
  53368. float sliderPos,
  53369. float minSliderPos,
  53370. float maxSliderPos,
  53371. const Slider::SliderStyle style,
  53372. Slider& slider)
  53373. {
  53374. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53375. if (style == Slider::LinearBar)
  53376. {
  53377. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53378. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53379. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53380. false, isMouseOver,
  53381. isMouseOver || slider.isMouseButtonDown()));
  53382. drawShinyButtonShape (g,
  53383. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53384. baseColour,
  53385. slider.isEnabled() ? 0.9f : 0.3f,
  53386. true, true, true, true);
  53387. }
  53388. else
  53389. {
  53390. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53391. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53392. }
  53393. }
  53394. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53395. {
  53396. return jmin (7,
  53397. slider.getHeight() / 2,
  53398. slider.getWidth() / 2) + 2;
  53399. }
  53400. void LookAndFeel::drawRotarySlider (Graphics& g,
  53401. int x, int y,
  53402. int width, int height,
  53403. float sliderPos,
  53404. const float rotaryStartAngle,
  53405. const float rotaryEndAngle,
  53406. Slider& slider)
  53407. {
  53408. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53409. const float centreX = x + width * 0.5f;
  53410. const float centreY = y + height * 0.5f;
  53411. const float rx = centreX - radius;
  53412. const float ry = centreY - radius;
  53413. const float rw = radius * 2.0f;
  53414. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53415. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53416. if (radius > 12.0f)
  53417. {
  53418. if (slider.isEnabled())
  53419. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53420. else
  53421. g.setColour (Colour (0x80808080));
  53422. const float thickness = 0.7f;
  53423. {
  53424. Path filledArc;
  53425. filledArc.addPieSegment (rx, ry, rw, rw,
  53426. rotaryStartAngle,
  53427. angle,
  53428. thickness);
  53429. g.fillPath (filledArc);
  53430. }
  53431. if (thickness > 0)
  53432. {
  53433. const float innerRadius = radius * 0.2f;
  53434. Path p;
  53435. p.addTriangle (-innerRadius, 0.0f,
  53436. 0.0f, -radius * thickness * 1.1f,
  53437. innerRadius, 0.0f);
  53438. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53439. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53440. }
  53441. if (slider.isEnabled())
  53442. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53443. else
  53444. g.setColour (Colour (0x80808080));
  53445. Path outlineArc;
  53446. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53447. outlineArc.closeSubPath();
  53448. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53449. }
  53450. else
  53451. {
  53452. if (slider.isEnabled())
  53453. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53454. else
  53455. g.setColour (Colour (0x80808080));
  53456. Path p;
  53457. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53458. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53459. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53460. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53461. }
  53462. }
  53463. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53464. {
  53465. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53466. }
  53467. class SliderLabelComp : public Label
  53468. {
  53469. public:
  53470. SliderLabelComp() : Label (String::empty, String::empty) {}
  53471. ~SliderLabelComp() {}
  53472. void mouseWheelMove (const MouseEvent&, float, float) {}
  53473. };
  53474. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53475. {
  53476. Label* const l = new SliderLabelComp();
  53477. l->setJustificationType (Justification::centred);
  53478. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53479. l->setColour (Label::backgroundColourId,
  53480. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53481. : slider.findColour (Slider::textBoxBackgroundColourId));
  53482. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53483. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53484. l->setColour (TextEditor::backgroundColourId,
  53485. slider.findColour (Slider::textBoxBackgroundColourId)
  53486. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53487. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53488. return l;
  53489. }
  53490. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53491. {
  53492. return 0;
  53493. }
  53494. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53495. {
  53496. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53497. width = tl.getWidth() + 14;
  53498. height = tl.getHeight() + 6;
  53499. }
  53500. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53501. {
  53502. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53503. const Colour textCol (findColour (TooltipWindow::textColourId));
  53504. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53505. g.setColour (findColour (TooltipWindow::outlineColourId));
  53506. g.drawRect (0, 0, width, height, 1);
  53507. #endif
  53508. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53509. g.setColour (findColour (TooltipWindow::textColourId));
  53510. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53511. }
  53512. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53513. {
  53514. return new TextButton (text, TRANS("click to browse for a different file"));
  53515. }
  53516. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53517. ComboBox* filenameBox,
  53518. Button* browseButton)
  53519. {
  53520. browseButton->setSize (80, filenameComp.getHeight());
  53521. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53522. if (tb != 0)
  53523. tb->changeWidthToFitText();
  53524. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53525. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53526. }
  53527. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53528. int imageX, int imageY, int imageW, int imageH,
  53529. const Colour& overlayColour,
  53530. float imageOpacity,
  53531. ImageButton& button)
  53532. {
  53533. if (! button.isEnabled())
  53534. imageOpacity *= 0.3f;
  53535. if (! overlayColour.isOpaque())
  53536. {
  53537. g.setOpacity (imageOpacity);
  53538. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53539. 0, 0, image->getWidth(), image->getHeight(), false);
  53540. }
  53541. if (! overlayColour.isTransparent())
  53542. {
  53543. g.setColour (overlayColour);
  53544. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53545. 0, 0, image->getWidth(), image->getHeight(), true);
  53546. }
  53547. }
  53548. void LookAndFeel::drawCornerResizer (Graphics& g,
  53549. int w, int h,
  53550. bool /*isMouseOver*/,
  53551. bool /*isMouseDragging*/)
  53552. {
  53553. const float lineThickness = jmin (w, h) * 0.075f;
  53554. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53555. {
  53556. g.setColour (Colours::lightgrey);
  53557. g.drawLine (w * i,
  53558. h + 1.0f,
  53559. w + 1.0f,
  53560. h * i,
  53561. lineThickness);
  53562. g.setColour (Colours::darkgrey);
  53563. g.drawLine (w * i + lineThickness,
  53564. h + 1.0f,
  53565. w + 1.0f,
  53566. h * i + lineThickness,
  53567. lineThickness);
  53568. }
  53569. }
  53570. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53571. {
  53572. if (! border.isEmpty())
  53573. {
  53574. const Rectangle<int> fullSize (0, 0, w, h);
  53575. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53576. g.saveState();
  53577. g.excludeClipRegion (centreArea);
  53578. g.setColour (Colour (0x50000000));
  53579. g.drawRect (fullSize);
  53580. g.setColour (Colour (0x19000000));
  53581. g.drawRect (centreArea.expanded (1, 1));
  53582. g.restoreState();
  53583. }
  53584. }
  53585. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53586. const BorderSize& /*border*/, ResizableWindow& window)
  53587. {
  53588. g.fillAll (window.getBackgroundColour());
  53589. }
  53590. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53591. const BorderSize& /*border*/, ResizableWindow&)
  53592. {
  53593. }
  53594. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53595. Graphics& g, int w, int h,
  53596. int titleSpaceX, int titleSpaceW,
  53597. const Image* icon,
  53598. bool drawTitleTextOnLeft)
  53599. {
  53600. const bool isActive = window.isActiveWindow();
  53601. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53602. 0.0f, 0.0f,
  53603. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53604. 0.0f, (float) h, false));
  53605. g.fillAll();
  53606. Font font (h * 0.65f, Font::bold);
  53607. g.setFont (font);
  53608. int textW = font.getStringWidth (window.getName());
  53609. int iconW = 0;
  53610. int iconH = 0;
  53611. if (icon != 0)
  53612. {
  53613. iconH = (int) font.getHeight();
  53614. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53615. }
  53616. textW = jmin (titleSpaceW, textW + iconW);
  53617. int textX = drawTitleTextOnLeft ? titleSpaceX
  53618. : jmax (titleSpaceX, (w - textW) / 2);
  53619. if (textX + textW > titleSpaceX + titleSpaceW)
  53620. textX = titleSpaceX + titleSpaceW - textW;
  53621. if (icon != 0)
  53622. {
  53623. g.setOpacity (isActive ? 1.0f : 0.6f);
  53624. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53625. RectanglePlacement::centred, false);
  53626. textX += iconW;
  53627. textW -= iconW;
  53628. }
  53629. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53630. g.setColour (findColour (DocumentWindow::textColourId));
  53631. else
  53632. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53633. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53634. }
  53635. class GlassWindowButton : public Button
  53636. {
  53637. public:
  53638. GlassWindowButton (const String& name, const Colour& col,
  53639. const Path& normalShape_,
  53640. const Path& toggledShape_) throw()
  53641. : Button (name),
  53642. colour (col),
  53643. normalShape (normalShape_),
  53644. toggledShape (toggledShape_)
  53645. {
  53646. }
  53647. ~GlassWindowButton()
  53648. {
  53649. }
  53650. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53651. {
  53652. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53653. if (! isEnabled())
  53654. alpha *= 0.5f;
  53655. float x = 0, y = 0, diam;
  53656. if (getWidth() < getHeight())
  53657. {
  53658. diam = (float) getWidth();
  53659. y = (getHeight() - getWidth()) * 0.5f;
  53660. }
  53661. else
  53662. {
  53663. diam = (float) getHeight();
  53664. y = (getWidth() - getHeight()) * 0.5f;
  53665. }
  53666. x += diam * 0.05f;
  53667. y += diam * 0.05f;
  53668. diam *= 0.9f;
  53669. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53670. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53671. g.fillEllipse (x, y, diam, diam);
  53672. x += 2.0f;
  53673. y += 2.0f;
  53674. diam -= 4.0f;
  53675. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53676. Path& p = getToggleState() ? toggledShape : normalShape;
  53677. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53678. diam * 0.4f, diam * 0.4f, true));
  53679. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53680. g.fillPath (p, t);
  53681. }
  53682. private:
  53683. Colour colour;
  53684. Path normalShape, toggledShape;
  53685. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53686. };
  53687. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53688. {
  53689. Path shape;
  53690. const float crossThickness = 0.25f;
  53691. if (buttonType == DocumentWindow::closeButton)
  53692. {
  53693. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53694. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53695. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53696. }
  53697. else if (buttonType == DocumentWindow::minimiseButton)
  53698. {
  53699. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53700. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53701. }
  53702. else if (buttonType == DocumentWindow::maximiseButton)
  53703. {
  53704. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53705. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53706. Path fullscreenShape;
  53707. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53708. fullscreenShape.lineTo (0.0f, 100.0f);
  53709. fullscreenShape.lineTo (0.0f, 0.0f);
  53710. fullscreenShape.lineTo (100.0f, 0.0f);
  53711. fullscreenShape.lineTo (100.0f, 45.0f);
  53712. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53713. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53714. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53715. }
  53716. jassertfalse;
  53717. return 0;
  53718. }
  53719. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53720. int titleBarX,
  53721. int titleBarY,
  53722. int titleBarW,
  53723. int titleBarH,
  53724. Button* minimiseButton,
  53725. Button* maximiseButton,
  53726. Button* closeButton,
  53727. bool positionTitleBarButtonsOnLeft)
  53728. {
  53729. const int buttonW = titleBarH - titleBarH / 8;
  53730. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53731. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53732. if (closeButton != 0)
  53733. {
  53734. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53735. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53736. }
  53737. if (positionTitleBarButtonsOnLeft)
  53738. swapVariables (minimiseButton, maximiseButton);
  53739. if (maximiseButton != 0)
  53740. {
  53741. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53742. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53743. }
  53744. if (minimiseButton != 0)
  53745. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53746. }
  53747. int LookAndFeel::getDefaultMenuBarHeight()
  53748. {
  53749. return 24;
  53750. }
  53751. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53752. {
  53753. return new DropShadower (0.4f, 1, 5, 10);
  53754. }
  53755. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53756. int w, int h,
  53757. bool /*isVerticalBar*/,
  53758. bool isMouseOver,
  53759. bool isMouseDragging)
  53760. {
  53761. float alpha = 0.5f;
  53762. if (isMouseOver || isMouseDragging)
  53763. {
  53764. g.fillAll (Colour (0x190000ff));
  53765. alpha = 1.0f;
  53766. }
  53767. const float cx = w * 0.5f;
  53768. const float cy = h * 0.5f;
  53769. const float cr = jmin (w, h) * 0.4f;
  53770. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53771. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53772. true));
  53773. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53774. }
  53775. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53776. const String& text,
  53777. const Justification& position,
  53778. GroupComponent& group)
  53779. {
  53780. const float textH = 15.0f;
  53781. const float indent = 3.0f;
  53782. const float textEdgeGap = 4.0f;
  53783. float cs = 5.0f;
  53784. Font f (textH);
  53785. Path p;
  53786. float x = indent;
  53787. float y = f.getAscent() - 3.0f;
  53788. float w = jmax (0.0f, width - x * 2.0f);
  53789. float h = jmax (0.0f, height - y - indent);
  53790. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53791. const float cs2 = 2.0f * cs;
  53792. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53793. float textX = cs + textEdgeGap;
  53794. if (position.testFlags (Justification::horizontallyCentred))
  53795. textX = cs + (w - cs2 - textW) * 0.5f;
  53796. else if (position.testFlags (Justification::right))
  53797. textX = w - cs - textW - textEdgeGap;
  53798. p.startNewSubPath (x + textX + textW, y);
  53799. p.lineTo (x + w - cs, y);
  53800. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53801. p.lineTo (x + w, y + h - cs);
  53802. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53803. p.lineTo (x + cs, y + h);
  53804. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53805. p.lineTo (x, y + cs);
  53806. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53807. p.lineTo (x + textX, y);
  53808. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53809. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53810. .withMultipliedAlpha (alpha));
  53811. g.strokePath (p, PathStrokeType (2.0f));
  53812. g.setColour (group.findColour (GroupComponent::textColourId)
  53813. .withMultipliedAlpha (alpha));
  53814. g.setFont (f);
  53815. g.drawText (text,
  53816. roundToInt (x + textX), 0,
  53817. roundToInt (textW),
  53818. roundToInt (textH),
  53819. Justification::centred, true);
  53820. }
  53821. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53822. {
  53823. return 1 + tabDepth / 3;
  53824. }
  53825. int LookAndFeel::getTabButtonSpaceAroundImage()
  53826. {
  53827. return 4;
  53828. }
  53829. void LookAndFeel::createTabButtonShape (Path& p,
  53830. int width, int height,
  53831. int /*tabIndex*/,
  53832. const String& /*text*/,
  53833. Button& /*button*/,
  53834. TabbedButtonBar::Orientation orientation,
  53835. const bool /*isMouseOver*/,
  53836. const bool /*isMouseDown*/,
  53837. const bool /*isFrontTab*/)
  53838. {
  53839. const float w = (float) width;
  53840. const float h = (float) height;
  53841. float length = w;
  53842. float depth = h;
  53843. if (orientation == TabbedButtonBar::TabsAtLeft
  53844. || orientation == TabbedButtonBar::TabsAtRight)
  53845. {
  53846. swapVariables (length, depth);
  53847. }
  53848. const float indent = (float) getTabButtonOverlap ((int) depth);
  53849. const float overhang = 4.0f;
  53850. if (orientation == TabbedButtonBar::TabsAtLeft)
  53851. {
  53852. p.startNewSubPath (w, 0.0f);
  53853. p.lineTo (0.0f, indent);
  53854. p.lineTo (0.0f, h - indent);
  53855. p.lineTo (w, h);
  53856. p.lineTo (w + overhang, h + overhang);
  53857. p.lineTo (w + overhang, -overhang);
  53858. }
  53859. else if (orientation == TabbedButtonBar::TabsAtRight)
  53860. {
  53861. p.startNewSubPath (0.0f, 0.0f);
  53862. p.lineTo (w, indent);
  53863. p.lineTo (w, h - indent);
  53864. p.lineTo (0.0f, h);
  53865. p.lineTo (-overhang, h + overhang);
  53866. p.lineTo (-overhang, -overhang);
  53867. }
  53868. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53869. {
  53870. p.startNewSubPath (0.0f, 0.0f);
  53871. p.lineTo (indent, h);
  53872. p.lineTo (w - indent, h);
  53873. p.lineTo (w, 0.0f);
  53874. p.lineTo (w + overhang, -overhang);
  53875. p.lineTo (-overhang, -overhang);
  53876. }
  53877. else
  53878. {
  53879. p.startNewSubPath (0.0f, h);
  53880. p.lineTo (indent, 0.0f);
  53881. p.lineTo (w - indent, 0.0f);
  53882. p.lineTo (w, h);
  53883. p.lineTo (w + overhang, h + overhang);
  53884. p.lineTo (-overhang, h + overhang);
  53885. }
  53886. p.closeSubPath();
  53887. p = p.createPathWithRoundedCorners (3.0f);
  53888. }
  53889. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53890. const Path& path,
  53891. const Colour& preferredColour,
  53892. int /*tabIndex*/,
  53893. const String& /*text*/,
  53894. Button& button,
  53895. TabbedButtonBar::Orientation /*orientation*/,
  53896. const bool /*isMouseOver*/,
  53897. const bool /*isMouseDown*/,
  53898. const bool isFrontTab)
  53899. {
  53900. g.setColour (isFrontTab ? preferredColour
  53901. : preferredColour.withMultipliedAlpha (0.9f));
  53902. g.fillPath (path);
  53903. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53904. : TabbedButtonBar::tabOutlineColourId, false)
  53905. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53906. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53907. }
  53908. void LookAndFeel::drawTabButtonText (Graphics& g,
  53909. int x, int y, int w, int h,
  53910. const Colour& preferredBackgroundColour,
  53911. int /*tabIndex*/,
  53912. const String& text,
  53913. Button& button,
  53914. TabbedButtonBar::Orientation orientation,
  53915. const bool isMouseOver,
  53916. const bool isMouseDown,
  53917. const bool isFrontTab)
  53918. {
  53919. int length = w;
  53920. int depth = h;
  53921. if (orientation == TabbedButtonBar::TabsAtLeft
  53922. || orientation == TabbedButtonBar::TabsAtRight)
  53923. {
  53924. swapVariables (length, depth);
  53925. }
  53926. Font font (depth * 0.6f);
  53927. font.setUnderline (button.hasKeyboardFocus (false));
  53928. GlyphArrangement textLayout;
  53929. textLayout.addFittedText (font, text.trim(),
  53930. 0.0f, 0.0f, (float) length, (float) depth,
  53931. Justification::centred,
  53932. jmax (1, depth / 12));
  53933. AffineTransform transform;
  53934. if (orientation == TabbedButtonBar::TabsAtLeft)
  53935. {
  53936. transform = transform.rotated (float_Pi * -0.5f)
  53937. .translated ((float) x, (float) (y + h));
  53938. }
  53939. else if (orientation == TabbedButtonBar::TabsAtRight)
  53940. {
  53941. transform = transform.rotated (float_Pi * 0.5f)
  53942. .translated ((float) (x + w), (float) y);
  53943. }
  53944. else
  53945. {
  53946. transform = transform.translated ((float) x, (float) y);
  53947. }
  53948. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53949. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53950. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53951. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53952. else
  53953. g.setColour (preferredBackgroundColour.contrasting());
  53954. if (! (isMouseOver || isMouseDown))
  53955. g.setOpacity (0.8f);
  53956. if (! button.isEnabled())
  53957. g.setOpacity (0.3f);
  53958. textLayout.draw (g, transform);
  53959. }
  53960. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53961. const String& text,
  53962. int tabDepth,
  53963. Button&)
  53964. {
  53965. Font f (tabDepth * 0.6f);
  53966. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53967. }
  53968. void LookAndFeel::drawTabButton (Graphics& g,
  53969. int w, int h,
  53970. const Colour& preferredColour,
  53971. int tabIndex,
  53972. const String& text,
  53973. Button& button,
  53974. TabbedButtonBar::Orientation orientation,
  53975. const bool isMouseOver,
  53976. const bool isMouseDown,
  53977. const bool isFrontTab)
  53978. {
  53979. int length = w;
  53980. int depth = h;
  53981. if (orientation == TabbedButtonBar::TabsAtLeft
  53982. || orientation == TabbedButtonBar::TabsAtRight)
  53983. {
  53984. swapVariables (length, depth);
  53985. }
  53986. Path tabShape;
  53987. createTabButtonShape (tabShape, w, h,
  53988. tabIndex, text, button, orientation,
  53989. isMouseOver, isMouseDown, isFrontTab);
  53990. fillTabButtonShape (g, tabShape, preferredColour,
  53991. tabIndex, text, button, orientation,
  53992. isMouseOver, isMouseDown, isFrontTab);
  53993. const int indent = getTabButtonOverlap (depth);
  53994. int x = 0, y = 0;
  53995. if (orientation == TabbedButtonBar::TabsAtLeft
  53996. || orientation == TabbedButtonBar::TabsAtRight)
  53997. {
  53998. y += indent;
  53999. h -= indent * 2;
  54000. }
  54001. else
  54002. {
  54003. x += indent;
  54004. w -= indent * 2;
  54005. }
  54006. drawTabButtonText (g, x, y, w, h, preferredColour,
  54007. tabIndex, text, button, orientation,
  54008. isMouseOver, isMouseDown, isFrontTab);
  54009. }
  54010. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54011. int w, int h,
  54012. TabbedButtonBar& tabBar,
  54013. TabbedButtonBar::Orientation orientation)
  54014. {
  54015. const float shadowSize = 0.2f;
  54016. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54017. Rectangle<int> shadowRect;
  54018. if (orientation == TabbedButtonBar::TabsAtLeft)
  54019. {
  54020. x1 = (float) w;
  54021. x2 = w * (1.0f - shadowSize);
  54022. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54023. }
  54024. else if (orientation == TabbedButtonBar::TabsAtRight)
  54025. {
  54026. x2 = w * shadowSize;
  54027. shadowRect.setBounds (0, 0, (int) x2, h);
  54028. }
  54029. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54030. {
  54031. y2 = h * shadowSize;
  54032. shadowRect.setBounds (0, 0, w, (int) y2);
  54033. }
  54034. else
  54035. {
  54036. y1 = (float) h;
  54037. y2 = h * (1.0f - shadowSize);
  54038. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54039. }
  54040. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54041. Colours::transparentBlack, x2, y2, false));
  54042. shadowRect.expand (2, 2);
  54043. g.fillRect (shadowRect);
  54044. g.setColour (Colour (0x80000000));
  54045. if (orientation == TabbedButtonBar::TabsAtLeft)
  54046. {
  54047. g.fillRect (w - 1, 0, 1, h);
  54048. }
  54049. else if (orientation == TabbedButtonBar::TabsAtRight)
  54050. {
  54051. g.fillRect (0, 0, 1, h);
  54052. }
  54053. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54054. {
  54055. g.fillRect (0, 0, w, 1);
  54056. }
  54057. else
  54058. {
  54059. g.fillRect (0, h - 1, w, 1);
  54060. }
  54061. }
  54062. Button* LookAndFeel::createTabBarExtrasButton()
  54063. {
  54064. const float thickness = 7.0f;
  54065. const float indent = 22.0f;
  54066. Path p;
  54067. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54068. DrawablePath ellipse;
  54069. ellipse.setPath (p);
  54070. ellipse.setFill (Colour (0x99ffffff));
  54071. p.clear();
  54072. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54073. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54074. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54075. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54076. p.setUsingNonZeroWinding (false);
  54077. DrawablePath dp;
  54078. dp.setPath (p);
  54079. dp.setFill (Colour (0x59000000));
  54080. DrawableComposite normalImage;
  54081. normalImage.insertDrawable (ellipse);
  54082. normalImage.insertDrawable (dp);
  54083. dp.setFill (Colour (0xcc000000));
  54084. DrawableComposite overImage;
  54085. overImage.insertDrawable (ellipse);
  54086. overImage.insertDrawable (dp);
  54087. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54088. db->setImages (&normalImage, &overImage, 0);
  54089. return db;
  54090. }
  54091. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54092. {
  54093. g.fillAll (Colours::white);
  54094. const int w = header.getWidth();
  54095. const int h = header.getHeight();
  54096. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54097. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54098. false));
  54099. g.fillRect (0, h / 2, w, h);
  54100. g.setColour (Colour (0x33000000));
  54101. g.fillRect (0, h - 1, w, 1);
  54102. for (int i = header.getNumColumns (true); --i >= 0;)
  54103. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54104. }
  54105. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54106. int width, int height,
  54107. bool isMouseOver, bool isMouseDown,
  54108. int columnFlags)
  54109. {
  54110. if (isMouseDown)
  54111. g.fillAll (Colour (0x8899aadd));
  54112. else if (isMouseOver)
  54113. g.fillAll (Colour (0x5599aadd));
  54114. int rightOfText = width - 4;
  54115. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54116. {
  54117. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54118. const float bottom = height - top;
  54119. const float w = height * 0.5f;
  54120. const float x = rightOfText - (w * 1.25f);
  54121. rightOfText = (int) x;
  54122. Path sortArrow;
  54123. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54124. g.setColour (Colour (0x99000000));
  54125. g.fillPath (sortArrow);
  54126. }
  54127. g.setColour (Colours::black);
  54128. g.setFont (height * 0.5f, Font::bold);
  54129. const int textX = 4;
  54130. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54131. }
  54132. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54133. {
  54134. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54135. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54136. background.darker (0.1f),
  54137. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54138. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54139. false));
  54140. g.fillAll();
  54141. }
  54142. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54143. {
  54144. return createTabBarExtrasButton();
  54145. }
  54146. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54147. bool isMouseOver, bool isMouseDown,
  54148. ToolbarItemComponent& component)
  54149. {
  54150. if (isMouseDown)
  54151. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54152. else if (isMouseOver)
  54153. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54154. }
  54155. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54156. const String& text, ToolbarItemComponent& component)
  54157. {
  54158. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54159. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54160. const float fontHeight = jmin (14.0f, height * 0.85f);
  54161. g.setFont (fontHeight);
  54162. g.drawFittedText (text,
  54163. x, y, width, height,
  54164. Justification::centred,
  54165. jmax (1, height / (int) fontHeight));
  54166. }
  54167. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54168. bool isOpen, int width, int height)
  54169. {
  54170. const int buttonSize = (height * 3) / 4;
  54171. const int buttonIndent = (height - buttonSize) / 2;
  54172. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54173. const int textX = buttonIndent * 2 + buttonSize + 2;
  54174. g.setColour (Colours::black);
  54175. g.setFont (height * 0.7f, Font::bold);
  54176. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54177. }
  54178. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54179. PropertyComponent&)
  54180. {
  54181. g.setColour (Colour (0x66ffffff));
  54182. g.fillRect (0, 0, width, height - 1);
  54183. }
  54184. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54185. PropertyComponent& component)
  54186. {
  54187. g.setColour (Colours::black);
  54188. if (! component.isEnabled())
  54189. g.setOpacity (0.6f);
  54190. g.setFont (jmin (height, 24) * 0.65f);
  54191. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54192. g.drawFittedText (component.getName(),
  54193. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54194. Justification::centredLeft, 2);
  54195. }
  54196. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54197. {
  54198. return Rectangle<int> (component.getWidth() / 3, 1,
  54199. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54200. }
  54201. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54202. {
  54203. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54204. {
  54205. Graphics g2 (content);
  54206. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54207. g2.fillPath (path);
  54208. g2.setColour (Colours::white.withAlpha (0.8f));
  54209. g2.strokePath (path, PathStrokeType (2.0f));
  54210. }
  54211. DropShadowEffect shadow;
  54212. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54213. shadow.applyEffect (content, g, 1.0f);
  54214. }
  54215. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54216. const String& instructions,
  54217. GlyphArrangement& text,
  54218. int width)
  54219. {
  54220. text.clear();
  54221. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54222. 8.0f, 22.0f, width - 16.0f,
  54223. Justification::centred);
  54224. text.addJustifiedText (Font (14.0f), instructions,
  54225. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54226. Justification::centred);
  54227. }
  54228. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54229. const String& filename, Image* icon,
  54230. const String& fileSizeDescription,
  54231. const String& fileTimeDescription,
  54232. const bool isDirectory,
  54233. const bool isItemSelected,
  54234. const int /*itemIndex*/,
  54235. DirectoryContentsDisplayComponent&)
  54236. {
  54237. if (isItemSelected)
  54238. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54239. const int x = 32;
  54240. g.setColour (Colours::black);
  54241. if (icon != 0 && icon->isValid())
  54242. {
  54243. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54244. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54245. false);
  54246. }
  54247. else
  54248. {
  54249. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54250. : getDefaultDocumentFileImage();
  54251. if (d != 0)
  54252. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54253. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54254. }
  54255. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54256. g.setFont (height * 0.7f);
  54257. if (width > 450 && ! isDirectory)
  54258. {
  54259. const int sizeX = roundToInt (width * 0.7f);
  54260. const int dateX = roundToInt (width * 0.8f);
  54261. g.drawFittedText (filename,
  54262. x, 0, sizeX - x, height,
  54263. Justification::centredLeft, 1);
  54264. g.setFont (height * 0.5f);
  54265. g.setColour (Colours::darkgrey);
  54266. if (! isDirectory)
  54267. {
  54268. g.drawFittedText (fileSizeDescription,
  54269. sizeX, 0, dateX - sizeX - 8, height,
  54270. Justification::centredRight, 1);
  54271. g.drawFittedText (fileTimeDescription,
  54272. dateX, 0, width - 8 - dateX, height,
  54273. Justification::centredRight, 1);
  54274. }
  54275. }
  54276. else
  54277. {
  54278. g.drawFittedText (filename,
  54279. x, 0, width - x, height,
  54280. Justification::centredLeft, 1);
  54281. }
  54282. }
  54283. Button* LookAndFeel::createFileBrowserGoUpButton()
  54284. {
  54285. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54286. Path arrowPath;
  54287. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54288. DrawablePath arrowImage;
  54289. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54290. arrowImage.setPath (arrowPath);
  54291. goUpButton->setImages (&arrowImage);
  54292. return goUpButton;
  54293. }
  54294. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54295. DirectoryContentsDisplayComponent* fileListComponent,
  54296. FilePreviewComponent* previewComp,
  54297. ComboBox* currentPathBox,
  54298. TextEditor* filenameBox,
  54299. Button* goUpButton)
  54300. {
  54301. const int x = 8;
  54302. int w = browserComp.getWidth() - x - x;
  54303. if (previewComp != 0)
  54304. {
  54305. const int previewWidth = w / 3;
  54306. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54307. w -= previewWidth + 4;
  54308. }
  54309. int y = 4;
  54310. const int controlsHeight = 22;
  54311. const int bottomSectionHeight = controlsHeight + 8;
  54312. const int upButtonWidth = 50;
  54313. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54314. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54315. y += controlsHeight + 4;
  54316. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54317. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54318. y = listAsComp->getBottom() + 4;
  54319. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54320. }
  54321. // Pulls a drawable out of compressed valuetree data..
  54322. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54323. {
  54324. MemoryInputStream m (data, numBytes, false);
  54325. GZIPDecompressorInputStream gz (m);
  54326. ValueTree drawable (ValueTree::readFromStream (gz));
  54327. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54328. }
  54329. const Drawable* LookAndFeel::getDefaultFolderImage()
  54330. {
  54331. if (folderImage == 0)
  54332. {
  54333. static const unsigned char drawableData[] =
  54334. { 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,
  54335. 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,
  54336. 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,
  54337. 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,
  54338. 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,
  54339. 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,
  54340. 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,
  54341. 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,
  54342. 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,
  54343. 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,
  54344. 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,
  54345. 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,
  54346. 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,
  54347. 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,
  54348. 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 };
  54349. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54350. }
  54351. return folderImage;
  54352. }
  54353. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54354. {
  54355. if (documentImage == 0)
  54356. {
  54357. static const unsigned char drawableData[] =
  54358. { 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,
  54359. 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,
  54360. 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,
  54361. 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,
  54362. 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,
  54363. 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,
  54364. 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,
  54365. 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,
  54366. 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,
  54367. 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,
  54368. 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,
  54369. 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,
  54370. 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,
  54371. 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,
  54372. 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,
  54373. 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,
  54374. 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,
  54375. 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,
  54376. 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,
  54377. 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,
  54378. 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,
  54379. 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,
  54380. 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 };
  54381. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54382. }
  54383. return documentImage;
  54384. }
  54385. void LookAndFeel::playAlertSound()
  54386. {
  54387. PlatformUtilities::beep();
  54388. }
  54389. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54390. {
  54391. g.setColour (Colours::white.withAlpha (0.7f));
  54392. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54393. g.setColour (Colours::black.withAlpha (0.2f));
  54394. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54395. const int totalBlocks = 7;
  54396. const int numBlocks = roundToInt (totalBlocks * level);
  54397. const float w = (width - 6.0f) / (float) totalBlocks;
  54398. for (int i = 0; i < totalBlocks; ++i)
  54399. {
  54400. if (i >= numBlocks)
  54401. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54402. else
  54403. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54404. : Colours::red);
  54405. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54406. }
  54407. }
  54408. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54409. {
  54410. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54411. if (keyDescription.isNotEmpty())
  54412. {
  54413. if (button.isEnabled())
  54414. {
  54415. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54416. g.fillAll (textColour.withAlpha (alpha));
  54417. g.setOpacity (0.3f);
  54418. g.drawBevel (0, 0, width, height, 2);
  54419. }
  54420. g.setColour (textColour);
  54421. g.setFont (height * 0.6f);
  54422. g.drawFittedText (keyDescription,
  54423. 3, 0, width - 6, height,
  54424. Justification::centred, 1);
  54425. }
  54426. else
  54427. {
  54428. const float thickness = 7.0f;
  54429. const float indent = 22.0f;
  54430. Path p;
  54431. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54432. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54433. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54434. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54435. p.setUsingNonZeroWinding (false);
  54436. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54437. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54438. }
  54439. if (button.hasKeyboardFocus (false))
  54440. {
  54441. g.setColour (textColour.withAlpha (0.4f));
  54442. g.drawRect (0, 0, width, height);
  54443. }
  54444. }
  54445. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54446. float x, float y, float w, float h,
  54447. float maxCornerSize,
  54448. const Colour& baseColour,
  54449. const float strokeWidth,
  54450. const bool flatOnLeft,
  54451. const bool flatOnRight,
  54452. const bool flatOnTop,
  54453. const bool flatOnBottom) throw()
  54454. {
  54455. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54456. return;
  54457. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54458. Path outline;
  54459. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54460. ! (flatOnLeft || flatOnTop),
  54461. ! (flatOnRight || flatOnTop),
  54462. ! (flatOnLeft || flatOnBottom),
  54463. ! (flatOnRight || flatOnBottom));
  54464. ColourGradient cg (baseColour, 0.0f, y,
  54465. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54466. false);
  54467. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54468. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54469. g.setGradientFill (cg);
  54470. g.fillPath (outline);
  54471. g.setColour (Colour (0x80000000));
  54472. g.strokePath (outline, PathStrokeType (strokeWidth));
  54473. }
  54474. void LookAndFeel::drawGlassSphere (Graphics& g,
  54475. const float x, const float y,
  54476. const float diameter,
  54477. const Colour& colour,
  54478. const float outlineThickness) throw()
  54479. {
  54480. if (diameter <= outlineThickness)
  54481. return;
  54482. Path p;
  54483. p.addEllipse (x, y, diameter, diameter);
  54484. {
  54485. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54486. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54487. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54488. g.setGradientFill (cg);
  54489. g.fillPath (p);
  54490. }
  54491. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54492. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54493. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54494. ColourGradient cg (Colours::transparentBlack,
  54495. x + diameter * 0.5f, y + diameter * 0.5f,
  54496. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54497. x, y + diameter * 0.5f, true);
  54498. cg.addColour (0.7, Colours::transparentBlack);
  54499. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54500. g.setGradientFill (cg);
  54501. g.fillPath (p);
  54502. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54503. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54504. }
  54505. void LookAndFeel::drawGlassPointer (Graphics& g,
  54506. const float x, const float y,
  54507. const float diameter,
  54508. const Colour& colour, const float outlineThickness,
  54509. const int direction) throw()
  54510. {
  54511. if (diameter <= outlineThickness)
  54512. return;
  54513. Path p;
  54514. p.startNewSubPath (x + diameter * 0.5f, y);
  54515. p.lineTo (x + diameter, y + diameter * 0.6f);
  54516. p.lineTo (x + diameter, y + diameter);
  54517. p.lineTo (x, y + diameter);
  54518. p.lineTo (x, y + diameter * 0.6f);
  54519. p.closeSubPath();
  54520. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54521. {
  54522. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54523. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54524. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54525. g.setGradientFill (cg);
  54526. g.fillPath (p);
  54527. }
  54528. ColourGradient cg (Colours::transparentBlack,
  54529. x + diameter * 0.5f, y + diameter * 0.5f,
  54530. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54531. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54532. cg.addColour (0.5, Colours::transparentBlack);
  54533. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54534. g.setGradientFill (cg);
  54535. g.fillPath (p);
  54536. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54537. g.strokePath (p, PathStrokeType (outlineThickness));
  54538. }
  54539. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54540. const float x, const float y,
  54541. const float width, const float height,
  54542. const Colour& colour,
  54543. const float outlineThickness,
  54544. const float cornerSize,
  54545. const bool flatOnLeft,
  54546. const bool flatOnRight,
  54547. const bool flatOnTop,
  54548. const bool flatOnBottom) throw()
  54549. {
  54550. if (width <= outlineThickness || height <= outlineThickness)
  54551. return;
  54552. const int intX = (int) x;
  54553. const int intY = (int) y;
  54554. const int intW = (int) width;
  54555. const int intH = (int) height;
  54556. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54557. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54558. const int intEdge = (int) edgeBlurRadius;
  54559. Path outline;
  54560. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54561. ! (flatOnLeft || flatOnTop),
  54562. ! (flatOnRight || flatOnTop),
  54563. ! (flatOnLeft || flatOnBottom),
  54564. ! (flatOnRight || flatOnBottom));
  54565. {
  54566. ColourGradient cg (colour.darker (0.2f), 0, y,
  54567. colour.darker (0.2f), 0, y + height, false);
  54568. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54569. cg.addColour (0.4, colour);
  54570. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54571. g.setGradientFill (cg);
  54572. g.fillPath (outline);
  54573. }
  54574. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54575. colour.darker (0.2f), x, y + height * 0.5f, true);
  54576. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54577. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54578. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54579. {
  54580. g.saveState();
  54581. g.setGradientFill (cg);
  54582. g.reduceClipRegion (intX, intY, intEdge, intH);
  54583. g.fillPath (outline);
  54584. g.restoreState();
  54585. }
  54586. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54587. {
  54588. cg.point1.setX (x + width - edgeBlurRadius);
  54589. cg.point2.setX (x + width);
  54590. g.saveState();
  54591. g.setGradientFill (cg);
  54592. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54593. g.fillPath (outline);
  54594. g.restoreState();
  54595. }
  54596. {
  54597. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54598. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54599. Path highlight;
  54600. LookAndFeelHelpers::createRoundedPath (highlight,
  54601. x + leftIndent,
  54602. y + cs * 0.1f,
  54603. width - (leftIndent + rightIndent),
  54604. height * 0.4f, cs * 0.4f,
  54605. ! (flatOnLeft || flatOnTop),
  54606. ! (flatOnRight || flatOnTop),
  54607. ! (flatOnLeft || flatOnBottom),
  54608. ! (flatOnRight || flatOnBottom));
  54609. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54610. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54611. g.fillPath (highlight);
  54612. }
  54613. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54614. g.strokePath (outline, PathStrokeType (outlineThickness));
  54615. }
  54616. END_JUCE_NAMESPACE
  54617. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54618. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54619. BEGIN_JUCE_NAMESPACE
  54620. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54621. {
  54622. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54623. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54624. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54625. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54626. setColour (Slider::thumbColourId, Colours::white);
  54627. setColour (Slider::trackColourId, Colour (0x7f000000));
  54628. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54629. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54630. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54631. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54632. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54633. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54634. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54635. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54636. }
  54637. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54638. {
  54639. }
  54640. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54641. Button& button,
  54642. const Colour& backgroundColour,
  54643. bool isMouseOverButton,
  54644. bool isButtonDown)
  54645. {
  54646. const int width = button.getWidth();
  54647. const int height = button.getHeight();
  54648. const float indent = 2.0f;
  54649. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54650. roundToInt (height * 0.4f));
  54651. Path p;
  54652. p.addRoundedRectangle (indent, indent,
  54653. width - indent * 2.0f,
  54654. height - indent * 2.0f,
  54655. (float) cornerSize);
  54656. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54657. if (isMouseOverButton)
  54658. {
  54659. if (isButtonDown)
  54660. bc = bc.brighter();
  54661. else if (bc.getBrightness() > 0.5f)
  54662. bc = bc.darker (0.1f);
  54663. else
  54664. bc = bc.brighter (0.1f);
  54665. }
  54666. g.setColour (bc);
  54667. g.fillPath (p);
  54668. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54669. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54670. }
  54671. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54672. Component& /*component*/,
  54673. float x, float y, float w, float h,
  54674. const bool ticked,
  54675. const bool isEnabled,
  54676. const bool /*isMouseOverButton*/,
  54677. const bool isButtonDown)
  54678. {
  54679. Path box;
  54680. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54681. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54682. : Colours::lightgrey.withAlpha (0.1f));
  54683. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54684. g.fillPath (box, trans);
  54685. g.setColour (Colours::black.withAlpha (0.6f));
  54686. g.strokePath (box, PathStrokeType (0.9f), trans);
  54687. if (ticked)
  54688. {
  54689. Path tick;
  54690. tick.startNewSubPath (1.5f, 3.0f);
  54691. tick.lineTo (3.0f, 6.0f);
  54692. tick.lineTo (6.0f, 0.0f);
  54693. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54694. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54695. }
  54696. }
  54697. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54698. ToggleButton& button,
  54699. bool isMouseOverButton,
  54700. bool isButtonDown)
  54701. {
  54702. if (button.hasKeyboardFocus (true))
  54703. {
  54704. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54705. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54706. }
  54707. const int tickWidth = jmin (20, button.getHeight() - 4);
  54708. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54709. (float) tickWidth, (float) tickWidth,
  54710. button.getToggleState(),
  54711. button.isEnabled(),
  54712. isMouseOverButton,
  54713. isButtonDown);
  54714. g.setColour (button.findColour (ToggleButton::textColourId));
  54715. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54716. if (! button.isEnabled())
  54717. g.setOpacity (0.5f);
  54718. const int textX = tickWidth + 5;
  54719. g.drawFittedText (button.getButtonText(),
  54720. textX, 4,
  54721. button.getWidth() - textX - 2, button.getHeight() - 8,
  54722. Justification::centredLeft, 10);
  54723. }
  54724. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54725. int width, int height,
  54726. double progress, const String& textToShow)
  54727. {
  54728. if (progress < 0 || progress >= 1.0)
  54729. {
  54730. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54731. }
  54732. else
  54733. {
  54734. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54735. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54736. g.fillAll (background);
  54737. g.setColour (foreground);
  54738. g.fillRect (1, 1,
  54739. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54740. height - 2);
  54741. if (textToShow.isNotEmpty())
  54742. {
  54743. g.setColour (Colour::contrasting (background, foreground));
  54744. g.setFont (height * 0.6f);
  54745. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54746. }
  54747. }
  54748. }
  54749. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54750. ScrollBar& bar,
  54751. int width, int height,
  54752. int buttonDirection,
  54753. bool isScrollbarVertical,
  54754. bool isMouseOverButton,
  54755. bool isButtonDown)
  54756. {
  54757. if (isScrollbarVertical)
  54758. width -= 2;
  54759. else
  54760. height -= 2;
  54761. Path p;
  54762. if (buttonDirection == 0)
  54763. p.addTriangle (width * 0.5f, height * 0.2f,
  54764. width * 0.1f, height * 0.7f,
  54765. width * 0.9f, height * 0.7f);
  54766. else if (buttonDirection == 1)
  54767. p.addTriangle (width * 0.8f, height * 0.5f,
  54768. width * 0.3f, height * 0.1f,
  54769. width * 0.3f, height * 0.9f);
  54770. else if (buttonDirection == 2)
  54771. p.addTriangle (width * 0.5f, height * 0.8f,
  54772. width * 0.1f, height * 0.3f,
  54773. width * 0.9f, height * 0.3f);
  54774. else if (buttonDirection == 3)
  54775. p.addTriangle (width * 0.2f, height * 0.5f,
  54776. width * 0.7f, height * 0.1f,
  54777. width * 0.7f, height * 0.9f);
  54778. if (isButtonDown)
  54779. g.setColour (Colours::white);
  54780. else if (isMouseOverButton)
  54781. g.setColour (Colours::white.withAlpha (0.7f));
  54782. else
  54783. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54784. g.fillPath (p);
  54785. g.setColour (Colours::black.withAlpha (0.5f));
  54786. g.strokePath (p, PathStrokeType (0.5f));
  54787. }
  54788. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54789. ScrollBar& bar,
  54790. int x, int y,
  54791. int width, int height,
  54792. bool isScrollbarVertical,
  54793. int thumbStartPosition,
  54794. int thumbSize,
  54795. bool isMouseOver,
  54796. bool isMouseDown)
  54797. {
  54798. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54799. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54800. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54801. if (thumbSize > 0.0f)
  54802. {
  54803. Rectangle<int> thumb;
  54804. if (isScrollbarVertical)
  54805. {
  54806. width -= 2;
  54807. g.fillRect (x + roundToInt (width * 0.35f), y,
  54808. roundToInt (width * 0.3f), height);
  54809. thumb.setBounds (x + 1, thumbStartPosition,
  54810. width - 2, thumbSize);
  54811. }
  54812. else
  54813. {
  54814. height -= 2;
  54815. g.fillRect (x, y + roundToInt (height * 0.35f),
  54816. width, roundToInt (height * 0.3f));
  54817. thumb.setBounds (thumbStartPosition, y + 1,
  54818. thumbSize, height - 2);
  54819. }
  54820. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54821. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54822. g.fillRect (thumb);
  54823. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54824. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54825. if (thumbSize > 16)
  54826. {
  54827. for (int i = 3; --i >= 0;)
  54828. {
  54829. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54830. g.setColour (Colours::black.withAlpha (0.15f));
  54831. if (isScrollbarVertical)
  54832. {
  54833. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54834. g.setColour (Colours::white.withAlpha (0.15f));
  54835. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54836. }
  54837. else
  54838. {
  54839. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54840. g.setColour (Colours::white.withAlpha (0.15f));
  54841. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54842. }
  54843. }
  54844. }
  54845. }
  54846. }
  54847. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54848. {
  54849. return &scrollbarShadow;
  54850. }
  54851. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54852. {
  54853. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54854. g.setColour (Colours::black.withAlpha (0.6f));
  54855. g.drawRect (0, 0, width, height);
  54856. }
  54857. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54858. bool, MenuBarComponent& menuBar)
  54859. {
  54860. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54861. }
  54862. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54863. {
  54864. if (textEditor.isEnabled())
  54865. {
  54866. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54867. g.drawRect (0, 0, width, height);
  54868. }
  54869. }
  54870. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54871. const bool isButtonDown,
  54872. int buttonX, int buttonY,
  54873. int buttonW, int buttonH,
  54874. ComboBox& box)
  54875. {
  54876. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54877. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54878. : ComboBox::backgroundColourId));
  54879. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54880. g.setColour (box.findColour (ComboBox::outlineColourId));
  54881. g.drawRect (0, 0, width, height);
  54882. const float arrowX = 0.2f;
  54883. const float arrowH = 0.3f;
  54884. if (box.isEnabled())
  54885. {
  54886. Path p;
  54887. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54888. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54889. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54890. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54891. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54892. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54893. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54894. : ComboBox::buttonColourId));
  54895. g.fillPath (p);
  54896. }
  54897. }
  54898. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54899. {
  54900. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54901. f.setHorizontalScale (0.9f);
  54902. return f;
  54903. }
  54904. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54905. {
  54906. Path p;
  54907. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54908. g.setColour (fill);
  54909. g.fillPath (p);
  54910. g.setColour (outline);
  54911. g.strokePath (p, PathStrokeType (0.3f));
  54912. }
  54913. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54914. int x, int y,
  54915. int w, int h,
  54916. float sliderPos,
  54917. float minSliderPos,
  54918. float maxSliderPos,
  54919. const Slider::SliderStyle style,
  54920. Slider& slider)
  54921. {
  54922. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54923. if (style == Slider::LinearBar)
  54924. {
  54925. g.setColour (slider.findColour (Slider::thumbColourId));
  54926. g.fillRect (x, y, (int) sliderPos - x, h);
  54927. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54928. g.drawRect (x, y, (int) sliderPos - x, h);
  54929. }
  54930. else
  54931. {
  54932. g.setColour (slider.findColour (Slider::trackColourId)
  54933. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54934. if (slider.isHorizontal())
  54935. {
  54936. g.fillRect (x, y + roundToInt (h * 0.6f),
  54937. w, roundToInt (h * 0.2f));
  54938. }
  54939. else
  54940. {
  54941. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54942. jmin (4, roundToInt (w * 0.2f)), h);
  54943. }
  54944. float alpha = 0.35f;
  54945. if (slider.isEnabled())
  54946. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54947. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54948. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54949. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54950. {
  54951. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54952. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54953. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54954. fill, outline);
  54955. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54956. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54957. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54958. fill, outline);
  54959. }
  54960. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54961. {
  54962. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54963. minSliderPos - 7.0f, y + h * 0.9f ,
  54964. minSliderPos, y + h * 0.9f,
  54965. fill, outline);
  54966. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54967. maxSliderPos, y + h * 0.9f,
  54968. maxSliderPos + 7.0f, y + h * 0.9f,
  54969. fill, outline);
  54970. }
  54971. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54972. {
  54973. drawTriangle (g, sliderPos, y + h * 0.9f,
  54974. sliderPos - 7.0f, y + h * 0.2f,
  54975. sliderPos + 7.0f, y + h * 0.2f,
  54976. fill, outline);
  54977. }
  54978. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54979. {
  54980. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54981. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54982. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54983. fill, outline);
  54984. }
  54985. }
  54986. }
  54987. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54988. {
  54989. if (isIncrement)
  54990. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54991. else
  54992. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54993. }
  54994. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54995. {
  54996. return &scrollbarShadow;
  54997. }
  54998. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54999. {
  55000. return 8;
  55001. }
  55002. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55003. int w, int h,
  55004. bool isMouseOver,
  55005. bool isMouseDragging)
  55006. {
  55007. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55008. : Colours::darkgrey);
  55009. const float lineThickness = jmin (w, h) * 0.1f;
  55010. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55011. {
  55012. g.drawLine (w * i,
  55013. h + 1.0f,
  55014. w + 1.0f,
  55015. h * i,
  55016. lineThickness);
  55017. }
  55018. }
  55019. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55020. {
  55021. Path shape;
  55022. if (buttonType == DocumentWindow::closeButton)
  55023. {
  55024. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55025. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55026. ShapeButton* const b = new ShapeButton ("close",
  55027. Colour (0x7fff3333),
  55028. Colour (0xd7ff3333),
  55029. Colour (0xf7ff3333));
  55030. b->setShape (shape, true, true, true);
  55031. return b;
  55032. }
  55033. else if (buttonType == DocumentWindow::minimiseButton)
  55034. {
  55035. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55036. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55037. DrawablePath dp;
  55038. dp.setPath (shape);
  55039. dp.setFill (Colours::black.withAlpha (0.3f));
  55040. b->setImages (&dp);
  55041. return b;
  55042. }
  55043. else if (buttonType == DocumentWindow::maximiseButton)
  55044. {
  55045. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55046. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55047. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55048. DrawablePath dp;
  55049. dp.setPath (shape);
  55050. dp.setFill (Colours::black.withAlpha (0.3f));
  55051. b->setImages (&dp);
  55052. return b;
  55053. }
  55054. jassertfalse;
  55055. return 0;
  55056. }
  55057. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55058. int titleBarX,
  55059. int titleBarY,
  55060. int titleBarW,
  55061. int titleBarH,
  55062. Button* minimiseButton,
  55063. Button* maximiseButton,
  55064. Button* closeButton,
  55065. bool positionTitleBarButtonsOnLeft)
  55066. {
  55067. titleBarY += titleBarH / 8;
  55068. titleBarH -= titleBarH / 4;
  55069. const int buttonW = titleBarH;
  55070. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55071. : titleBarX + titleBarW - buttonW - 4;
  55072. if (closeButton != 0)
  55073. {
  55074. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55075. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55076. : -(buttonW + buttonW / 5);
  55077. }
  55078. if (positionTitleBarButtonsOnLeft)
  55079. swapVariables (minimiseButton, maximiseButton);
  55080. if (maximiseButton != 0)
  55081. {
  55082. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55083. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55084. }
  55085. if (minimiseButton != 0)
  55086. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55087. }
  55088. END_JUCE_NAMESPACE
  55089. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55090. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55091. BEGIN_JUCE_NAMESPACE
  55092. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55093. : model (0),
  55094. itemUnderMouse (-1),
  55095. currentPopupIndex (-1),
  55096. topLevelIndexClicked (0),
  55097. lastMouseX (0),
  55098. lastMouseY (0)
  55099. {
  55100. setRepaintsOnMouseActivity (true);
  55101. setWantsKeyboardFocus (false);
  55102. setMouseClickGrabsKeyboardFocus (false);
  55103. setModel (model_);
  55104. }
  55105. MenuBarComponent::~MenuBarComponent()
  55106. {
  55107. setModel (0);
  55108. Desktop::getInstance().removeGlobalMouseListener (this);
  55109. }
  55110. MenuBarModel* MenuBarComponent::getModel() const throw()
  55111. {
  55112. return model;
  55113. }
  55114. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55115. {
  55116. if (model != newModel)
  55117. {
  55118. if (model != 0)
  55119. model->removeListener (this);
  55120. model = newModel;
  55121. if (model != 0)
  55122. model->addListener (this);
  55123. repaint();
  55124. menuBarItemsChanged (0);
  55125. }
  55126. }
  55127. void MenuBarComponent::paint (Graphics& g)
  55128. {
  55129. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55130. getLookAndFeel().drawMenuBarBackground (g,
  55131. getWidth(),
  55132. getHeight(),
  55133. isMouseOverBar,
  55134. *this);
  55135. if (model != 0)
  55136. {
  55137. for (int i = 0; i < menuNames.size(); ++i)
  55138. {
  55139. Graphics::ScopedSaveState ss (g);
  55140. g.setOrigin (xPositions [i], 0);
  55141. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55142. getLookAndFeel().drawMenuBarItem (g,
  55143. xPositions[i + 1] - xPositions[i],
  55144. getHeight(),
  55145. i,
  55146. menuNames[i],
  55147. i == itemUnderMouse,
  55148. i == currentPopupIndex,
  55149. isMouseOverBar,
  55150. *this);
  55151. }
  55152. }
  55153. }
  55154. void MenuBarComponent::resized()
  55155. {
  55156. xPositions.clear();
  55157. int x = 0;
  55158. xPositions.add (x);
  55159. for (int i = 0; i < menuNames.size(); ++i)
  55160. {
  55161. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55162. xPositions.add (x);
  55163. }
  55164. }
  55165. int MenuBarComponent::getItemAt (const int x, const int y)
  55166. {
  55167. for (int i = 0; i < xPositions.size(); ++i)
  55168. if (x >= xPositions[i] && x < xPositions[i + 1])
  55169. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55170. return -1;
  55171. }
  55172. void MenuBarComponent::repaintMenuItem (int index)
  55173. {
  55174. if (isPositiveAndBelow (index, xPositions.size()))
  55175. {
  55176. const int x1 = xPositions [index];
  55177. const int x2 = xPositions [index + 1];
  55178. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55179. }
  55180. }
  55181. void MenuBarComponent::setItemUnderMouse (const int index)
  55182. {
  55183. if (itemUnderMouse != index)
  55184. {
  55185. repaintMenuItem (itemUnderMouse);
  55186. itemUnderMouse = index;
  55187. repaintMenuItem (itemUnderMouse);
  55188. }
  55189. }
  55190. void MenuBarComponent::setOpenItem (int index)
  55191. {
  55192. if (currentPopupIndex != index)
  55193. {
  55194. repaintMenuItem (currentPopupIndex);
  55195. currentPopupIndex = index;
  55196. repaintMenuItem (currentPopupIndex);
  55197. if (index >= 0)
  55198. Desktop::getInstance().addGlobalMouseListener (this);
  55199. else
  55200. Desktop::getInstance().removeGlobalMouseListener (this);
  55201. }
  55202. }
  55203. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55204. {
  55205. setItemUnderMouse (getItemAt (x, y));
  55206. }
  55207. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55208. {
  55209. public:
  55210. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55211. : bar (bar_), topLevelIndex (topLevelIndex_)
  55212. {
  55213. }
  55214. void modalStateFinished (int returnValue)
  55215. {
  55216. if (bar != 0)
  55217. bar->menuDismissed (topLevelIndex, returnValue);
  55218. }
  55219. private:
  55220. Component::SafePointer<MenuBarComponent> bar;
  55221. const int topLevelIndex;
  55222. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55223. };
  55224. void MenuBarComponent::showMenu (int index)
  55225. {
  55226. if (index != currentPopupIndex)
  55227. {
  55228. PopupMenu::dismissAllActiveMenus();
  55229. menuBarItemsChanged (0);
  55230. setOpenItem (index);
  55231. setItemUnderMouse (index);
  55232. if (index >= 0)
  55233. {
  55234. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55235. menuNames [itemUnderMouse]));
  55236. if (m.lookAndFeel == 0)
  55237. m.setLookAndFeel (&getLookAndFeel());
  55238. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55239. m.showMenu (localAreaToGlobal (itemPos),
  55240. 0, itemPos.getWidth(), 0, 0, this,
  55241. new AsyncCallback (this, index));
  55242. }
  55243. }
  55244. }
  55245. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55246. {
  55247. topLevelIndexClicked = topLevelIndex;
  55248. postCommandMessage (itemId);
  55249. }
  55250. void MenuBarComponent::handleCommandMessage (int commandId)
  55251. {
  55252. const Point<int> mousePos (getMouseXYRelative());
  55253. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55254. if (currentPopupIndex == topLevelIndexClicked)
  55255. setOpenItem (-1);
  55256. if (commandId != 0 && model != 0)
  55257. model->menuItemSelected (commandId, topLevelIndexClicked);
  55258. }
  55259. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55260. {
  55261. if (e.eventComponent == this)
  55262. updateItemUnderMouse (e.x, e.y);
  55263. }
  55264. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55265. {
  55266. if (e.eventComponent == this)
  55267. updateItemUnderMouse (e.x, e.y);
  55268. }
  55269. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55270. {
  55271. if (currentPopupIndex < 0)
  55272. {
  55273. const MouseEvent e2 (e.getEventRelativeTo (this));
  55274. updateItemUnderMouse (e2.x, e2.y);
  55275. currentPopupIndex = -2;
  55276. showMenu (itemUnderMouse);
  55277. }
  55278. }
  55279. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55280. {
  55281. const MouseEvent e2 (e.getEventRelativeTo (this));
  55282. const int item = getItemAt (e2.x, e2.y);
  55283. if (item >= 0)
  55284. showMenu (item);
  55285. }
  55286. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55287. {
  55288. const MouseEvent e2 (e.getEventRelativeTo (this));
  55289. updateItemUnderMouse (e2.x, e2.y);
  55290. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55291. {
  55292. setOpenItem (-1);
  55293. PopupMenu::dismissAllActiveMenus();
  55294. }
  55295. }
  55296. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55297. {
  55298. const MouseEvent e2 (e.getEventRelativeTo (this));
  55299. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55300. {
  55301. if (currentPopupIndex >= 0)
  55302. {
  55303. const int item = getItemAt (e2.x, e2.y);
  55304. if (item >= 0)
  55305. showMenu (item);
  55306. }
  55307. else
  55308. {
  55309. updateItemUnderMouse (e2.x, e2.y);
  55310. }
  55311. lastMouseX = e2.x;
  55312. lastMouseY = e2.y;
  55313. }
  55314. }
  55315. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55316. {
  55317. bool used = false;
  55318. const int numMenus = menuNames.size();
  55319. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55320. if (key.isKeyCode (KeyPress::leftKey))
  55321. {
  55322. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55323. used = true;
  55324. }
  55325. else if (key.isKeyCode (KeyPress::rightKey))
  55326. {
  55327. showMenu ((currentIndex + 1) % numMenus);
  55328. used = true;
  55329. }
  55330. return used;
  55331. }
  55332. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55333. {
  55334. StringArray newNames;
  55335. if (model != 0)
  55336. newNames = model->getMenuBarNames();
  55337. if (newNames != menuNames)
  55338. {
  55339. menuNames = newNames;
  55340. repaint();
  55341. resized();
  55342. }
  55343. }
  55344. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55345. const ApplicationCommandTarget::InvocationInfo& info)
  55346. {
  55347. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55348. return;
  55349. for (int i = 0; i < menuNames.size(); ++i)
  55350. {
  55351. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55352. if (menu.containsCommandItem (info.commandID))
  55353. {
  55354. setItemUnderMouse (i);
  55355. startTimer (200);
  55356. break;
  55357. }
  55358. }
  55359. }
  55360. void MenuBarComponent::timerCallback()
  55361. {
  55362. stopTimer();
  55363. const Point<int> mousePos (getMouseXYRelative());
  55364. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55365. }
  55366. END_JUCE_NAMESPACE
  55367. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55368. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55369. BEGIN_JUCE_NAMESPACE
  55370. MenuBarModel::MenuBarModel() throw()
  55371. : manager (0)
  55372. {
  55373. }
  55374. MenuBarModel::~MenuBarModel()
  55375. {
  55376. setApplicationCommandManagerToWatch (0);
  55377. }
  55378. void MenuBarModel::menuItemsChanged()
  55379. {
  55380. triggerAsyncUpdate();
  55381. }
  55382. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55383. {
  55384. if (manager != newManager)
  55385. {
  55386. if (manager != 0)
  55387. manager->removeListener (this);
  55388. manager = newManager;
  55389. if (manager != 0)
  55390. manager->addListener (this);
  55391. }
  55392. }
  55393. void MenuBarModel::addListener (Listener* const newListener) throw()
  55394. {
  55395. listeners.add (newListener);
  55396. }
  55397. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55398. {
  55399. // Trying to remove a listener that isn't on the list!
  55400. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55401. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55402. jassert (listeners.contains (listenerToRemove));
  55403. listeners.remove (listenerToRemove);
  55404. }
  55405. void MenuBarModel::handleAsyncUpdate()
  55406. {
  55407. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55408. }
  55409. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55410. {
  55411. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55412. }
  55413. void MenuBarModel::applicationCommandListChanged()
  55414. {
  55415. menuItemsChanged();
  55416. }
  55417. END_JUCE_NAMESPACE
  55418. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55419. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55420. BEGIN_JUCE_NAMESPACE
  55421. class PopupMenu::Item
  55422. {
  55423. public:
  55424. Item()
  55425. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55426. usesColour (false), customComp (0), commandManager (0)
  55427. {
  55428. }
  55429. Item (const int itemId_,
  55430. const String& text_,
  55431. const bool active_,
  55432. const bool isTicked_,
  55433. const Image& im,
  55434. const Colour& textColour_,
  55435. const bool usesColour_,
  55436. PopupMenuCustomComponent* const customComp_,
  55437. const PopupMenu* const subMenu_,
  55438. ApplicationCommandManager* const commandManager_)
  55439. : itemId (itemId_), text (text_), textColour (textColour_),
  55440. active (active_), isSeparator (false), isTicked (isTicked_),
  55441. usesColour (usesColour_), image (im), customComp (customComp_),
  55442. commandManager (commandManager_)
  55443. {
  55444. if (subMenu_ != 0)
  55445. subMenu = new PopupMenu (*subMenu_);
  55446. if (commandManager_ != 0 && itemId_ != 0)
  55447. {
  55448. String shortcutKey;
  55449. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55450. ->getKeyPressesAssignedToCommand (itemId_));
  55451. for (int i = 0; i < keyPresses.size(); ++i)
  55452. {
  55453. const String key (keyPresses.getReference(i).getTextDescription());
  55454. if (shortcutKey.isNotEmpty())
  55455. shortcutKey << ", ";
  55456. if (key.length() == 1)
  55457. shortcutKey << "shortcut: '" << key << '\'';
  55458. else
  55459. shortcutKey << key;
  55460. }
  55461. shortcutKey = shortcutKey.trim();
  55462. if (shortcutKey.isNotEmpty())
  55463. text << "<end>" << shortcutKey;
  55464. }
  55465. }
  55466. Item (const Item& other)
  55467. : itemId (other.itemId),
  55468. text (other.text),
  55469. textColour (other.textColour),
  55470. active (other.active),
  55471. isSeparator (other.isSeparator),
  55472. isTicked (other.isTicked),
  55473. usesColour (other.usesColour),
  55474. image (other.image),
  55475. customComp (other.customComp),
  55476. commandManager (other.commandManager)
  55477. {
  55478. if (other.subMenu != 0)
  55479. subMenu = new PopupMenu (*(other.subMenu));
  55480. }
  55481. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55482. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55483. const int itemId;
  55484. String text;
  55485. const Colour textColour;
  55486. const bool active, isSeparator, isTicked, usesColour;
  55487. Image image;
  55488. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55489. ScopedPointer <PopupMenu> subMenu;
  55490. ApplicationCommandManager* const commandManager;
  55491. private:
  55492. Item& operator= (const Item&);
  55493. JUCE_LEAK_DETECTOR (Item);
  55494. };
  55495. class PopupMenu::ItemComponent : public Component
  55496. {
  55497. public:
  55498. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight)
  55499. : itemInfo (itemInfo_),
  55500. isHighlighted (false)
  55501. {
  55502. if (itemInfo.customComp != 0)
  55503. addAndMakeVisible (itemInfo.customComp);
  55504. int itemW = 80;
  55505. int itemH = 16;
  55506. getIdealSize (itemW, itemH, standardItemHeight);
  55507. setSize (itemW, jlimit (2, 600, itemH));
  55508. }
  55509. ~ItemComponent()
  55510. {
  55511. if (itemInfo.customComp != 0)
  55512. removeChildComponent (itemInfo.customComp);
  55513. }
  55514. void getIdealSize (int& idealWidth,
  55515. int& idealHeight,
  55516. const int standardItemHeight)
  55517. {
  55518. if (itemInfo.customComp != 0)
  55519. {
  55520. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55521. }
  55522. else
  55523. {
  55524. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55525. itemInfo.isSeparator,
  55526. standardItemHeight,
  55527. idealWidth,
  55528. idealHeight);
  55529. }
  55530. }
  55531. void paint (Graphics& g)
  55532. {
  55533. if (itemInfo.customComp == 0)
  55534. {
  55535. String mainText (itemInfo.text);
  55536. String endText;
  55537. const int endIndex = mainText.indexOf ("<end>");
  55538. if (endIndex >= 0)
  55539. {
  55540. endText = mainText.substring (endIndex + 5).trim();
  55541. mainText = mainText.substring (0, endIndex);
  55542. }
  55543. getLookAndFeel()
  55544. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55545. itemInfo.isSeparator,
  55546. itemInfo.active,
  55547. isHighlighted,
  55548. itemInfo.isTicked,
  55549. itemInfo.subMenu != 0,
  55550. mainText, endText,
  55551. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55552. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55553. }
  55554. }
  55555. void resized()
  55556. {
  55557. if (getNumChildComponents() > 0)
  55558. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55559. }
  55560. void setHighlighted (bool shouldBeHighlighted)
  55561. {
  55562. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55563. if (isHighlighted != shouldBeHighlighted)
  55564. {
  55565. isHighlighted = shouldBeHighlighted;
  55566. if (itemInfo.customComp != 0)
  55567. {
  55568. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55569. itemInfo.customComp->repaint();
  55570. }
  55571. repaint();
  55572. }
  55573. }
  55574. PopupMenu::Item itemInfo;
  55575. private:
  55576. bool isHighlighted;
  55577. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55578. };
  55579. namespace PopupMenuSettings
  55580. {
  55581. const int scrollZone = 24;
  55582. const int borderSize = 2;
  55583. const int timerInterval = 50;
  55584. const int dismissCommandId = 0x6287345f;
  55585. }
  55586. class PopupMenu::Window : public Component,
  55587. private Timer
  55588. {
  55589. public:
  55590. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55591. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55592. const int minimumWidth_, const int maximumNumColumns_,
  55593. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55594. ApplicationCommandManager** const managerOfChosenCommand_,
  55595. Component* const componentAttachedTo_)
  55596. : Component ("menu"),
  55597. owner (owner_),
  55598. activeSubMenu (0),
  55599. managerOfChosenCommand (managerOfChosenCommand_),
  55600. componentAttachedTo (componentAttachedTo_),
  55601. componentAttachedToOriginal (componentAttachedTo_),
  55602. minimumWidth (minimumWidth_),
  55603. maximumNumColumns (maximumNumColumns_),
  55604. standardItemHeight (standardItemHeight_),
  55605. isOver (false),
  55606. hasBeenOver (false),
  55607. isDown (false),
  55608. needsToScroll (false),
  55609. dismissOnMouseUp (dismissOnMouseUp_),
  55610. hideOnExit (false),
  55611. disableMouseMoves (false),
  55612. hasAnyJuceCompHadFocus (false),
  55613. numColumns (0),
  55614. contentHeight (0),
  55615. childYOffset (0),
  55616. menuCreationTime (Time::getMillisecondCounter()),
  55617. lastMouseMoveTime (0),
  55618. timeEnteredCurrentChildComp (0),
  55619. scrollAcceleration (1.0)
  55620. {
  55621. lastFocused = lastScroll = menuCreationTime;
  55622. setWantsKeyboardFocus (false);
  55623. setMouseClickGrabsKeyboardFocus (false);
  55624. setAlwaysOnTop (true);
  55625. setLookAndFeel (menu.lookAndFeel);
  55626. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55627. for (int i = 0; i < menu.items.size(); ++i)
  55628. {
  55629. PopupMenu::ItemComponent* const itemComp = new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight);
  55630. items.add (itemComp);
  55631. addAndMakeVisible (itemComp);
  55632. itemComp->addMouseListener (this, false);
  55633. }
  55634. calculateWindowPos (target, alignToRectangle);
  55635. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55636. updateYPositions();
  55637. if (itemIdThatMustBeVisible != 0)
  55638. {
  55639. const int y = target.getY() - windowPos.getY();
  55640. ensureItemIsVisible (itemIdThatMustBeVisible,
  55641. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55642. }
  55643. resizeToBestWindowPos();
  55644. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55645. getActiveWindows().add (this);
  55646. Desktop::getInstance().addGlobalMouseListener (this);
  55647. }
  55648. ~Window()
  55649. {
  55650. getActiveWindows().removeValue (this);
  55651. Desktop::getInstance().removeGlobalMouseListener (this);
  55652. activeSubMenu = 0;
  55653. items.clear();
  55654. }
  55655. static Window* create (const PopupMenu& menu,
  55656. bool dismissOnMouseUp,
  55657. Window* const owner_,
  55658. const Rectangle<int>& target,
  55659. int minimumWidth,
  55660. int maximumNumColumns,
  55661. int standardItemHeight,
  55662. bool alignToRectangle,
  55663. int itemIdThatMustBeVisible,
  55664. ApplicationCommandManager** managerOfChosenCommand,
  55665. Component* componentAttachedTo)
  55666. {
  55667. if (menu.items.size() > 0)
  55668. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55669. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55670. managerOfChosenCommand, componentAttachedTo);
  55671. return 0;
  55672. }
  55673. void paint (Graphics& g)
  55674. {
  55675. if (isOpaque())
  55676. g.fillAll (Colours::white);
  55677. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55678. }
  55679. void paintOverChildren (Graphics& g)
  55680. {
  55681. if (isScrolling())
  55682. {
  55683. LookAndFeel& lf = getLookAndFeel();
  55684. if (isScrollZoneActive (false))
  55685. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55686. if (isScrollZoneActive (true))
  55687. {
  55688. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55689. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55690. }
  55691. }
  55692. }
  55693. bool isScrollZoneActive (bool bottomOne) const
  55694. {
  55695. return isScrolling()
  55696. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55697. : childYOffset > 0);
  55698. }
  55699. // hide this and all sub-comps
  55700. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55701. {
  55702. if (isVisible())
  55703. {
  55704. activeSubMenu = 0;
  55705. currentChild = 0;
  55706. exitModalState (item != 0 ? item->itemId : 0);
  55707. if (makeInvisible)
  55708. setVisible (false);
  55709. if (item != 0
  55710. && item->commandManager != 0
  55711. && item->itemId != 0)
  55712. {
  55713. *managerOfChosenCommand = item->commandManager;
  55714. }
  55715. }
  55716. }
  55717. void dismissMenu (const PopupMenu::Item* const item)
  55718. {
  55719. if (owner != 0)
  55720. {
  55721. owner->dismissMenu (item);
  55722. }
  55723. else
  55724. {
  55725. if (item != 0)
  55726. {
  55727. // need a copy of this on the stack as the one passed in will get deleted during this call
  55728. const PopupMenu::Item mi (*item);
  55729. hide (&mi, false);
  55730. }
  55731. else
  55732. {
  55733. hide (0, false);
  55734. }
  55735. }
  55736. }
  55737. void mouseMove (const MouseEvent&) { timerCallback(); }
  55738. void mouseDown (const MouseEvent&) { timerCallback(); }
  55739. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55740. void mouseUp (const MouseEvent&) { timerCallback(); }
  55741. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55742. {
  55743. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55744. lastMouse = Point<int> (-1, -1);
  55745. }
  55746. bool keyPressed (const KeyPress& key)
  55747. {
  55748. if (key.isKeyCode (KeyPress::downKey))
  55749. {
  55750. selectNextItem (1);
  55751. }
  55752. else if (key.isKeyCode (KeyPress::upKey))
  55753. {
  55754. selectNextItem (-1);
  55755. }
  55756. else if (key.isKeyCode (KeyPress::leftKey))
  55757. {
  55758. if (owner != 0)
  55759. {
  55760. Component::SafePointer<Window> parentWindow (owner);
  55761. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55762. hide (0, true);
  55763. if (parentWindow != 0)
  55764. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55765. disableTimerUntilMouseMoves();
  55766. }
  55767. else if (componentAttachedTo != 0)
  55768. {
  55769. componentAttachedTo->keyPressed (key);
  55770. }
  55771. }
  55772. else if (key.isKeyCode (KeyPress::rightKey))
  55773. {
  55774. disableTimerUntilMouseMoves();
  55775. if (showSubMenuFor (currentChild))
  55776. {
  55777. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55778. activeSubMenu->selectNextItem (1);
  55779. }
  55780. else if (componentAttachedTo != 0)
  55781. {
  55782. componentAttachedTo->keyPressed (key);
  55783. }
  55784. }
  55785. else if (key.isKeyCode (KeyPress::returnKey))
  55786. {
  55787. triggerCurrentlyHighlightedItem();
  55788. }
  55789. else if (key.isKeyCode (KeyPress::escapeKey))
  55790. {
  55791. dismissMenu (0);
  55792. }
  55793. else
  55794. {
  55795. return false;
  55796. }
  55797. return true;
  55798. }
  55799. void inputAttemptWhenModal()
  55800. {
  55801. WeakReference<Component> deletionChecker (this);
  55802. timerCallback();
  55803. if (deletionChecker != 0 && ! isOverAnyMenu())
  55804. {
  55805. if (componentAttachedTo != 0)
  55806. {
  55807. // we want to dismiss the menu, but if we do it synchronously, then
  55808. // the mouse-click will be allowed to pass through. That's good, except
  55809. // when the user clicks on the button that orginally popped the menu up,
  55810. // as they'll expect the menu to go away, and in fact it'll just
  55811. // come back. So only dismiss synchronously if they're not on the original
  55812. // comp that we're attached to.
  55813. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55814. if (componentAttachedTo->reallyContains (mousePos, true))
  55815. {
  55816. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55817. return;
  55818. }
  55819. }
  55820. dismissMenu (0);
  55821. }
  55822. }
  55823. void handleCommandMessage (int commandId)
  55824. {
  55825. Component::handleCommandMessage (commandId);
  55826. if (commandId == PopupMenuSettings::dismissCommandId)
  55827. dismissMenu (0);
  55828. }
  55829. void timerCallback()
  55830. {
  55831. if (! isVisible())
  55832. return;
  55833. if (componentAttachedTo != componentAttachedToOriginal)
  55834. {
  55835. dismissMenu (0);
  55836. return;
  55837. }
  55838. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55839. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55840. return;
  55841. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55842. // move rather than a real timer callback
  55843. const Point<int> globalMousePos (Desktop::getMousePosition());
  55844. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55845. const uint32 now = Time::getMillisecondCounter();
  55846. if (now > timeEnteredCurrentChildComp + 100
  55847. && reallyContains (localMousePos, true)
  55848. && currentChild != 0
  55849. && (! disableMouseMoves)
  55850. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55851. {
  55852. showSubMenuFor (currentChild);
  55853. }
  55854. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55855. {
  55856. highlightItemUnderMouse (globalMousePos, localMousePos);
  55857. }
  55858. bool overScrollArea = false;
  55859. if (isScrolling()
  55860. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  55861. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55862. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55863. {
  55864. if (now > lastScroll + 20)
  55865. {
  55866. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55867. int amount = 0;
  55868. for (int i = 0; i < items.size() && amount == 0; ++i)
  55869. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55870. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55871. lastScroll = now;
  55872. }
  55873. overScrollArea = true;
  55874. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55875. }
  55876. else
  55877. {
  55878. scrollAcceleration = 1.0;
  55879. }
  55880. const bool wasDown = isDown;
  55881. bool isOverAny = isOverAnyMenu();
  55882. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55883. {
  55884. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55885. isOverAny = isOverAnyMenu();
  55886. }
  55887. if (hideOnExit && hasBeenOver && ! isOverAny)
  55888. {
  55889. hide (0, true);
  55890. }
  55891. else
  55892. {
  55893. isDown = hasBeenOver
  55894. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55895. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55896. bool anyFocused = Process::isForegroundProcess();
  55897. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55898. {
  55899. // because no component at all may have focus, our test here will
  55900. // only be triggered when something has focus and then loses it.
  55901. anyFocused = ! hasAnyJuceCompHadFocus;
  55902. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55903. {
  55904. if (ComponentPeer::getPeer (i)->isFocused())
  55905. {
  55906. anyFocused = true;
  55907. hasAnyJuceCompHadFocus = true;
  55908. break;
  55909. }
  55910. }
  55911. }
  55912. if (! anyFocused)
  55913. {
  55914. if (now > lastFocused + 10)
  55915. {
  55916. wasHiddenBecauseOfAppChange() = true;
  55917. dismissMenu (0);
  55918. return; // may have been deleted by the previous call..
  55919. }
  55920. }
  55921. else if (wasDown && now > menuCreationTime + 250
  55922. && ! (isDown || overScrollArea))
  55923. {
  55924. isOver = reallyContains (localMousePos, true);
  55925. if (isOver)
  55926. {
  55927. triggerCurrentlyHighlightedItem();
  55928. }
  55929. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55930. {
  55931. dismissMenu (0);
  55932. }
  55933. return; // may have been deleted by the previous calls..
  55934. }
  55935. else
  55936. {
  55937. lastFocused = now;
  55938. }
  55939. }
  55940. }
  55941. static Array<Window*>& getActiveWindows()
  55942. {
  55943. static Array<Window*> activeMenuWindows;
  55944. return activeMenuWindows;
  55945. }
  55946. static bool& wasHiddenBecauseOfAppChange() throw()
  55947. {
  55948. static bool b = false;
  55949. return b;
  55950. }
  55951. private:
  55952. Window* owner;
  55953. OwnedArray <PopupMenu::ItemComponent> items;
  55954. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55955. ScopedPointer <Window> activeSubMenu;
  55956. ApplicationCommandManager** managerOfChosenCommand;
  55957. WeakReference<Component> componentAttachedTo;
  55958. Component* componentAttachedToOriginal;
  55959. Rectangle<int> windowPos;
  55960. Point<int> lastMouse;
  55961. int minimumWidth, maximumNumColumns, standardItemHeight;
  55962. bool isOver, hasBeenOver, isDown, needsToScroll;
  55963. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55964. int numColumns, contentHeight, childYOffset;
  55965. Array <int> columnWidths;
  55966. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55967. double scrollAcceleration;
  55968. bool overlaps (const Rectangle<int>& r) const
  55969. {
  55970. return r.intersects (getBounds())
  55971. || (owner != 0 && owner->overlaps (r));
  55972. }
  55973. bool isOverAnyMenu() const
  55974. {
  55975. return (owner != 0) ? owner->isOverAnyMenu()
  55976. : isOverChildren();
  55977. }
  55978. bool isOverChildren() const
  55979. {
  55980. return isVisible()
  55981. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55982. }
  55983. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55984. {
  55985. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  55986. isOver = reallyContains (relPos, true);
  55987. if (activeSubMenu != 0)
  55988. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55989. }
  55990. bool treeContains (const Window* const window) const throw()
  55991. {
  55992. const Window* mw = this;
  55993. while (mw->owner != 0)
  55994. mw = mw->owner;
  55995. while (mw != 0)
  55996. {
  55997. if (mw == window)
  55998. return true;
  55999. mw = mw->activeSubMenu;
  56000. }
  56001. return false;
  56002. }
  56003. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56004. {
  56005. const Rectangle<int> mon (Desktop::getInstance()
  56006. .getMonitorAreaContaining (target.getCentre(),
  56007. #if JUCE_MAC
  56008. true));
  56009. #else
  56010. false)); // on windows, don't stop the menu overlapping the taskbar
  56011. #endif
  56012. int x, y, widthToUse, heightToUse;
  56013. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56014. if (alignToRectangle)
  56015. {
  56016. x = target.getX();
  56017. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56018. const int spaceOver = target.getY() - mon.getY();
  56019. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56020. y = target.getBottom();
  56021. else
  56022. y = target.getY() - heightToUse;
  56023. }
  56024. else
  56025. {
  56026. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56027. if (owner != 0)
  56028. {
  56029. if (owner->owner != 0)
  56030. {
  56031. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56032. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56033. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56034. tendTowardsRight = true;
  56035. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56036. tendTowardsRight = false;
  56037. }
  56038. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56039. {
  56040. tendTowardsRight = true;
  56041. }
  56042. }
  56043. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56044. target.getX() - mon.getX()) - 32;
  56045. if (biggestSpace < widthToUse)
  56046. {
  56047. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56048. if (numColumns > 1)
  56049. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56050. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56051. }
  56052. if (tendTowardsRight)
  56053. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56054. else
  56055. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56056. y = target.getY();
  56057. if (target.getCentreY() > mon.getCentreY())
  56058. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56059. }
  56060. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56061. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56062. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56063. // sets this flag if it's big enough to obscure any of its parent menus
  56064. hideOnExit = (owner != 0)
  56065. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56066. }
  56067. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56068. {
  56069. numColumns = 0;
  56070. contentHeight = 0;
  56071. const int maxMenuH = getParentHeight() - 24;
  56072. int totalW;
  56073. do
  56074. {
  56075. ++numColumns;
  56076. totalW = workOutBestSize (maxMenuW);
  56077. if (totalW > maxMenuW)
  56078. {
  56079. numColumns = jmax (1, numColumns - 1);
  56080. totalW = workOutBestSize (maxMenuW); // to update col widths
  56081. break;
  56082. }
  56083. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56084. {
  56085. break;
  56086. }
  56087. } while (numColumns < maximumNumColumns);
  56088. const int actualH = jmin (contentHeight, maxMenuH);
  56089. needsToScroll = contentHeight > actualH;
  56090. width = updateYPositions();
  56091. height = actualH + PopupMenuSettings::borderSize * 2;
  56092. }
  56093. int workOutBestSize (const int maxMenuW)
  56094. {
  56095. int totalW = 0;
  56096. contentHeight = 0;
  56097. int childNum = 0;
  56098. for (int col = 0; col < numColumns; ++col)
  56099. {
  56100. int i, colW = 50, colH = 0;
  56101. const int numChildren = jmin (items.size() - childNum,
  56102. (items.size() + numColumns - 1) / numColumns);
  56103. for (i = numChildren; --i >= 0;)
  56104. {
  56105. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56106. colH += items.getUnchecked (childNum + i)->getHeight();
  56107. }
  56108. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56109. columnWidths.set (col, colW);
  56110. totalW += colW;
  56111. contentHeight = jmax (contentHeight, colH);
  56112. childNum += numChildren;
  56113. }
  56114. if (totalW < minimumWidth)
  56115. {
  56116. totalW = minimumWidth;
  56117. for (int col = 0; col < numColumns; ++col)
  56118. columnWidths.set (0, totalW / numColumns);
  56119. }
  56120. return totalW;
  56121. }
  56122. void ensureItemIsVisible (const int itemId, int wantedY)
  56123. {
  56124. jassert (itemId != 0)
  56125. for (int i = items.size(); --i >= 0;)
  56126. {
  56127. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56128. if (m != 0
  56129. && m->itemInfo.itemId == itemId
  56130. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56131. {
  56132. const int currentY = m->getY();
  56133. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56134. {
  56135. if (wantedY < 0)
  56136. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56137. jmax (PopupMenuSettings::scrollZone,
  56138. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56139. currentY);
  56140. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56141. int deltaY = wantedY - currentY;
  56142. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56143. jmin (windowPos.getHeight(), mon.getHeight()));
  56144. const int newY = jlimit (mon.getY(),
  56145. mon.getBottom() - windowPos.getHeight(),
  56146. windowPos.getY() + deltaY);
  56147. deltaY -= newY - windowPos.getY();
  56148. childYOffset -= deltaY;
  56149. windowPos.setPosition (windowPos.getX(), newY);
  56150. updateYPositions();
  56151. }
  56152. break;
  56153. }
  56154. }
  56155. }
  56156. void resizeToBestWindowPos()
  56157. {
  56158. Rectangle<int> r (windowPos);
  56159. if (childYOffset < 0)
  56160. {
  56161. r.setBounds (r.getX(), r.getY() - childYOffset,
  56162. r.getWidth(), r.getHeight() + childYOffset);
  56163. }
  56164. else if (childYOffset > 0)
  56165. {
  56166. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56167. if (spaceAtBottom > 0)
  56168. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56169. }
  56170. setBounds (r);
  56171. updateYPositions();
  56172. }
  56173. void alterChildYPos (const int delta)
  56174. {
  56175. if (isScrolling())
  56176. {
  56177. childYOffset += delta;
  56178. if (delta < 0)
  56179. {
  56180. childYOffset = jmax (childYOffset, 0);
  56181. }
  56182. else if (delta > 0)
  56183. {
  56184. childYOffset = jmin (childYOffset,
  56185. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56186. }
  56187. updateYPositions();
  56188. }
  56189. else
  56190. {
  56191. childYOffset = 0;
  56192. }
  56193. resizeToBestWindowPos();
  56194. repaint();
  56195. }
  56196. int updateYPositions()
  56197. {
  56198. int x = 0;
  56199. int childNum = 0;
  56200. for (int col = 0; col < numColumns; ++col)
  56201. {
  56202. const int numChildren = jmin (items.size() - childNum,
  56203. (items.size() + numColumns - 1) / numColumns);
  56204. const int colW = columnWidths [col];
  56205. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56206. for (int i = 0; i < numChildren; ++i)
  56207. {
  56208. Component* const c = items.getUnchecked (childNum + i);
  56209. c->setBounds (x, y, colW, c->getHeight());
  56210. y += c->getHeight();
  56211. }
  56212. x += colW;
  56213. childNum += numChildren;
  56214. }
  56215. return x;
  56216. }
  56217. bool isScrolling() const throw()
  56218. {
  56219. return childYOffset != 0 || needsToScroll;
  56220. }
  56221. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56222. {
  56223. if (currentChild != 0)
  56224. currentChild->setHighlighted (false);
  56225. currentChild = child;
  56226. if (currentChild != 0)
  56227. {
  56228. currentChild->setHighlighted (true);
  56229. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56230. }
  56231. }
  56232. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56233. {
  56234. activeSubMenu = 0;
  56235. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56236. {
  56237. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56238. dismissOnMouseUp,
  56239. this,
  56240. childComp->getScreenBounds(),
  56241. 0, maximumNumColumns,
  56242. standardItemHeight,
  56243. false, 0, managerOfChosenCommand,
  56244. componentAttachedTo);
  56245. if (activeSubMenu != 0)
  56246. {
  56247. activeSubMenu->setVisible (true);
  56248. activeSubMenu->enterModalState (false);
  56249. activeSubMenu->toFront (false);
  56250. return true;
  56251. }
  56252. }
  56253. return false;
  56254. }
  56255. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56256. {
  56257. isOver = reallyContains (localMousePos, true);
  56258. if (isOver)
  56259. hasBeenOver = true;
  56260. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56261. {
  56262. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56263. if (disableMouseMoves && isOver)
  56264. disableMouseMoves = false;
  56265. }
  56266. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56267. return;
  56268. bool isMovingTowardsMenu = false;
  56269. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56270. {
  56271. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56272. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56273. // extends from the last mouse pos to the submenu's rectangle..
  56274. float subX = (float) activeSubMenu->getScreenX();
  56275. if (activeSubMenu->getX() > getX())
  56276. {
  56277. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56278. }
  56279. else
  56280. {
  56281. lastMouse += Point<int> (2, 0);
  56282. subX += activeSubMenu->getWidth();
  56283. }
  56284. Path areaTowardsSubMenu;
  56285. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56286. subX, (float) activeSubMenu->getScreenY(),
  56287. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56288. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56289. }
  56290. lastMouse = globalMousePos;
  56291. if (! isMovingTowardsMenu)
  56292. {
  56293. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56294. if (c == this)
  56295. c = 0;
  56296. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56297. if (mic == 0 && c != 0)
  56298. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56299. if (mic != currentChild
  56300. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56301. {
  56302. if (isOver && (c != 0) && (activeSubMenu != 0))
  56303. {
  56304. activeSubMenu->hide (0, true);
  56305. }
  56306. if (! isOver)
  56307. mic = 0;
  56308. setCurrentlyHighlightedChild (mic);
  56309. }
  56310. }
  56311. }
  56312. void triggerCurrentlyHighlightedItem()
  56313. {
  56314. if (currentChild != 0
  56315. && currentChild->itemInfo.canBeTriggered()
  56316. && (currentChild->itemInfo.customComp == 0
  56317. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56318. {
  56319. dismissMenu (&currentChild->itemInfo);
  56320. }
  56321. }
  56322. void selectNextItem (const int delta)
  56323. {
  56324. disableTimerUntilMouseMoves();
  56325. PopupMenu::ItemComponent* mic = 0;
  56326. bool wasLastOne = (currentChild == 0);
  56327. const int numItems = items.size();
  56328. for (int i = 0; i < numItems + 1; ++i)
  56329. {
  56330. int index = (delta > 0) ? i : (numItems - 1 - i);
  56331. index = (index + numItems) % numItems;
  56332. mic = items.getUnchecked (index);
  56333. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56334. && wasLastOne)
  56335. break;
  56336. if (mic == currentChild)
  56337. wasLastOne = true;
  56338. }
  56339. setCurrentlyHighlightedChild (mic);
  56340. }
  56341. void disableTimerUntilMouseMoves()
  56342. {
  56343. disableMouseMoves = true;
  56344. if (owner != 0)
  56345. owner->disableTimerUntilMouseMoves();
  56346. }
  56347. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56348. };
  56349. PopupMenu::PopupMenu()
  56350. : lookAndFeel (0),
  56351. separatorPending (false)
  56352. {
  56353. }
  56354. PopupMenu::PopupMenu (const PopupMenu& other)
  56355. : lookAndFeel (other.lookAndFeel),
  56356. separatorPending (false)
  56357. {
  56358. items.addCopiesOf (other.items);
  56359. }
  56360. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56361. {
  56362. if (this != &other)
  56363. {
  56364. lookAndFeel = other.lookAndFeel;
  56365. clear();
  56366. items.addCopiesOf (other.items);
  56367. }
  56368. return *this;
  56369. }
  56370. PopupMenu::~PopupMenu()
  56371. {
  56372. clear();
  56373. }
  56374. void PopupMenu::clear()
  56375. {
  56376. items.clear();
  56377. separatorPending = false;
  56378. }
  56379. void PopupMenu::addSeparatorIfPending()
  56380. {
  56381. if (separatorPending)
  56382. {
  56383. separatorPending = false;
  56384. if (items.size() > 0)
  56385. items.add (new Item());
  56386. }
  56387. }
  56388. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56389. const bool isActive, const bool isTicked, const Image& iconToUse)
  56390. {
  56391. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56392. // didn't pick anything, so you shouldn't use it as the id
  56393. // for an item..
  56394. addSeparatorIfPending();
  56395. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56396. Colours::black, false, 0, 0, 0));
  56397. }
  56398. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56399. const int commandID,
  56400. const String& displayName)
  56401. {
  56402. jassert (commandManager != 0 && commandID != 0);
  56403. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56404. if (registeredInfo != 0)
  56405. {
  56406. ApplicationCommandInfo info (*registeredInfo);
  56407. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56408. addSeparatorIfPending();
  56409. items.add (new Item (commandID,
  56410. displayName.isNotEmpty() ? displayName
  56411. : info.shortName,
  56412. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56413. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56414. Image::null,
  56415. Colours::black,
  56416. false,
  56417. 0, 0,
  56418. commandManager));
  56419. }
  56420. }
  56421. void PopupMenu::addColouredItem (const int itemResultId,
  56422. const String& itemText,
  56423. const Colour& itemTextColour,
  56424. const bool isActive,
  56425. const bool isTicked,
  56426. const Image& iconToUse)
  56427. {
  56428. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56429. // didn't pick anything, so you shouldn't use it as the id
  56430. // for an item..
  56431. addSeparatorIfPending();
  56432. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56433. itemTextColour, true, 0, 0, 0));
  56434. }
  56435. void PopupMenu::addCustomItem (const int itemResultId,
  56436. PopupMenuCustomComponent* const customComponent)
  56437. {
  56438. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56439. // didn't pick anything, so you shouldn't use it as the id
  56440. // for an item..
  56441. addSeparatorIfPending();
  56442. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56443. Colours::black, false, customComponent, 0, 0));
  56444. }
  56445. class NormalComponentWrapper : public PopupMenuCustomComponent
  56446. {
  56447. public:
  56448. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56449. const bool triggerMenuItemAutomaticallyWhenClicked)
  56450. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56451. width (w), height (h)
  56452. {
  56453. addAndMakeVisible (comp);
  56454. }
  56455. ~NormalComponentWrapper() {}
  56456. void getIdealSize (int& idealWidth, int& idealHeight)
  56457. {
  56458. idealWidth = width;
  56459. idealHeight = height;
  56460. }
  56461. void resized()
  56462. {
  56463. if (getChildComponent(0) != 0)
  56464. getChildComponent(0)->setBounds (getLocalBounds());
  56465. }
  56466. private:
  56467. const int width, height;
  56468. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56469. };
  56470. void PopupMenu::addCustomItem (const int itemResultId,
  56471. Component* customComponent,
  56472. int idealWidth, int idealHeight,
  56473. const bool triggerMenuItemAutomaticallyWhenClicked)
  56474. {
  56475. addCustomItem (itemResultId,
  56476. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56477. triggerMenuItemAutomaticallyWhenClicked));
  56478. }
  56479. void PopupMenu::addSubMenu (const String& subMenuName,
  56480. const PopupMenu& subMenu,
  56481. const bool isActive,
  56482. const Image& iconToUse,
  56483. const bool isTicked)
  56484. {
  56485. addSeparatorIfPending();
  56486. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56487. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56488. }
  56489. void PopupMenu::addSeparator()
  56490. {
  56491. separatorPending = true;
  56492. }
  56493. class HeaderItemComponent : public PopupMenuCustomComponent
  56494. {
  56495. public:
  56496. HeaderItemComponent (const String& name)
  56497. : PopupMenuCustomComponent (false)
  56498. {
  56499. setName (name);
  56500. }
  56501. void paint (Graphics& g)
  56502. {
  56503. Font f (getLookAndFeel().getPopupMenuFont());
  56504. f.setBold (true);
  56505. g.setFont (f);
  56506. g.setColour (findColour (PopupMenu::headerTextColourId));
  56507. g.drawFittedText (getName(),
  56508. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56509. Justification::bottomLeft, 1);
  56510. }
  56511. void getIdealSize (int& idealWidth,
  56512. int& idealHeight)
  56513. {
  56514. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56515. idealHeight += idealHeight / 2;
  56516. idealWidth += idealWidth / 4;
  56517. }
  56518. private:
  56519. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56520. };
  56521. void PopupMenu::addSectionHeader (const String& title)
  56522. {
  56523. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56524. }
  56525. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56526. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56527. {
  56528. public:
  56529. PopupMenuCompletionCallback()
  56530. : managerOfChosenCommand (0)
  56531. {
  56532. }
  56533. void modalStateFinished (int result)
  56534. {
  56535. if (managerOfChosenCommand != 0 && result != 0)
  56536. {
  56537. ApplicationCommandTarget::InvocationInfo info (result);
  56538. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56539. managerOfChosenCommand->invoke (info, true);
  56540. }
  56541. // (this would be the place to fade out the component, if that's what's required)
  56542. component = 0;
  56543. }
  56544. ApplicationCommandManager* managerOfChosenCommand;
  56545. ScopedPointer<Component> component;
  56546. private:
  56547. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56548. };
  56549. int PopupMenu::showMenu (const Rectangle<int>& target,
  56550. const int itemIdThatMustBeVisible,
  56551. const int minimumWidth,
  56552. const int maximumNumColumns,
  56553. const int standardItemHeight,
  56554. Component* const componentAttachedTo,
  56555. ModalComponentManager::Callback* userCallback)
  56556. {
  56557. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56558. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56559. WeakReference<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56560. Window::wasHiddenBecauseOfAppChange() = false;
  56561. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56562. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56563. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56564. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56565. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56566. &callback->managerOfChosenCommand, componentAttachedTo);
  56567. if (callback->component == 0)
  56568. return 0;
  56569. callback->component->enterModalState (false, userCallbackDeleter.release());
  56570. callback->component->toFront (false); // need to do this after making it modal, or it could
  56571. // be stuck behind other comps that are already modal..
  56572. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56573. callbackDeleter.release();
  56574. if (userCallback != 0)
  56575. return 0;
  56576. const int result = callback->component->runModalLoop();
  56577. if (! Window::wasHiddenBecauseOfAppChange())
  56578. {
  56579. if (prevTopLevel != 0)
  56580. prevTopLevel->toFront (true);
  56581. if (prevFocused != 0)
  56582. prevFocused->grabKeyboardFocus();
  56583. }
  56584. return result;
  56585. }
  56586. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56587. const int minimumWidth, const int maximumNumColumns,
  56588. const int standardItemHeight,
  56589. ModalComponentManager::Callback* callback)
  56590. {
  56591. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56592. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56593. standardItemHeight, 0, callback);
  56594. }
  56595. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56596. const int itemIdThatMustBeVisible,
  56597. const int minimumWidth, const int maximumNumColumns,
  56598. const int standardItemHeight,
  56599. ModalComponentManager::Callback* callback)
  56600. {
  56601. return showMenu (screenAreaToAttachTo,
  56602. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56603. standardItemHeight, 0, callback);
  56604. }
  56605. int PopupMenu::showAt (Component* componentToAttachTo,
  56606. const int itemIdThatMustBeVisible,
  56607. const int minimumWidth, const int maximumNumColumns,
  56608. const int standardItemHeight,
  56609. ModalComponentManager::Callback* callback)
  56610. {
  56611. if (componentToAttachTo != 0)
  56612. {
  56613. return showMenu (componentToAttachTo->getScreenBounds(),
  56614. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56615. standardItemHeight, componentToAttachTo, callback);
  56616. }
  56617. else
  56618. {
  56619. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56620. standardItemHeight, callback);
  56621. }
  56622. }
  56623. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56624. {
  56625. const int numWindows = Window::getActiveWindows().size();
  56626. for (int i = numWindows; --i >= 0;)
  56627. {
  56628. Window* const pmw = Window::getActiveWindows()[i];
  56629. if (pmw != 0)
  56630. pmw->dismissMenu (0);
  56631. }
  56632. return numWindows > 0;
  56633. }
  56634. int PopupMenu::getNumItems() const throw()
  56635. {
  56636. int num = 0;
  56637. for (int i = items.size(); --i >= 0;)
  56638. if (! (items.getUnchecked(i))->isSeparator)
  56639. ++num;
  56640. return num;
  56641. }
  56642. bool PopupMenu::containsCommandItem (const int commandID) const
  56643. {
  56644. for (int i = items.size(); --i >= 0;)
  56645. {
  56646. const Item* mi = items.getUnchecked (i);
  56647. if ((mi->itemId == commandID && mi->commandManager != 0)
  56648. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56649. {
  56650. return true;
  56651. }
  56652. }
  56653. return false;
  56654. }
  56655. bool PopupMenu::containsAnyActiveItems() const throw()
  56656. {
  56657. for (int i = items.size(); --i >= 0;)
  56658. {
  56659. const Item* const mi = items.getUnchecked (i);
  56660. if (mi->subMenu != 0)
  56661. {
  56662. if (mi->subMenu->containsAnyActiveItems())
  56663. return true;
  56664. }
  56665. else if (mi->active)
  56666. {
  56667. return true;
  56668. }
  56669. }
  56670. return false;
  56671. }
  56672. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56673. {
  56674. lookAndFeel = newLookAndFeel;
  56675. }
  56676. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56677. : isHighlighted (false),
  56678. isTriggeredAutomatically (isTriggeredAutomatically_)
  56679. {
  56680. }
  56681. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56682. {
  56683. }
  56684. void PopupMenuCustomComponent::triggerMenuItem()
  56685. {
  56686. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56687. if (mic != 0)
  56688. {
  56689. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56690. if (pmw != 0)
  56691. {
  56692. pmw->dismissMenu (&mic->itemInfo);
  56693. }
  56694. else
  56695. {
  56696. // something must have gone wrong with the component hierarchy if this happens..
  56697. jassertfalse;
  56698. }
  56699. }
  56700. else
  56701. {
  56702. // why isn't this component inside a menu? Not much point triggering the item if
  56703. // there's no menu.
  56704. jassertfalse;
  56705. }
  56706. }
  56707. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56708. : subMenu (0),
  56709. itemId (0),
  56710. isSeparator (false),
  56711. isTicked (false),
  56712. isEnabled (false),
  56713. isCustomComponent (false),
  56714. isSectionHeader (false),
  56715. customColour (0),
  56716. customImage (0),
  56717. menu (menu_),
  56718. index (0)
  56719. {
  56720. }
  56721. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56722. {
  56723. }
  56724. bool PopupMenu::MenuItemIterator::next()
  56725. {
  56726. if (index >= menu.items.size())
  56727. return false;
  56728. const Item* const item = menu.items.getUnchecked (index);
  56729. ++index;
  56730. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56731. subMenu = item->subMenu;
  56732. itemId = item->itemId;
  56733. isSeparator = item->isSeparator;
  56734. isTicked = item->isTicked;
  56735. isEnabled = item->active;
  56736. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <PopupMenuCustomComponent*> (item->customComp)) != 0;
  56737. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56738. customColour = item->usesColour ? &(item->textColour) : 0;
  56739. customImage = item->image;
  56740. commandManager = item->commandManager;
  56741. return true;
  56742. }
  56743. END_JUCE_NAMESPACE
  56744. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56745. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56746. BEGIN_JUCE_NAMESPACE
  56747. ComponentDragger::ComponentDragger()
  56748. {
  56749. }
  56750. ComponentDragger::~ComponentDragger()
  56751. {
  56752. }
  56753. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56754. {
  56755. jassert (componentToDrag != 0);
  56756. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56757. if (componentToDrag != 0)
  56758. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56759. }
  56760. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56761. ComponentBoundsConstrainer* const constrainer)
  56762. {
  56763. jassert (componentToDrag != 0);
  56764. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56765. if (componentToDrag != 0)
  56766. {
  56767. Rectangle<int> bounds (componentToDrag->getBounds());
  56768. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  56769. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  56770. // the current mouse position instead of the one that the event contains...
  56771. if (componentToDrag->isOnDesktop())
  56772. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  56773. else
  56774. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56775. if (constrainer != 0)
  56776. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56777. else
  56778. componentToDrag->setBounds (bounds);
  56779. }
  56780. }
  56781. END_JUCE_NAMESPACE
  56782. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56783. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56784. BEGIN_JUCE_NAMESPACE
  56785. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56786. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56787. class DragImageComponent : public Component,
  56788. public Timer
  56789. {
  56790. public:
  56791. DragImageComponent (const Image& im,
  56792. const String& desc,
  56793. Component* const sourceComponent,
  56794. Component* const mouseDragSource_,
  56795. DragAndDropContainer* const o,
  56796. const Point<int>& imageOffset_)
  56797. : image (im),
  56798. source (sourceComponent),
  56799. mouseDragSource (mouseDragSource_),
  56800. owner (o),
  56801. dragDesc (desc),
  56802. imageOffset (imageOffset_),
  56803. hasCheckedForExternalDrag (false),
  56804. drawImage (true)
  56805. {
  56806. setSize (im.getWidth(), im.getHeight());
  56807. if (mouseDragSource == 0)
  56808. mouseDragSource = source;
  56809. mouseDragSource->addMouseListener (this, false);
  56810. startTimer (200);
  56811. setInterceptsMouseClicks (false, false);
  56812. setAlwaysOnTop (true);
  56813. }
  56814. ~DragImageComponent()
  56815. {
  56816. if (owner->dragImageComponent == this)
  56817. owner->dragImageComponent.release();
  56818. if (mouseDragSource != 0)
  56819. {
  56820. mouseDragSource->removeMouseListener (this);
  56821. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56822. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56823. }
  56824. }
  56825. void paint (Graphics& g)
  56826. {
  56827. if (isOpaque())
  56828. g.fillAll (Colours::white);
  56829. if (drawImage)
  56830. {
  56831. g.setOpacity (1.0f);
  56832. g.drawImageAt (image, 0, 0);
  56833. }
  56834. }
  56835. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56836. {
  56837. Component* hit = getParentComponent();
  56838. if (hit == 0)
  56839. {
  56840. hit = Desktop::getInstance().findComponentAt (screenPos);
  56841. }
  56842. else
  56843. {
  56844. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56845. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56846. }
  56847. // (note: use a local copy of the dragDesc member in case the callback runs
  56848. // a modal loop and deletes this object before the method completes)
  56849. const String dragDescLocal (dragDesc);
  56850. while (hit != 0)
  56851. {
  56852. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56853. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56854. {
  56855. relativePos = hit->getLocalPoint (0, screenPos);
  56856. return ddt;
  56857. }
  56858. hit = hit->getParentComponent();
  56859. }
  56860. return 0;
  56861. }
  56862. void mouseUp (const MouseEvent& e)
  56863. {
  56864. if (e.originalComponent != this)
  56865. {
  56866. if (mouseDragSource != 0)
  56867. mouseDragSource->removeMouseListener (this);
  56868. bool dropAccepted = false;
  56869. DragAndDropTarget* ddt = 0;
  56870. Point<int> relPos;
  56871. if (isVisible())
  56872. {
  56873. setVisible (false);
  56874. ddt = findTarget (e.getScreenPosition(), relPos);
  56875. // fade this component and remove it - it'll be deleted later by the timer callback
  56876. dropAccepted = ddt != 0;
  56877. setVisible (true);
  56878. if (dropAccepted || source == 0)
  56879. {
  56880. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56881. }
  56882. else
  56883. {
  56884. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56885. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56886. Desktop::getInstance().getAnimator().animateComponent (this,
  56887. getBounds() + (target - ourCentre),
  56888. 0.0f, 120,
  56889. true, 1.0, 1.0);
  56890. }
  56891. }
  56892. if (getParentComponent() != 0)
  56893. getParentComponent()->removeChildComponent (this);
  56894. if (dropAccepted && ddt != 0)
  56895. {
  56896. // (note: use a local copy of the dragDesc member in case the callback runs
  56897. // a modal loop and deletes this object before the method completes)
  56898. const String dragDescLocal (dragDesc);
  56899. currentlyOverComp = 0;
  56900. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56901. }
  56902. // careful - this object could now be deleted..
  56903. }
  56904. }
  56905. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56906. {
  56907. // (note: use a local copy of the dragDesc member in case the callback runs
  56908. // a modal loop and deletes this object before it returns)
  56909. const String dragDescLocal (dragDesc);
  56910. Point<int> newPos (screenPos + imageOffset);
  56911. if (getParentComponent() != 0)
  56912. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56913. //if (newX != getX() || newY != getY())
  56914. {
  56915. setTopLeftPosition (newPos.getX(), newPos.getY());
  56916. Point<int> relPos;
  56917. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56918. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56919. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56920. if (ddtComp != currentlyOverComp)
  56921. {
  56922. if (currentlyOverComp != 0 && source != 0
  56923. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56924. {
  56925. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56926. }
  56927. currentlyOverComp = ddtComp;
  56928. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56929. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56930. }
  56931. DragAndDropTarget* target = getCurrentlyOver();
  56932. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56933. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56934. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56935. {
  56936. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56937. {
  56938. hasCheckedForExternalDrag = true;
  56939. StringArray files;
  56940. bool canMoveFiles = false;
  56941. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56942. && files.size() > 0)
  56943. {
  56944. WeakReference<Component> cdw (this);
  56945. setVisible (false);
  56946. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56947. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56948. if (cdw != 0)
  56949. delete this;
  56950. return;
  56951. }
  56952. }
  56953. }
  56954. }
  56955. }
  56956. void mouseDrag (const MouseEvent& e)
  56957. {
  56958. if (e.originalComponent != this)
  56959. updateLocation (true, e.getScreenPosition());
  56960. }
  56961. void timerCallback()
  56962. {
  56963. if (source == 0)
  56964. {
  56965. delete this;
  56966. }
  56967. else if (! isMouseButtonDownAnywhere())
  56968. {
  56969. if (mouseDragSource != 0)
  56970. mouseDragSource->removeMouseListener (this);
  56971. delete this;
  56972. }
  56973. }
  56974. private:
  56975. Image image;
  56976. WeakReference<Component> source;
  56977. WeakReference<Component> mouseDragSource;
  56978. DragAndDropContainer* const owner;
  56979. WeakReference<Component> currentlyOverComp;
  56980. DragAndDropTarget* getCurrentlyOver()
  56981. {
  56982. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56983. }
  56984. String dragDesc;
  56985. const Point<int> imageOffset;
  56986. bool hasCheckedForExternalDrag, drawImage;
  56987. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  56988. };
  56989. DragAndDropContainer::DragAndDropContainer()
  56990. {
  56991. }
  56992. DragAndDropContainer::~DragAndDropContainer()
  56993. {
  56994. dragImageComponent = 0;
  56995. }
  56996. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56997. Component* sourceComponent,
  56998. const Image& dragImage_,
  56999. const bool allowDraggingToExternalWindows,
  57000. const Point<int>* imageOffsetFromMouse)
  57001. {
  57002. Image dragImage (dragImage_);
  57003. if (dragImageComponent == 0)
  57004. {
  57005. Component* const thisComp = dynamic_cast <Component*> (this);
  57006. if (thisComp == 0)
  57007. {
  57008. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57009. return;
  57010. }
  57011. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57012. if (draggingSource == 0 || ! draggingSource->isDragging())
  57013. {
  57014. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57015. return;
  57016. }
  57017. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57018. Point<int> imageOffset;
  57019. if (dragImage.isNull())
  57020. {
  57021. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57022. .convertedToFormat (Image::ARGB);
  57023. dragImage.multiplyAllAlphas (0.6f);
  57024. const int lo = 150;
  57025. const int hi = 400;
  57026. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  57027. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57028. for (int y = dragImage.getHeight(); --y >= 0;)
  57029. {
  57030. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57031. for (int x = dragImage.getWidth(); --x >= 0;)
  57032. {
  57033. const int dx = x - clipped.getX();
  57034. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57035. if (distance > lo)
  57036. {
  57037. const float alpha = (distance > hi) ? 0
  57038. : (hi - distance) / (float) (hi - lo)
  57039. + Random::getSystemRandom().nextFloat() * 0.008f;
  57040. dragImage.multiplyAlphaAt (x, y, alpha);
  57041. }
  57042. }
  57043. }
  57044. imageOffset = -clipped;
  57045. }
  57046. else
  57047. {
  57048. if (imageOffsetFromMouse == 0)
  57049. imageOffset = -dragImage.getBounds().getCentre();
  57050. else
  57051. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57052. }
  57053. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57054. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57055. currentDragDesc = sourceDescription;
  57056. if (allowDraggingToExternalWindows)
  57057. {
  57058. if (! Desktop::canUseSemiTransparentWindows())
  57059. dragImageComponent->setOpaque (true);
  57060. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57061. | ComponentPeer::windowIsTemporary
  57062. | ComponentPeer::windowIgnoresKeyPresses);
  57063. }
  57064. else
  57065. thisComp->addChildComponent (dragImageComponent);
  57066. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57067. dragImageComponent->setVisible (true);
  57068. }
  57069. }
  57070. bool DragAndDropContainer::isDragAndDropActive() const
  57071. {
  57072. return dragImageComponent != 0;
  57073. }
  57074. const String DragAndDropContainer::getCurrentDragDescription() const
  57075. {
  57076. return (dragImageComponent != 0) ? currentDragDesc
  57077. : String::empty;
  57078. }
  57079. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57080. {
  57081. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57082. }
  57083. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57084. {
  57085. return false;
  57086. }
  57087. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57088. {
  57089. }
  57090. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57091. {
  57092. }
  57093. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57094. {
  57095. }
  57096. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57097. {
  57098. return true;
  57099. }
  57100. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57101. {
  57102. }
  57103. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57104. {
  57105. }
  57106. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57107. {
  57108. }
  57109. END_JUCE_NAMESPACE
  57110. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57111. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57112. BEGIN_JUCE_NAMESPACE
  57113. class MouseCursor::SharedCursorHandle
  57114. {
  57115. public:
  57116. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57117. : handle (createStandardMouseCursor (type)),
  57118. refCount (1),
  57119. standardType (type),
  57120. isStandard (true)
  57121. {
  57122. }
  57123. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57124. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57125. refCount (1),
  57126. standardType (MouseCursor::NormalCursor),
  57127. isStandard (false)
  57128. {
  57129. }
  57130. ~SharedCursorHandle()
  57131. {
  57132. deleteMouseCursor (handle, isStandard);
  57133. }
  57134. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57135. {
  57136. const ScopedLock sl (getLock());
  57137. for (int i = 0; i < getCursors().size(); ++i)
  57138. {
  57139. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57140. if (sc->standardType == type)
  57141. return sc->retain();
  57142. }
  57143. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57144. getCursors().add (sc);
  57145. return sc;
  57146. }
  57147. SharedCursorHandle* retain() throw()
  57148. {
  57149. ++refCount;
  57150. return this;
  57151. }
  57152. void release()
  57153. {
  57154. if (--refCount == 0)
  57155. {
  57156. if (isStandard)
  57157. {
  57158. const ScopedLock sl (getLock());
  57159. getCursors().removeValue (this);
  57160. }
  57161. delete this;
  57162. }
  57163. }
  57164. void* getHandle() const throw() { return handle; }
  57165. private:
  57166. void* const handle;
  57167. Atomic <int> refCount;
  57168. const MouseCursor::StandardCursorType standardType;
  57169. const bool isStandard;
  57170. static CriticalSection& getLock()
  57171. {
  57172. static CriticalSection lock;
  57173. return lock;
  57174. }
  57175. static Array <SharedCursorHandle*>& getCursors()
  57176. {
  57177. static Array <SharedCursorHandle*> cursors;
  57178. return cursors;
  57179. }
  57180. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57181. };
  57182. MouseCursor::MouseCursor()
  57183. : cursorHandle (0)
  57184. {
  57185. }
  57186. MouseCursor::MouseCursor (const StandardCursorType type)
  57187. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57188. {
  57189. }
  57190. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57191. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57192. {
  57193. }
  57194. MouseCursor::MouseCursor (const MouseCursor& other)
  57195. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57196. {
  57197. }
  57198. MouseCursor::~MouseCursor()
  57199. {
  57200. if (cursorHandle != 0)
  57201. cursorHandle->release();
  57202. }
  57203. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57204. {
  57205. if (other.cursorHandle != 0)
  57206. other.cursorHandle->retain();
  57207. if (cursorHandle != 0)
  57208. cursorHandle->release();
  57209. cursorHandle = other.cursorHandle;
  57210. return *this;
  57211. }
  57212. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57213. {
  57214. return getHandle() == other.getHandle();
  57215. }
  57216. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57217. {
  57218. return getHandle() != other.getHandle();
  57219. }
  57220. void* MouseCursor::getHandle() const throw()
  57221. {
  57222. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57223. }
  57224. void MouseCursor::showWaitCursor()
  57225. {
  57226. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57227. }
  57228. void MouseCursor::hideWaitCursor()
  57229. {
  57230. Desktop::getInstance().getMainMouseSource().revealCursor();
  57231. }
  57232. END_JUCE_NAMESPACE
  57233. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57234. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57235. BEGIN_JUCE_NAMESPACE
  57236. MouseEvent::MouseEvent (MouseInputSource& source_,
  57237. const Point<int>& position,
  57238. const ModifierKeys& mods_,
  57239. Component* const eventComponent_,
  57240. Component* const originator,
  57241. const Time& eventTime_,
  57242. const Point<int> mouseDownPos_,
  57243. const Time& mouseDownTime_,
  57244. const int numberOfClicks_,
  57245. const bool mouseWasDragged) throw()
  57246. : x (position.getX()),
  57247. y (position.getY()),
  57248. mods (mods_),
  57249. eventComponent (eventComponent_),
  57250. originalComponent (originator),
  57251. eventTime (eventTime_),
  57252. source (source_),
  57253. mouseDownPos (mouseDownPos_),
  57254. mouseDownTime (mouseDownTime_),
  57255. numberOfClicks (numberOfClicks_),
  57256. wasMovedSinceMouseDown (mouseWasDragged)
  57257. {
  57258. }
  57259. MouseEvent::~MouseEvent() throw()
  57260. {
  57261. }
  57262. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57263. {
  57264. if (otherComponent == 0)
  57265. {
  57266. jassertfalse;
  57267. return *this;
  57268. }
  57269. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57270. mods, otherComponent, originalComponent, eventTime,
  57271. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57272. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57273. }
  57274. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57275. {
  57276. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57277. eventTime, mouseDownPos, mouseDownTime,
  57278. numberOfClicks, wasMovedSinceMouseDown);
  57279. }
  57280. bool MouseEvent::mouseWasClicked() const throw()
  57281. {
  57282. return ! wasMovedSinceMouseDown;
  57283. }
  57284. int MouseEvent::getMouseDownX() const throw()
  57285. {
  57286. return mouseDownPos.getX();
  57287. }
  57288. int MouseEvent::getMouseDownY() const throw()
  57289. {
  57290. return mouseDownPos.getY();
  57291. }
  57292. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57293. {
  57294. return mouseDownPos;
  57295. }
  57296. int MouseEvent::getDistanceFromDragStartX() const throw()
  57297. {
  57298. return x - mouseDownPos.getX();
  57299. }
  57300. int MouseEvent::getDistanceFromDragStartY() const throw()
  57301. {
  57302. return y - mouseDownPos.getY();
  57303. }
  57304. int MouseEvent::getDistanceFromDragStart() const throw()
  57305. {
  57306. return mouseDownPos.getDistanceFrom (getPosition());
  57307. }
  57308. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57309. {
  57310. return getPosition() - mouseDownPos;
  57311. }
  57312. int MouseEvent::getLengthOfMousePress() const throw()
  57313. {
  57314. if (mouseDownTime.toMilliseconds() > 0)
  57315. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57316. return 0;
  57317. }
  57318. const Point<int> MouseEvent::getPosition() const throw()
  57319. {
  57320. return Point<int> (x, y);
  57321. }
  57322. int MouseEvent::getScreenX() const
  57323. {
  57324. return getScreenPosition().getX();
  57325. }
  57326. int MouseEvent::getScreenY() const
  57327. {
  57328. return getScreenPosition().getY();
  57329. }
  57330. const Point<int> MouseEvent::getScreenPosition() const
  57331. {
  57332. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57333. }
  57334. int MouseEvent::getMouseDownScreenX() const
  57335. {
  57336. return getMouseDownScreenPosition().getX();
  57337. }
  57338. int MouseEvent::getMouseDownScreenY() const
  57339. {
  57340. return getMouseDownScreenPosition().getY();
  57341. }
  57342. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57343. {
  57344. return eventComponent->localPointToGlobal (mouseDownPos);
  57345. }
  57346. int MouseEvent::doubleClickTimeOutMs = 400;
  57347. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57348. {
  57349. doubleClickTimeOutMs = newTime;
  57350. }
  57351. int MouseEvent::getDoubleClickTimeout() throw()
  57352. {
  57353. return doubleClickTimeOutMs;
  57354. }
  57355. END_JUCE_NAMESPACE
  57356. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57357. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57358. BEGIN_JUCE_NAMESPACE
  57359. class MouseInputSourceInternal : public AsyncUpdater
  57360. {
  57361. public:
  57362. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57363. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57364. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57365. mouseEventCounter (0)
  57366. {
  57367. }
  57368. bool isDragging() const throw()
  57369. {
  57370. return buttonState.isAnyMouseButtonDown();
  57371. }
  57372. Component* getComponentUnderMouse() const
  57373. {
  57374. return static_cast <Component*> (componentUnderMouse);
  57375. }
  57376. const ModifierKeys getCurrentModifiers() const
  57377. {
  57378. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57379. }
  57380. ComponentPeer* getPeer()
  57381. {
  57382. if (! ComponentPeer::isValidPeer (lastPeer))
  57383. lastPeer = 0;
  57384. return lastPeer;
  57385. }
  57386. Component* findComponentAt (const Point<int>& screenPos)
  57387. {
  57388. ComponentPeer* const peer = getPeer();
  57389. if (peer != 0)
  57390. {
  57391. Component* const comp = peer->getComponent();
  57392. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57393. // (the contains() call is needed to test for overlapping desktop windows)
  57394. if (comp->contains (relativePos))
  57395. return comp->getComponentAt (relativePos);
  57396. }
  57397. return 0;
  57398. }
  57399. const Point<int> getScreenPosition() const
  57400. {
  57401. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57402. // value, because that can cause continuity problems.
  57403. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57404. : lastScreenPos);
  57405. }
  57406. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57407. {
  57408. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57409. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57410. }
  57411. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57412. {
  57413. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57414. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57415. }
  57416. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57417. {
  57418. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57419. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57420. }
  57421. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57422. {
  57423. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57424. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57425. }
  57426. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57427. {
  57428. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57429. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57430. }
  57431. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57432. {
  57433. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57434. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57435. }
  57436. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57437. {
  57438. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57439. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57440. }
  57441. // (returns true if the button change caused a modal event loop)
  57442. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57443. {
  57444. if (buttonState == newButtonState)
  57445. return false;
  57446. setScreenPos (screenPos, time, false);
  57447. // (ignore secondary clicks when there's already a button down)
  57448. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57449. {
  57450. buttonState = newButtonState;
  57451. return false;
  57452. }
  57453. const int lastCounter = mouseEventCounter;
  57454. if (buttonState.isAnyMouseButtonDown())
  57455. {
  57456. Component* const current = getComponentUnderMouse();
  57457. if (current != 0)
  57458. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57459. enableUnboundedMouseMovement (false, false);
  57460. }
  57461. buttonState = newButtonState;
  57462. if (buttonState.isAnyMouseButtonDown())
  57463. {
  57464. Desktop::getInstance().incrementMouseClickCounter();
  57465. Component* const current = getComponentUnderMouse();
  57466. if (current != 0)
  57467. {
  57468. registerMouseDown (screenPos, time, current, buttonState);
  57469. sendMouseDown (current, screenPos, time);
  57470. }
  57471. }
  57472. return lastCounter != mouseEventCounter;
  57473. }
  57474. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57475. {
  57476. Component* current = getComponentUnderMouse();
  57477. if (newComponent != current)
  57478. {
  57479. WeakReference<Component> safeNewComp (newComponent);
  57480. const ModifierKeys originalButtonState (buttonState);
  57481. if (current != 0)
  57482. {
  57483. setButtons (screenPos, time, ModifierKeys());
  57484. sendMouseExit (current, screenPos, time);
  57485. buttonState = originalButtonState;
  57486. }
  57487. componentUnderMouse = safeNewComp;
  57488. current = getComponentUnderMouse();
  57489. if (current != 0)
  57490. sendMouseEnter (current, screenPos, time);
  57491. revealCursor (false);
  57492. setButtons (screenPos, time, originalButtonState);
  57493. }
  57494. }
  57495. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57496. {
  57497. ModifierKeys::updateCurrentModifiers();
  57498. if (newPeer != lastPeer)
  57499. {
  57500. setComponentUnderMouse (0, screenPos, time);
  57501. lastPeer = newPeer;
  57502. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57503. }
  57504. }
  57505. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57506. {
  57507. if (! isDragging())
  57508. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57509. if (newScreenPos != lastScreenPos || forceUpdate)
  57510. {
  57511. cancelPendingUpdate();
  57512. lastScreenPos = newScreenPos;
  57513. Component* const current = getComponentUnderMouse();
  57514. if (current != 0)
  57515. {
  57516. if (isDragging())
  57517. {
  57518. registerMouseDrag (newScreenPos);
  57519. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57520. if (isUnboundedMouseModeOn)
  57521. handleUnboundedDrag (current);
  57522. }
  57523. else
  57524. {
  57525. sendMouseMove (current, newScreenPos, time);
  57526. }
  57527. }
  57528. revealCursor (false);
  57529. }
  57530. }
  57531. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57532. {
  57533. jassert (newPeer != 0);
  57534. lastTime = time;
  57535. ++mouseEventCounter;
  57536. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57537. if (isDragging() && newMods.isAnyMouseButtonDown())
  57538. {
  57539. setScreenPos (screenPos, time, false);
  57540. }
  57541. else
  57542. {
  57543. setPeer (newPeer, screenPos, time);
  57544. ComponentPeer* peer = getPeer();
  57545. if (peer != 0)
  57546. {
  57547. if (setButtons (screenPos, time, newMods))
  57548. return; // some modal events have been dispatched, so the current event is now out-of-date
  57549. peer = getPeer();
  57550. if (peer != 0)
  57551. setScreenPos (screenPos, time, false);
  57552. }
  57553. }
  57554. }
  57555. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57556. {
  57557. jassert (peer != 0);
  57558. lastTime = time;
  57559. ++mouseEventCounter;
  57560. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57561. setPeer (peer, screenPos, time);
  57562. setScreenPos (screenPos, time, false);
  57563. triggerFakeMove();
  57564. if (! isDragging())
  57565. {
  57566. Component* current = getComponentUnderMouse();
  57567. if (current != 0)
  57568. sendMouseWheel (current, screenPos, time, x, y);
  57569. }
  57570. }
  57571. const Time getLastMouseDownTime() const throw()
  57572. {
  57573. return Time (mouseDowns[0].time);
  57574. }
  57575. const Point<int> getLastMouseDownPosition() const throw()
  57576. {
  57577. return mouseDowns[0].position;
  57578. }
  57579. int getNumberOfMultipleClicks() const throw()
  57580. {
  57581. int numClicks = 0;
  57582. if (mouseDowns[0].time != Time())
  57583. {
  57584. if (! mouseMovedSignificantlySincePressed)
  57585. ++numClicks;
  57586. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57587. {
  57588. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57589. ++numClicks;
  57590. else
  57591. break;
  57592. }
  57593. }
  57594. return numClicks;
  57595. }
  57596. bool hasMouseMovedSignificantlySincePressed() const throw()
  57597. {
  57598. return mouseMovedSignificantlySincePressed
  57599. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57600. }
  57601. void triggerFakeMove()
  57602. {
  57603. triggerAsyncUpdate();
  57604. }
  57605. void handleAsyncUpdate()
  57606. {
  57607. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57608. }
  57609. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57610. {
  57611. enable = enable && isDragging();
  57612. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57613. if (enable != isUnboundedMouseModeOn)
  57614. {
  57615. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57616. {
  57617. // when released, return the mouse to within the component's bounds
  57618. Component* current = getComponentUnderMouse();
  57619. if (current != 0)
  57620. Desktop::setMousePosition (current->getScreenBounds()
  57621. .getConstrainedPoint (lastScreenPos));
  57622. }
  57623. isUnboundedMouseModeOn = enable;
  57624. unboundedMouseOffset = Point<int>();
  57625. revealCursor (true);
  57626. }
  57627. }
  57628. void handleUnboundedDrag (Component* current)
  57629. {
  57630. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57631. if (! screenArea.contains (lastScreenPos))
  57632. {
  57633. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57634. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57635. Desktop::setMousePosition (componentCentre);
  57636. }
  57637. else if (isCursorVisibleUntilOffscreen
  57638. && (! unboundedMouseOffset.isOrigin())
  57639. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57640. {
  57641. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57642. unboundedMouseOffset = Point<int>();
  57643. }
  57644. }
  57645. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57646. {
  57647. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57648. {
  57649. cursor = MouseCursor::NoCursor;
  57650. forcedUpdate = true;
  57651. }
  57652. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57653. {
  57654. currentCursorHandle = cursor.getHandle();
  57655. cursor.showInWindow (getPeer());
  57656. }
  57657. }
  57658. void hideCursor()
  57659. {
  57660. showMouseCursor (MouseCursor::NoCursor, true);
  57661. }
  57662. void revealCursor (bool forcedUpdate)
  57663. {
  57664. MouseCursor mc (MouseCursor::NormalCursor);
  57665. Component* current = getComponentUnderMouse();
  57666. if (current != 0)
  57667. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57668. showMouseCursor (mc, forcedUpdate);
  57669. }
  57670. const int index;
  57671. const bool isMouseDevice;
  57672. Point<int> lastScreenPos;
  57673. ModifierKeys buttonState;
  57674. private:
  57675. MouseInputSource& source;
  57676. WeakReference<Component> componentUnderMouse;
  57677. ComponentPeer* lastPeer;
  57678. Point<int> unboundedMouseOffset;
  57679. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57680. void* currentCursorHandle;
  57681. int mouseEventCounter;
  57682. struct RecentMouseDown
  57683. {
  57684. RecentMouseDown() : component (0)
  57685. {
  57686. }
  57687. Point<int> position;
  57688. Time time;
  57689. Component* component;
  57690. ModifierKeys buttons;
  57691. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57692. {
  57693. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57694. && abs (position.getX() - other.position.getX()) < 8
  57695. && abs (position.getY() - other.position.getY()) < 8
  57696. && buttons == other.buttons;;
  57697. }
  57698. };
  57699. RecentMouseDown mouseDowns[4];
  57700. bool mouseMovedSignificantlySincePressed;
  57701. Time lastTime;
  57702. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  57703. Component* const component, const ModifierKeys& modifiers) throw()
  57704. {
  57705. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57706. mouseDowns[i] = mouseDowns[i - 1];
  57707. mouseDowns[0].position = screenPos;
  57708. mouseDowns[0].time = time;
  57709. mouseDowns[0].component = component;
  57710. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57711. mouseMovedSignificantlySincePressed = false;
  57712. }
  57713. void registerMouseDrag (const Point<int>& screenPos) throw()
  57714. {
  57715. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57716. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57717. }
  57718. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57719. };
  57720. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57721. {
  57722. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57723. }
  57724. MouseInputSource::~MouseInputSource()
  57725. {
  57726. }
  57727. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57728. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57729. bool MouseInputSource::canHover() const { return isMouse(); }
  57730. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57731. int MouseInputSource::getIndex() const { return pimpl->index; }
  57732. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57733. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57734. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57735. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57736. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57737. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57738. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57739. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57740. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57741. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57742. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57743. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57744. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57745. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57746. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57747. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57748. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57749. {
  57750. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  57751. }
  57752. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57753. {
  57754. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  57755. }
  57756. END_JUCE_NAMESPACE
  57757. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57758. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57759. BEGIN_JUCE_NAMESPACE
  57760. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57761. : source (0),
  57762. hoverTimeMillisecs (hoverTimeMillisecs_),
  57763. hasJustHovered (false)
  57764. {
  57765. internalTimer.owner = this;
  57766. }
  57767. MouseHoverDetector::~MouseHoverDetector()
  57768. {
  57769. setHoverComponent (0);
  57770. }
  57771. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57772. {
  57773. hoverTimeMillisecs = newTimeInMillisecs;
  57774. }
  57775. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57776. {
  57777. if (source != newSourceComponent)
  57778. {
  57779. internalTimer.stopTimer();
  57780. hasJustHovered = false;
  57781. if (source != 0)
  57782. source->removeMouseListener (&internalTimer);
  57783. source = newSourceComponent;
  57784. if (newSourceComponent != 0)
  57785. newSourceComponent->addMouseListener (&internalTimer, false);
  57786. }
  57787. }
  57788. void MouseHoverDetector::hoverTimerCallback()
  57789. {
  57790. internalTimer.stopTimer();
  57791. if (source != 0)
  57792. {
  57793. const Point<int> pos (source->getMouseXYRelative());
  57794. if (source->reallyContains (pos, false))
  57795. {
  57796. hasJustHovered = true;
  57797. mouseHovered (pos.getX(), pos.getY());
  57798. }
  57799. }
  57800. }
  57801. void MouseHoverDetector::checkJustHoveredCallback()
  57802. {
  57803. if (hasJustHovered)
  57804. {
  57805. hasJustHovered = false;
  57806. mouseMovedAfterHover();
  57807. }
  57808. }
  57809. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57810. {
  57811. owner->hoverTimerCallback();
  57812. }
  57813. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57814. {
  57815. stopTimer();
  57816. owner->checkJustHoveredCallback();
  57817. }
  57818. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57819. {
  57820. stopTimer();
  57821. owner->checkJustHoveredCallback();
  57822. }
  57823. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57824. {
  57825. stopTimer();
  57826. owner->checkJustHoveredCallback();
  57827. }
  57828. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57829. {
  57830. stopTimer();
  57831. owner->checkJustHoveredCallback();
  57832. }
  57833. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57834. {
  57835. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57836. {
  57837. lastX = e.x;
  57838. lastY = e.y;
  57839. if (owner->source != 0)
  57840. startTimer (owner->hoverTimeMillisecs);
  57841. owner->checkJustHoveredCallback();
  57842. }
  57843. }
  57844. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57845. {
  57846. stopTimer();
  57847. owner->checkJustHoveredCallback();
  57848. }
  57849. END_JUCE_NAMESPACE
  57850. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57851. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57852. BEGIN_JUCE_NAMESPACE
  57853. void MouseListener::mouseEnter (const MouseEvent&)
  57854. {
  57855. }
  57856. void MouseListener::mouseExit (const MouseEvent&)
  57857. {
  57858. }
  57859. void MouseListener::mouseDown (const MouseEvent&)
  57860. {
  57861. }
  57862. void MouseListener::mouseUp (const MouseEvent&)
  57863. {
  57864. }
  57865. void MouseListener::mouseDrag (const MouseEvent&)
  57866. {
  57867. }
  57868. void MouseListener::mouseMove (const MouseEvent&)
  57869. {
  57870. }
  57871. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57872. {
  57873. }
  57874. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57875. {
  57876. }
  57877. END_JUCE_NAMESPACE
  57878. /*** End of inlined file: juce_MouseListener.cpp ***/
  57879. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57880. BEGIN_JUCE_NAMESPACE
  57881. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57882. const String& buttonTextWhenTrue,
  57883. const String& buttonTextWhenFalse)
  57884. : PropertyComponent (name),
  57885. onText (buttonTextWhenTrue),
  57886. offText (buttonTextWhenFalse)
  57887. {
  57888. addAndMakeVisible (&button);
  57889. button.setClickingTogglesState (false);
  57890. button.addListener (this);
  57891. }
  57892. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57893. const String& name,
  57894. const String& buttonText)
  57895. : PropertyComponent (name),
  57896. onText (buttonText),
  57897. offText (buttonText)
  57898. {
  57899. addAndMakeVisible (&button);
  57900. button.setClickingTogglesState (false);
  57901. button.setButtonText (buttonText);
  57902. button.getToggleStateValue().referTo (valueToControl);
  57903. button.setClickingTogglesState (true);
  57904. }
  57905. BooleanPropertyComponent::~BooleanPropertyComponent()
  57906. {
  57907. }
  57908. void BooleanPropertyComponent::setState (const bool newState)
  57909. {
  57910. button.setToggleState (newState, true);
  57911. }
  57912. bool BooleanPropertyComponent::getState() const
  57913. {
  57914. return button.getToggleState();
  57915. }
  57916. void BooleanPropertyComponent::paint (Graphics& g)
  57917. {
  57918. PropertyComponent::paint (g);
  57919. g.setColour (Colours::white);
  57920. g.fillRect (button.getBounds());
  57921. g.setColour (findColour (ComboBox::outlineColourId));
  57922. g.drawRect (button.getBounds());
  57923. }
  57924. void BooleanPropertyComponent::refresh()
  57925. {
  57926. button.setToggleState (getState(), false);
  57927. button.setButtonText (button.getToggleState() ? onText : offText);
  57928. }
  57929. void BooleanPropertyComponent::buttonClicked (Button*)
  57930. {
  57931. setState (! getState());
  57932. }
  57933. END_JUCE_NAMESPACE
  57934. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57935. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57936. BEGIN_JUCE_NAMESPACE
  57937. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57938. const bool triggerOnMouseDown)
  57939. : PropertyComponent (name)
  57940. {
  57941. addAndMakeVisible (&button);
  57942. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57943. button.addListener (this);
  57944. }
  57945. ButtonPropertyComponent::~ButtonPropertyComponent()
  57946. {
  57947. }
  57948. void ButtonPropertyComponent::refresh()
  57949. {
  57950. button.setButtonText (getButtonText());
  57951. }
  57952. void ButtonPropertyComponent::buttonClicked (Button*)
  57953. {
  57954. buttonClicked();
  57955. }
  57956. END_JUCE_NAMESPACE
  57957. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57958. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57959. BEGIN_JUCE_NAMESPACE
  57960. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57961. public ValueListener
  57962. {
  57963. public:
  57964. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57965. : sourceValue (sourceValue_),
  57966. mappings (mappings_)
  57967. {
  57968. sourceValue.addListener (this);
  57969. }
  57970. ~RemapperValueSource() {}
  57971. const var getValue() const
  57972. {
  57973. return mappings.indexOf (sourceValue.getValue()) + 1;
  57974. }
  57975. void setValue (const var& newValue)
  57976. {
  57977. const var remappedVal (mappings [(int) newValue - 1]);
  57978. if (remappedVal != sourceValue)
  57979. sourceValue = remappedVal;
  57980. }
  57981. void valueChanged (Value&)
  57982. {
  57983. sendChangeMessage (true);
  57984. }
  57985. protected:
  57986. Value sourceValue;
  57987. Array<var> mappings;
  57988. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57989. };
  57990. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57991. : PropertyComponent (name),
  57992. isCustomClass (true)
  57993. {
  57994. }
  57995. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57996. const String& name,
  57997. const StringArray& choices_,
  57998. const Array <var>& correspondingValues)
  57999. : PropertyComponent (name),
  58000. choices (choices_),
  58001. isCustomClass (false)
  58002. {
  58003. // The array of corresponding values must contain one value for each of the items in
  58004. // the choices array!
  58005. jassert (correspondingValues.size() == choices.size());
  58006. createComboBox();
  58007. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58008. }
  58009. ChoicePropertyComponent::~ChoicePropertyComponent()
  58010. {
  58011. }
  58012. void ChoicePropertyComponent::createComboBox()
  58013. {
  58014. addAndMakeVisible (&comboBox);
  58015. for (int i = 0; i < choices.size(); ++i)
  58016. {
  58017. if (choices[i].isNotEmpty())
  58018. comboBox.addItem (choices[i], i + 1);
  58019. else
  58020. comboBox.addSeparator();
  58021. }
  58022. comboBox.setEditableText (false);
  58023. }
  58024. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58025. {
  58026. jassertfalse; // you need to override this method in your subclass!
  58027. }
  58028. int ChoicePropertyComponent::getIndex() const
  58029. {
  58030. jassertfalse; // you need to override this method in your subclass!
  58031. return -1;
  58032. }
  58033. const StringArray& ChoicePropertyComponent::getChoices() const
  58034. {
  58035. return choices;
  58036. }
  58037. void ChoicePropertyComponent::refresh()
  58038. {
  58039. if (isCustomClass)
  58040. {
  58041. if (! comboBox.isVisible())
  58042. {
  58043. createComboBox();
  58044. comboBox.addListener (this);
  58045. }
  58046. comboBox.setSelectedId (getIndex() + 1, true);
  58047. }
  58048. }
  58049. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58050. {
  58051. if (isCustomClass)
  58052. {
  58053. const int newIndex = comboBox.getSelectedId() - 1;
  58054. if (newIndex != getIndex())
  58055. setIndex (newIndex);
  58056. }
  58057. }
  58058. END_JUCE_NAMESPACE
  58059. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58060. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58061. BEGIN_JUCE_NAMESPACE
  58062. PropertyComponent::PropertyComponent (const String& name,
  58063. const int preferredHeight_)
  58064. : Component (name),
  58065. preferredHeight (preferredHeight_)
  58066. {
  58067. jassert (name.isNotEmpty());
  58068. }
  58069. PropertyComponent::~PropertyComponent()
  58070. {
  58071. }
  58072. void PropertyComponent::paint (Graphics& g)
  58073. {
  58074. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58075. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58076. }
  58077. void PropertyComponent::resized()
  58078. {
  58079. if (getNumChildComponents() > 0)
  58080. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58081. }
  58082. void PropertyComponent::enablementChanged()
  58083. {
  58084. repaint();
  58085. }
  58086. END_JUCE_NAMESPACE
  58087. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58088. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58089. BEGIN_JUCE_NAMESPACE
  58090. class PropertySectionComponent : public Component
  58091. {
  58092. public:
  58093. PropertySectionComponent (const String& sectionTitle,
  58094. const Array <PropertyComponent*>& newProperties,
  58095. const bool sectionIsOpen_)
  58096. : Component (sectionTitle),
  58097. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58098. sectionIsOpen (sectionIsOpen_)
  58099. {
  58100. propertyComps.addArray (newProperties);
  58101. for (int i = propertyComps.size(); --i >= 0;)
  58102. {
  58103. addAndMakeVisible (propertyComps.getUnchecked(i));
  58104. propertyComps.getUnchecked(i)->refresh();
  58105. }
  58106. }
  58107. ~PropertySectionComponent()
  58108. {
  58109. propertyComps.clear();
  58110. }
  58111. void paint (Graphics& g)
  58112. {
  58113. if (titleHeight > 0)
  58114. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58115. }
  58116. void resized()
  58117. {
  58118. int y = titleHeight;
  58119. for (int i = 0; i < propertyComps.size(); ++i)
  58120. {
  58121. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  58122. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  58123. y = pec->getBottom();
  58124. }
  58125. }
  58126. int getPreferredHeight() const
  58127. {
  58128. int y = titleHeight;
  58129. if (isOpen())
  58130. {
  58131. for (int i = propertyComps.size(); --i >= 0;)
  58132. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  58133. }
  58134. return y;
  58135. }
  58136. void setOpen (const bool open)
  58137. {
  58138. if (sectionIsOpen != open)
  58139. {
  58140. sectionIsOpen = open;
  58141. for (int i = propertyComps.size(); --i >= 0;)
  58142. propertyComps.getUnchecked(i)->setVisible (open);
  58143. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58144. if (pp != 0)
  58145. pp->resized();
  58146. }
  58147. }
  58148. bool isOpen() const
  58149. {
  58150. return sectionIsOpen;
  58151. }
  58152. void refreshAll() const
  58153. {
  58154. for (int i = propertyComps.size(); --i >= 0;)
  58155. propertyComps.getUnchecked (i)->refresh();
  58156. }
  58157. void mouseUp (const MouseEvent& e)
  58158. {
  58159. if (e.getMouseDownX() < titleHeight
  58160. && e.x < titleHeight
  58161. && e.y < titleHeight
  58162. && e.getNumberOfClicks() != 2)
  58163. {
  58164. setOpen (! isOpen());
  58165. }
  58166. }
  58167. void mouseDoubleClick (const MouseEvent& e)
  58168. {
  58169. if (e.y < titleHeight)
  58170. setOpen (! isOpen());
  58171. }
  58172. private:
  58173. OwnedArray <PropertyComponent> propertyComps;
  58174. int titleHeight;
  58175. bool sectionIsOpen;
  58176. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58177. };
  58178. class PropertyPanel::PropertyHolderComponent : public Component
  58179. {
  58180. public:
  58181. PropertyHolderComponent() {}
  58182. void paint (Graphics&) {}
  58183. void updateLayout (int width)
  58184. {
  58185. int y = 0;
  58186. for (int i = 0; i < sections.size(); ++i)
  58187. {
  58188. PropertySectionComponent* const section = sections.getUnchecked(i);
  58189. section->setBounds (0, y, width, section->getPreferredHeight());
  58190. y = section->getBottom();
  58191. }
  58192. setSize (width, y);
  58193. repaint();
  58194. }
  58195. void refreshAll() const
  58196. {
  58197. for (int i = 0; i < sections.size(); ++i)
  58198. sections.getUnchecked(i)->refreshAll();
  58199. }
  58200. void clear()
  58201. {
  58202. sections.clear();
  58203. }
  58204. void addSection (PropertySectionComponent* newSection)
  58205. {
  58206. sections.add (newSection);
  58207. addAndMakeVisible (newSection, 0);
  58208. }
  58209. int getNumSections() const throw() { return sections.size(); }
  58210. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58211. private:
  58212. OwnedArray<PropertySectionComponent> sections;
  58213. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58214. };
  58215. PropertyPanel::PropertyPanel()
  58216. {
  58217. messageWhenEmpty = TRANS("(nothing selected)");
  58218. addAndMakeVisible (&viewport);
  58219. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58220. viewport.setFocusContainer (true);
  58221. }
  58222. PropertyPanel::~PropertyPanel()
  58223. {
  58224. clear();
  58225. }
  58226. void PropertyPanel::paint (Graphics& g)
  58227. {
  58228. if (propertyHolderComponent->getNumSections() == 0)
  58229. {
  58230. g.setColour (Colours::black.withAlpha (0.5f));
  58231. g.setFont (14.0f);
  58232. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58233. Justification::centred, true);
  58234. }
  58235. }
  58236. void PropertyPanel::resized()
  58237. {
  58238. viewport.setBounds (getLocalBounds());
  58239. updatePropHolderLayout();
  58240. }
  58241. void PropertyPanel::clear()
  58242. {
  58243. if (propertyHolderComponent->getNumSections() > 0)
  58244. {
  58245. propertyHolderComponent->clear();
  58246. repaint();
  58247. }
  58248. }
  58249. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58250. {
  58251. if (propertyHolderComponent->getNumSections() == 0)
  58252. repaint();
  58253. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58254. updatePropHolderLayout();
  58255. }
  58256. void PropertyPanel::addSection (const String& sectionTitle,
  58257. const Array <PropertyComponent*>& newProperties,
  58258. const bool shouldBeOpen)
  58259. {
  58260. jassert (sectionTitle.isNotEmpty());
  58261. if (propertyHolderComponent->getNumSections() == 0)
  58262. repaint();
  58263. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58264. updatePropHolderLayout();
  58265. }
  58266. void PropertyPanel::updatePropHolderLayout() const
  58267. {
  58268. const int maxWidth = viewport.getMaximumVisibleWidth();
  58269. propertyHolderComponent->updateLayout (maxWidth);
  58270. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58271. if (maxWidth != newMaxWidth)
  58272. {
  58273. // need to do this twice because of scrollbars changing the size, etc.
  58274. propertyHolderComponent->updateLayout (newMaxWidth);
  58275. }
  58276. }
  58277. void PropertyPanel::refreshAll() const
  58278. {
  58279. propertyHolderComponent->refreshAll();
  58280. }
  58281. const StringArray PropertyPanel::getSectionNames() const
  58282. {
  58283. StringArray s;
  58284. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58285. {
  58286. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58287. if (section->getName().isNotEmpty())
  58288. s.add (section->getName());
  58289. }
  58290. return s;
  58291. }
  58292. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58293. {
  58294. int index = 0;
  58295. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58296. {
  58297. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58298. if (section->getName().isNotEmpty())
  58299. {
  58300. if (index == sectionIndex)
  58301. return section->isOpen();
  58302. ++index;
  58303. }
  58304. }
  58305. return false;
  58306. }
  58307. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58308. {
  58309. int index = 0;
  58310. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58311. {
  58312. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58313. if (section->getName().isNotEmpty())
  58314. {
  58315. if (index == sectionIndex)
  58316. {
  58317. section->setOpen (shouldBeOpen);
  58318. break;
  58319. }
  58320. ++index;
  58321. }
  58322. }
  58323. }
  58324. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58325. {
  58326. int index = 0;
  58327. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58328. {
  58329. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58330. if (section->getName().isNotEmpty())
  58331. {
  58332. if (index == sectionIndex)
  58333. {
  58334. section->setEnabled (shouldBeEnabled);
  58335. break;
  58336. }
  58337. ++index;
  58338. }
  58339. }
  58340. }
  58341. XmlElement* PropertyPanel::getOpennessState() const
  58342. {
  58343. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58344. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58345. const StringArray sections (getSectionNames());
  58346. for (int i = 0; i < sections.size(); ++i)
  58347. {
  58348. if (sections[i].isNotEmpty())
  58349. {
  58350. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58351. e->setAttribute ("name", sections[i]);
  58352. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58353. }
  58354. }
  58355. return xml;
  58356. }
  58357. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58358. {
  58359. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58360. {
  58361. const StringArray sections (getSectionNames());
  58362. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58363. {
  58364. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58365. e->getBoolAttribute ("open"));
  58366. }
  58367. viewport.setViewPosition (viewport.getViewPositionX(),
  58368. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58369. }
  58370. }
  58371. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58372. {
  58373. if (messageWhenEmpty != newMessage)
  58374. {
  58375. messageWhenEmpty = newMessage;
  58376. repaint();
  58377. }
  58378. }
  58379. const String& PropertyPanel::getMessageWhenEmpty() const
  58380. {
  58381. return messageWhenEmpty;
  58382. }
  58383. END_JUCE_NAMESPACE
  58384. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58385. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58386. BEGIN_JUCE_NAMESPACE
  58387. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58388. const double rangeMin,
  58389. const double rangeMax,
  58390. const double interval,
  58391. const double skewFactor)
  58392. : PropertyComponent (name)
  58393. {
  58394. addAndMakeVisible (&slider);
  58395. slider.setRange (rangeMin, rangeMax, interval);
  58396. slider.setSkewFactor (skewFactor);
  58397. slider.setSliderStyle (Slider::LinearBar);
  58398. slider.addListener (this);
  58399. }
  58400. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58401. const String& name,
  58402. const double rangeMin,
  58403. const double rangeMax,
  58404. const double interval,
  58405. const double skewFactor)
  58406. : PropertyComponent (name)
  58407. {
  58408. addAndMakeVisible (&slider);
  58409. slider.setRange (rangeMin, rangeMax, interval);
  58410. slider.setSkewFactor (skewFactor);
  58411. slider.setSliderStyle (Slider::LinearBar);
  58412. slider.getValueObject().referTo (valueToControl);
  58413. }
  58414. SliderPropertyComponent::~SliderPropertyComponent()
  58415. {
  58416. }
  58417. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58418. {
  58419. }
  58420. double SliderPropertyComponent::getValue() const
  58421. {
  58422. return slider.getValue();
  58423. }
  58424. void SliderPropertyComponent::refresh()
  58425. {
  58426. slider.setValue (getValue(), false);
  58427. }
  58428. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58429. {
  58430. if (getValue() != slider.getValue())
  58431. setValue (slider.getValue());
  58432. }
  58433. END_JUCE_NAMESPACE
  58434. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58435. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58436. BEGIN_JUCE_NAMESPACE
  58437. class TextPropLabel : public Label
  58438. {
  58439. public:
  58440. TextPropLabel (TextPropertyComponent& owner_,
  58441. const int maxChars_, const bool isMultiline_)
  58442. : Label (String::empty, String::empty),
  58443. owner (owner_),
  58444. maxChars (maxChars_),
  58445. isMultiline (isMultiline_)
  58446. {
  58447. setEditable (true, true, false);
  58448. setColour (backgroundColourId, Colours::white);
  58449. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58450. }
  58451. TextEditor* createEditorComponent()
  58452. {
  58453. TextEditor* const textEditor = Label::createEditorComponent();
  58454. textEditor->setInputRestrictions (maxChars);
  58455. if (isMultiline)
  58456. {
  58457. textEditor->setMultiLine (true, true);
  58458. textEditor->setReturnKeyStartsNewLine (true);
  58459. }
  58460. return textEditor;
  58461. }
  58462. void textWasEdited()
  58463. {
  58464. owner.textWasEdited();
  58465. }
  58466. private:
  58467. TextPropertyComponent& owner;
  58468. int maxChars;
  58469. bool isMultiline;
  58470. };
  58471. TextPropertyComponent::TextPropertyComponent (const String& name,
  58472. const int maxNumChars,
  58473. const bool isMultiLine)
  58474. : PropertyComponent (name)
  58475. {
  58476. createEditor (maxNumChars, isMultiLine);
  58477. }
  58478. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58479. const String& name,
  58480. const int maxNumChars,
  58481. const bool isMultiLine)
  58482. : PropertyComponent (name)
  58483. {
  58484. createEditor (maxNumChars, isMultiLine);
  58485. textEditor->getTextValue().referTo (valueToControl);
  58486. }
  58487. TextPropertyComponent::~TextPropertyComponent()
  58488. {
  58489. }
  58490. void TextPropertyComponent::setText (const String& newText)
  58491. {
  58492. textEditor->setText (newText, true);
  58493. }
  58494. const String TextPropertyComponent::getText() const
  58495. {
  58496. return textEditor->getText();
  58497. }
  58498. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58499. {
  58500. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58501. if (isMultiLine)
  58502. {
  58503. textEditor->setJustificationType (Justification::topLeft);
  58504. preferredHeight = 120;
  58505. }
  58506. }
  58507. void TextPropertyComponent::refresh()
  58508. {
  58509. textEditor->setText (getText(), false);
  58510. }
  58511. void TextPropertyComponent::textWasEdited()
  58512. {
  58513. const String newText (textEditor->getText());
  58514. if (getText() != newText)
  58515. setText (newText);
  58516. }
  58517. END_JUCE_NAMESPACE
  58518. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58519. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58520. BEGIN_JUCE_NAMESPACE
  58521. class SimpleDeviceManagerInputLevelMeter : public Component,
  58522. public Timer
  58523. {
  58524. public:
  58525. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58526. : manager (manager_),
  58527. level (0)
  58528. {
  58529. startTimer (50);
  58530. manager->enableInputLevelMeasurement (true);
  58531. }
  58532. ~SimpleDeviceManagerInputLevelMeter()
  58533. {
  58534. manager->enableInputLevelMeasurement (false);
  58535. }
  58536. void timerCallback()
  58537. {
  58538. const float newLevel = (float) manager->getCurrentInputLevel();
  58539. if (std::abs (level - newLevel) > 0.005f)
  58540. {
  58541. level = newLevel;
  58542. repaint();
  58543. }
  58544. }
  58545. void paint (Graphics& g)
  58546. {
  58547. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58548. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58549. }
  58550. private:
  58551. AudioDeviceManager* const manager;
  58552. float level;
  58553. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58554. };
  58555. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58556. public ListBoxModel
  58557. {
  58558. public:
  58559. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58560. const String& noItemsMessage_,
  58561. const int minNumber_,
  58562. const int maxNumber_)
  58563. : ListBox (String::empty, 0),
  58564. deviceManager (deviceManager_),
  58565. noItemsMessage (noItemsMessage_),
  58566. minNumber (minNumber_),
  58567. maxNumber (maxNumber_)
  58568. {
  58569. items = MidiInput::getDevices();
  58570. setModel (this);
  58571. setOutlineThickness (1);
  58572. }
  58573. ~MidiInputSelectorComponentListBox()
  58574. {
  58575. }
  58576. int getNumRows()
  58577. {
  58578. return items.size();
  58579. }
  58580. void paintListBoxItem (int row,
  58581. Graphics& g,
  58582. int width, int height,
  58583. bool rowIsSelected)
  58584. {
  58585. if (isPositiveAndBelow (row, items.size()))
  58586. {
  58587. if (rowIsSelected)
  58588. g.fillAll (findColour (TextEditor::highlightColourId)
  58589. .withMultipliedAlpha (0.3f));
  58590. const String item (items [row]);
  58591. bool enabled = deviceManager.isMidiInputEnabled (item);
  58592. const int x = getTickX();
  58593. const float tickW = height * 0.75f;
  58594. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58595. enabled, true, true, false);
  58596. g.setFont (height * 0.6f);
  58597. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58598. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58599. }
  58600. }
  58601. void listBoxItemClicked (int row, const MouseEvent& e)
  58602. {
  58603. selectRow (row);
  58604. if (e.x < getTickX())
  58605. flipEnablement (row);
  58606. }
  58607. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58608. {
  58609. flipEnablement (row);
  58610. }
  58611. void returnKeyPressed (int row)
  58612. {
  58613. flipEnablement (row);
  58614. }
  58615. void paint (Graphics& g)
  58616. {
  58617. ListBox::paint (g);
  58618. if (items.size() == 0)
  58619. {
  58620. g.setColour (Colours::grey);
  58621. g.setFont (13.0f);
  58622. g.drawText (noItemsMessage,
  58623. 0, 0, getWidth(), getHeight() / 2,
  58624. Justification::centred, true);
  58625. }
  58626. }
  58627. int getBestHeight (const int preferredHeight)
  58628. {
  58629. const int extra = getOutlineThickness() * 2;
  58630. return jmax (getRowHeight() * 2 + extra,
  58631. jmin (getRowHeight() * getNumRows() + extra,
  58632. preferredHeight));
  58633. }
  58634. private:
  58635. AudioDeviceManager& deviceManager;
  58636. const String noItemsMessage;
  58637. StringArray items;
  58638. int minNumber, maxNumber;
  58639. void flipEnablement (const int row)
  58640. {
  58641. if (isPositiveAndBelow (row, items.size()))
  58642. {
  58643. const String item (items [row]);
  58644. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58645. }
  58646. }
  58647. int getTickX() const
  58648. {
  58649. return getRowHeight() + 5;
  58650. }
  58651. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58652. };
  58653. class AudioDeviceSettingsPanel : public Component,
  58654. public ChangeListener,
  58655. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58656. public ButtonListener
  58657. {
  58658. public:
  58659. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58660. AudioIODeviceType::DeviceSetupDetails& setup_,
  58661. const bool hideAdvancedOptionsWithButton)
  58662. : type (type_),
  58663. setup (setup_)
  58664. {
  58665. if (hideAdvancedOptionsWithButton)
  58666. {
  58667. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58668. showAdvancedSettingsButton->addListener (this);
  58669. }
  58670. type->scanForDevices();
  58671. setup.manager->addChangeListener (this);
  58672. changeListenerCallback (0);
  58673. }
  58674. ~AudioDeviceSettingsPanel()
  58675. {
  58676. setup.manager->removeChangeListener (this);
  58677. }
  58678. void resized()
  58679. {
  58680. const int lx = proportionOfWidth (0.35f);
  58681. const int w = proportionOfWidth (0.4f);
  58682. const int h = 24;
  58683. const int space = 6;
  58684. const int dh = h + space;
  58685. int y = 0;
  58686. if (outputDeviceDropDown != 0)
  58687. {
  58688. outputDeviceDropDown->setBounds (lx, y, w, h);
  58689. if (testButton != 0)
  58690. testButton->setBounds (proportionOfWidth (0.77f),
  58691. outputDeviceDropDown->getY(),
  58692. proportionOfWidth (0.18f),
  58693. h);
  58694. y += dh;
  58695. }
  58696. if (inputDeviceDropDown != 0)
  58697. {
  58698. inputDeviceDropDown->setBounds (lx, y, w, h);
  58699. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58700. inputDeviceDropDown->getY(),
  58701. proportionOfWidth (0.18f),
  58702. h);
  58703. y += dh;
  58704. }
  58705. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58706. if (outputChanList != 0)
  58707. {
  58708. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58709. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58710. y += bh + space;
  58711. }
  58712. if (inputChanList != 0)
  58713. {
  58714. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58715. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58716. y += bh + space;
  58717. }
  58718. y += space * 2;
  58719. if (showAdvancedSettingsButton != 0)
  58720. {
  58721. showAdvancedSettingsButton->changeWidthToFitText (h);
  58722. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58723. }
  58724. if (sampleRateDropDown != 0)
  58725. {
  58726. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58727. || ! showAdvancedSettingsButton->isVisible());
  58728. sampleRateDropDown->setBounds (lx, y, w, h);
  58729. y += dh;
  58730. }
  58731. if (bufferSizeDropDown != 0)
  58732. {
  58733. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58734. || ! showAdvancedSettingsButton->isVisible());
  58735. bufferSizeDropDown->setBounds (lx, y, w, h);
  58736. y += dh;
  58737. }
  58738. if (showUIButton != 0)
  58739. {
  58740. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58741. || ! showAdvancedSettingsButton->isVisible());
  58742. showUIButton->changeWidthToFitText (h);
  58743. showUIButton->setTopLeftPosition (lx, y);
  58744. }
  58745. }
  58746. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58747. {
  58748. if (comboBoxThatHasChanged == 0)
  58749. return;
  58750. AudioDeviceManager::AudioDeviceSetup config;
  58751. setup.manager->getAudioDeviceSetup (config);
  58752. String error;
  58753. if (comboBoxThatHasChanged == outputDeviceDropDown
  58754. || comboBoxThatHasChanged == inputDeviceDropDown)
  58755. {
  58756. if (outputDeviceDropDown != 0)
  58757. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58758. : outputDeviceDropDown->getText();
  58759. if (inputDeviceDropDown != 0)
  58760. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58761. : inputDeviceDropDown->getText();
  58762. if (! type->hasSeparateInputsAndOutputs())
  58763. config.inputDeviceName = config.outputDeviceName;
  58764. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58765. config.useDefaultInputChannels = true;
  58766. else
  58767. config.useDefaultOutputChannels = true;
  58768. error = setup.manager->setAudioDeviceSetup (config, true);
  58769. showCorrectDeviceName (inputDeviceDropDown, true);
  58770. showCorrectDeviceName (outputDeviceDropDown, false);
  58771. updateControlPanelButton();
  58772. resized();
  58773. }
  58774. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58775. {
  58776. if (sampleRateDropDown->getSelectedId() > 0)
  58777. {
  58778. config.sampleRate = sampleRateDropDown->getSelectedId();
  58779. error = setup.manager->setAudioDeviceSetup (config, true);
  58780. }
  58781. }
  58782. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58783. {
  58784. if (bufferSizeDropDown->getSelectedId() > 0)
  58785. {
  58786. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58787. error = setup.manager->setAudioDeviceSetup (config, true);
  58788. }
  58789. }
  58790. if (error.isNotEmpty())
  58791. {
  58792. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58793. "Error when trying to open audio device!",
  58794. error);
  58795. }
  58796. }
  58797. void buttonClicked (Button* button)
  58798. {
  58799. if (button == showAdvancedSettingsButton)
  58800. {
  58801. showAdvancedSettingsButton->setVisible (false);
  58802. resized();
  58803. }
  58804. else if (button == showUIButton)
  58805. {
  58806. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58807. if (device != 0 && device->showControlPanel())
  58808. {
  58809. setup.manager->closeAudioDevice();
  58810. setup.manager->restartLastAudioDevice();
  58811. getTopLevelComponent()->toFront (true);
  58812. }
  58813. }
  58814. else if (button == testButton && testButton != 0)
  58815. {
  58816. setup.manager->playTestSound();
  58817. }
  58818. }
  58819. void updateControlPanelButton()
  58820. {
  58821. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58822. showUIButton = 0;
  58823. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58824. {
  58825. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58826. TRANS ("opens the device's own control panel")));
  58827. showUIButton->addListener (this);
  58828. }
  58829. resized();
  58830. }
  58831. void changeListenerCallback (ChangeBroadcaster*)
  58832. {
  58833. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58834. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58835. {
  58836. if (outputDeviceDropDown == 0)
  58837. {
  58838. outputDeviceDropDown = new ComboBox (String::empty);
  58839. outputDeviceDropDown->addListener (this);
  58840. addAndMakeVisible (outputDeviceDropDown);
  58841. outputDeviceLabel = new Label (String::empty,
  58842. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58843. : TRANS ("device:"));
  58844. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58845. if (setup.maxNumOutputChannels > 0)
  58846. {
  58847. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58848. testButton->addListener (this);
  58849. }
  58850. }
  58851. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58852. }
  58853. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58854. {
  58855. if (inputDeviceDropDown == 0)
  58856. {
  58857. inputDeviceDropDown = new ComboBox (String::empty);
  58858. inputDeviceDropDown->addListener (this);
  58859. addAndMakeVisible (inputDeviceDropDown);
  58860. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58861. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58862. addAndMakeVisible (inputLevelMeter
  58863. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58864. }
  58865. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58866. }
  58867. updateControlPanelButton();
  58868. showCorrectDeviceName (inputDeviceDropDown, true);
  58869. showCorrectDeviceName (outputDeviceDropDown, false);
  58870. if (currentDevice != 0)
  58871. {
  58872. if (setup.maxNumOutputChannels > 0
  58873. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58874. {
  58875. if (outputChanList == 0)
  58876. {
  58877. addAndMakeVisible (outputChanList
  58878. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58879. TRANS ("(no audio output channels found)")));
  58880. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58881. outputChanLabel->attachToComponent (outputChanList, true);
  58882. }
  58883. outputChanList->refresh();
  58884. }
  58885. else
  58886. {
  58887. outputChanLabel = 0;
  58888. outputChanList = 0;
  58889. }
  58890. if (setup.maxNumInputChannels > 0
  58891. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58892. {
  58893. if (inputChanList == 0)
  58894. {
  58895. addAndMakeVisible (inputChanList
  58896. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58897. TRANS ("(no audio input channels found)")));
  58898. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58899. inputChanLabel->attachToComponent (inputChanList, true);
  58900. }
  58901. inputChanList->refresh();
  58902. }
  58903. else
  58904. {
  58905. inputChanLabel = 0;
  58906. inputChanList = 0;
  58907. }
  58908. // sample rate..
  58909. {
  58910. if (sampleRateDropDown == 0)
  58911. {
  58912. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58913. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58914. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58915. }
  58916. else
  58917. {
  58918. sampleRateDropDown->clear();
  58919. sampleRateDropDown->removeListener (this);
  58920. }
  58921. const int numRates = currentDevice->getNumSampleRates();
  58922. for (int i = 0; i < numRates; ++i)
  58923. {
  58924. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58925. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58926. }
  58927. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58928. sampleRateDropDown->addListener (this);
  58929. }
  58930. // buffer size
  58931. {
  58932. if (bufferSizeDropDown == 0)
  58933. {
  58934. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58935. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58936. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58937. }
  58938. else
  58939. {
  58940. bufferSizeDropDown->clear();
  58941. bufferSizeDropDown->removeListener (this);
  58942. }
  58943. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58944. double currentRate = currentDevice->getCurrentSampleRate();
  58945. if (currentRate == 0)
  58946. currentRate = 48000.0;
  58947. for (int i = 0; i < numBufferSizes; ++i)
  58948. {
  58949. const int bs = currentDevice->getBufferSizeSamples (i);
  58950. bufferSizeDropDown->addItem (String (bs)
  58951. + " samples ("
  58952. + String (bs * 1000.0 / currentRate, 1)
  58953. + " ms)",
  58954. bs);
  58955. }
  58956. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58957. bufferSizeDropDown->addListener (this);
  58958. }
  58959. }
  58960. else
  58961. {
  58962. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58963. sampleRateLabel = 0;
  58964. bufferSizeLabel = 0;
  58965. sampleRateDropDown = 0;
  58966. bufferSizeDropDown = 0;
  58967. if (outputDeviceDropDown != 0)
  58968. outputDeviceDropDown->setSelectedId (-1, true);
  58969. if (inputDeviceDropDown != 0)
  58970. inputDeviceDropDown->setSelectedId (-1, true);
  58971. }
  58972. resized();
  58973. setSize (getWidth(), getLowestY() + 4);
  58974. }
  58975. private:
  58976. AudioIODeviceType* const type;
  58977. const AudioIODeviceType::DeviceSetupDetails setup;
  58978. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58979. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58980. ScopedPointer<TextButton> testButton;
  58981. ScopedPointer<Component> inputLevelMeter;
  58982. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58983. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58984. {
  58985. if (box != 0)
  58986. {
  58987. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58988. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58989. box->setSelectedId (index + 1, true);
  58990. if (testButton != 0 && ! isInput)
  58991. testButton->setEnabled (index >= 0);
  58992. }
  58993. }
  58994. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58995. {
  58996. const StringArray devs (type->getDeviceNames (isInputs));
  58997. combo.clear (true);
  58998. for (int i = 0; i < devs.size(); ++i)
  58999. combo.addItem (devs[i], i + 1);
  59000. combo.addItem (TRANS("<< none >>"), -1);
  59001. combo.setSelectedId (-1, true);
  59002. }
  59003. int getLowestY() const
  59004. {
  59005. int y = 0;
  59006. for (int i = getNumChildComponents(); --i >= 0;)
  59007. y = jmax (y, getChildComponent (i)->getBottom());
  59008. return y;
  59009. }
  59010. public:
  59011. class ChannelSelectorListBox : public ListBox,
  59012. public ListBoxModel
  59013. {
  59014. public:
  59015. enum BoxType
  59016. {
  59017. audioInputType,
  59018. audioOutputType
  59019. };
  59020. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59021. const BoxType type_,
  59022. const String& noItemsMessage_)
  59023. : ListBox (String::empty, 0),
  59024. setup (setup_),
  59025. type (type_),
  59026. noItemsMessage (noItemsMessage_)
  59027. {
  59028. refresh();
  59029. setModel (this);
  59030. setOutlineThickness (1);
  59031. }
  59032. ~ChannelSelectorListBox()
  59033. {
  59034. }
  59035. void refresh()
  59036. {
  59037. items.clear();
  59038. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59039. if (currentDevice != 0)
  59040. {
  59041. if (type == audioInputType)
  59042. items = currentDevice->getInputChannelNames();
  59043. else if (type == audioOutputType)
  59044. items = currentDevice->getOutputChannelNames();
  59045. if (setup.useStereoPairs)
  59046. {
  59047. StringArray pairs;
  59048. for (int i = 0; i < items.size(); i += 2)
  59049. {
  59050. const String name (items[i]);
  59051. const String name2 (items[i + 1]);
  59052. String commonBit;
  59053. for (int j = 0; j < name.length(); ++j)
  59054. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59055. commonBit = name.substring (0, j);
  59056. // Make sure we only split the name at a space, because otherwise, things
  59057. // like "input 11" + "input 12" would become "input 11 + 2"
  59058. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59059. commonBit = commonBit.dropLastCharacters (1);
  59060. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59061. }
  59062. items = pairs;
  59063. }
  59064. }
  59065. updateContent();
  59066. repaint();
  59067. }
  59068. int getNumRows()
  59069. {
  59070. return items.size();
  59071. }
  59072. void paintListBoxItem (int row,
  59073. Graphics& g,
  59074. int width, int height,
  59075. bool rowIsSelected)
  59076. {
  59077. if (isPositiveAndBelow (row, items.size()))
  59078. {
  59079. if (rowIsSelected)
  59080. g.fillAll (findColour (TextEditor::highlightColourId)
  59081. .withMultipliedAlpha (0.3f));
  59082. const String item (items [row]);
  59083. bool enabled = false;
  59084. AudioDeviceManager::AudioDeviceSetup config;
  59085. setup.manager->getAudioDeviceSetup (config);
  59086. if (setup.useStereoPairs)
  59087. {
  59088. if (type == audioInputType)
  59089. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59090. else if (type == audioOutputType)
  59091. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59092. }
  59093. else
  59094. {
  59095. if (type == audioInputType)
  59096. enabled = config.inputChannels [row];
  59097. else if (type == audioOutputType)
  59098. enabled = config.outputChannels [row];
  59099. }
  59100. const int x = getTickX();
  59101. const float tickW = height * 0.75f;
  59102. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59103. enabled, true, true, false);
  59104. g.setFont (height * 0.6f);
  59105. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59106. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59107. }
  59108. }
  59109. void listBoxItemClicked (int row, const MouseEvent& e)
  59110. {
  59111. selectRow (row);
  59112. if (e.x < getTickX())
  59113. flipEnablement (row);
  59114. }
  59115. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59116. {
  59117. flipEnablement (row);
  59118. }
  59119. void returnKeyPressed (int row)
  59120. {
  59121. flipEnablement (row);
  59122. }
  59123. void paint (Graphics& g)
  59124. {
  59125. ListBox::paint (g);
  59126. if (items.size() == 0)
  59127. {
  59128. g.setColour (Colours::grey);
  59129. g.setFont (13.0f);
  59130. g.drawText (noItemsMessage,
  59131. 0, 0, getWidth(), getHeight() / 2,
  59132. Justification::centred, true);
  59133. }
  59134. }
  59135. int getBestHeight (int maxHeight)
  59136. {
  59137. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59138. getNumRows())
  59139. + getOutlineThickness() * 2;
  59140. }
  59141. private:
  59142. const AudioIODeviceType::DeviceSetupDetails setup;
  59143. const BoxType type;
  59144. const String noItemsMessage;
  59145. StringArray items;
  59146. void flipEnablement (const int row)
  59147. {
  59148. jassert (type == audioInputType || type == audioOutputType);
  59149. if (isPositiveAndBelow (row, items.size()))
  59150. {
  59151. AudioDeviceManager::AudioDeviceSetup config;
  59152. setup.manager->getAudioDeviceSetup (config);
  59153. if (setup.useStereoPairs)
  59154. {
  59155. BigInteger bits;
  59156. BigInteger& original = (type == audioInputType ? config.inputChannels
  59157. : config.outputChannels);
  59158. int i;
  59159. for (i = 0; i < 256; i += 2)
  59160. bits.setBit (i / 2, original [i] || original [i + 1]);
  59161. if (type == audioInputType)
  59162. {
  59163. config.useDefaultInputChannels = false;
  59164. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59165. }
  59166. else
  59167. {
  59168. config.useDefaultOutputChannels = false;
  59169. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59170. }
  59171. for (i = 0; i < 256; ++i)
  59172. original.setBit (i, bits [i / 2]);
  59173. }
  59174. else
  59175. {
  59176. if (type == audioInputType)
  59177. {
  59178. config.useDefaultInputChannels = false;
  59179. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59180. }
  59181. else
  59182. {
  59183. config.useDefaultOutputChannels = false;
  59184. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59185. }
  59186. }
  59187. String error (setup.manager->setAudioDeviceSetup (config, true));
  59188. if (! error.isEmpty())
  59189. {
  59190. //xxx
  59191. }
  59192. }
  59193. }
  59194. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59195. {
  59196. const int numActive = chans.countNumberOfSetBits();
  59197. if (chans [index])
  59198. {
  59199. if (numActive > minNumber)
  59200. chans.setBit (index, false);
  59201. }
  59202. else
  59203. {
  59204. if (numActive >= maxNumber)
  59205. {
  59206. const int firstActiveChan = chans.findNextSetBit();
  59207. chans.setBit (index > firstActiveChan
  59208. ? firstActiveChan : chans.getHighestBit(),
  59209. false);
  59210. }
  59211. chans.setBit (index, true);
  59212. }
  59213. }
  59214. int getTickX() const
  59215. {
  59216. return getRowHeight() + 5;
  59217. }
  59218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59219. };
  59220. private:
  59221. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59222. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59223. };
  59224. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59225. const int minInputChannels_,
  59226. const int maxInputChannels_,
  59227. const int minOutputChannels_,
  59228. const int maxOutputChannels_,
  59229. const bool showMidiInputOptions,
  59230. const bool showMidiOutputSelector,
  59231. const bool showChannelsAsStereoPairs_,
  59232. const bool hideAdvancedOptionsWithButton_)
  59233. : deviceManager (deviceManager_),
  59234. deviceTypeDropDown (0),
  59235. deviceTypeDropDownLabel (0),
  59236. minOutputChannels (minOutputChannels_),
  59237. maxOutputChannels (maxOutputChannels_),
  59238. minInputChannels (minInputChannels_),
  59239. maxInputChannels (maxInputChannels_),
  59240. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59241. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59242. {
  59243. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59244. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59245. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59246. {
  59247. deviceTypeDropDown = new ComboBox (String::empty);
  59248. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59249. {
  59250. deviceTypeDropDown
  59251. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59252. i + 1);
  59253. }
  59254. addAndMakeVisible (deviceTypeDropDown);
  59255. deviceTypeDropDown->addListener (this);
  59256. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59257. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59258. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59259. }
  59260. if (showMidiInputOptions)
  59261. {
  59262. addAndMakeVisible (midiInputsList
  59263. = new MidiInputSelectorComponentListBox (deviceManager,
  59264. TRANS("(no midi inputs available)"),
  59265. 0, 0));
  59266. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59267. midiInputsLabel->setJustificationType (Justification::topRight);
  59268. midiInputsLabel->attachToComponent (midiInputsList, true);
  59269. }
  59270. else
  59271. {
  59272. midiInputsList = 0;
  59273. midiInputsLabel = 0;
  59274. }
  59275. if (showMidiOutputSelector)
  59276. {
  59277. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59278. midiOutputSelector->addListener (this);
  59279. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59280. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59281. }
  59282. else
  59283. {
  59284. midiOutputSelector = 0;
  59285. midiOutputLabel = 0;
  59286. }
  59287. deviceManager_.addChangeListener (this);
  59288. changeListenerCallback (0);
  59289. }
  59290. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59291. {
  59292. deviceManager.removeChangeListener (this);
  59293. }
  59294. void AudioDeviceSelectorComponent::resized()
  59295. {
  59296. const int lx = proportionOfWidth (0.35f);
  59297. const int w = proportionOfWidth (0.4f);
  59298. const int h = 24;
  59299. const int space = 6;
  59300. const int dh = h + space;
  59301. int y = 15;
  59302. if (deviceTypeDropDown != 0)
  59303. {
  59304. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59305. y += dh + space * 2;
  59306. }
  59307. if (audioDeviceSettingsComp != 0)
  59308. {
  59309. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59310. y += audioDeviceSettingsComp->getHeight() + space;
  59311. }
  59312. if (midiInputsList != 0)
  59313. {
  59314. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59315. midiInputsList->setBounds (lx, y, w, bh);
  59316. y += bh + space;
  59317. }
  59318. if (midiOutputSelector != 0)
  59319. midiOutputSelector->setBounds (lx, y, w, h);
  59320. }
  59321. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59322. {
  59323. if (child == audioDeviceSettingsComp)
  59324. resized();
  59325. }
  59326. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59327. {
  59328. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59329. if (device != 0 && device->hasControlPanel())
  59330. {
  59331. if (device->showControlPanel())
  59332. deviceManager.restartLastAudioDevice();
  59333. getTopLevelComponent()->toFront (true);
  59334. }
  59335. }
  59336. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59337. {
  59338. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59339. {
  59340. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59341. if (type != 0)
  59342. {
  59343. audioDeviceSettingsComp = 0;
  59344. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59345. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59346. }
  59347. }
  59348. else if (comboBoxThatHasChanged == midiOutputSelector)
  59349. {
  59350. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59351. }
  59352. }
  59353. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59354. {
  59355. if (deviceTypeDropDown != 0)
  59356. {
  59357. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59358. }
  59359. if (audioDeviceSettingsComp == 0
  59360. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59361. {
  59362. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59363. audioDeviceSettingsComp = 0;
  59364. AudioIODeviceType* const type
  59365. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59366. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59367. if (type != 0)
  59368. {
  59369. AudioIODeviceType::DeviceSetupDetails details;
  59370. details.manager = &deviceManager;
  59371. details.minNumInputChannels = minInputChannels;
  59372. details.maxNumInputChannels = maxInputChannels;
  59373. details.minNumOutputChannels = minOutputChannels;
  59374. details.maxNumOutputChannels = maxOutputChannels;
  59375. details.useStereoPairs = showChannelsAsStereoPairs;
  59376. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59377. if (audioDeviceSettingsComp != 0)
  59378. {
  59379. addAndMakeVisible (audioDeviceSettingsComp);
  59380. audioDeviceSettingsComp->resized();
  59381. }
  59382. }
  59383. }
  59384. if (midiInputsList != 0)
  59385. {
  59386. midiInputsList->updateContent();
  59387. midiInputsList->repaint();
  59388. }
  59389. if (midiOutputSelector != 0)
  59390. {
  59391. midiOutputSelector->clear();
  59392. const StringArray midiOuts (MidiOutput::getDevices());
  59393. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59394. midiOutputSelector->addSeparator();
  59395. for (int i = 0; i < midiOuts.size(); ++i)
  59396. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59397. int current = -1;
  59398. if (deviceManager.getDefaultMidiOutput() != 0)
  59399. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59400. midiOutputSelector->setSelectedId (current, true);
  59401. }
  59402. resized();
  59403. }
  59404. END_JUCE_NAMESPACE
  59405. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59406. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59407. BEGIN_JUCE_NAMESPACE
  59408. BubbleComponent::BubbleComponent()
  59409. : side (0),
  59410. allowablePlacements (above | below | left | right),
  59411. arrowTipX (0.0f),
  59412. arrowTipY (0.0f)
  59413. {
  59414. setInterceptsMouseClicks (false, false);
  59415. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59416. setComponentEffect (&shadow);
  59417. }
  59418. BubbleComponent::~BubbleComponent()
  59419. {
  59420. }
  59421. void BubbleComponent::paint (Graphics& g)
  59422. {
  59423. int x = content.getX();
  59424. int y = content.getY();
  59425. int w = content.getWidth();
  59426. int h = content.getHeight();
  59427. int cw, ch;
  59428. getContentSize (cw, ch);
  59429. if (side == 3)
  59430. x += w - cw;
  59431. else if (side != 1)
  59432. x += (w - cw) / 2;
  59433. w = cw;
  59434. if (side == 2)
  59435. y += h - ch;
  59436. else if (side != 0)
  59437. y += (h - ch) / 2;
  59438. h = ch;
  59439. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59440. (float) x, (float) y,
  59441. (float) w, (float) h);
  59442. const int cx = x + (w - cw) / 2;
  59443. const int cy = y + (h - ch) / 2;
  59444. const int indent = 3;
  59445. g.setOrigin (cx + indent, cy + indent);
  59446. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59447. paintContent (g, cw - indent * 2, ch - indent * 2);
  59448. }
  59449. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59450. {
  59451. allowablePlacements = newPlacement;
  59452. }
  59453. void BubbleComponent::setPosition (Component* componentToPointTo)
  59454. {
  59455. jassert (componentToPointTo != 0);
  59456. Point<int> pos;
  59457. if (getParentComponent() != 0)
  59458. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59459. else
  59460. pos = componentToPointTo->localPointToGlobal (pos);
  59461. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59462. }
  59463. void BubbleComponent::setPosition (const int arrowTipX_,
  59464. const int arrowTipY_)
  59465. {
  59466. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59467. }
  59468. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59469. {
  59470. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59471. : getParentMonitorArea());
  59472. int x = 0;
  59473. int y = 0;
  59474. int w = 150;
  59475. int h = 30;
  59476. getContentSize (w, h);
  59477. w += 30;
  59478. h += 30;
  59479. const float edgeIndent = 2.0f;
  59480. const int arrowLength = jmin (10, h / 3, w / 3);
  59481. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59482. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59483. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59484. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59485. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59486. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59487. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59488. {
  59489. spaceLeft = spaceRight = 0;
  59490. }
  59491. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59492. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59493. {
  59494. spaceAbove = spaceBelow = 0;
  59495. }
  59496. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59497. {
  59498. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59499. arrowTipX = w * 0.5f;
  59500. content.setSize (w, h - arrowLength);
  59501. if (spaceAbove >= spaceBelow)
  59502. {
  59503. // above
  59504. y = rectangleToPointTo.getY() - h;
  59505. content.setPosition (0, 0);
  59506. arrowTipY = h - edgeIndent;
  59507. side = 2;
  59508. }
  59509. else
  59510. {
  59511. // below
  59512. y = rectangleToPointTo.getBottom();
  59513. content.setPosition (0, arrowLength);
  59514. arrowTipY = edgeIndent;
  59515. side = 0;
  59516. }
  59517. }
  59518. else
  59519. {
  59520. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59521. arrowTipY = h * 0.5f;
  59522. content.setSize (w - arrowLength, h);
  59523. if (spaceLeft > spaceRight)
  59524. {
  59525. // on the left
  59526. x = rectangleToPointTo.getX() - w;
  59527. content.setPosition (0, 0);
  59528. arrowTipX = w - edgeIndent;
  59529. side = 3;
  59530. }
  59531. else
  59532. {
  59533. // on the right
  59534. x = rectangleToPointTo.getRight();
  59535. content.setPosition (arrowLength, 0);
  59536. arrowTipX = edgeIndent;
  59537. side = 1;
  59538. }
  59539. }
  59540. setBounds (x, y, w, h);
  59541. }
  59542. END_JUCE_NAMESPACE
  59543. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59544. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59545. BEGIN_JUCE_NAMESPACE
  59546. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59547. : fadeOutLength (fadeOutLengthMs),
  59548. deleteAfterUse (false)
  59549. {
  59550. }
  59551. BubbleMessageComponent::~BubbleMessageComponent()
  59552. {
  59553. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59554. }
  59555. void BubbleMessageComponent::showAt (int x, int y,
  59556. const String& text,
  59557. const int numMillisecondsBeforeRemoving,
  59558. const bool removeWhenMouseClicked,
  59559. const bool deleteSelfAfterUse)
  59560. {
  59561. textLayout.clear();
  59562. textLayout.setText (text, Font (14.0f));
  59563. textLayout.layout (256, Justification::centredLeft, true);
  59564. setPosition (x, y);
  59565. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59566. }
  59567. void BubbleMessageComponent::showAt (Component* const component,
  59568. const String& text,
  59569. const int numMillisecondsBeforeRemoving,
  59570. const bool removeWhenMouseClicked,
  59571. const bool deleteSelfAfterUse)
  59572. {
  59573. textLayout.clear();
  59574. textLayout.setText (text, Font (14.0f));
  59575. textLayout.layout (256, Justification::centredLeft, true);
  59576. setPosition (component);
  59577. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59578. }
  59579. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59580. const bool removeWhenMouseClicked,
  59581. const bool deleteSelfAfterUse)
  59582. {
  59583. setVisible (true);
  59584. deleteAfterUse = deleteSelfAfterUse;
  59585. if (numMillisecondsBeforeRemoving > 0)
  59586. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59587. else
  59588. expiryTime = 0;
  59589. startTimer (77);
  59590. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59591. if (! (removeWhenMouseClicked && isShowing()))
  59592. mouseClickCounter += 0xfffff;
  59593. repaint();
  59594. }
  59595. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59596. {
  59597. w = textLayout.getWidth() + 16;
  59598. h = textLayout.getHeight() + 16;
  59599. }
  59600. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59601. {
  59602. g.setColour (findColour (TooltipWindow::textColourId));
  59603. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59604. }
  59605. void BubbleMessageComponent::timerCallback()
  59606. {
  59607. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59608. {
  59609. stopTimer();
  59610. setVisible (false);
  59611. if (deleteAfterUse)
  59612. delete this;
  59613. }
  59614. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59615. {
  59616. stopTimer();
  59617. if (deleteAfterUse)
  59618. delete this;
  59619. else
  59620. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59621. }
  59622. }
  59623. END_JUCE_NAMESPACE
  59624. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59625. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59626. BEGIN_JUCE_NAMESPACE
  59627. class ColourComponentSlider : public Slider
  59628. {
  59629. public:
  59630. ColourComponentSlider (const String& name)
  59631. : Slider (name)
  59632. {
  59633. setRange (0.0, 255.0, 1.0);
  59634. }
  59635. const String getTextFromValue (double value)
  59636. {
  59637. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59638. }
  59639. double getValueFromText (const String& text)
  59640. {
  59641. return (double) text.getHexValue32();
  59642. }
  59643. private:
  59644. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59645. };
  59646. class ColourSpaceMarker : public Component
  59647. {
  59648. public:
  59649. ColourSpaceMarker()
  59650. {
  59651. setInterceptsMouseClicks (false, false);
  59652. }
  59653. void paint (Graphics& g)
  59654. {
  59655. g.setColour (Colour::greyLevel (0.1f));
  59656. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59657. g.setColour (Colour::greyLevel (0.9f));
  59658. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59659. }
  59660. private:
  59661. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59662. };
  59663. class ColourSelector::ColourSpaceView : public Component
  59664. {
  59665. public:
  59666. ColourSpaceView (ColourSelector& owner_,
  59667. float& h_, float& s_, float& v_,
  59668. const int edgeSize)
  59669. : owner (owner_),
  59670. h (h_), s (s_), v (v_),
  59671. lastHue (0.0f),
  59672. edge (edgeSize)
  59673. {
  59674. addAndMakeVisible (&marker);
  59675. setMouseCursor (MouseCursor::CrosshairCursor);
  59676. }
  59677. void paint (Graphics& g)
  59678. {
  59679. if (colours.isNull())
  59680. {
  59681. const int width = getWidth() / 2;
  59682. const int height = getHeight() / 2;
  59683. colours = Image (Image::RGB, width, height, false);
  59684. Image::BitmapData pixels (colours, true);
  59685. for (int y = 0; y < height; ++y)
  59686. {
  59687. const float val = 1.0f - y / (float) height;
  59688. for (int x = 0; x < width; ++x)
  59689. {
  59690. const float sat = x / (float) width;
  59691. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59692. }
  59693. }
  59694. }
  59695. g.setOpacity (1.0f);
  59696. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59697. 0, 0, colours.getWidth(), colours.getHeight());
  59698. }
  59699. void mouseDown (const MouseEvent& e)
  59700. {
  59701. mouseDrag (e);
  59702. }
  59703. void mouseDrag (const MouseEvent& e)
  59704. {
  59705. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59706. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59707. owner.setSV (sat, val);
  59708. }
  59709. void updateIfNeeded()
  59710. {
  59711. if (lastHue != h)
  59712. {
  59713. lastHue = h;
  59714. colours = Image::null;
  59715. repaint();
  59716. }
  59717. updateMarker();
  59718. }
  59719. void resized()
  59720. {
  59721. colours = Image::null;
  59722. updateMarker();
  59723. }
  59724. private:
  59725. ColourSelector& owner;
  59726. float& h;
  59727. float& s;
  59728. float& v;
  59729. float lastHue;
  59730. ColourSpaceMarker marker;
  59731. const int edge;
  59732. Image colours;
  59733. void updateMarker()
  59734. {
  59735. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59736. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59737. edge * 2, edge * 2);
  59738. }
  59739. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59740. };
  59741. class HueSelectorMarker : public Component
  59742. {
  59743. public:
  59744. HueSelectorMarker()
  59745. {
  59746. setInterceptsMouseClicks (false, false);
  59747. }
  59748. void paint (Graphics& g)
  59749. {
  59750. Path p;
  59751. p.addTriangle (1.0f, 1.0f,
  59752. getWidth() * 0.3f, getHeight() * 0.5f,
  59753. 1.0f, getHeight() - 1.0f);
  59754. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59755. getWidth() * 0.7f, getHeight() * 0.5f,
  59756. getWidth() - 1.0f, getHeight() - 1.0f);
  59757. g.setColour (Colours::white.withAlpha (0.75f));
  59758. g.fillPath (p);
  59759. g.setColour (Colours::black.withAlpha (0.75f));
  59760. g.strokePath (p, PathStrokeType (1.2f));
  59761. }
  59762. private:
  59763. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59764. };
  59765. class ColourSelector::HueSelectorComp : public Component
  59766. {
  59767. public:
  59768. HueSelectorComp (ColourSelector& owner_,
  59769. float& h_, float& s_, float& v_,
  59770. const int edgeSize)
  59771. : owner (owner_),
  59772. h (h_), s (s_), v (v_),
  59773. lastHue (0.0f),
  59774. edge (edgeSize)
  59775. {
  59776. addAndMakeVisible (&marker);
  59777. }
  59778. void paint (Graphics& g)
  59779. {
  59780. const float yScale = 1.0f / (getHeight() - edge * 2);
  59781. const Rectangle<int> clip (g.getClipBounds());
  59782. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59783. {
  59784. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59785. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59786. }
  59787. }
  59788. void resized()
  59789. {
  59790. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59791. getWidth(), edge * 2);
  59792. }
  59793. void mouseDown (const MouseEvent& e)
  59794. {
  59795. mouseDrag (e);
  59796. }
  59797. void mouseDrag (const MouseEvent& e)
  59798. {
  59799. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59800. }
  59801. void updateIfNeeded()
  59802. {
  59803. resized();
  59804. }
  59805. private:
  59806. ColourSelector& owner;
  59807. float& h;
  59808. float& s;
  59809. float& v;
  59810. float lastHue;
  59811. HueSelectorMarker marker;
  59812. const int edge;
  59813. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59814. };
  59815. class ColourSelector::SwatchComponent : public Component
  59816. {
  59817. public:
  59818. SwatchComponent (ColourSelector& owner_, int index_)
  59819. : owner (owner_), index (index_)
  59820. {
  59821. }
  59822. void paint (Graphics& g)
  59823. {
  59824. const Colour colour (owner.getSwatchColour (index));
  59825. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59826. Colour (0xffdddddd).overlaidWith (colour),
  59827. Colour (0xffffffff).overlaidWith (colour));
  59828. }
  59829. void mouseDown (const MouseEvent&)
  59830. {
  59831. PopupMenu m;
  59832. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59833. m.addSeparator();
  59834. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59835. const int r = m.showAt (this);
  59836. if (r == 1)
  59837. {
  59838. owner.setCurrentColour (owner.getSwatchColour (index));
  59839. }
  59840. else if (r == 2)
  59841. {
  59842. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59843. {
  59844. owner.setSwatchColour (index, owner.getCurrentColour());
  59845. repaint();
  59846. }
  59847. }
  59848. }
  59849. private:
  59850. ColourSelector& owner;
  59851. const int index;
  59852. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59853. };
  59854. ColourSelector::ColourSelector (const int flags_,
  59855. const int edgeGap_,
  59856. const int gapAroundColourSpaceComponent)
  59857. : colour (Colours::white),
  59858. flags (flags_),
  59859. edgeGap (edgeGap_)
  59860. {
  59861. // not much point having a selector with no components in it!
  59862. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59863. updateHSV();
  59864. if ((flags & showSliders) != 0)
  59865. {
  59866. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59867. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59868. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59869. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59870. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59871. for (int i = 4; --i >= 0;)
  59872. sliders[i]->addListener (this);
  59873. }
  59874. if ((flags & showColourspace) != 0)
  59875. {
  59876. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59877. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59878. }
  59879. update();
  59880. }
  59881. ColourSelector::~ColourSelector()
  59882. {
  59883. dispatchPendingMessages();
  59884. swatchComponents.clear();
  59885. }
  59886. const Colour ColourSelector::getCurrentColour() const
  59887. {
  59888. return ((flags & showAlphaChannel) != 0) ? colour
  59889. : colour.withAlpha ((uint8) 0xff);
  59890. }
  59891. void ColourSelector::setCurrentColour (const Colour& c)
  59892. {
  59893. if (c != colour)
  59894. {
  59895. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59896. updateHSV();
  59897. update();
  59898. }
  59899. }
  59900. void ColourSelector::setHue (float newH)
  59901. {
  59902. newH = jlimit (0.0f, 1.0f, newH);
  59903. if (h != newH)
  59904. {
  59905. h = newH;
  59906. colour = Colour (h, s, v, colour.getFloatAlpha());
  59907. update();
  59908. }
  59909. }
  59910. void ColourSelector::setSV (float newS, float newV)
  59911. {
  59912. newS = jlimit (0.0f, 1.0f, newS);
  59913. newV = jlimit (0.0f, 1.0f, newV);
  59914. if (s != newS || v != newV)
  59915. {
  59916. s = newS;
  59917. v = newV;
  59918. colour = Colour (h, s, v, colour.getFloatAlpha());
  59919. update();
  59920. }
  59921. }
  59922. void ColourSelector::updateHSV()
  59923. {
  59924. colour.getHSB (h, s, v);
  59925. }
  59926. void ColourSelector::update()
  59927. {
  59928. if (sliders[0] != 0)
  59929. {
  59930. sliders[0]->setValue ((int) colour.getRed());
  59931. sliders[1]->setValue ((int) colour.getGreen());
  59932. sliders[2]->setValue ((int) colour.getBlue());
  59933. sliders[3]->setValue ((int) colour.getAlpha());
  59934. }
  59935. if (colourSpace != 0)
  59936. {
  59937. colourSpace->updateIfNeeded();
  59938. hueSelector->updateIfNeeded();
  59939. }
  59940. if ((flags & showColourAtTop) != 0)
  59941. repaint (previewArea);
  59942. sendChangeMessage();
  59943. }
  59944. void ColourSelector::paint (Graphics& g)
  59945. {
  59946. g.fillAll (findColour (backgroundColourId));
  59947. if ((flags & showColourAtTop) != 0)
  59948. {
  59949. const Colour currentColour (getCurrentColour());
  59950. g.fillCheckerBoard (previewArea, 10, 10,
  59951. Colour (0xffdddddd).overlaidWith (currentColour),
  59952. Colour (0xffffffff).overlaidWith (currentColour));
  59953. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59954. g.setFont (14.0f, true);
  59955. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59956. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59957. Justification::centred, false);
  59958. }
  59959. if ((flags & showSliders) != 0)
  59960. {
  59961. g.setColour (findColour (labelTextColourId));
  59962. g.setFont (11.0f);
  59963. for (int i = 4; --i >= 0;)
  59964. {
  59965. if (sliders[i]->isVisible())
  59966. g.drawText (sliders[i]->getName() + ":",
  59967. 0, sliders[i]->getY(),
  59968. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59969. Justification::centredRight, false);
  59970. }
  59971. }
  59972. }
  59973. void ColourSelector::resized()
  59974. {
  59975. const int swatchesPerRow = 8;
  59976. const int swatchHeight = 22;
  59977. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59978. const int numSwatches = getNumSwatches();
  59979. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59980. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59981. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59982. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59983. int y = topSpace;
  59984. if ((flags & showColourspace) != 0)
  59985. {
  59986. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59987. colourSpace->setBounds (edgeGap, y,
  59988. getWidth() - hueWidth - edgeGap - 4,
  59989. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59990. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59991. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59992. colourSpace->getHeight());
  59993. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59994. }
  59995. if ((flags & showSliders) != 0)
  59996. {
  59997. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59998. for (int i = 0; i < numSliders; ++i)
  59999. {
  60000. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60001. proportionOfWidth (0.72f), sliderHeight - 2);
  60002. y += sliderHeight;
  60003. }
  60004. }
  60005. if (numSwatches > 0)
  60006. {
  60007. const int startX = 8;
  60008. const int xGap = 4;
  60009. const int yGap = 4;
  60010. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60011. y += edgeGap;
  60012. if (swatchComponents.size() != numSwatches)
  60013. {
  60014. swatchComponents.clear();
  60015. for (int i = 0; i < numSwatches; ++i)
  60016. {
  60017. SwatchComponent* const sc = new SwatchComponent (*this, i);
  60018. swatchComponents.add (sc);
  60019. addAndMakeVisible (sc);
  60020. }
  60021. }
  60022. int x = startX;
  60023. for (int i = 0; i < swatchComponents.size(); ++i)
  60024. {
  60025. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60026. sc->setBounds (x + xGap / 2,
  60027. y + yGap / 2,
  60028. swatchWidth - xGap,
  60029. swatchHeight - yGap);
  60030. if (((i + 1) % swatchesPerRow) == 0)
  60031. {
  60032. x = startX;
  60033. y += swatchHeight;
  60034. }
  60035. else
  60036. {
  60037. x += swatchWidth;
  60038. }
  60039. }
  60040. }
  60041. }
  60042. void ColourSelector::sliderValueChanged (Slider*)
  60043. {
  60044. if (sliders[0] != 0)
  60045. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60046. (uint8) sliders[1]->getValue(),
  60047. (uint8) sliders[2]->getValue(),
  60048. (uint8) sliders[3]->getValue()));
  60049. }
  60050. int ColourSelector::getNumSwatches() const
  60051. {
  60052. return 0;
  60053. }
  60054. const Colour ColourSelector::getSwatchColour (const int) const
  60055. {
  60056. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60057. return Colours::black;
  60058. }
  60059. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60060. {
  60061. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60062. }
  60063. END_JUCE_NAMESPACE
  60064. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60065. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60066. BEGIN_JUCE_NAMESPACE
  60067. class ShadowWindow : public Component
  60068. {
  60069. public:
  60070. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  60071. : topLeft (shadowImageSections [type_ * 3]),
  60072. bottomRight (shadowImageSections [type_ * 3 + 1]),
  60073. filler (shadowImageSections [type_ * 3 + 2]),
  60074. type (type_)
  60075. {
  60076. setInterceptsMouseClicks (false, false);
  60077. if (owner.isOnDesktop())
  60078. {
  60079. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60080. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60081. | ComponentPeer::windowIsTemporary
  60082. | ComponentPeer::windowIgnoresKeyPresses);
  60083. }
  60084. else if (owner.getParentComponent() != 0)
  60085. {
  60086. owner.getParentComponent()->addChildComponent (this);
  60087. }
  60088. }
  60089. void paint (Graphics& g)
  60090. {
  60091. g.setOpacity (1.0f);
  60092. if (type < 2)
  60093. {
  60094. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60095. g.drawImage (topLeft,
  60096. 0, 0, topLeft.getWidth(), imH,
  60097. 0, 0, topLeft.getWidth(), imH);
  60098. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60099. g.drawImage (bottomRight,
  60100. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60101. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60102. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60103. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60104. }
  60105. else
  60106. {
  60107. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60108. g.drawImage (topLeft,
  60109. 0, 0, imW, topLeft.getHeight(),
  60110. 0, 0, imW, topLeft.getHeight());
  60111. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60112. g.drawImage (bottomRight,
  60113. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60114. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60115. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60116. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60117. }
  60118. }
  60119. void resized()
  60120. {
  60121. repaint(); // (needed for correct repainting)
  60122. }
  60123. private:
  60124. const Image topLeft, bottomRight, filler;
  60125. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60126. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  60127. };
  60128. DropShadower::DropShadower (const float alpha_,
  60129. const int xOffset_,
  60130. const int yOffset_,
  60131. const float blurRadius_)
  60132. : owner (0),
  60133. xOffset (xOffset_),
  60134. yOffset (yOffset_),
  60135. alpha (alpha_),
  60136. blurRadius (blurRadius_),
  60137. reentrant (false)
  60138. {
  60139. }
  60140. DropShadower::~DropShadower()
  60141. {
  60142. if (owner != 0)
  60143. owner->removeComponentListener (this);
  60144. reentrant = true;
  60145. shadowWindows.clear();
  60146. }
  60147. void DropShadower::setOwner (Component* componentToFollow)
  60148. {
  60149. if (componentToFollow != owner)
  60150. {
  60151. if (owner != 0)
  60152. owner->removeComponentListener (this);
  60153. // (the component can't be null)
  60154. jassert (componentToFollow != 0);
  60155. owner = componentToFollow;
  60156. jassert (owner != 0);
  60157. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60158. owner->addComponentListener (this);
  60159. updateShadows();
  60160. }
  60161. }
  60162. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60163. {
  60164. updateShadows();
  60165. }
  60166. void DropShadower::componentBroughtToFront (Component&)
  60167. {
  60168. bringShadowWindowsToFront();
  60169. }
  60170. void DropShadower::componentParentHierarchyChanged (Component&)
  60171. {
  60172. shadowWindows.clear();
  60173. updateShadows();
  60174. }
  60175. void DropShadower::componentVisibilityChanged (Component&)
  60176. {
  60177. updateShadows();
  60178. }
  60179. void DropShadower::updateShadows()
  60180. {
  60181. if (reentrant || owner == 0)
  60182. return;
  60183. reentrant = true;
  60184. ComponentPeer* const peer = owner->getPeer();
  60185. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  60186. const bool createShadowWindows = shadowWindows.size() == 0
  60187. && owner->getWidth() > 0
  60188. && owner->getHeight() > 0
  60189. && isOwnerVisible
  60190. && (Desktop::canUseSemiTransparentWindows()
  60191. || owner->getParentComponent() != 0);
  60192. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  60193. if (createShadowWindows)
  60194. {
  60195. // keep a cached version of the image to save doing the gaussian too often
  60196. String imageId;
  60197. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60198. const int hash = imageId.hashCode();
  60199. Image bigIm (ImageCache::getFromHashCode (hash));
  60200. if (bigIm.isNull())
  60201. {
  60202. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60203. Graphics bigG (bigIm);
  60204. bigG.setColour (Colours::black.withAlpha (alpha));
  60205. bigG.fillRect (shadowEdge + xOffset,
  60206. shadowEdge + yOffset,
  60207. bigIm.getWidth() - (shadowEdge * 2),
  60208. bigIm.getHeight() - (shadowEdge * 2));
  60209. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60210. blurKernel.createGaussianBlur (blurRadius);
  60211. blurKernel.applyToImage (bigIm, bigIm,
  60212. Rectangle<int> (xOffset, yOffset,
  60213. bigIm.getWidth(), bigIm.getHeight()));
  60214. ImageCache::addImageToCache (bigIm, hash);
  60215. }
  60216. const int iw = bigIm.getWidth();
  60217. const int ih = bigIm.getHeight();
  60218. const int shadowEdge2 = shadowEdge * 2;
  60219. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60220. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60221. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60222. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60223. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60224. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60225. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60226. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60227. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60228. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60229. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60230. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60231. for (int i = 0; i < 4; ++i)
  60232. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  60233. }
  60234. if (shadowWindows.size() >= 4)
  60235. {
  60236. for (int i = shadowWindows.size(); --i >= 0;)
  60237. {
  60238. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60239. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60240. }
  60241. const int x = owner->getX();
  60242. const int y = owner->getY() - shadowEdge;
  60243. const int w = owner->getWidth();
  60244. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60245. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60246. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60247. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60248. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60249. }
  60250. reentrant = false;
  60251. if (createShadowWindows)
  60252. bringShadowWindowsToFront();
  60253. }
  60254. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60255. const int sx, const int sy)
  60256. {
  60257. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60258. Graphics g (shadowImageSections[num]);
  60259. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60260. }
  60261. void DropShadower::bringShadowWindowsToFront()
  60262. {
  60263. if (! reentrant)
  60264. {
  60265. updateShadows();
  60266. reentrant = true;
  60267. for (int i = shadowWindows.size(); --i >= 0;)
  60268. shadowWindows.getUnchecked(i)->toBehind (owner);
  60269. reentrant = false;
  60270. }
  60271. }
  60272. END_JUCE_NAMESPACE
  60273. /*** End of inlined file: juce_DropShadower.cpp ***/
  60274. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60275. BEGIN_JUCE_NAMESPACE
  60276. class MagnifyingPeer : public ComponentPeer
  60277. {
  60278. public:
  60279. MagnifyingPeer (Component* const component_,
  60280. MagnifierComponent* const magnifierComp_)
  60281. : ComponentPeer (component_, 0),
  60282. magnifierComp (magnifierComp_)
  60283. {
  60284. }
  60285. ~MagnifyingPeer()
  60286. {
  60287. }
  60288. void* getNativeHandle() const { return 0; }
  60289. void setVisible (bool) {}
  60290. void setTitle (const String&) {}
  60291. void setPosition (int, int) {}
  60292. void setSize (int, int) {}
  60293. void setBounds (int, int, int, int, bool) {}
  60294. void setMinimised (bool) {}
  60295. void setAlpha (float /*newAlpha*/) {}
  60296. bool isMinimised() const { return false; }
  60297. void setFullScreen (bool) {}
  60298. bool isFullScreen() const { return false; }
  60299. const BorderSize getFrameSize() const { return BorderSize (0); }
  60300. bool setAlwaysOnTop (bool) { return true; }
  60301. void toFront (bool) {}
  60302. void toBehind (ComponentPeer*) {}
  60303. void setIcon (const Image&) {}
  60304. bool isFocused() const
  60305. {
  60306. return magnifierComp->hasKeyboardFocus (true);
  60307. }
  60308. void grabFocus()
  60309. {
  60310. ComponentPeer* peer = magnifierComp->getPeer();
  60311. if (peer != 0)
  60312. peer->grabFocus();
  60313. }
  60314. void textInputRequired (const Point<int>& position)
  60315. {
  60316. ComponentPeer* peer = magnifierComp->getPeer();
  60317. if (peer != 0)
  60318. peer->textInputRequired (position);
  60319. }
  60320. const Rectangle<int> getBounds() const
  60321. {
  60322. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60323. component->getWidth(), component->getHeight());
  60324. }
  60325. const Point<int> getScreenPosition() const
  60326. {
  60327. return magnifierComp->getScreenPosition();
  60328. }
  60329. const Point<int> localToGlobal (const Point<int>& relativePosition)
  60330. {
  60331. const double zoom = magnifierComp->getScaleFactor();
  60332. return magnifierComp->localPointToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60333. roundToInt (relativePosition.getY() * zoom)));
  60334. }
  60335. const Point<int> globalToLocal (const Point<int>& screenPosition)
  60336. {
  60337. const Point<int> p (magnifierComp->getLocalPoint (0, screenPosition));
  60338. const double zoom = magnifierComp->getScaleFactor();
  60339. return Point<int> (roundToInt (p.getX() / zoom),
  60340. roundToInt (p.getY() / zoom));
  60341. }
  60342. bool contains (const Point<int>& position, bool) const
  60343. {
  60344. return isPositiveAndBelow (position.getX(), magnifierComp->getWidth())
  60345. && isPositiveAndBelow (position.getY(), magnifierComp->getHeight());
  60346. }
  60347. void repaint (const Rectangle<int>& area)
  60348. {
  60349. const double zoom = magnifierComp->getScaleFactor();
  60350. magnifierComp->repaint ((int) (area.getX() * zoom),
  60351. (int) (area.getY() * zoom),
  60352. roundToInt (area.getWidth() * zoom) + 1,
  60353. roundToInt (area.getHeight() * zoom) + 1);
  60354. }
  60355. void performAnyPendingRepaintsNow()
  60356. {
  60357. }
  60358. private:
  60359. MagnifierComponent* const magnifierComp;
  60360. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MagnifyingPeer);
  60361. };
  60362. class PeerHolderComp : public Component
  60363. {
  60364. public:
  60365. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60366. : magnifierComp (magnifierComp_)
  60367. {
  60368. setVisible (true);
  60369. }
  60370. ~PeerHolderComp()
  60371. {
  60372. }
  60373. ComponentPeer* createNewPeer (int, void*)
  60374. {
  60375. return new MagnifyingPeer (this, magnifierComp);
  60376. }
  60377. void childBoundsChanged (Component* c)
  60378. {
  60379. if (c != 0)
  60380. {
  60381. setSize (c->getWidth(), c->getHeight());
  60382. magnifierComp->childBoundsChanged (this);
  60383. }
  60384. }
  60385. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60386. {
  60387. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60388. Component* const p = magnifierComp->getParentComponent();
  60389. if (p != 0)
  60390. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60391. }
  60392. private:
  60393. MagnifierComponent* const magnifierComp;
  60394. JUCE_DECLARE_NON_COPYABLE (PeerHolderComp);
  60395. };
  60396. MagnifierComponent::MagnifierComponent (Component* const content_,
  60397. const bool deleteContentCompWhenNoLongerNeeded)
  60398. : content (content_),
  60399. scaleFactor (0.0),
  60400. peer (0),
  60401. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60402. quality (Graphics::lowResamplingQuality),
  60403. mouseSource (0, true)
  60404. {
  60405. holderComp = new PeerHolderComp (this);
  60406. setScaleFactor (1.0);
  60407. }
  60408. MagnifierComponent::~MagnifierComponent()
  60409. {
  60410. delete holderComp;
  60411. if (deleteContent)
  60412. delete content;
  60413. }
  60414. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60415. {
  60416. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60417. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60418. if (scaleFactor != newScaleFactor)
  60419. {
  60420. scaleFactor = newScaleFactor;
  60421. if (scaleFactor == 1.0)
  60422. {
  60423. holderComp->removeFromDesktop();
  60424. peer = 0;
  60425. addChildComponent (content);
  60426. childBoundsChanged (content);
  60427. }
  60428. else
  60429. {
  60430. holderComp->addAndMakeVisible (content);
  60431. holderComp->childBoundsChanged (content);
  60432. childBoundsChanged (holderComp);
  60433. holderComp->addToDesktop (0);
  60434. peer = holderComp->getPeer();
  60435. }
  60436. repaint();
  60437. }
  60438. }
  60439. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60440. {
  60441. quality = newQuality;
  60442. }
  60443. void MagnifierComponent::paint (Graphics& g)
  60444. {
  60445. const int w = holderComp->getWidth();
  60446. const int h = holderComp->getHeight();
  60447. if (w == 0 || h == 0)
  60448. return;
  60449. const Rectangle<int> r (g.getClipBounds());
  60450. const int srcX = (int) (r.getX() / scaleFactor);
  60451. const int srcY = (int) (r.getY() / scaleFactor);
  60452. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60453. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60454. if (scaleFactor >= 1.0)
  60455. {
  60456. ++srcW;
  60457. ++srcH;
  60458. }
  60459. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60460. const Rectangle<int> area (srcX, srcY, srcW, srcH);
  60461. temp.clear (area);
  60462. {
  60463. Graphics g2 (temp);
  60464. g2.reduceClipRegion (area);
  60465. holderComp->paintEntireComponent (g2, false);
  60466. }
  60467. g.setImageResamplingQuality (quality);
  60468. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60469. }
  60470. void MagnifierComponent::childBoundsChanged (Component* c)
  60471. {
  60472. if (c != 0)
  60473. setSize (roundToInt (c->getWidth() * scaleFactor),
  60474. roundToInt (c->getHeight() * scaleFactor));
  60475. }
  60476. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60477. {
  60478. if (peer != 0)
  60479. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60480. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60481. }
  60482. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60483. {
  60484. passOnMouseEventToPeer (e);
  60485. }
  60486. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60487. {
  60488. passOnMouseEventToPeer (e);
  60489. }
  60490. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60491. {
  60492. passOnMouseEventToPeer (e);
  60493. }
  60494. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60495. {
  60496. passOnMouseEventToPeer (e);
  60497. }
  60498. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60499. {
  60500. passOnMouseEventToPeer (e);
  60501. }
  60502. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60503. {
  60504. passOnMouseEventToPeer (e);
  60505. }
  60506. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60507. {
  60508. if (peer != 0)
  60509. peer->handleMouseWheel (e.source.getIndex(),
  60510. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60511. ix * 256.0f, iy * 256.0f);
  60512. else
  60513. Component::mouseWheelMove (e, ix, iy);
  60514. }
  60515. int MagnifierComponent::scaleInt (const int n) const
  60516. {
  60517. return roundToInt (n / scaleFactor);
  60518. }
  60519. END_JUCE_NAMESPACE
  60520. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60521. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60522. BEGIN_JUCE_NAMESPACE
  60523. class MidiKeyboardUpDownButton : public Button
  60524. {
  60525. public:
  60526. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60527. : Button (String::empty),
  60528. owner (owner_),
  60529. delta (delta_)
  60530. {
  60531. setOpaque (true);
  60532. }
  60533. void clicked()
  60534. {
  60535. int note = owner.getLowestVisibleKey();
  60536. if (delta < 0)
  60537. note = (note - 1) / 12;
  60538. else
  60539. note = note / 12 + 1;
  60540. owner.setLowestVisibleKey (note * 12);
  60541. }
  60542. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60543. {
  60544. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60545. isMouseOverButton, isButtonDown,
  60546. delta > 0);
  60547. }
  60548. private:
  60549. MidiKeyboardComponent& owner;
  60550. const int delta;
  60551. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60552. };
  60553. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60554. const Orientation orientation_)
  60555. : state (state_),
  60556. xOffset (0),
  60557. blackNoteLength (1),
  60558. keyWidth (16.0f),
  60559. orientation (orientation_),
  60560. midiChannel (1),
  60561. midiInChannelMask (0xffff),
  60562. velocity (1.0f),
  60563. noteUnderMouse (-1),
  60564. mouseDownNote (-1),
  60565. rangeStart (0),
  60566. rangeEnd (127),
  60567. firstKey (12 * 4),
  60568. canScroll (true),
  60569. mouseDragging (false),
  60570. useMousePositionForVelocity (true),
  60571. keyMappingOctave (6),
  60572. octaveNumForMiddleC (3)
  60573. {
  60574. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60575. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60576. // initialise with a default set of querty key-mappings..
  60577. const char* const keymap = "awsedftgyhujkolp;";
  60578. for (int i = String (keymap).length(); --i >= 0;)
  60579. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60580. setOpaque (true);
  60581. setWantsKeyboardFocus (true);
  60582. state.addListener (this);
  60583. }
  60584. MidiKeyboardComponent::~MidiKeyboardComponent()
  60585. {
  60586. state.removeListener (this);
  60587. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60588. }
  60589. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60590. {
  60591. keyWidth = widthInPixels;
  60592. resized();
  60593. }
  60594. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60595. {
  60596. if (orientation != newOrientation)
  60597. {
  60598. orientation = newOrientation;
  60599. resized();
  60600. }
  60601. }
  60602. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60603. const int highestNote)
  60604. {
  60605. jassert (lowestNote >= 0 && lowestNote <= 127);
  60606. jassert (highestNote >= 0 && highestNote <= 127);
  60607. jassert (lowestNote <= highestNote);
  60608. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60609. {
  60610. rangeStart = jlimit (0, 127, lowestNote);
  60611. rangeEnd = jlimit (0, 127, highestNote);
  60612. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60613. resized();
  60614. }
  60615. }
  60616. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60617. {
  60618. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60619. if (noteNumber != firstKey)
  60620. {
  60621. firstKey = noteNumber;
  60622. sendChangeMessage();
  60623. resized();
  60624. }
  60625. }
  60626. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60627. {
  60628. if (canScroll != canScroll_)
  60629. {
  60630. canScroll = canScroll_;
  60631. resized();
  60632. }
  60633. }
  60634. void MidiKeyboardComponent::colourChanged()
  60635. {
  60636. repaint();
  60637. }
  60638. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60639. {
  60640. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60641. if (midiChannel != midiChannelNumber)
  60642. {
  60643. resetAnyKeysInUse();
  60644. midiChannel = jlimit (1, 16, midiChannelNumber);
  60645. }
  60646. }
  60647. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60648. {
  60649. midiInChannelMask = midiChannelMask;
  60650. triggerAsyncUpdate();
  60651. }
  60652. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60653. {
  60654. velocity = jlimit (0.0f, 1.0f, velocity_);
  60655. useMousePositionForVelocity = useMousePositionForVelocity_;
  60656. }
  60657. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60658. {
  60659. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60660. static const float blackNoteWidth = 0.7f;
  60661. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60662. 1.0f, 2 - blackNoteWidth * 0.4f,
  60663. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60664. 4.0f, 5 - blackNoteWidth * 0.5f,
  60665. 5.0f, 6 - blackNoteWidth * 0.3f,
  60666. 6.0f };
  60667. static const float widths[] = { 1.0f, blackNoteWidth,
  60668. 1.0f, blackNoteWidth,
  60669. 1.0f, 1.0f, blackNoteWidth,
  60670. 1.0f, blackNoteWidth,
  60671. 1.0f, blackNoteWidth,
  60672. 1.0f };
  60673. const int octave = midiNoteNumber / 12;
  60674. const int note = midiNoteNumber % 12;
  60675. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60676. w = roundToInt (widths [note] * keyWidth_);
  60677. }
  60678. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60679. {
  60680. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60681. int rx, rw;
  60682. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60683. x -= xOffset + rx;
  60684. }
  60685. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60686. {
  60687. int x, y;
  60688. getKeyPos (midiNoteNumber, x, y);
  60689. return x;
  60690. }
  60691. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60692. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60693. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60694. {
  60695. if (! reallyContains (pos, false))
  60696. return -1;
  60697. Point<int> p (pos);
  60698. if (orientation != horizontalKeyboard)
  60699. {
  60700. p = Point<int> (p.getY(), p.getX());
  60701. if (orientation == verticalKeyboardFacingLeft)
  60702. p = Point<int> (p.getX(), getWidth() - p.getY());
  60703. else
  60704. p = Point<int> (getHeight() - p.getX(), p.getY());
  60705. }
  60706. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60707. }
  60708. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60709. {
  60710. if (pos.getY() < blackNoteLength)
  60711. {
  60712. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60713. {
  60714. for (int i = 0; i < 5; ++i)
  60715. {
  60716. const int note = octaveStart + blackNotes [i];
  60717. if (note >= rangeStart && note <= rangeEnd)
  60718. {
  60719. int kx, kw;
  60720. getKeyPos (note, kx, kw);
  60721. kx += xOffset;
  60722. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60723. {
  60724. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60725. return note;
  60726. }
  60727. }
  60728. }
  60729. }
  60730. }
  60731. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60732. {
  60733. for (int i = 0; i < 7; ++i)
  60734. {
  60735. const int note = octaveStart + whiteNotes [i];
  60736. if (note >= rangeStart && note <= rangeEnd)
  60737. {
  60738. int kx, kw;
  60739. getKeyPos (note, kx, kw);
  60740. kx += xOffset;
  60741. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60742. {
  60743. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60744. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60745. return note;
  60746. }
  60747. }
  60748. }
  60749. }
  60750. mousePositionVelocity = 0;
  60751. return -1;
  60752. }
  60753. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60754. {
  60755. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60756. {
  60757. int x, w;
  60758. getKeyPos (noteNum, x, w);
  60759. if (orientation == horizontalKeyboard)
  60760. repaint (x, 0, w, getHeight());
  60761. else if (orientation == verticalKeyboardFacingLeft)
  60762. repaint (0, x, getWidth(), w);
  60763. else if (orientation == verticalKeyboardFacingRight)
  60764. repaint (0, getHeight() - x - w, getWidth(), w);
  60765. }
  60766. }
  60767. void MidiKeyboardComponent::paint (Graphics& g)
  60768. {
  60769. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60770. const Colour lineColour (findColour (keySeparatorLineColourId));
  60771. const Colour textColour (findColour (textLabelColourId));
  60772. int x, w, octave;
  60773. for (octave = 0; octave < 128; octave += 12)
  60774. {
  60775. for (int white = 0; white < 7; ++white)
  60776. {
  60777. const int noteNum = octave + whiteNotes [white];
  60778. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60779. {
  60780. getKeyPos (noteNum, x, w);
  60781. if (orientation == horizontalKeyboard)
  60782. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60783. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60784. noteUnderMouse == noteNum,
  60785. lineColour, textColour);
  60786. else if (orientation == verticalKeyboardFacingLeft)
  60787. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60788. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60789. noteUnderMouse == noteNum,
  60790. lineColour, textColour);
  60791. else if (orientation == verticalKeyboardFacingRight)
  60792. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60793. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60794. noteUnderMouse == noteNum,
  60795. lineColour, textColour);
  60796. }
  60797. }
  60798. }
  60799. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60800. if (orientation == verticalKeyboardFacingLeft)
  60801. {
  60802. x1 = getWidth() - 1.0f;
  60803. x2 = getWidth() - 5.0f;
  60804. }
  60805. else if (orientation == verticalKeyboardFacingRight)
  60806. x2 = 5.0f;
  60807. else
  60808. y2 = 5.0f;
  60809. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60810. Colours::transparentBlack, x2, y2, false));
  60811. getKeyPos (rangeEnd, x, w);
  60812. x += w;
  60813. if (orientation == verticalKeyboardFacingLeft)
  60814. g.fillRect (getWidth() - 5, 0, 5, x);
  60815. else if (orientation == verticalKeyboardFacingRight)
  60816. g.fillRect (0, 0, 5, x);
  60817. else
  60818. g.fillRect (0, 0, x, 5);
  60819. g.setColour (lineColour);
  60820. if (orientation == verticalKeyboardFacingLeft)
  60821. g.fillRect (0, 0, 1, x);
  60822. else if (orientation == verticalKeyboardFacingRight)
  60823. g.fillRect (getWidth() - 1, 0, 1, x);
  60824. else
  60825. g.fillRect (0, getHeight() - 1, x, 1);
  60826. const Colour blackNoteColour (findColour (blackNoteColourId));
  60827. for (octave = 0; octave < 128; octave += 12)
  60828. {
  60829. for (int black = 0; black < 5; ++black)
  60830. {
  60831. const int noteNum = octave + blackNotes [black];
  60832. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60833. {
  60834. getKeyPos (noteNum, x, w);
  60835. if (orientation == horizontalKeyboard)
  60836. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60837. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60838. noteUnderMouse == noteNum,
  60839. blackNoteColour);
  60840. else if (orientation == verticalKeyboardFacingLeft)
  60841. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60842. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60843. noteUnderMouse == noteNum,
  60844. blackNoteColour);
  60845. else if (orientation == verticalKeyboardFacingRight)
  60846. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60847. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60848. noteUnderMouse == noteNum,
  60849. blackNoteColour);
  60850. }
  60851. }
  60852. }
  60853. }
  60854. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60855. Graphics& g, int x, int y, int w, int h,
  60856. bool isDown, bool isOver,
  60857. const Colour& lineColour,
  60858. const Colour& textColour)
  60859. {
  60860. Colour c (Colours::transparentWhite);
  60861. if (isDown)
  60862. c = findColour (keyDownOverlayColourId);
  60863. if (isOver)
  60864. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60865. g.setColour (c);
  60866. g.fillRect (x, y, w, h);
  60867. const String text (getWhiteNoteText (midiNoteNumber));
  60868. if (! text.isEmpty())
  60869. {
  60870. g.setColour (textColour);
  60871. Font f (jmin (12.0f, keyWidth * 0.9f));
  60872. f.setHorizontalScale (0.8f);
  60873. g.setFont (f);
  60874. Justification justification (Justification::centredBottom);
  60875. if (orientation == verticalKeyboardFacingLeft)
  60876. justification = Justification::centredLeft;
  60877. else if (orientation == verticalKeyboardFacingRight)
  60878. justification = Justification::centredRight;
  60879. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60880. }
  60881. g.setColour (lineColour);
  60882. if (orientation == horizontalKeyboard)
  60883. g.fillRect (x, y, 1, h);
  60884. else if (orientation == verticalKeyboardFacingLeft)
  60885. g.fillRect (x, y, w, 1);
  60886. else if (orientation == verticalKeyboardFacingRight)
  60887. g.fillRect (x, y + h - 1, w, 1);
  60888. if (midiNoteNumber == rangeEnd)
  60889. {
  60890. if (orientation == horizontalKeyboard)
  60891. g.fillRect (x + w, y, 1, h);
  60892. else if (orientation == verticalKeyboardFacingLeft)
  60893. g.fillRect (x, y + h, w, 1);
  60894. else if (orientation == verticalKeyboardFacingRight)
  60895. g.fillRect (x, y - 1, w, 1);
  60896. }
  60897. }
  60898. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60899. Graphics& g, int x, int y, int w, int h,
  60900. bool isDown, bool isOver,
  60901. const Colour& noteFillColour)
  60902. {
  60903. Colour c (noteFillColour);
  60904. if (isDown)
  60905. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60906. if (isOver)
  60907. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60908. g.setColour (c);
  60909. g.fillRect (x, y, w, h);
  60910. if (isDown)
  60911. {
  60912. g.setColour (noteFillColour);
  60913. g.drawRect (x, y, w, h);
  60914. }
  60915. else
  60916. {
  60917. const int xIndent = jmax (1, jmin (w, h) / 8);
  60918. g.setColour (c.brighter());
  60919. if (orientation == horizontalKeyboard)
  60920. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60921. else if (orientation == verticalKeyboardFacingLeft)
  60922. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60923. else if (orientation == verticalKeyboardFacingRight)
  60924. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60925. }
  60926. }
  60927. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60928. {
  60929. octaveNumForMiddleC = octaveNumForMiddleC_;
  60930. repaint();
  60931. }
  60932. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60933. {
  60934. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60935. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60936. return String::empty;
  60937. }
  60938. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60939. const bool isMouseOver_,
  60940. const bool isButtonDown,
  60941. const bool movesOctavesUp)
  60942. {
  60943. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60944. float angle;
  60945. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60946. angle = movesOctavesUp ? 0.0f : 0.5f;
  60947. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60948. angle = movesOctavesUp ? 0.25f : 0.75f;
  60949. else
  60950. angle = movesOctavesUp ? 0.75f : 0.25f;
  60951. Path path;
  60952. path.lineTo (0.0f, 1.0f);
  60953. path.lineTo (1.0f, 0.5f);
  60954. path.closeSubPath();
  60955. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60956. g.setColour (findColour (upDownButtonArrowColourId)
  60957. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60958. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60959. w - 2.0f,
  60960. h - 2.0f,
  60961. true));
  60962. }
  60963. void MidiKeyboardComponent::resized()
  60964. {
  60965. int w = getWidth();
  60966. int h = getHeight();
  60967. if (w > 0 && h > 0)
  60968. {
  60969. if (orientation != horizontalKeyboard)
  60970. swapVariables (w, h);
  60971. blackNoteLength = roundToInt (h * 0.7f);
  60972. int kx2, kw2;
  60973. getKeyPos (rangeEnd, kx2, kw2);
  60974. kx2 += kw2;
  60975. if (firstKey != rangeStart)
  60976. {
  60977. int kx1, kw1;
  60978. getKeyPos (rangeStart, kx1, kw1);
  60979. if (kx2 - kx1 <= w)
  60980. {
  60981. firstKey = rangeStart;
  60982. sendChangeMessage();
  60983. repaint();
  60984. }
  60985. }
  60986. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60987. scrollDown->setVisible (showScrollButtons);
  60988. scrollUp->setVisible (showScrollButtons);
  60989. xOffset = 0;
  60990. if (showScrollButtons)
  60991. {
  60992. const int scrollButtonW = jmin (12, w / 2);
  60993. if (orientation == horizontalKeyboard)
  60994. {
  60995. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60996. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60997. }
  60998. else if (orientation == verticalKeyboardFacingLeft)
  60999. {
  61000. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61001. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61002. }
  61003. else if (orientation == verticalKeyboardFacingRight)
  61004. {
  61005. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61006. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61007. }
  61008. int endOfLastKey, kw;
  61009. getKeyPos (rangeEnd, endOfLastKey, kw);
  61010. endOfLastKey += kw;
  61011. float mousePositionVelocity;
  61012. const int spaceAvailable = w - scrollButtonW * 2;
  61013. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61014. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61015. {
  61016. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61017. sendChangeMessage();
  61018. }
  61019. int newOffset = 0;
  61020. getKeyPos (firstKey, newOffset, kw);
  61021. xOffset = newOffset - scrollButtonW;
  61022. }
  61023. else
  61024. {
  61025. firstKey = rangeStart;
  61026. }
  61027. timerCallback();
  61028. repaint();
  61029. }
  61030. }
  61031. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61032. {
  61033. triggerAsyncUpdate();
  61034. }
  61035. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61036. {
  61037. triggerAsyncUpdate();
  61038. }
  61039. void MidiKeyboardComponent::handleAsyncUpdate()
  61040. {
  61041. for (int i = rangeStart; i <= rangeEnd; ++i)
  61042. {
  61043. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61044. {
  61045. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61046. repaintNote (i);
  61047. }
  61048. }
  61049. }
  61050. void MidiKeyboardComponent::resetAnyKeysInUse()
  61051. {
  61052. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61053. {
  61054. state.allNotesOff (midiChannel);
  61055. keysPressed.clear();
  61056. mouseDownNote = -1;
  61057. }
  61058. }
  61059. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61060. {
  61061. float mousePositionVelocity = 0.0f;
  61062. const int newNote = (mouseDragging || isMouseOver())
  61063. ? xyToNote (pos, mousePositionVelocity) : -1;
  61064. if (noteUnderMouse != newNote)
  61065. {
  61066. if (mouseDownNote >= 0)
  61067. {
  61068. state.noteOff (midiChannel, mouseDownNote);
  61069. mouseDownNote = -1;
  61070. }
  61071. if (mouseDragging && newNote >= 0)
  61072. {
  61073. if (! useMousePositionForVelocity)
  61074. mousePositionVelocity = 1.0f;
  61075. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61076. mouseDownNote = newNote;
  61077. }
  61078. repaintNote (noteUnderMouse);
  61079. noteUnderMouse = newNote;
  61080. repaintNote (noteUnderMouse);
  61081. }
  61082. else if (mouseDownNote >= 0 && ! mouseDragging)
  61083. {
  61084. state.noteOff (midiChannel, mouseDownNote);
  61085. mouseDownNote = -1;
  61086. }
  61087. }
  61088. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61089. {
  61090. updateNoteUnderMouse (e.getPosition());
  61091. stopTimer();
  61092. }
  61093. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61094. {
  61095. float mousePositionVelocity;
  61096. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61097. if (newNote >= 0)
  61098. mouseDraggedToKey (newNote, e);
  61099. updateNoteUnderMouse (e.getPosition());
  61100. }
  61101. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61102. {
  61103. return true;
  61104. }
  61105. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61106. {
  61107. }
  61108. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61109. {
  61110. float mousePositionVelocity;
  61111. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61112. mouseDragging = false;
  61113. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61114. {
  61115. repaintNote (noteUnderMouse);
  61116. noteUnderMouse = -1;
  61117. mouseDragging = true;
  61118. updateNoteUnderMouse (e.getPosition());
  61119. startTimer (500);
  61120. }
  61121. }
  61122. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61123. {
  61124. mouseDragging = false;
  61125. updateNoteUnderMouse (e.getPosition());
  61126. stopTimer();
  61127. }
  61128. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61129. {
  61130. updateNoteUnderMouse (e.getPosition());
  61131. }
  61132. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61133. {
  61134. updateNoteUnderMouse (e.getPosition());
  61135. }
  61136. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61137. {
  61138. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61139. }
  61140. void MidiKeyboardComponent::timerCallback()
  61141. {
  61142. updateNoteUnderMouse (getMouseXYRelative());
  61143. }
  61144. void MidiKeyboardComponent::clearKeyMappings()
  61145. {
  61146. resetAnyKeysInUse();
  61147. keyPressNotes.clear();
  61148. keyPresses.clear();
  61149. }
  61150. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61151. const int midiNoteOffsetFromC)
  61152. {
  61153. removeKeyPressForNote (midiNoteOffsetFromC);
  61154. keyPressNotes.add (midiNoteOffsetFromC);
  61155. keyPresses.add (key);
  61156. }
  61157. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61158. {
  61159. for (int i = keyPressNotes.size(); --i >= 0;)
  61160. {
  61161. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61162. {
  61163. keyPressNotes.remove (i);
  61164. keyPresses.remove (i);
  61165. }
  61166. }
  61167. }
  61168. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61169. {
  61170. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61171. keyMappingOctave = newOctaveNumber;
  61172. }
  61173. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61174. {
  61175. bool keyPressUsed = false;
  61176. for (int i = keyPresses.size(); --i >= 0;)
  61177. {
  61178. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61179. if (keyPresses.getReference(i).isCurrentlyDown())
  61180. {
  61181. if (! keysPressed [note])
  61182. {
  61183. keysPressed.setBit (note);
  61184. state.noteOn (midiChannel, note, velocity);
  61185. keyPressUsed = true;
  61186. }
  61187. }
  61188. else
  61189. {
  61190. if (keysPressed [note])
  61191. {
  61192. keysPressed.clearBit (note);
  61193. state.noteOff (midiChannel, note);
  61194. keyPressUsed = true;
  61195. }
  61196. }
  61197. }
  61198. return keyPressUsed;
  61199. }
  61200. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61201. {
  61202. resetAnyKeysInUse();
  61203. }
  61204. END_JUCE_NAMESPACE
  61205. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61206. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61207. #if JUCE_OPENGL
  61208. BEGIN_JUCE_NAMESPACE
  61209. extern void juce_glViewport (const int w, const int h);
  61210. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61211. const int alphaBits_,
  61212. const int depthBufferBits_,
  61213. const int stencilBufferBits_)
  61214. : redBits (bitsPerRGBComponent),
  61215. greenBits (bitsPerRGBComponent),
  61216. blueBits (bitsPerRGBComponent),
  61217. alphaBits (alphaBits_),
  61218. depthBufferBits (depthBufferBits_),
  61219. stencilBufferBits (stencilBufferBits_),
  61220. accumulationBufferRedBits (0),
  61221. accumulationBufferGreenBits (0),
  61222. accumulationBufferBlueBits (0),
  61223. accumulationBufferAlphaBits (0),
  61224. fullSceneAntiAliasingNumSamples (0)
  61225. {
  61226. }
  61227. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61228. : redBits (other.redBits),
  61229. greenBits (other.greenBits),
  61230. blueBits (other.blueBits),
  61231. alphaBits (other.alphaBits),
  61232. depthBufferBits (other.depthBufferBits),
  61233. stencilBufferBits (other.stencilBufferBits),
  61234. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61235. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61236. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61237. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61238. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61239. {
  61240. }
  61241. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61242. {
  61243. redBits = other.redBits;
  61244. greenBits = other.greenBits;
  61245. blueBits = other.blueBits;
  61246. alphaBits = other.alphaBits;
  61247. depthBufferBits = other.depthBufferBits;
  61248. stencilBufferBits = other.stencilBufferBits;
  61249. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61250. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61251. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61252. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61253. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61254. return *this;
  61255. }
  61256. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61257. {
  61258. return redBits == other.redBits
  61259. && greenBits == other.greenBits
  61260. && blueBits == other.blueBits
  61261. && alphaBits == other.alphaBits
  61262. && depthBufferBits == other.depthBufferBits
  61263. && stencilBufferBits == other.stencilBufferBits
  61264. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61265. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61266. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61267. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61268. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61269. }
  61270. static Array<OpenGLContext*> knownContexts;
  61271. OpenGLContext::OpenGLContext() throw()
  61272. {
  61273. knownContexts.add (this);
  61274. }
  61275. OpenGLContext::~OpenGLContext()
  61276. {
  61277. knownContexts.removeValue (this);
  61278. }
  61279. OpenGLContext* OpenGLContext::getCurrentContext()
  61280. {
  61281. for (int i = knownContexts.size(); --i >= 0;)
  61282. {
  61283. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61284. if (oglc->isActive())
  61285. return oglc;
  61286. }
  61287. return 0;
  61288. }
  61289. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61290. {
  61291. public:
  61292. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61293. : ComponentMovementWatcher (owner_),
  61294. owner (owner_),
  61295. wasShowing (false)
  61296. {
  61297. }
  61298. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61299. {
  61300. owner->updateContextPosition();
  61301. }
  61302. void componentPeerChanged()
  61303. {
  61304. const ScopedLock sl (owner->getContextLock());
  61305. owner->deleteContext();
  61306. }
  61307. void componentVisibilityChanged (Component&)
  61308. {
  61309. const bool isShowingNow = owner->isShowing();
  61310. if (wasShowing != isShowingNow)
  61311. {
  61312. wasShowing = isShowingNow;
  61313. if (! isShowingNow)
  61314. {
  61315. const ScopedLock sl (owner->getContextLock());
  61316. owner->deleteContext();
  61317. }
  61318. }
  61319. }
  61320. private:
  61321. OpenGLComponent* const owner;
  61322. bool wasShowing;
  61323. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  61324. };
  61325. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61326. : type (type_),
  61327. contextToShareListsWith (0),
  61328. needToUpdateViewport (true)
  61329. {
  61330. setOpaque (true);
  61331. componentWatcher = new OpenGLComponentWatcher (this);
  61332. }
  61333. OpenGLComponent::~OpenGLComponent()
  61334. {
  61335. deleteContext();
  61336. componentWatcher = 0;
  61337. }
  61338. void OpenGLComponent::deleteContext()
  61339. {
  61340. const ScopedLock sl (contextLock);
  61341. context = 0;
  61342. }
  61343. void OpenGLComponent::updateContextPosition()
  61344. {
  61345. needToUpdateViewport = true;
  61346. if (getWidth() > 0 && getHeight() > 0)
  61347. {
  61348. Component* const topComp = getTopLevelComponent();
  61349. if (topComp->getPeer() != 0)
  61350. {
  61351. const ScopedLock sl (contextLock);
  61352. if (context != 0)
  61353. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61354. getScreenY() - topComp->getScreenY(),
  61355. getWidth(),
  61356. getHeight(),
  61357. topComp->getHeight());
  61358. }
  61359. }
  61360. }
  61361. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61362. {
  61363. OpenGLPixelFormat pf;
  61364. const ScopedLock sl (contextLock);
  61365. if (context != 0)
  61366. pf = context->getPixelFormat();
  61367. return pf;
  61368. }
  61369. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61370. {
  61371. if (! (preferredPixelFormat == formatToUse))
  61372. {
  61373. const ScopedLock sl (contextLock);
  61374. deleteContext();
  61375. preferredPixelFormat = formatToUse;
  61376. }
  61377. }
  61378. void OpenGLComponent::shareWith (OpenGLContext* c)
  61379. {
  61380. if (contextToShareListsWith != c)
  61381. {
  61382. const ScopedLock sl (contextLock);
  61383. deleteContext();
  61384. contextToShareListsWith = c;
  61385. }
  61386. }
  61387. bool OpenGLComponent::makeCurrentContextActive()
  61388. {
  61389. if (context == 0)
  61390. {
  61391. const ScopedLock sl (contextLock);
  61392. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61393. {
  61394. context = createContext();
  61395. if (context != 0)
  61396. {
  61397. updateContextPosition();
  61398. if (context->makeActive())
  61399. newOpenGLContextCreated();
  61400. }
  61401. }
  61402. }
  61403. return context != 0 && context->makeActive();
  61404. }
  61405. void OpenGLComponent::makeCurrentContextInactive()
  61406. {
  61407. if (context != 0)
  61408. context->makeInactive();
  61409. }
  61410. bool OpenGLComponent::isActiveContext() const throw()
  61411. {
  61412. return context != 0 && context->isActive();
  61413. }
  61414. void OpenGLComponent::swapBuffers()
  61415. {
  61416. if (context != 0)
  61417. context->swapBuffers();
  61418. }
  61419. void OpenGLComponent::paint (Graphics&)
  61420. {
  61421. if (renderAndSwapBuffers())
  61422. {
  61423. ComponentPeer* const peer = getPeer();
  61424. if (peer != 0)
  61425. {
  61426. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61427. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61428. }
  61429. }
  61430. }
  61431. bool OpenGLComponent::renderAndSwapBuffers()
  61432. {
  61433. const ScopedLock sl (contextLock);
  61434. if (! makeCurrentContextActive())
  61435. return false;
  61436. if (needToUpdateViewport)
  61437. {
  61438. needToUpdateViewport = false;
  61439. juce_glViewport (getWidth(), getHeight());
  61440. }
  61441. renderOpenGL();
  61442. swapBuffers();
  61443. return true;
  61444. }
  61445. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61446. {
  61447. Component::internalRepaint (x, y, w, h);
  61448. if (context != 0)
  61449. context->repaint();
  61450. }
  61451. END_JUCE_NAMESPACE
  61452. #endif
  61453. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61454. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61455. BEGIN_JUCE_NAMESPACE
  61456. PreferencesPanel::PreferencesPanel()
  61457. : buttonSize (70)
  61458. {
  61459. }
  61460. PreferencesPanel::~PreferencesPanel()
  61461. {
  61462. }
  61463. void PreferencesPanel::addSettingsPage (const String& title,
  61464. const Drawable* icon,
  61465. const Drawable* overIcon,
  61466. const Drawable* downIcon)
  61467. {
  61468. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61469. buttons.add (button);
  61470. button->setImages (icon, overIcon, downIcon);
  61471. button->setRadioGroupId (1);
  61472. button->addListener (this);
  61473. button->setClickingTogglesState (true);
  61474. button->setWantsKeyboardFocus (false);
  61475. addAndMakeVisible (button);
  61476. resized();
  61477. if (currentPage == 0)
  61478. setCurrentPage (title);
  61479. }
  61480. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61481. {
  61482. DrawableImage icon, iconOver, iconDown;
  61483. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61484. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61485. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61486. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61487. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61488. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61489. }
  61490. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61491. {
  61492. setSize (dialogWidth, dialogHeight);
  61493. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61494. }
  61495. void PreferencesPanel::resized()
  61496. {
  61497. for (int i = 0; i < buttons.size(); ++i)
  61498. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61499. if (currentPage != 0)
  61500. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61501. }
  61502. void PreferencesPanel::paint (Graphics& g)
  61503. {
  61504. g.setColour (Colours::grey);
  61505. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61506. }
  61507. void PreferencesPanel::setCurrentPage (const String& pageName)
  61508. {
  61509. if (currentPageName != pageName)
  61510. {
  61511. currentPageName = pageName;
  61512. currentPage = 0;
  61513. currentPage = createComponentForPage (pageName);
  61514. if (currentPage != 0)
  61515. {
  61516. addAndMakeVisible (currentPage);
  61517. currentPage->toBack();
  61518. resized();
  61519. }
  61520. for (int i = 0; i < buttons.size(); ++i)
  61521. {
  61522. if (buttons.getUnchecked(i)->getName() == pageName)
  61523. {
  61524. buttons.getUnchecked(i)->setToggleState (true, false);
  61525. break;
  61526. }
  61527. }
  61528. }
  61529. }
  61530. void PreferencesPanel::buttonClicked (Button*)
  61531. {
  61532. for (int i = 0; i < buttons.size(); ++i)
  61533. {
  61534. if (buttons.getUnchecked(i)->getToggleState())
  61535. {
  61536. setCurrentPage (buttons.getUnchecked(i)->getName());
  61537. break;
  61538. }
  61539. }
  61540. }
  61541. END_JUCE_NAMESPACE
  61542. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61543. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61544. #if JUCE_WINDOWS || JUCE_LINUX
  61545. BEGIN_JUCE_NAMESPACE
  61546. SystemTrayIconComponent::SystemTrayIconComponent()
  61547. {
  61548. addToDesktop (0);
  61549. }
  61550. SystemTrayIconComponent::~SystemTrayIconComponent()
  61551. {
  61552. }
  61553. END_JUCE_NAMESPACE
  61554. #endif
  61555. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61556. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61557. BEGIN_JUCE_NAMESPACE
  61558. class AlertWindowTextEditor : public TextEditor
  61559. {
  61560. public:
  61561. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61562. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61563. {
  61564. setSelectAllWhenFocused (true);
  61565. }
  61566. void returnPressed()
  61567. {
  61568. // pass these up the component hierarchy to be trigger the buttons
  61569. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61570. }
  61571. void escapePressed()
  61572. {
  61573. // pass these up the component hierarchy to be trigger the buttons
  61574. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61575. }
  61576. private:
  61577. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61578. static juce_wchar getDefaultPasswordChar() throw()
  61579. {
  61580. #if JUCE_LINUX
  61581. return 0x2022;
  61582. #else
  61583. return 0x25cf;
  61584. #endif
  61585. }
  61586. };
  61587. AlertWindow::AlertWindow (const String& title,
  61588. const String& message,
  61589. AlertIconType iconType,
  61590. Component* associatedComponent_)
  61591. : TopLevelWindow (title, true),
  61592. alertIconType (iconType),
  61593. associatedComponent (associatedComponent_)
  61594. {
  61595. if (message.isEmpty())
  61596. text = " "; // to force an update if the message is empty
  61597. setMessage (message);
  61598. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61599. {
  61600. Component* const c = Desktop::getInstance().getComponent (i);
  61601. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61602. {
  61603. setAlwaysOnTop (true);
  61604. break;
  61605. }
  61606. }
  61607. if (! JUCEApplication::isStandaloneApp())
  61608. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61609. lookAndFeelChanged();
  61610. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61611. }
  61612. AlertWindow::~AlertWindow()
  61613. {
  61614. removeAllChildren();
  61615. }
  61616. void AlertWindow::userTriedToCloseWindow()
  61617. {
  61618. exitModalState (0);
  61619. }
  61620. void AlertWindow::setMessage (const String& message)
  61621. {
  61622. const String newMessage (message.substring (0, 2048));
  61623. if (text != newMessage)
  61624. {
  61625. text = newMessage;
  61626. font.setHeight (15.0f);
  61627. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61628. textLayout.setText (getName() + "\n\n", titleFont);
  61629. textLayout.appendText (text, font);
  61630. updateLayout (true);
  61631. repaint();
  61632. }
  61633. }
  61634. void AlertWindow::buttonClicked (Button* button)
  61635. {
  61636. if (button->getParentComponent() != 0)
  61637. button->getParentComponent()->exitModalState (button->getCommandID());
  61638. }
  61639. void AlertWindow::addButton (const String& name,
  61640. const int returnValue,
  61641. const KeyPress& shortcutKey1,
  61642. const KeyPress& shortcutKey2)
  61643. {
  61644. TextButton* const b = new TextButton (name, String::empty);
  61645. buttons.add (b);
  61646. b->setWantsKeyboardFocus (true);
  61647. b->setMouseClickGrabsKeyboardFocus (false);
  61648. b->setCommandToTrigger (0, returnValue, false);
  61649. b->addShortcut (shortcutKey1);
  61650. b->addShortcut (shortcutKey2);
  61651. b->addListener (this);
  61652. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61653. addAndMakeVisible (b, 0);
  61654. updateLayout (false);
  61655. }
  61656. int AlertWindow::getNumButtons() const
  61657. {
  61658. return buttons.size();
  61659. }
  61660. void AlertWindow::triggerButtonClick (const String& buttonName)
  61661. {
  61662. for (int i = buttons.size(); --i >= 0;)
  61663. {
  61664. TextButton* const b = buttons.getUnchecked(i);
  61665. if (buttonName == b->getName())
  61666. {
  61667. b->triggerClick();
  61668. break;
  61669. }
  61670. }
  61671. }
  61672. void AlertWindow::addTextEditor (const String& name,
  61673. const String& initialContents,
  61674. const String& onScreenLabel,
  61675. const bool isPasswordBox)
  61676. {
  61677. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61678. textBoxes.add (tc);
  61679. allComps.add (tc);
  61680. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61681. tc->setFont (font);
  61682. tc->setText (initialContents);
  61683. tc->setCaretPosition (initialContents.length());
  61684. addAndMakeVisible (tc);
  61685. textboxNames.add (onScreenLabel);
  61686. updateLayout (false);
  61687. }
  61688. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61689. {
  61690. for (int i = textBoxes.size(); --i >= 0;)
  61691. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61692. return textBoxes.getUnchecked(i);
  61693. return 0;
  61694. }
  61695. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61696. {
  61697. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61698. return t != 0 ? t->getText() : String::empty;
  61699. }
  61700. void AlertWindow::addComboBox (const String& name,
  61701. const StringArray& items,
  61702. const String& onScreenLabel)
  61703. {
  61704. ComboBox* const cb = new ComboBox (name);
  61705. comboBoxes.add (cb);
  61706. allComps.add (cb);
  61707. for (int i = 0; i < items.size(); ++i)
  61708. cb->addItem (items[i], i + 1);
  61709. addAndMakeVisible (cb);
  61710. cb->setSelectedItemIndex (0);
  61711. comboBoxNames.add (onScreenLabel);
  61712. updateLayout (false);
  61713. }
  61714. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61715. {
  61716. for (int i = comboBoxes.size(); --i >= 0;)
  61717. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61718. return comboBoxes.getUnchecked(i);
  61719. return 0;
  61720. }
  61721. class AlertTextComp : public TextEditor
  61722. {
  61723. public:
  61724. AlertTextComp (const String& message,
  61725. const Font& font)
  61726. {
  61727. setReadOnly (true);
  61728. setMultiLine (true, true);
  61729. setCaretVisible (false);
  61730. setScrollbarsShown (true);
  61731. lookAndFeelChanged();
  61732. setWantsKeyboardFocus (false);
  61733. setFont (font);
  61734. setText (message, false);
  61735. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61736. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61737. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61738. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61739. }
  61740. ~AlertTextComp()
  61741. {
  61742. }
  61743. int getPreferredWidth() const throw() { return bestWidth; }
  61744. void updateLayout (const int width)
  61745. {
  61746. TextLayout text;
  61747. text.appendText (getText(), getFont());
  61748. text.layout (width - 8, Justification::topLeft, true);
  61749. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61750. }
  61751. private:
  61752. int bestWidth;
  61753. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61754. };
  61755. void AlertWindow::addTextBlock (const String& textBlock)
  61756. {
  61757. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61758. textBlocks.add (c);
  61759. allComps.add (c);
  61760. addAndMakeVisible (c);
  61761. updateLayout (false);
  61762. }
  61763. void AlertWindow::addProgressBarComponent (double& progressValue)
  61764. {
  61765. ProgressBar* const pb = new ProgressBar (progressValue);
  61766. progressBars.add (pb);
  61767. allComps.add (pb);
  61768. addAndMakeVisible (pb);
  61769. updateLayout (false);
  61770. }
  61771. void AlertWindow::addCustomComponent (Component* const component)
  61772. {
  61773. customComps.add (component);
  61774. allComps.add (component);
  61775. addAndMakeVisible (component);
  61776. updateLayout (false);
  61777. }
  61778. int AlertWindow::getNumCustomComponents() const
  61779. {
  61780. return customComps.size();
  61781. }
  61782. Component* AlertWindow::getCustomComponent (const int index) const
  61783. {
  61784. return customComps [index];
  61785. }
  61786. Component* AlertWindow::removeCustomComponent (const int index)
  61787. {
  61788. Component* const c = getCustomComponent (index);
  61789. if (c != 0)
  61790. {
  61791. customComps.removeValue (c);
  61792. allComps.removeValue (c);
  61793. removeChildComponent (c);
  61794. updateLayout (false);
  61795. }
  61796. return c;
  61797. }
  61798. void AlertWindow::paint (Graphics& g)
  61799. {
  61800. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61801. g.setColour (findColour (textColourId));
  61802. g.setFont (getLookAndFeel().getAlertWindowFont());
  61803. int i;
  61804. for (i = textBoxes.size(); --i >= 0;)
  61805. {
  61806. const TextEditor* const te = textBoxes.getUnchecked(i);
  61807. g.drawFittedText (textboxNames[i],
  61808. te->getX(), te->getY() - 14,
  61809. te->getWidth(), 14,
  61810. Justification::centredLeft, 1);
  61811. }
  61812. for (i = comboBoxNames.size(); --i >= 0;)
  61813. {
  61814. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61815. g.drawFittedText (comboBoxNames[i],
  61816. cb->getX(), cb->getY() - 14,
  61817. cb->getWidth(), 14,
  61818. Justification::centredLeft, 1);
  61819. }
  61820. for (i = customComps.size(); --i >= 0;)
  61821. {
  61822. const Component* const c = customComps.getUnchecked(i);
  61823. g.drawFittedText (c->getName(),
  61824. c->getX(), c->getY() - 14,
  61825. c->getWidth(), 14,
  61826. Justification::centredLeft, 1);
  61827. }
  61828. }
  61829. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61830. {
  61831. const int titleH = 24;
  61832. const int iconWidth = 80;
  61833. const int wid = jmax (font.getStringWidth (text),
  61834. font.getStringWidth (getName()));
  61835. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61836. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61837. const int edgeGap = 10;
  61838. const int labelHeight = 18;
  61839. int iconSpace;
  61840. if (alertIconType == NoIcon)
  61841. {
  61842. textLayout.layout (w, Justification::horizontallyCentred, true);
  61843. iconSpace = 0;
  61844. }
  61845. else
  61846. {
  61847. textLayout.layout (w, Justification::left, true);
  61848. iconSpace = iconWidth;
  61849. }
  61850. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61851. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61852. const int textLayoutH = textLayout.getHeight();
  61853. const int textBottom = 16 + titleH + textLayoutH;
  61854. int h = textBottom;
  61855. int buttonW = 40;
  61856. int i;
  61857. for (i = 0; i < buttons.size(); ++i)
  61858. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61859. w = jmax (buttonW, w);
  61860. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61861. if (buttons.size() > 0)
  61862. h += 20 + buttons.getUnchecked(0)->getHeight();
  61863. for (i = customComps.size(); --i >= 0;)
  61864. {
  61865. Component* c = customComps.getUnchecked(i);
  61866. w = jmax (w, (c->getWidth() * 100) / 80);
  61867. h += 10 + c->getHeight();
  61868. if (c->getName().isNotEmpty())
  61869. h += labelHeight;
  61870. }
  61871. for (i = textBlocks.size(); --i >= 0;)
  61872. {
  61873. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61874. w = jmax (w, ac->getPreferredWidth());
  61875. }
  61876. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61877. for (i = textBlocks.size(); --i >= 0;)
  61878. {
  61879. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61880. ac->updateLayout ((int) (w * 0.8f));
  61881. h += ac->getHeight() + 10;
  61882. }
  61883. h = jmin (getParentHeight() - 50, h);
  61884. if (onlyIncreaseSize)
  61885. {
  61886. w = jmax (w, getWidth());
  61887. h = jmax (h, getHeight());
  61888. }
  61889. if (! isVisible())
  61890. {
  61891. centreAroundComponent (associatedComponent, w, h);
  61892. }
  61893. else
  61894. {
  61895. const int cx = getX() + getWidth() / 2;
  61896. const int cy = getY() + getHeight() / 2;
  61897. setBounds (cx - w / 2,
  61898. cy - h / 2,
  61899. w, h);
  61900. }
  61901. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61902. const int spacer = 16;
  61903. int totalWidth = -spacer;
  61904. for (i = buttons.size(); --i >= 0;)
  61905. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61906. int x = (w - totalWidth) / 2;
  61907. int y = (int) (getHeight() * 0.95f);
  61908. for (i = 0; i < buttons.size(); ++i)
  61909. {
  61910. TextButton* const c = buttons.getUnchecked(i);
  61911. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61912. c->setTopLeftPosition (x, ny);
  61913. if (ny < y)
  61914. y = ny;
  61915. x += c->getWidth() + spacer;
  61916. c->toFront (false);
  61917. }
  61918. y = textBottom;
  61919. for (i = 0; i < allComps.size(); ++i)
  61920. {
  61921. Component* const c = allComps.getUnchecked(i);
  61922. h = 22;
  61923. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61924. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61925. y += labelHeight;
  61926. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61927. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61928. y += labelHeight;
  61929. if (customComps.contains (c))
  61930. {
  61931. if (c->getName().isNotEmpty())
  61932. y += labelHeight;
  61933. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61934. h = c->getHeight();
  61935. }
  61936. else if (textBlocks.contains (c))
  61937. {
  61938. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61939. h = c->getHeight();
  61940. }
  61941. else
  61942. {
  61943. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61944. }
  61945. y += h + 10;
  61946. }
  61947. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61948. }
  61949. bool AlertWindow::containsAnyExtraComponents() const
  61950. {
  61951. return allComps.size() > 0;
  61952. }
  61953. void AlertWindow::mouseDown (const MouseEvent& e)
  61954. {
  61955. dragger.startDraggingComponent (this, e);
  61956. }
  61957. void AlertWindow::mouseDrag (const MouseEvent& e)
  61958. {
  61959. dragger.dragComponent (this, e, &constrainer);
  61960. }
  61961. bool AlertWindow::keyPressed (const KeyPress& key)
  61962. {
  61963. for (int i = buttons.size(); --i >= 0;)
  61964. {
  61965. TextButton* const b = buttons.getUnchecked(i);
  61966. if (b->isRegisteredForShortcut (key))
  61967. {
  61968. b->triggerClick();
  61969. return true;
  61970. }
  61971. }
  61972. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61973. {
  61974. exitModalState (0);
  61975. return true;
  61976. }
  61977. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61978. {
  61979. buttons.getUnchecked(0)->triggerClick();
  61980. return true;
  61981. }
  61982. return false;
  61983. }
  61984. void AlertWindow::lookAndFeelChanged()
  61985. {
  61986. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61987. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61988. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61989. }
  61990. int AlertWindow::getDesktopWindowStyleFlags() const
  61991. {
  61992. return getLookAndFeel().getAlertBoxWindowFlags();
  61993. }
  61994. class AlertWindowInfo
  61995. {
  61996. public:
  61997. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61998. AlertWindow::AlertIconType iconType_, int numButtons_)
  61999. : title (title_), message (message_), iconType (iconType_),
  62000. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  62001. {
  62002. }
  62003. String title, message, button1, button2, button3;
  62004. AlertWindow::AlertIconType iconType;
  62005. int numButtons, returnValue;
  62006. WeakReference<Component> associatedComponent;
  62007. int showModal() const
  62008. {
  62009. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62010. return returnValue;
  62011. }
  62012. private:
  62013. void show()
  62014. {
  62015. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62016. : LookAndFeel::getDefaultLookAndFeel();
  62017. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62018. iconType, numButtons, associatedComponent));
  62019. jassert (alertBox != 0); // you have to return one of these!
  62020. returnValue = alertBox->runModalLoop();
  62021. }
  62022. static void* showCallback (void* userData)
  62023. {
  62024. static_cast <AlertWindowInfo*> (userData)->show();
  62025. return 0;
  62026. }
  62027. };
  62028. void AlertWindow::showMessageBox (AlertIconType iconType,
  62029. const String& title,
  62030. const String& message,
  62031. const String& buttonText,
  62032. Component* associatedComponent)
  62033. {
  62034. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  62035. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62036. info.showModal();
  62037. }
  62038. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62039. const String& title,
  62040. const String& message,
  62041. const String& button1Text,
  62042. const String& button2Text,
  62043. Component* associatedComponent)
  62044. {
  62045. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  62046. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62047. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62048. return info.showModal() != 0;
  62049. }
  62050. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62051. const String& title,
  62052. const String& message,
  62053. const String& button1Text,
  62054. const String& button2Text,
  62055. const String& button3Text,
  62056. Component* associatedComponent)
  62057. {
  62058. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  62059. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62060. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62061. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62062. return info.showModal();
  62063. }
  62064. END_JUCE_NAMESPACE
  62065. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62066. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62067. BEGIN_JUCE_NAMESPACE
  62068. CallOutBox::CallOutBox (Component& contentComponent,
  62069. Component& componentToPointTo,
  62070. Component* const parentComponent)
  62071. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62072. {
  62073. addAndMakeVisible (&content);
  62074. if (parentComponent != 0)
  62075. {
  62076. parentComponent->addChildComponent (this);
  62077. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  62078. parentComponent->getLocalBounds());
  62079. setVisible (true);
  62080. }
  62081. else
  62082. {
  62083. if (! JUCEApplication::isStandaloneApp())
  62084. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62085. updatePosition (componentToPointTo.getScreenBounds(),
  62086. componentToPointTo.getParentMonitorArea());
  62087. addToDesktop (ComponentPeer::windowIsTemporary);
  62088. }
  62089. }
  62090. CallOutBox::~CallOutBox()
  62091. {
  62092. }
  62093. void CallOutBox::setArrowSize (const float newSize)
  62094. {
  62095. arrowSize = newSize;
  62096. borderSpace = jmax (20, (int) arrowSize);
  62097. refreshPath();
  62098. }
  62099. void CallOutBox::paint (Graphics& g)
  62100. {
  62101. if (background.isNull())
  62102. {
  62103. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62104. Graphics g (background);
  62105. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62106. }
  62107. g.setColour (Colours::black);
  62108. g.drawImageAt (background, 0, 0);
  62109. }
  62110. void CallOutBox::resized()
  62111. {
  62112. content.setTopLeftPosition (borderSpace, borderSpace);
  62113. refreshPath();
  62114. }
  62115. void CallOutBox::moved()
  62116. {
  62117. refreshPath();
  62118. }
  62119. void CallOutBox::childBoundsChanged (Component*)
  62120. {
  62121. updatePosition (targetArea, availableArea);
  62122. }
  62123. bool CallOutBox::hitTest (int x, int y)
  62124. {
  62125. return outline.contains ((float) x, (float) y);
  62126. }
  62127. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62128. void CallOutBox::inputAttemptWhenModal()
  62129. {
  62130. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62131. if (targetArea.contains (mousePos))
  62132. {
  62133. // if you click on the area that originally popped-up the callout, you expect it
  62134. // to get rid of the box, but deleting the box here allows the click to pass through and
  62135. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62136. postCommandMessage (callOutBoxDismissCommandId);
  62137. }
  62138. else
  62139. {
  62140. exitModalState (0);
  62141. setVisible (false);
  62142. }
  62143. }
  62144. void CallOutBox::handleCommandMessage (int commandId)
  62145. {
  62146. Component::handleCommandMessage (commandId);
  62147. if (commandId == callOutBoxDismissCommandId)
  62148. {
  62149. exitModalState (0);
  62150. setVisible (false);
  62151. }
  62152. }
  62153. bool CallOutBox::keyPressed (const KeyPress& key)
  62154. {
  62155. if (key.isKeyCode (KeyPress::escapeKey))
  62156. {
  62157. inputAttemptWhenModal();
  62158. return true;
  62159. }
  62160. return false;
  62161. }
  62162. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62163. {
  62164. targetArea = newAreaToPointTo;
  62165. availableArea = newAreaToFitIn;
  62166. Rectangle<int> bounds (0, 0,
  62167. content.getWidth() + borderSpace * 2,
  62168. content.getHeight() + borderSpace * 2);
  62169. const int hw = bounds.getWidth() / 2;
  62170. const int hh = bounds.getHeight() / 2;
  62171. const float hwReduced = (float) (hw - borderSpace * 3);
  62172. const float hhReduced = (float) (hh - borderSpace * 3);
  62173. const float arrowIndent = borderSpace - arrowSize;
  62174. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62175. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62176. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62177. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62178. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62179. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62180. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62181. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62182. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62183. float nearest = 1.0e9f;
  62184. for (int i = 0; i < 4; ++i)
  62185. {
  62186. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62187. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62188. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62189. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62190. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62191. distanceFromCentre *= 2.0f;
  62192. if (distanceFromCentre < nearest)
  62193. {
  62194. nearest = distanceFromCentre;
  62195. targetPoint = targets[i];
  62196. bounds.setPosition ((int) (centre.getX() - hw),
  62197. (int) (centre.getY() - hh));
  62198. }
  62199. }
  62200. setBounds (bounds);
  62201. }
  62202. void CallOutBox::refreshPath()
  62203. {
  62204. repaint();
  62205. background = Image::null;
  62206. outline.clear();
  62207. const float gap = 4.5f;
  62208. const float cornerSize = 9.0f;
  62209. const float cornerSize2 = 2.0f * cornerSize;
  62210. const float arrowBaseWidth = arrowSize * 0.7f;
  62211. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62212. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62213. outline.startNewSubPath (left + cornerSize, top);
  62214. if (targetY <= top)
  62215. {
  62216. outline.lineTo (targetX - arrowBaseWidth, top);
  62217. outline.lineTo (targetX, targetY);
  62218. outline.lineTo (targetX + arrowBaseWidth, top);
  62219. }
  62220. outline.lineTo (right - cornerSize, top);
  62221. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62222. if (targetX >= right)
  62223. {
  62224. outline.lineTo (right, targetY - arrowBaseWidth);
  62225. outline.lineTo (targetX, targetY);
  62226. outline.lineTo (right, targetY + arrowBaseWidth);
  62227. }
  62228. outline.lineTo (right, bottom - cornerSize);
  62229. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62230. if (targetY >= bottom)
  62231. {
  62232. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62233. outline.lineTo (targetX, targetY);
  62234. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62235. }
  62236. outline.lineTo (left + cornerSize, bottom);
  62237. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62238. if (targetX <= left)
  62239. {
  62240. outline.lineTo (left, targetY + arrowBaseWidth);
  62241. outline.lineTo (targetX, targetY);
  62242. outline.lineTo (left, targetY - arrowBaseWidth);
  62243. }
  62244. outline.lineTo (left, top + cornerSize);
  62245. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62246. outline.closeSubPath();
  62247. }
  62248. END_JUCE_NAMESPACE
  62249. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62250. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62251. BEGIN_JUCE_NAMESPACE
  62252. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62253. static Array <ComponentPeer*> heavyweightPeers;
  62254. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62255. : component (component_),
  62256. styleFlags (styleFlags_),
  62257. lastPaintTime (0),
  62258. constrainer (0),
  62259. lastDragAndDropCompUnderMouse (0),
  62260. fakeMouseMessageSent (false),
  62261. isWindowMinimised (false)
  62262. {
  62263. heavyweightPeers.add (this);
  62264. }
  62265. ComponentPeer::~ComponentPeer()
  62266. {
  62267. heavyweightPeers.removeValue (this);
  62268. Desktop::getInstance().triggerFocusCallback();
  62269. }
  62270. int ComponentPeer::getNumPeers() throw()
  62271. {
  62272. return heavyweightPeers.size();
  62273. }
  62274. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62275. {
  62276. return heavyweightPeers [index];
  62277. }
  62278. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62279. {
  62280. for (int i = heavyweightPeers.size(); --i >= 0;)
  62281. {
  62282. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62283. if (peer->getComponent() == component)
  62284. return peer;
  62285. }
  62286. return 0;
  62287. }
  62288. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62289. {
  62290. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62291. }
  62292. void ComponentPeer::updateCurrentModifiers() throw()
  62293. {
  62294. ModifierKeys::updateCurrentModifiers();
  62295. }
  62296. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62297. {
  62298. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62299. jassert (mouse != 0); // not enough sources!
  62300. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62301. }
  62302. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62303. {
  62304. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62305. jassert (mouse != 0); // not enough sources!
  62306. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62307. }
  62308. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62309. {
  62310. Graphics g (&contextToPaintTo);
  62311. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62312. g.saveState();
  62313. #endif
  62314. JUCE_TRY
  62315. {
  62316. component->paintEntireComponent (g, true);
  62317. }
  62318. JUCE_CATCH_EXCEPTION
  62319. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62320. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62321. // clearly when things are being repainted.
  62322. g.restoreState();
  62323. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62324. (uint8) Random::getSystemRandom().nextInt (255),
  62325. (uint8) Random::getSystemRandom().nextInt (255),
  62326. (uint8) 0x50));
  62327. #endif
  62328. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62329. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62330. mess up a lot of the calculations that the library needs to do.
  62331. */
  62332. jassert (roundToInt (10.1f) == 10);
  62333. }
  62334. bool ComponentPeer::handleKeyPress (const int keyCode,
  62335. const juce_wchar textCharacter)
  62336. {
  62337. updateCurrentModifiers();
  62338. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62339. ? Component::getCurrentlyFocusedComponent()
  62340. : component;
  62341. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62342. {
  62343. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62344. if (currentModalComp != 0)
  62345. target = currentModalComp;
  62346. }
  62347. const KeyPress keyInfo (keyCode,
  62348. ModifierKeys::getCurrentModifiers().getRawFlags()
  62349. & ModifierKeys::allKeyboardModifiers,
  62350. textCharacter);
  62351. bool keyWasUsed = false;
  62352. while (target != 0)
  62353. {
  62354. const WeakReference<Component> deletionChecker (target);
  62355. if (target->keyListeners_ != 0)
  62356. {
  62357. for (int i = target->keyListeners_->size(); --i >= 0;)
  62358. {
  62359. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62360. if (keyWasUsed || deletionChecker == 0)
  62361. return keyWasUsed;
  62362. i = jmin (i, target->keyListeners_->size());
  62363. }
  62364. }
  62365. keyWasUsed = target->keyPressed (keyInfo);
  62366. if (keyWasUsed || deletionChecker == 0)
  62367. break;
  62368. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62369. {
  62370. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62371. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62372. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62373. break;
  62374. }
  62375. target = target->parentComponent_;
  62376. }
  62377. return keyWasUsed;
  62378. }
  62379. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62380. {
  62381. updateCurrentModifiers();
  62382. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62383. ? Component::getCurrentlyFocusedComponent()
  62384. : component;
  62385. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62386. {
  62387. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62388. if (currentModalComp != 0)
  62389. target = currentModalComp;
  62390. }
  62391. bool keyWasUsed = false;
  62392. while (target != 0)
  62393. {
  62394. const WeakReference<Component> deletionChecker (target);
  62395. keyWasUsed = target->keyStateChanged (isKeyDown);
  62396. if (keyWasUsed || deletionChecker == 0)
  62397. break;
  62398. if (target->keyListeners_ != 0)
  62399. {
  62400. for (int i = target->keyListeners_->size(); --i >= 0;)
  62401. {
  62402. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62403. if (keyWasUsed || deletionChecker == 0)
  62404. return keyWasUsed;
  62405. i = jmin (i, target->keyListeners_->size());
  62406. }
  62407. }
  62408. target = target->parentComponent_;
  62409. }
  62410. return keyWasUsed;
  62411. }
  62412. void ComponentPeer::handleModifierKeysChange()
  62413. {
  62414. updateCurrentModifiers();
  62415. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62416. if (target == 0)
  62417. target = Component::getCurrentlyFocusedComponent();
  62418. if (target == 0)
  62419. target = component;
  62420. if (target != 0)
  62421. target->internalModifierKeysChanged();
  62422. }
  62423. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62424. {
  62425. Component* const c = Component::getCurrentlyFocusedComponent();
  62426. if (component->isParentOf (c))
  62427. {
  62428. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62429. if (ti != 0 && ti->isTextInputActive())
  62430. return ti;
  62431. }
  62432. return 0;
  62433. }
  62434. void ComponentPeer::handleBroughtToFront()
  62435. {
  62436. updateCurrentModifiers();
  62437. if (component != 0)
  62438. component->internalBroughtToFront();
  62439. }
  62440. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62441. {
  62442. constrainer = newConstrainer;
  62443. }
  62444. void ComponentPeer::handleMovedOrResized()
  62445. {
  62446. updateCurrentModifiers();
  62447. const bool nowMinimised = isMinimised();
  62448. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62449. {
  62450. const WeakReference<Component> deletionChecker (component);
  62451. const Rectangle<int> newBounds (getBounds());
  62452. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62453. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62454. if (wasMoved || wasResized)
  62455. {
  62456. component->bounds_ = newBounds;
  62457. if (wasResized)
  62458. component->repaint();
  62459. component->sendMovedResizedMessages (wasMoved, wasResized);
  62460. if (deletionChecker == 0)
  62461. return;
  62462. }
  62463. }
  62464. if (isWindowMinimised != nowMinimised)
  62465. {
  62466. isWindowMinimised = nowMinimised;
  62467. component->minimisationStateChanged (nowMinimised);
  62468. component->sendVisibilityChangeMessage();
  62469. }
  62470. if (! isFullScreen())
  62471. lastNonFullscreenBounds = component->getBounds();
  62472. }
  62473. void ComponentPeer::handleFocusGain()
  62474. {
  62475. updateCurrentModifiers();
  62476. if (component->isParentOf (lastFocusedComponent))
  62477. {
  62478. Component::currentlyFocusedComponent = lastFocusedComponent;
  62479. Desktop::getInstance().triggerFocusCallback();
  62480. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62481. }
  62482. else
  62483. {
  62484. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62485. component->grabKeyboardFocus();
  62486. else
  62487. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62488. }
  62489. }
  62490. void ComponentPeer::handleFocusLoss()
  62491. {
  62492. updateCurrentModifiers();
  62493. if (component->hasKeyboardFocus (true))
  62494. {
  62495. lastFocusedComponent = Component::currentlyFocusedComponent;
  62496. if (lastFocusedComponent != 0)
  62497. {
  62498. Component::currentlyFocusedComponent = 0;
  62499. Desktop::getInstance().triggerFocusCallback();
  62500. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62501. }
  62502. }
  62503. }
  62504. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62505. {
  62506. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62507. ? static_cast <Component*> (lastFocusedComponent)
  62508. : component;
  62509. }
  62510. void ComponentPeer::handleScreenSizeChange()
  62511. {
  62512. updateCurrentModifiers();
  62513. component->parentSizeChanged();
  62514. handleMovedOrResized();
  62515. }
  62516. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62517. {
  62518. lastNonFullscreenBounds = newBounds;
  62519. }
  62520. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62521. {
  62522. return lastNonFullscreenBounds;
  62523. }
  62524. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62525. {
  62526. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62527. }
  62528. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62529. {
  62530. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62531. }
  62532. namespace ComponentPeerHelpers
  62533. {
  62534. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62535. const StringArray& files,
  62536. FileDragAndDropTarget* const lastOne)
  62537. {
  62538. while (c != 0)
  62539. {
  62540. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62541. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62542. return t;
  62543. c = c->getParentComponent();
  62544. }
  62545. return 0;
  62546. }
  62547. }
  62548. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62549. {
  62550. updateCurrentModifiers();
  62551. FileDragAndDropTarget* lastTarget
  62552. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62553. FileDragAndDropTarget* newTarget = 0;
  62554. Component* const compUnderMouse = component->getComponentAt (position);
  62555. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62556. {
  62557. lastDragAndDropCompUnderMouse = compUnderMouse;
  62558. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62559. if (newTarget != lastTarget)
  62560. {
  62561. if (lastTarget != 0)
  62562. lastTarget->fileDragExit (files);
  62563. dragAndDropTargetComponent = 0;
  62564. if (newTarget != 0)
  62565. {
  62566. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62567. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62568. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62569. }
  62570. }
  62571. }
  62572. else
  62573. {
  62574. newTarget = lastTarget;
  62575. }
  62576. if (newTarget != 0)
  62577. {
  62578. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62579. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62580. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62581. }
  62582. }
  62583. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62584. {
  62585. handleFileDragMove (files, Point<int> (-1, -1));
  62586. jassert (dragAndDropTargetComponent == 0);
  62587. lastDragAndDropCompUnderMouse = 0;
  62588. }
  62589. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62590. {
  62591. handleFileDragMove (files, position);
  62592. if (dragAndDropTargetComponent != 0)
  62593. {
  62594. FileDragAndDropTarget* const target
  62595. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62596. dragAndDropTargetComponent = 0;
  62597. lastDragAndDropCompUnderMouse = 0;
  62598. if (target != 0)
  62599. {
  62600. Component* const targetComp = dynamic_cast <Component*> (target);
  62601. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62602. {
  62603. targetComp->internalModalInputAttempt();
  62604. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62605. return;
  62606. }
  62607. // We'll use an async message to deliver the drop, because if the target decides
  62608. // to run a modal loop, it can gum-up the operating system..
  62609. class AsyncFileDropMessage : public CallbackMessage
  62610. {
  62611. public:
  62612. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62613. const Point<int>& position_, const StringArray& files_)
  62614. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62615. {
  62616. }
  62617. void messageCallback()
  62618. {
  62619. if (target != 0)
  62620. dropTarget->filesDropped (files, position.getX(), position.getY());
  62621. }
  62622. private:
  62623. WeakReference<Component> target;
  62624. FileDragAndDropTarget* dropTarget;
  62625. Point<int> position;
  62626. StringArray files;
  62627. // (NB: don't make this non-copyable, which messes up in VC)
  62628. };
  62629. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62630. }
  62631. }
  62632. }
  62633. void ComponentPeer::handleUserClosingWindow()
  62634. {
  62635. updateCurrentModifiers();
  62636. component->userTriedToCloseWindow();
  62637. }
  62638. void ComponentPeer::clearMaskedRegion()
  62639. {
  62640. maskedRegion.clear();
  62641. }
  62642. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62643. {
  62644. maskedRegion.add (x, y, w, h);
  62645. }
  62646. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62647. {
  62648. StringArray s;
  62649. s.add ("Software Renderer");
  62650. return s;
  62651. }
  62652. int ComponentPeer::getCurrentRenderingEngine() throw()
  62653. {
  62654. return 0;
  62655. }
  62656. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62657. {
  62658. }
  62659. END_JUCE_NAMESPACE
  62660. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62661. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62662. BEGIN_JUCE_NAMESPACE
  62663. DialogWindow::DialogWindow (const String& name,
  62664. const Colour& backgroundColour_,
  62665. const bool escapeKeyTriggersCloseButton_,
  62666. const bool addToDesktop_)
  62667. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62668. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62669. {
  62670. }
  62671. DialogWindow::~DialogWindow()
  62672. {
  62673. }
  62674. void DialogWindow::resized()
  62675. {
  62676. DocumentWindow::resized();
  62677. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62678. if (escapeKeyTriggersCloseButton
  62679. && getCloseButton() != 0
  62680. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62681. {
  62682. getCloseButton()->addShortcut (esc);
  62683. }
  62684. }
  62685. // (Sadly, this can't be made a local class inside the showModalDialog function, because the
  62686. // VC compiler complains about the undefined copy constructor)
  62687. class TempDialogWindow : public DialogWindow
  62688. {
  62689. public:
  62690. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62691. : DialogWindow (title, colour, escapeCloses, true)
  62692. {
  62693. if (! JUCEApplication::isStandaloneApp())
  62694. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62695. }
  62696. void closeButtonPressed()
  62697. {
  62698. setVisible (false);
  62699. }
  62700. private:
  62701. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62702. };
  62703. int DialogWindow::showModalDialog (const String& dialogTitle,
  62704. Component* contentComponent,
  62705. Component* componentToCentreAround,
  62706. const Colour& colour,
  62707. const bool escapeKeyTriggersCloseButton,
  62708. const bool shouldBeResizable,
  62709. const bool useBottomRightCornerResizer)
  62710. {
  62711. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62712. dw.setContentComponent (contentComponent, true, true);
  62713. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62714. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62715. const int result = dw.runModalLoop();
  62716. dw.setContentComponent (0, false);
  62717. return result;
  62718. }
  62719. END_JUCE_NAMESPACE
  62720. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62721. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62722. BEGIN_JUCE_NAMESPACE
  62723. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62724. {
  62725. public:
  62726. ButtonListenerProxy (DocumentWindow& owner_)
  62727. : owner (owner_)
  62728. {
  62729. }
  62730. void buttonClicked (Button* button)
  62731. {
  62732. if (button == owner.getMinimiseButton())
  62733. owner.minimiseButtonPressed();
  62734. else if (button == owner.getMaximiseButton())
  62735. owner.maximiseButtonPressed();
  62736. else if (button == owner.getCloseButton())
  62737. owner.closeButtonPressed();
  62738. }
  62739. private:
  62740. DocumentWindow& owner;
  62741. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62742. };
  62743. DocumentWindow::DocumentWindow (const String& title,
  62744. const Colour& backgroundColour,
  62745. const int requiredButtons_,
  62746. const bool addToDesktop_)
  62747. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62748. titleBarHeight (26),
  62749. menuBarHeight (24),
  62750. requiredButtons (requiredButtons_),
  62751. #if JUCE_MAC
  62752. positionTitleBarButtonsOnLeft (true),
  62753. #else
  62754. positionTitleBarButtonsOnLeft (false),
  62755. #endif
  62756. drawTitleTextCentred (true),
  62757. menuBarModel (0)
  62758. {
  62759. setResizeLimits (128, 128, 32768, 32768);
  62760. lookAndFeelChanged();
  62761. }
  62762. DocumentWindow::~DocumentWindow()
  62763. {
  62764. // Don't delete or remove the resizer components yourself! They're managed by the
  62765. // DocumentWindow, and you should leave them alone! You may have deleted them
  62766. // accidentally by careless use of deleteAllChildren()..?
  62767. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62768. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62769. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62770. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62771. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62772. titleBarButtons[i] = 0;
  62773. menuBar = 0;
  62774. }
  62775. void DocumentWindow::repaintTitleBar()
  62776. {
  62777. repaint (getTitleBarArea());
  62778. }
  62779. void DocumentWindow::setName (const String& newName)
  62780. {
  62781. if (newName != getName())
  62782. {
  62783. Component::setName (newName);
  62784. repaintTitleBar();
  62785. }
  62786. }
  62787. void DocumentWindow::setIcon (const Image& imageToUse)
  62788. {
  62789. titleBarIcon = imageToUse;
  62790. repaintTitleBar();
  62791. }
  62792. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62793. {
  62794. titleBarHeight = newHeight;
  62795. resized();
  62796. repaintTitleBar();
  62797. }
  62798. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62799. const bool positionTitleBarButtonsOnLeft_)
  62800. {
  62801. requiredButtons = requiredButtons_;
  62802. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62803. lookAndFeelChanged();
  62804. }
  62805. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62806. {
  62807. drawTitleTextCentred = textShouldBeCentred;
  62808. repaintTitleBar();
  62809. }
  62810. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62811. const int menuBarHeight_)
  62812. {
  62813. if (menuBarModel != menuBarModel_)
  62814. {
  62815. menuBar = 0;
  62816. menuBarModel = menuBarModel_;
  62817. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62818. : getLookAndFeel().getDefaultMenuBarHeight();
  62819. if (menuBarModel != 0)
  62820. {
  62821. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62822. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62823. menuBar->setEnabled (isActiveWindow());
  62824. }
  62825. resized();
  62826. }
  62827. }
  62828. void DocumentWindow::closeButtonPressed()
  62829. {
  62830. /* If you've got a close button, you have to override this method to get
  62831. rid of your window!
  62832. If the window is just a pop-up, you should override this method and make
  62833. it delete the window in whatever way is appropriate for your app. E.g. you
  62834. might just want to call "delete this".
  62835. If your app is centred around this window such that the whole app should quit when
  62836. the window is closed, then you will probably want to use this method as an opportunity
  62837. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62838. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62839. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62840. or closing it via the taskbar icon on Windows).
  62841. */
  62842. jassertfalse;
  62843. }
  62844. void DocumentWindow::minimiseButtonPressed()
  62845. {
  62846. setMinimised (true);
  62847. }
  62848. void DocumentWindow::maximiseButtonPressed()
  62849. {
  62850. setFullScreen (! isFullScreen());
  62851. }
  62852. void DocumentWindow::paint (Graphics& g)
  62853. {
  62854. ResizableWindow::paint (g);
  62855. if (resizableBorder == 0)
  62856. {
  62857. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62858. const BorderSize border (getBorderThickness());
  62859. g.fillRect (0, 0, getWidth(), border.getTop());
  62860. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62861. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62862. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62863. }
  62864. const Rectangle<int> titleBarArea (getTitleBarArea());
  62865. g.reduceClipRegion (titleBarArea);
  62866. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62867. int titleSpaceX1 = 6;
  62868. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62869. for (int i = 0; i < 3; ++i)
  62870. {
  62871. if (titleBarButtons[i] != 0)
  62872. {
  62873. if (positionTitleBarButtonsOnLeft)
  62874. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62875. else
  62876. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62877. }
  62878. }
  62879. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62880. titleBarArea.getWidth(),
  62881. titleBarArea.getHeight(),
  62882. titleSpaceX1,
  62883. jmax (1, titleSpaceX2 - titleSpaceX1),
  62884. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62885. ! drawTitleTextCentred);
  62886. }
  62887. void DocumentWindow::resized()
  62888. {
  62889. ResizableWindow::resized();
  62890. if (titleBarButtons[1] != 0)
  62891. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62892. const Rectangle<int> titleBarArea (getTitleBarArea());
  62893. getLookAndFeel()
  62894. .positionDocumentWindowButtons (*this,
  62895. titleBarArea.getX(), titleBarArea.getY(),
  62896. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62897. titleBarButtons[0],
  62898. titleBarButtons[1],
  62899. titleBarButtons[2],
  62900. positionTitleBarButtonsOnLeft);
  62901. if (menuBar != 0)
  62902. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62903. titleBarArea.getWidth(), menuBarHeight);
  62904. }
  62905. const BorderSize DocumentWindow::getBorderThickness()
  62906. {
  62907. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62908. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62909. }
  62910. const BorderSize DocumentWindow::getContentComponentBorder()
  62911. {
  62912. BorderSize border (getBorderThickness());
  62913. border.setTop (border.getTop()
  62914. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62915. + (menuBar != 0 ? menuBarHeight : 0));
  62916. return border;
  62917. }
  62918. int DocumentWindow::getTitleBarHeight() const
  62919. {
  62920. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62921. }
  62922. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62923. {
  62924. const BorderSize border (getBorderThickness());
  62925. return Rectangle<int> (border.getLeft(), border.getTop(),
  62926. getWidth() - border.getLeftAndRight(),
  62927. getTitleBarHeight());
  62928. }
  62929. Button* DocumentWindow::getCloseButton() const throw()
  62930. {
  62931. return titleBarButtons[2];
  62932. }
  62933. Button* DocumentWindow::getMinimiseButton() const throw()
  62934. {
  62935. return titleBarButtons[0];
  62936. }
  62937. Button* DocumentWindow::getMaximiseButton() const throw()
  62938. {
  62939. return titleBarButtons[1];
  62940. }
  62941. int DocumentWindow::getDesktopWindowStyleFlags() const
  62942. {
  62943. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62944. if ((requiredButtons & minimiseButton) != 0)
  62945. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62946. if ((requiredButtons & maximiseButton) != 0)
  62947. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62948. if ((requiredButtons & closeButton) != 0)
  62949. styleFlags |= ComponentPeer::windowHasCloseButton;
  62950. return styleFlags;
  62951. }
  62952. void DocumentWindow::lookAndFeelChanged()
  62953. {
  62954. int i;
  62955. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62956. titleBarButtons[i] = 0;
  62957. if (! isUsingNativeTitleBar())
  62958. {
  62959. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62960. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62961. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62962. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62963. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62964. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62965. for (i = 0; i < 3; ++i)
  62966. {
  62967. if (titleBarButtons[i] != 0)
  62968. {
  62969. if (buttonListener == 0)
  62970. buttonListener = new ButtonListenerProxy (*this);
  62971. titleBarButtons[i]->addListener (buttonListener);
  62972. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62973. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62974. Component::addAndMakeVisible (titleBarButtons[i]);
  62975. }
  62976. }
  62977. if (getCloseButton() != 0)
  62978. {
  62979. #if JUCE_MAC
  62980. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62981. #else
  62982. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62983. #endif
  62984. }
  62985. }
  62986. activeWindowStatusChanged();
  62987. ResizableWindow::lookAndFeelChanged();
  62988. }
  62989. void DocumentWindow::parentHierarchyChanged()
  62990. {
  62991. lookAndFeelChanged();
  62992. }
  62993. void DocumentWindow::activeWindowStatusChanged()
  62994. {
  62995. ResizableWindow::activeWindowStatusChanged();
  62996. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62997. if (titleBarButtons[i] != 0)
  62998. titleBarButtons[i]->setEnabled (isActiveWindow());
  62999. if (menuBar != 0)
  63000. menuBar->setEnabled (isActiveWindow());
  63001. }
  63002. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63003. {
  63004. if (getTitleBarArea().contains (e.x, e.y)
  63005. && getMaximiseButton() != 0)
  63006. {
  63007. getMaximiseButton()->triggerClick();
  63008. }
  63009. }
  63010. void DocumentWindow::userTriedToCloseWindow()
  63011. {
  63012. closeButtonPressed();
  63013. }
  63014. END_JUCE_NAMESPACE
  63015. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63016. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63017. BEGIN_JUCE_NAMESPACE
  63018. ResizableWindow::ResizableWindow (const String& name,
  63019. const bool addToDesktop_)
  63020. : TopLevelWindow (name, addToDesktop_),
  63021. resizeToFitContent (false),
  63022. fullscreen (false),
  63023. lastNonFullScreenPos (50, 50, 256, 256),
  63024. constrainer (0)
  63025. #if JUCE_DEBUG
  63026. , hasBeenResized (false)
  63027. #endif
  63028. {
  63029. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63030. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63031. if (addToDesktop_)
  63032. Component::addToDesktop (getDesktopWindowStyleFlags());
  63033. }
  63034. ResizableWindow::ResizableWindow (const String& name,
  63035. const Colour& backgroundColour_,
  63036. const bool addToDesktop_)
  63037. : TopLevelWindow (name, addToDesktop_),
  63038. resizeToFitContent (false),
  63039. fullscreen (false),
  63040. lastNonFullScreenPos (50, 50, 256, 256),
  63041. constrainer (0)
  63042. #if JUCE_DEBUG
  63043. , hasBeenResized (false)
  63044. #endif
  63045. {
  63046. setBackgroundColour (backgroundColour_);
  63047. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63048. if (addToDesktop_)
  63049. Component::addToDesktop (getDesktopWindowStyleFlags());
  63050. }
  63051. ResizableWindow::~ResizableWindow()
  63052. {
  63053. // Don't delete or remove the resizer components yourself! They're managed by the
  63054. // ResizableWindow, and you should leave them alone! You may have deleted them
  63055. // accidentally by careless use of deleteAllChildren()..?
  63056. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  63057. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  63058. resizableCorner = 0;
  63059. resizableBorder = 0;
  63060. contentComponent.deleteAndZero();
  63061. // have you been adding your own components directly to this window..? tut tut tut.
  63062. // Read the instructions for using a ResizableWindow!
  63063. jassert (getNumChildComponents() == 0);
  63064. }
  63065. int ResizableWindow::getDesktopWindowStyleFlags() const
  63066. {
  63067. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63068. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63069. styleFlags |= ComponentPeer::windowIsResizable;
  63070. return styleFlags;
  63071. }
  63072. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63073. const bool deleteOldOne,
  63074. const bool resizeToFit)
  63075. {
  63076. resizeToFitContent = resizeToFit;
  63077. if (newContentComponent != static_cast <Component*> (contentComponent))
  63078. {
  63079. if (deleteOldOne)
  63080. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63081. // external deletion of the content comp)
  63082. else
  63083. removeChildComponent (contentComponent);
  63084. contentComponent = newContentComponent;
  63085. Component::addAndMakeVisible (contentComponent);
  63086. }
  63087. if (resizeToFit)
  63088. childBoundsChanged (contentComponent);
  63089. resized(); // must always be called to position the new content comp
  63090. }
  63091. void ResizableWindow::setContentComponentSize (int width, int height)
  63092. {
  63093. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63094. const BorderSize border (getContentComponentBorder());
  63095. setSize (width + border.getLeftAndRight(),
  63096. height + border.getTopAndBottom());
  63097. }
  63098. const BorderSize ResizableWindow::getBorderThickness()
  63099. {
  63100. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63101. }
  63102. const BorderSize ResizableWindow::getContentComponentBorder()
  63103. {
  63104. return getBorderThickness();
  63105. }
  63106. void ResizableWindow::moved()
  63107. {
  63108. updateLastPos();
  63109. }
  63110. void ResizableWindow::visibilityChanged()
  63111. {
  63112. TopLevelWindow::visibilityChanged();
  63113. updateLastPos();
  63114. }
  63115. void ResizableWindow::resized()
  63116. {
  63117. if (resizableBorder != 0)
  63118. {
  63119. #if JUCE_WINDOWS || JUCE_LINUX
  63120. // hide the resizable border if the OS already provides one..
  63121. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63122. #else
  63123. resizableBorder->setVisible (! isFullScreen());
  63124. #endif
  63125. resizableBorder->setBorderThickness (getBorderThickness());
  63126. resizableBorder->setSize (getWidth(), getHeight());
  63127. resizableBorder->toBack();
  63128. }
  63129. if (resizableCorner != 0)
  63130. {
  63131. #if JUCE_MAC
  63132. // hide the resizable border if the OS already provides one..
  63133. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63134. #else
  63135. resizableCorner->setVisible (! isFullScreen());
  63136. #endif
  63137. const int resizerSize = 18;
  63138. resizableCorner->setBounds (getWidth() - resizerSize,
  63139. getHeight() - resizerSize,
  63140. resizerSize, resizerSize);
  63141. }
  63142. if (contentComponent != 0)
  63143. contentComponent->setBoundsInset (getContentComponentBorder());
  63144. updateLastPos();
  63145. #if JUCE_DEBUG
  63146. hasBeenResized = true;
  63147. #endif
  63148. }
  63149. void ResizableWindow::childBoundsChanged (Component* child)
  63150. {
  63151. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63152. {
  63153. // not going to look very good if this component has a zero size..
  63154. jassert (child->getWidth() > 0);
  63155. jassert (child->getHeight() > 0);
  63156. const BorderSize borders (getContentComponentBorder());
  63157. setSize (child->getWidth() + borders.getLeftAndRight(),
  63158. child->getHeight() + borders.getTopAndBottom());
  63159. }
  63160. }
  63161. void ResizableWindow::activeWindowStatusChanged()
  63162. {
  63163. const BorderSize border (getContentComponentBorder());
  63164. Rectangle<int> area (getLocalBounds());
  63165. repaint (area.removeFromTop (border.getTop()));
  63166. repaint (area.removeFromLeft (border.getLeft()));
  63167. repaint (area.removeFromRight (border.getRight()));
  63168. repaint (area.removeFromBottom (border.getBottom()));
  63169. }
  63170. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63171. const bool useBottomRightCornerResizer)
  63172. {
  63173. if (shouldBeResizable)
  63174. {
  63175. if (useBottomRightCornerResizer)
  63176. {
  63177. resizableBorder = 0;
  63178. if (resizableCorner == 0)
  63179. {
  63180. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63181. resizableCorner->setAlwaysOnTop (true);
  63182. }
  63183. }
  63184. else
  63185. {
  63186. resizableCorner = 0;
  63187. if (resizableBorder == 0)
  63188. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63189. }
  63190. }
  63191. else
  63192. {
  63193. resizableCorner = 0;
  63194. resizableBorder = 0;
  63195. }
  63196. if (isUsingNativeTitleBar())
  63197. recreateDesktopWindow();
  63198. childBoundsChanged (contentComponent);
  63199. resized();
  63200. }
  63201. bool ResizableWindow::isResizable() const throw()
  63202. {
  63203. return resizableCorner != 0
  63204. || resizableBorder != 0;
  63205. }
  63206. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63207. const int newMinimumHeight,
  63208. const int newMaximumWidth,
  63209. const int newMaximumHeight) throw()
  63210. {
  63211. // if you've set up a custom constrainer then these settings won't have any effect..
  63212. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63213. if (constrainer == 0)
  63214. setConstrainer (&defaultConstrainer);
  63215. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63216. newMaximumWidth, newMaximumHeight);
  63217. setBoundsConstrained (getBounds());
  63218. }
  63219. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63220. {
  63221. if (constrainer != newConstrainer)
  63222. {
  63223. constrainer = newConstrainer;
  63224. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63225. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63226. resizableCorner = 0;
  63227. resizableBorder = 0;
  63228. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63229. ComponentPeer* const peer = getPeer();
  63230. if (peer != 0)
  63231. peer->setConstrainer (newConstrainer);
  63232. }
  63233. }
  63234. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63235. {
  63236. if (constrainer != 0)
  63237. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63238. else
  63239. setBounds (bounds);
  63240. }
  63241. void ResizableWindow::paint (Graphics& g)
  63242. {
  63243. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63244. getBorderThickness(), *this);
  63245. if (! isFullScreen())
  63246. {
  63247. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63248. getBorderThickness(), *this);
  63249. }
  63250. #if JUCE_DEBUG
  63251. /* If this fails, then you've probably written a subclass with a resized()
  63252. callback but forgotten to make it call its parent class's resized() method.
  63253. It's important when you override methods like resized(), moved(),
  63254. etc., that you make sure the base class methods also get called.
  63255. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63256. because your content should all be inside the content component - and it's the
  63257. content component's resized() method that you should be using to do your
  63258. layout.
  63259. */
  63260. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63261. #endif
  63262. }
  63263. void ResizableWindow::lookAndFeelChanged()
  63264. {
  63265. resized();
  63266. if (isOnDesktop())
  63267. {
  63268. Component::addToDesktop (getDesktopWindowStyleFlags());
  63269. ComponentPeer* const peer = getPeer();
  63270. if (peer != 0)
  63271. peer->setConstrainer (constrainer);
  63272. }
  63273. }
  63274. const Colour ResizableWindow::getBackgroundColour() const throw()
  63275. {
  63276. return findColour (backgroundColourId, false);
  63277. }
  63278. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63279. {
  63280. Colour backgroundColour (newColour);
  63281. if (! Desktop::canUseSemiTransparentWindows())
  63282. backgroundColour = newColour.withAlpha (1.0f);
  63283. setColour (backgroundColourId, backgroundColour);
  63284. setOpaque (backgroundColour.isOpaque());
  63285. repaint();
  63286. }
  63287. bool ResizableWindow::isFullScreen() const
  63288. {
  63289. if (isOnDesktop())
  63290. {
  63291. ComponentPeer* const peer = getPeer();
  63292. return peer != 0 && peer->isFullScreen();
  63293. }
  63294. return fullscreen;
  63295. }
  63296. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63297. {
  63298. if (shouldBeFullScreen != isFullScreen())
  63299. {
  63300. updateLastPos();
  63301. fullscreen = shouldBeFullScreen;
  63302. if (isOnDesktop())
  63303. {
  63304. ComponentPeer* const peer = getPeer();
  63305. if (peer != 0)
  63306. {
  63307. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63308. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63309. peer->setFullScreen (shouldBeFullScreen);
  63310. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63311. setBounds (lastPos);
  63312. }
  63313. else
  63314. {
  63315. jassertfalse;
  63316. }
  63317. }
  63318. else
  63319. {
  63320. if (shouldBeFullScreen)
  63321. setBounds (0, 0, getParentWidth(), getParentHeight());
  63322. else
  63323. setBounds (lastNonFullScreenPos);
  63324. }
  63325. resized();
  63326. }
  63327. }
  63328. bool ResizableWindow::isMinimised() const
  63329. {
  63330. ComponentPeer* const peer = getPeer();
  63331. return (peer != 0) && peer->isMinimised();
  63332. }
  63333. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63334. {
  63335. if (shouldMinimise != isMinimised())
  63336. {
  63337. ComponentPeer* const peer = getPeer();
  63338. if (peer != 0)
  63339. {
  63340. updateLastPos();
  63341. peer->setMinimised (shouldMinimise);
  63342. }
  63343. else
  63344. {
  63345. jassertfalse;
  63346. }
  63347. }
  63348. }
  63349. void ResizableWindow::updateLastPos()
  63350. {
  63351. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63352. {
  63353. lastNonFullScreenPos = getBounds();
  63354. }
  63355. }
  63356. void ResizableWindow::parentSizeChanged()
  63357. {
  63358. if (isFullScreen() && getParentComponent() != 0)
  63359. {
  63360. setBounds (0, 0, getParentWidth(), getParentHeight());
  63361. }
  63362. }
  63363. const String ResizableWindow::getWindowStateAsString()
  63364. {
  63365. updateLastPos();
  63366. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63367. }
  63368. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63369. {
  63370. StringArray tokens;
  63371. tokens.addTokens (s, false);
  63372. tokens.removeEmptyStrings();
  63373. tokens.trim();
  63374. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63375. const int firstCoord = fs ? 1 : 0;
  63376. if (tokens.size() != firstCoord + 4)
  63377. return false;
  63378. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63379. tokens[firstCoord + 1].getIntValue(),
  63380. tokens[firstCoord + 2].getIntValue(),
  63381. tokens[firstCoord + 3].getIntValue());
  63382. if (newPos.isEmpty())
  63383. return false;
  63384. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63385. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63386. if (peer != 0)
  63387. peer->getFrameSize().addTo (newPos);
  63388. if (! screen.contains (newPos))
  63389. {
  63390. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63391. jmin (newPos.getHeight(), screen.getHeight()));
  63392. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63393. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63394. }
  63395. if (peer != 0)
  63396. {
  63397. peer->getFrameSize().subtractFrom (newPos);
  63398. peer->setNonFullScreenBounds (newPos);
  63399. }
  63400. lastNonFullScreenPos = newPos;
  63401. setFullScreen (fs);
  63402. if (! fs)
  63403. setBoundsConstrained (newPos);
  63404. return true;
  63405. }
  63406. void ResizableWindow::mouseDown (const MouseEvent& e)
  63407. {
  63408. if (! isFullScreen())
  63409. dragger.startDraggingComponent (this, e);
  63410. }
  63411. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63412. {
  63413. if (! isFullScreen())
  63414. dragger.dragComponent (this, e, constrainer);
  63415. }
  63416. #if JUCE_DEBUG
  63417. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63418. {
  63419. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63420. manages its child components automatically, and if you add your own it'll cause
  63421. trouble. Instead, use setContentComponent() to give it a component which
  63422. will be automatically resized and kept in the right place - then you can add
  63423. subcomponents to the content comp. See the notes for the ResizableWindow class
  63424. for more info.
  63425. If you really know what you're doing and want to avoid this assertion, just call
  63426. Component::addChildComponent directly.
  63427. */
  63428. jassertfalse;
  63429. Component::addChildComponent (child, zOrder);
  63430. }
  63431. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63432. {
  63433. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63434. manages its child components automatically, and if you add your own it'll cause
  63435. trouble. Instead, use setContentComponent() to give it a component which
  63436. will be automatically resized and kept in the right place - then you can add
  63437. subcomponents to the content comp. See the notes for the ResizableWindow class
  63438. for more info.
  63439. If you really know what you're doing and want to avoid this assertion, just call
  63440. Component::addAndMakeVisible directly.
  63441. */
  63442. jassertfalse;
  63443. Component::addAndMakeVisible (child, zOrder);
  63444. }
  63445. #endif
  63446. END_JUCE_NAMESPACE
  63447. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63448. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63449. BEGIN_JUCE_NAMESPACE
  63450. SplashScreen::SplashScreen()
  63451. {
  63452. setOpaque (true);
  63453. }
  63454. SplashScreen::~SplashScreen()
  63455. {
  63456. }
  63457. void SplashScreen::show (const String& title,
  63458. const Image& backgroundImage_,
  63459. const int minimumTimeToDisplayFor,
  63460. const bool useDropShadow,
  63461. const bool removeOnMouseClick)
  63462. {
  63463. backgroundImage = backgroundImage_;
  63464. jassert (backgroundImage_.isValid());
  63465. if (backgroundImage_.isValid())
  63466. {
  63467. setOpaque (! backgroundImage_.hasAlphaChannel());
  63468. show (title,
  63469. backgroundImage_.getWidth(),
  63470. backgroundImage_.getHeight(),
  63471. minimumTimeToDisplayFor,
  63472. useDropShadow,
  63473. removeOnMouseClick);
  63474. }
  63475. }
  63476. void SplashScreen::show (const String& title,
  63477. const int width,
  63478. const int height,
  63479. const int minimumTimeToDisplayFor,
  63480. const bool useDropShadow,
  63481. const bool removeOnMouseClick)
  63482. {
  63483. setName (title);
  63484. setAlwaysOnTop (true);
  63485. setVisible (true);
  63486. centreWithSize (width, height);
  63487. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63488. toFront (false);
  63489. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63490. repaint();
  63491. originalClickCounter = removeOnMouseClick
  63492. ? Desktop::getMouseButtonClickCounter()
  63493. : std::numeric_limits<int>::max();
  63494. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63495. startTimer (50);
  63496. }
  63497. void SplashScreen::paint (Graphics& g)
  63498. {
  63499. g.setOpacity (1.0f);
  63500. g.drawImage (backgroundImage,
  63501. 0, 0, getWidth(), getHeight(),
  63502. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63503. }
  63504. void SplashScreen::timerCallback()
  63505. {
  63506. if (Time::getCurrentTime() > earliestTimeToDelete
  63507. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63508. {
  63509. delete this;
  63510. }
  63511. }
  63512. END_JUCE_NAMESPACE
  63513. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63514. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63515. BEGIN_JUCE_NAMESPACE
  63516. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63517. const bool hasProgressBar,
  63518. const bool hasCancelButton,
  63519. const int timeOutMsWhenCancelling_,
  63520. const String& cancelButtonText)
  63521. : Thread ("Juce Progress Window"),
  63522. progress (0.0),
  63523. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63524. {
  63525. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63526. .createAlertWindow (title, String::empty, cancelButtonText,
  63527. String::empty, String::empty,
  63528. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63529. if (hasProgressBar)
  63530. alertWindow->addProgressBarComponent (progress);
  63531. }
  63532. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63533. {
  63534. stopThread (timeOutMsWhenCancelling);
  63535. }
  63536. bool ThreadWithProgressWindow::runThread (const int priority)
  63537. {
  63538. startThread (priority);
  63539. startTimer (100);
  63540. {
  63541. const ScopedLock sl (messageLock);
  63542. alertWindow->setMessage (message);
  63543. }
  63544. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63545. stopThread (timeOutMsWhenCancelling);
  63546. alertWindow->setVisible (false);
  63547. return finishedNaturally;
  63548. }
  63549. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63550. {
  63551. progress = newProgress;
  63552. }
  63553. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63554. {
  63555. const ScopedLock sl (messageLock);
  63556. message = newStatusMessage;
  63557. }
  63558. void ThreadWithProgressWindow::timerCallback()
  63559. {
  63560. if (! isThreadRunning())
  63561. {
  63562. // thread has finished normally..
  63563. alertWindow->exitModalState (1);
  63564. alertWindow->setVisible (false);
  63565. }
  63566. else
  63567. {
  63568. const ScopedLock sl (messageLock);
  63569. alertWindow->setMessage (message);
  63570. }
  63571. }
  63572. END_JUCE_NAMESPACE
  63573. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63574. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63575. BEGIN_JUCE_NAMESPACE
  63576. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63577. const int millisecondsBeforeTipAppears_)
  63578. : Component ("tooltip"),
  63579. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63580. mouseClicks (0),
  63581. lastHideTime (0),
  63582. lastComponentUnderMouse (0),
  63583. changedCompsSinceShown (true)
  63584. {
  63585. if (Desktop::getInstance().getMainMouseSource().canHover())
  63586. startTimer (123);
  63587. setAlwaysOnTop (true);
  63588. setOpaque (true);
  63589. if (parentComponent != 0)
  63590. parentComponent->addChildComponent (this);
  63591. }
  63592. TooltipWindow::~TooltipWindow()
  63593. {
  63594. hide();
  63595. }
  63596. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63597. {
  63598. millisecondsBeforeTipAppears = newTimeMs;
  63599. }
  63600. void TooltipWindow::paint (Graphics& g)
  63601. {
  63602. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63603. }
  63604. void TooltipWindow::mouseEnter (const MouseEvent&)
  63605. {
  63606. hide();
  63607. }
  63608. void TooltipWindow::showFor (const String& tip)
  63609. {
  63610. jassert (tip.isNotEmpty());
  63611. if (tipShowing != tip)
  63612. repaint();
  63613. tipShowing = tip;
  63614. Point<int> mousePos (Desktop::getMousePosition());
  63615. if (getParentComponent() != 0)
  63616. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63617. int x, y, w, h;
  63618. getLookAndFeel().getTooltipSize (tip, w, h);
  63619. if (mousePos.getX() > getParentWidth() / 2)
  63620. x = mousePos.getX() - (w + 12);
  63621. else
  63622. x = mousePos.getX() + 24;
  63623. if (mousePos.getY() > getParentHeight() / 2)
  63624. y = mousePos.getY() - (h + 6);
  63625. else
  63626. y = mousePos.getY() + 6;
  63627. setBounds (x, y, w, h);
  63628. setVisible (true);
  63629. if (getParentComponent() == 0)
  63630. {
  63631. addToDesktop (ComponentPeer::windowHasDropShadow
  63632. | ComponentPeer::windowIsTemporary
  63633. | ComponentPeer::windowIgnoresKeyPresses);
  63634. }
  63635. toFront (false);
  63636. }
  63637. const String TooltipWindow::getTipFor (Component* const c)
  63638. {
  63639. if (c != 0
  63640. && Process::isForegroundProcess()
  63641. && ! Component::isMouseButtonDownAnywhere())
  63642. {
  63643. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63644. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63645. return ttc->getTooltip();
  63646. }
  63647. return String::empty;
  63648. }
  63649. void TooltipWindow::hide()
  63650. {
  63651. tipShowing = String::empty;
  63652. removeFromDesktop();
  63653. setVisible (false);
  63654. }
  63655. void TooltipWindow::timerCallback()
  63656. {
  63657. const unsigned int now = Time::getApproximateMillisecondCounter();
  63658. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63659. const String newTip (getTipFor (newComp));
  63660. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63661. lastComponentUnderMouse = newComp;
  63662. lastTipUnderMouse = newTip;
  63663. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63664. const bool mouseWasClicked = clickCount > mouseClicks;
  63665. mouseClicks = clickCount;
  63666. const Point<int> mousePos (Desktop::getMousePosition());
  63667. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63668. lastMousePos = mousePos;
  63669. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63670. lastCompChangeTime = now;
  63671. if (isVisible() || now < lastHideTime + 500)
  63672. {
  63673. // if a tip is currently visible (or has just disappeared), update to a new one
  63674. // immediately if needed..
  63675. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63676. {
  63677. if (isVisible())
  63678. {
  63679. lastHideTime = now;
  63680. hide();
  63681. }
  63682. }
  63683. else if (tipChanged)
  63684. {
  63685. showFor (newTip);
  63686. }
  63687. }
  63688. else
  63689. {
  63690. // if there isn't currently a tip, but one is needed, only let it
  63691. // appear after a timeout..
  63692. if (newTip.isNotEmpty()
  63693. && newTip != tipShowing
  63694. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63695. {
  63696. showFor (newTip);
  63697. }
  63698. }
  63699. }
  63700. END_JUCE_NAMESPACE
  63701. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63702. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63703. BEGIN_JUCE_NAMESPACE
  63704. /** Keeps track of the active top level window.
  63705. */
  63706. class TopLevelWindowManager : public Timer,
  63707. public DeletedAtShutdown
  63708. {
  63709. public:
  63710. TopLevelWindowManager()
  63711. : currentActive (0)
  63712. {
  63713. }
  63714. ~TopLevelWindowManager()
  63715. {
  63716. clearSingletonInstance();
  63717. }
  63718. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63719. void timerCallback()
  63720. {
  63721. startTimer (jmin (1731, getTimerInterval() * 2));
  63722. TopLevelWindow* active = 0;
  63723. if (Process::isForegroundProcess())
  63724. {
  63725. active = currentActive;
  63726. Component* const c = Component::getCurrentlyFocusedComponent();
  63727. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63728. if (tlw == 0 && c != 0)
  63729. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63730. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63731. if (tlw != 0)
  63732. active = tlw;
  63733. }
  63734. if (active != currentActive)
  63735. {
  63736. currentActive = active;
  63737. for (int i = windows.size(); --i >= 0;)
  63738. {
  63739. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63740. tlw->setWindowActive (isWindowActive (tlw));
  63741. i = jmin (i, windows.size() - 1);
  63742. }
  63743. Desktop::getInstance().triggerFocusCallback();
  63744. }
  63745. }
  63746. bool addWindow (TopLevelWindow* const w)
  63747. {
  63748. windows.add (w);
  63749. startTimer (10);
  63750. return isWindowActive (w);
  63751. }
  63752. void removeWindow (TopLevelWindow* const w)
  63753. {
  63754. startTimer (10);
  63755. if (currentActive == w)
  63756. currentActive = 0;
  63757. windows.removeValue (w);
  63758. if (windows.size() == 0)
  63759. deleteInstance();
  63760. }
  63761. Array <TopLevelWindow*> windows;
  63762. private:
  63763. TopLevelWindow* currentActive;
  63764. bool isWindowActive (TopLevelWindow* const tlw) const
  63765. {
  63766. return (tlw == currentActive
  63767. || tlw->isParentOf (currentActive)
  63768. || tlw->hasKeyboardFocus (true))
  63769. && tlw->isShowing();
  63770. }
  63771. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63772. };
  63773. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63774. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63775. {
  63776. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63777. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63778. }
  63779. TopLevelWindow::TopLevelWindow (const String& name,
  63780. const bool addToDesktop_)
  63781. : Component (name),
  63782. useDropShadow (true),
  63783. useNativeTitleBar (false),
  63784. windowIsActive_ (false)
  63785. {
  63786. setOpaque (true);
  63787. if (addToDesktop_)
  63788. Component::addToDesktop (getDesktopWindowStyleFlags());
  63789. else
  63790. setDropShadowEnabled (true);
  63791. setWantsKeyboardFocus (true);
  63792. setBroughtToFrontOnMouseClick (true);
  63793. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63794. }
  63795. TopLevelWindow::~TopLevelWindow()
  63796. {
  63797. shadower = 0;
  63798. TopLevelWindowManager::getInstance()->removeWindow (this);
  63799. }
  63800. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63801. {
  63802. if (hasKeyboardFocus (true))
  63803. TopLevelWindowManager::getInstance()->timerCallback();
  63804. else
  63805. TopLevelWindowManager::getInstance()->startTimer (10);
  63806. }
  63807. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63808. {
  63809. if (windowIsActive_ != isNowActive)
  63810. {
  63811. windowIsActive_ = isNowActive;
  63812. activeWindowStatusChanged();
  63813. }
  63814. }
  63815. void TopLevelWindow::activeWindowStatusChanged()
  63816. {
  63817. }
  63818. void TopLevelWindow::parentHierarchyChanged()
  63819. {
  63820. setDropShadowEnabled (useDropShadow);
  63821. }
  63822. void TopLevelWindow::visibilityChanged()
  63823. {
  63824. if (isShowing())
  63825. toFront (true);
  63826. }
  63827. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63828. {
  63829. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63830. if (useDropShadow)
  63831. styleFlags |= ComponentPeer::windowHasDropShadow;
  63832. if (useNativeTitleBar)
  63833. styleFlags |= ComponentPeer::windowHasTitleBar;
  63834. return styleFlags;
  63835. }
  63836. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63837. {
  63838. useDropShadow = useShadow;
  63839. if (isOnDesktop())
  63840. {
  63841. shadower = 0;
  63842. Component::addToDesktop (getDesktopWindowStyleFlags());
  63843. }
  63844. else
  63845. {
  63846. if (useShadow && isOpaque())
  63847. {
  63848. if (shadower == 0)
  63849. {
  63850. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63851. if (shadower != 0)
  63852. shadower->setOwner (this);
  63853. }
  63854. }
  63855. else
  63856. {
  63857. shadower = 0;
  63858. }
  63859. }
  63860. }
  63861. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63862. {
  63863. if (useNativeTitleBar != useNativeTitleBar_)
  63864. {
  63865. useNativeTitleBar = useNativeTitleBar_;
  63866. recreateDesktopWindow();
  63867. sendLookAndFeelChange();
  63868. }
  63869. }
  63870. void TopLevelWindow::recreateDesktopWindow()
  63871. {
  63872. if (isOnDesktop())
  63873. {
  63874. Component::addToDesktop (getDesktopWindowStyleFlags());
  63875. toFront (true);
  63876. }
  63877. }
  63878. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63879. {
  63880. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63881. because this class needs to make sure its layout corresponds with settings like whether
  63882. it's got a native title bar or not.
  63883. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63884. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63885. method, then add or remove whatever flags are necessary from this value before returning it.
  63886. */
  63887. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63888. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63889. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63890. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63891. sendLookAndFeelChange();
  63892. }
  63893. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63894. {
  63895. if (c == 0)
  63896. c = TopLevelWindow::getActiveTopLevelWindow();
  63897. if (c == 0)
  63898. {
  63899. centreWithSize (width, height);
  63900. }
  63901. else
  63902. {
  63903. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63904. Rectangle<int> parentArea (c->getParentMonitorArea());
  63905. if (getParentComponent() != 0)
  63906. {
  63907. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63908. parentArea = getParentComponent()->getLocalBounds();
  63909. }
  63910. parentArea.reduce (12, 12);
  63911. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63912. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63913. width, height);
  63914. }
  63915. }
  63916. int TopLevelWindow::getNumTopLevelWindows() throw()
  63917. {
  63918. return TopLevelWindowManager::getInstance()->windows.size();
  63919. }
  63920. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63921. {
  63922. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63923. }
  63924. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63925. {
  63926. TopLevelWindow* best = 0;
  63927. int bestNumTWLParents = -1;
  63928. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63929. {
  63930. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63931. if (tlw->isActiveWindow())
  63932. {
  63933. int numTWLParents = 0;
  63934. const Component* c = tlw->getParentComponent();
  63935. while (c != 0)
  63936. {
  63937. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63938. ++numTWLParents;
  63939. c = c->getParentComponent();
  63940. }
  63941. if (bestNumTWLParents < numTWLParents)
  63942. {
  63943. best = tlw;
  63944. bestNumTWLParents = numTWLParents;
  63945. }
  63946. }
  63947. }
  63948. return best;
  63949. }
  63950. END_JUCE_NAMESPACE
  63951. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63952. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63953. BEGIN_JUCE_NAMESPACE
  63954. namespace RelativeCoordinateHelpers
  63955. {
  63956. void skipComma (const juce_wchar* const s, int& i)
  63957. {
  63958. while (CharacterFunctions::isWhitespace (s[i]))
  63959. ++i;
  63960. if (s[i] == ',')
  63961. ++i;
  63962. }
  63963. }
  63964. const String RelativeCoordinate::Strings::parent ("parent");
  63965. const String RelativeCoordinate::Strings::left ("left");
  63966. const String RelativeCoordinate::Strings::right ("right");
  63967. const String RelativeCoordinate::Strings::top ("top");
  63968. const String RelativeCoordinate::Strings::bottom ("bottom");
  63969. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  63970. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  63971. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  63972. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  63973. RelativeCoordinate::RelativeCoordinate()
  63974. {
  63975. }
  63976. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  63977. : term (term_)
  63978. {
  63979. }
  63980. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  63981. : term (other.term)
  63982. {
  63983. }
  63984. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  63985. {
  63986. term = other.term;
  63987. return *this;
  63988. }
  63989. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63990. : term (absoluteDistanceFromOrigin)
  63991. {
  63992. }
  63993. RelativeCoordinate::RelativeCoordinate (const String& s)
  63994. {
  63995. try
  63996. {
  63997. term = Expression (s);
  63998. }
  63999. catch (...)
  64000. {}
  64001. }
  64002. RelativeCoordinate::~RelativeCoordinate()
  64003. {
  64004. }
  64005. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64006. {
  64007. return term.toString() == other.term.toString();
  64008. }
  64009. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64010. {
  64011. return ! operator== (other);
  64012. }
  64013. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64014. {
  64015. try
  64016. {
  64017. if (context != 0)
  64018. return term.evaluate (*context);
  64019. else
  64020. return term.evaluate();
  64021. }
  64022. catch (...)
  64023. {}
  64024. return 0.0;
  64025. }
  64026. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64027. {
  64028. try
  64029. {
  64030. if (context != 0)
  64031. term.evaluate (*context);
  64032. else
  64033. term.evaluate();
  64034. }
  64035. catch (...)
  64036. {
  64037. return true;
  64038. }
  64039. return false;
  64040. }
  64041. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64042. {
  64043. try
  64044. {
  64045. if (context != 0)
  64046. {
  64047. term = term.adjustedToGiveNewResult (newPos, *context);
  64048. }
  64049. else
  64050. {
  64051. Expression::EvaluationContext defaultContext;
  64052. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64053. }
  64054. }
  64055. catch (...)
  64056. {}
  64057. }
  64058. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64059. {
  64060. try
  64061. {
  64062. return term.referencesSymbol (coordName, context);
  64063. }
  64064. catch (...)
  64065. {}
  64066. return false;
  64067. }
  64068. bool RelativeCoordinate::isDynamic() const
  64069. {
  64070. return term.usesAnySymbols();
  64071. }
  64072. const String RelativeCoordinate::toString() const
  64073. {
  64074. return term.toString();
  64075. }
  64076. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64077. {
  64078. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64079. if (term.referencesSymbol (oldName, 0))
  64080. term = term.withRenamedSymbol (oldName, newName);
  64081. }
  64082. RelativePoint::RelativePoint()
  64083. {
  64084. }
  64085. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64086. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64087. {
  64088. }
  64089. RelativePoint::RelativePoint (const float x_, const float y_)
  64090. : x (x_), y (y_)
  64091. {
  64092. }
  64093. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64094. : x (x_), y (y_)
  64095. {
  64096. }
  64097. RelativePoint::RelativePoint (const String& s)
  64098. {
  64099. int i = 0;
  64100. x = RelativeCoordinate (Expression::parse (s, i));
  64101. RelativeCoordinateHelpers::skipComma (s, i);
  64102. y = RelativeCoordinate (Expression::parse (s, i));
  64103. }
  64104. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64105. {
  64106. return x == other.x && y == other.y;
  64107. }
  64108. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64109. {
  64110. return ! operator== (other);
  64111. }
  64112. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64113. {
  64114. return Point<float> ((float) x.resolve (context),
  64115. (float) y.resolve (context));
  64116. }
  64117. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64118. {
  64119. x.moveToAbsolute (newPos.getX(), context);
  64120. y.moveToAbsolute (newPos.getY(), context);
  64121. }
  64122. const String RelativePoint::toString() const
  64123. {
  64124. return x.toString() + ", " + y.toString();
  64125. }
  64126. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64127. {
  64128. x.renameSymbolIfUsed (oldName, newName);
  64129. y.renameSymbolIfUsed (oldName, newName);
  64130. }
  64131. bool RelativePoint::isDynamic() const
  64132. {
  64133. return x.isDynamic() || y.isDynamic();
  64134. }
  64135. RelativeRectangle::RelativeRectangle()
  64136. {
  64137. }
  64138. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64139. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64140. : left (left_), right (right_), top (top_), bottom (bottom_)
  64141. {
  64142. }
  64143. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64144. : left (rect.getX()),
  64145. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64146. top (rect.getY()),
  64147. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64148. {
  64149. }
  64150. RelativeRectangle::RelativeRectangle (const String& s)
  64151. {
  64152. int i = 0;
  64153. left = RelativeCoordinate (Expression::parse (s, i));
  64154. RelativeCoordinateHelpers::skipComma (s, i);
  64155. top = RelativeCoordinate (Expression::parse (s, i));
  64156. RelativeCoordinateHelpers::skipComma (s, i);
  64157. right = RelativeCoordinate (Expression::parse (s, i));
  64158. RelativeCoordinateHelpers::skipComma (s, i);
  64159. bottom = RelativeCoordinate (Expression::parse (s, i));
  64160. }
  64161. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64162. {
  64163. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64164. }
  64165. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64166. {
  64167. return ! operator== (other);
  64168. }
  64169. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64170. {
  64171. const double l = left.resolve (context);
  64172. const double r = right.resolve (context);
  64173. const double t = top.resolve (context);
  64174. const double b = bottom.resolve (context);
  64175. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64176. }
  64177. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64178. {
  64179. left.moveToAbsolute (newPos.getX(), context);
  64180. right.moveToAbsolute (newPos.getRight(), context);
  64181. top.moveToAbsolute (newPos.getY(), context);
  64182. bottom.moveToAbsolute (newPos.getBottom(), context);
  64183. }
  64184. const String RelativeRectangle::toString() const
  64185. {
  64186. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64187. }
  64188. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64189. {
  64190. left.renameSymbolIfUsed (oldName, newName);
  64191. right.renameSymbolIfUsed (oldName, newName);
  64192. top.renameSymbolIfUsed (oldName, newName);
  64193. bottom.renameSymbolIfUsed (oldName, newName);
  64194. }
  64195. RelativePointPath::RelativePointPath()
  64196. : usesNonZeroWinding (true),
  64197. containsDynamicPoints (false)
  64198. {
  64199. }
  64200. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64201. : usesNonZeroWinding (true),
  64202. containsDynamicPoints (false)
  64203. {
  64204. ValueTree state (DrawablePath::valueTreeType);
  64205. other.writeTo (state, 0);
  64206. parse (state);
  64207. }
  64208. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64209. : usesNonZeroWinding (true),
  64210. containsDynamicPoints (false)
  64211. {
  64212. parse (drawable);
  64213. }
  64214. RelativePointPath::RelativePointPath (const Path& path)
  64215. {
  64216. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64217. Path::Iterator i (path);
  64218. while (i.next())
  64219. {
  64220. switch (i.elementType)
  64221. {
  64222. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64223. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64224. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64225. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64226. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64227. default: jassertfalse; break;
  64228. }
  64229. }
  64230. }
  64231. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64232. {
  64233. DrawablePath::ValueTreeWrapper wrapper (state);
  64234. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64235. ValueTree pathTree (wrapper.getPathState());
  64236. pathTree.removeAllChildren (undoManager);
  64237. for (int i = 0; i < elements.size(); ++i)
  64238. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64239. }
  64240. void RelativePointPath::parse (const ValueTree& state)
  64241. {
  64242. DrawablePath::ValueTreeWrapper wrapper (state);
  64243. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64244. RelativePoint points[3];
  64245. const ValueTree pathTree (wrapper.getPathState());
  64246. const int num = pathTree.getNumChildren();
  64247. for (int i = 0; i < num; ++i)
  64248. {
  64249. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64250. const int numCps = e.getNumControlPoints();
  64251. for (int j = 0; j < numCps; ++j)
  64252. {
  64253. points[j] = e.getControlPoint (j);
  64254. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64255. }
  64256. const Identifier type (e.getType());
  64257. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64258. elements.add (new StartSubPath (points[0]));
  64259. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64260. elements.add (new CloseSubPath());
  64261. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64262. elements.add (new LineTo (points[0]));
  64263. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64264. elements.add (new QuadraticTo (points[0], points[1]));
  64265. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64266. elements.add (new CubicTo (points[0], points[1], points[2]));
  64267. else
  64268. jassertfalse;
  64269. }
  64270. }
  64271. RelativePointPath::~RelativePointPath()
  64272. {
  64273. }
  64274. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64275. {
  64276. elements.swapWithArray (other.elements);
  64277. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64278. }
  64279. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64280. {
  64281. for (int i = 0; i < elements.size(); ++i)
  64282. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64283. }
  64284. bool RelativePointPath::containsAnyDynamicPoints() const
  64285. {
  64286. return containsDynamicPoints;
  64287. }
  64288. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64289. {
  64290. }
  64291. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64292. : ElementBase (startSubPathElement), startPos (pos)
  64293. {
  64294. }
  64295. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64296. {
  64297. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64298. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64299. return v;
  64300. }
  64301. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64302. {
  64303. path.startNewSubPath (startPos.resolve (coordFinder));
  64304. }
  64305. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64306. {
  64307. numPoints = 1;
  64308. return &startPos;
  64309. }
  64310. RelativePointPath::CloseSubPath::CloseSubPath()
  64311. : ElementBase (closeSubPathElement)
  64312. {
  64313. }
  64314. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64315. {
  64316. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64317. }
  64318. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64319. {
  64320. path.closeSubPath();
  64321. }
  64322. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64323. {
  64324. numPoints = 0;
  64325. return 0;
  64326. }
  64327. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64328. : ElementBase (lineToElement), endPoint (endPoint_)
  64329. {
  64330. }
  64331. const ValueTree RelativePointPath::LineTo::createTree() const
  64332. {
  64333. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64334. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64335. return v;
  64336. }
  64337. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64338. {
  64339. path.lineTo (endPoint.resolve (coordFinder));
  64340. }
  64341. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64342. {
  64343. numPoints = 1;
  64344. return &endPoint;
  64345. }
  64346. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64347. : ElementBase (quadraticToElement)
  64348. {
  64349. controlPoints[0] = controlPoint;
  64350. controlPoints[1] = endPoint;
  64351. }
  64352. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64353. {
  64354. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64355. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64356. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64357. return v;
  64358. }
  64359. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64360. {
  64361. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64362. controlPoints[1].resolve (coordFinder));
  64363. }
  64364. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64365. {
  64366. numPoints = 2;
  64367. return controlPoints;
  64368. }
  64369. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64370. : ElementBase (cubicToElement)
  64371. {
  64372. controlPoints[0] = controlPoint1;
  64373. controlPoints[1] = controlPoint2;
  64374. controlPoints[2] = endPoint;
  64375. }
  64376. const ValueTree RelativePointPath::CubicTo::createTree() const
  64377. {
  64378. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64379. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64380. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64381. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64382. return v;
  64383. }
  64384. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64385. {
  64386. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64387. controlPoints[1].resolve (coordFinder),
  64388. controlPoints[2].resolve (coordFinder));
  64389. }
  64390. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64391. {
  64392. numPoints = 3;
  64393. return controlPoints;
  64394. }
  64395. RelativeParallelogram::RelativeParallelogram()
  64396. {
  64397. }
  64398. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64399. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64400. {
  64401. }
  64402. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64403. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64404. {
  64405. }
  64406. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64407. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64408. {
  64409. }
  64410. RelativeParallelogram::~RelativeParallelogram()
  64411. {
  64412. }
  64413. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64414. {
  64415. points[0] = topLeft.resolve (coordFinder);
  64416. points[1] = topRight.resolve (coordFinder);
  64417. points[2] = bottomLeft.resolve (coordFinder);
  64418. }
  64419. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64420. {
  64421. resolveThreePoints (points, coordFinder);
  64422. points[3] = points[1] + (points[2] - points[0]);
  64423. }
  64424. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64425. {
  64426. Point<float> points[4];
  64427. resolveFourCorners (points, coordFinder);
  64428. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64429. }
  64430. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64431. {
  64432. Point<float> points[4];
  64433. resolveFourCorners (points, coordFinder);
  64434. path.startNewSubPath (points[0]);
  64435. path.lineTo (points[1]);
  64436. path.lineTo (points[3]);
  64437. path.lineTo (points[2]);
  64438. path.closeSubPath();
  64439. }
  64440. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64441. {
  64442. Point<float> corners[3];
  64443. resolveThreePoints (corners, coordFinder);
  64444. const Line<float> top (corners[0], corners[1]);
  64445. const Line<float> left (corners[0], corners[2]);
  64446. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64447. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64448. topRight.moveToAbsolute (newTopRight, coordFinder);
  64449. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64450. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64451. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64452. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64453. }
  64454. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64455. {
  64456. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64457. }
  64458. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64459. {
  64460. return ! operator== (other);
  64461. }
  64462. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64463. {
  64464. const Point<float> tr (corners[1] - corners[0]);
  64465. const Point<float> bl (corners[2] - corners[0]);
  64466. target -= corners[0];
  64467. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64468. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64469. }
  64470. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64471. {
  64472. return corners[0]
  64473. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64474. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64475. }
  64476. END_JUCE_NAMESPACE
  64477. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64478. #endif
  64479. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64480. /*** Start of inlined file: juce_Colour.cpp ***/
  64481. BEGIN_JUCE_NAMESPACE
  64482. namespace ColourHelpers
  64483. {
  64484. uint8 floatAlphaToInt (const float alpha) throw()
  64485. {
  64486. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64487. }
  64488. void convertHSBtoRGB (float h, float s, float v,
  64489. uint8& r, uint8& g, uint8& b) throw()
  64490. {
  64491. v = jlimit (0.0f, 1.0f, v);
  64492. v *= 255.0f;
  64493. const uint8 intV = (uint8) roundToInt (v);
  64494. if (s <= 0)
  64495. {
  64496. r = intV;
  64497. g = intV;
  64498. b = intV;
  64499. }
  64500. else
  64501. {
  64502. s = jmin (1.0f, s);
  64503. h = jlimit (0.0f, 1.0f, h);
  64504. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64505. const float f = h - std::floor (h);
  64506. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64507. const float y = v * (1.0f - s * f);
  64508. const float z = v * (1.0f - (s * (1.0f - f)));
  64509. if (h < 1.0f)
  64510. {
  64511. r = intV;
  64512. g = (uint8) roundToInt (z);
  64513. b = x;
  64514. }
  64515. else if (h < 2.0f)
  64516. {
  64517. r = (uint8) roundToInt (y);
  64518. g = intV;
  64519. b = x;
  64520. }
  64521. else if (h < 3.0f)
  64522. {
  64523. r = x;
  64524. g = intV;
  64525. b = (uint8) roundToInt (z);
  64526. }
  64527. else if (h < 4.0f)
  64528. {
  64529. r = x;
  64530. g = (uint8) roundToInt (y);
  64531. b = intV;
  64532. }
  64533. else if (h < 5.0f)
  64534. {
  64535. r = (uint8) roundToInt (z);
  64536. g = x;
  64537. b = intV;
  64538. }
  64539. else if (h < 6.0f)
  64540. {
  64541. r = intV;
  64542. g = x;
  64543. b = (uint8) roundToInt (y);
  64544. }
  64545. else
  64546. {
  64547. r = 0;
  64548. g = 0;
  64549. b = 0;
  64550. }
  64551. }
  64552. }
  64553. }
  64554. Colour::Colour() throw()
  64555. : argb (0)
  64556. {
  64557. }
  64558. Colour::Colour (const Colour& other) throw()
  64559. : argb (other.argb)
  64560. {
  64561. }
  64562. Colour& Colour::operator= (const Colour& other) throw()
  64563. {
  64564. argb = other.argb;
  64565. return *this;
  64566. }
  64567. bool Colour::operator== (const Colour& other) const throw()
  64568. {
  64569. return argb.getARGB() == other.argb.getARGB();
  64570. }
  64571. bool Colour::operator!= (const Colour& other) const throw()
  64572. {
  64573. return argb.getARGB() != other.argb.getARGB();
  64574. }
  64575. Colour::Colour (const uint32 argb_) throw()
  64576. : argb (argb_)
  64577. {
  64578. }
  64579. Colour::Colour (const uint8 red,
  64580. const uint8 green,
  64581. const uint8 blue) throw()
  64582. {
  64583. argb.setARGB (0xff, red, green, blue);
  64584. }
  64585. const Colour Colour::fromRGB (const uint8 red,
  64586. const uint8 green,
  64587. const uint8 blue) throw()
  64588. {
  64589. return Colour (red, green, blue);
  64590. }
  64591. Colour::Colour (const uint8 red,
  64592. const uint8 green,
  64593. const uint8 blue,
  64594. const uint8 alpha) throw()
  64595. {
  64596. argb.setARGB (alpha, red, green, blue);
  64597. }
  64598. const Colour Colour::fromRGBA (const uint8 red,
  64599. const uint8 green,
  64600. const uint8 blue,
  64601. const uint8 alpha) throw()
  64602. {
  64603. return Colour (red, green, blue, alpha);
  64604. }
  64605. Colour::Colour (const uint8 red,
  64606. const uint8 green,
  64607. const uint8 blue,
  64608. const float alpha) throw()
  64609. {
  64610. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64611. }
  64612. const Colour Colour::fromRGBAFloat (const uint8 red,
  64613. const uint8 green,
  64614. const uint8 blue,
  64615. const float alpha) throw()
  64616. {
  64617. return Colour (red, green, blue, alpha);
  64618. }
  64619. Colour::Colour (const float hue,
  64620. const float saturation,
  64621. const float brightness,
  64622. const float alpha) throw()
  64623. {
  64624. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64625. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64626. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64627. }
  64628. const Colour Colour::fromHSV (const float hue,
  64629. const float saturation,
  64630. const float brightness,
  64631. const float alpha) throw()
  64632. {
  64633. return Colour (hue, saturation, brightness, alpha);
  64634. }
  64635. Colour::Colour (const float hue,
  64636. const float saturation,
  64637. const float brightness,
  64638. const uint8 alpha) throw()
  64639. {
  64640. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64641. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64642. argb.setARGB (alpha, r, g, b);
  64643. }
  64644. Colour::~Colour() throw()
  64645. {
  64646. }
  64647. const PixelARGB Colour::getPixelARGB() const throw()
  64648. {
  64649. PixelARGB p (argb);
  64650. p.premultiply();
  64651. return p;
  64652. }
  64653. uint32 Colour::getARGB() const throw()
  64654. {
  64655. return argb.getARGB();
  64656. }
  64657. bool Colour::isTransparent() const throw()
  64658. {
  64659. return getAlpha() == 0;
  64660. }
  64661. bool Colour::isOpaque() const throw()
  64662. {
  64663. return getAlpha() == 0xff;
  64664. }
  64665. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64666. {
  64667. PixelARGB newCol (argb);
  64668. newCol.setAlpha (newAlpha);
  64669. return Colour (newCol.getARGB());
  64670. }
  64671. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64672. {
  64673. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64674. PixelARGB newCol (argb);
  64675. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64676. return Colour (newCol.getARGB());
  64677. }
  64678. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64679. {
  64680. jassert (alphaMultiplier >= 0);
  64681. PixelARGB newCol (argb);
  64682. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64683. return Colour (newCol.getARGB());
  64684. }
  64685. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64686. {
  64687. const int destAlpha = getAlpha();
  64688. if (destAlpha > 0)
  64689. {
  64690. const int invA = 0xff - (int) src.getAlpha();
  64691. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64692. if (resA > 0)
  64693. {
  64694. const int da = (invA * destAlpha) / resA;
  64695. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64696. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64697. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64698. (uint8) resA);
  64699. }
  64700. return *this;
  64701. }
  64702. else
  64703. {
  64704. return src;
  64705. }
  64706. }
  64707. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64708. {
  64709. if (proportionOfOther <= 0)
  64710. return *this;
  64711. if (proportionOfOther >= 1.0f)
  64712. return other;
  64713. PixelARGB c1 (getPixelARGB());
  64714. const PixelARGB c2 (other.getPixelARGB());
  64715. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64716. c1.unpremultiply();
  64717. return Colour (c1.getARGB());
  64718. }
  64719. float Colour::getFloatRed() const throw()
  64720. {
  64721. return getRed() / 255.0f;
  64722. }
  64723. float Colour::getFloatGreen() const throw()
  64724. {
  64725. return getGreen() / 255.0f;
  64726. }
  64727. float Colour::getFloatBlue() const throw()
  64728. {
  64729. return getBlue() / 255.0f;
  64730. }
  64731. float Colour::getFloatAlpha() const throw()
  64732. {
  64733. return getAlpha() / 255.0f;
  64734. }
  64735. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64736. {
  64737. const int r = getRed();
  64738. const int g = getGreen();
  64739. const int b = getBlue();
  64740. const int hi = jmax (r, g, b);
  64741. const int lo = jmin (r, g, b);
  64742. if (hi != 0)
  64743. {
  64744. s = (hi - lo) / (float) hi;
  64745. if (s != 0)
  64746. {
  64747. const float invDiff = 1.0f / (hi - lo);
  64748. const float red = (hi - r) * invDiff;
  64749. const float green = (hi - g) * invDiff;
  64750. const float blue = (hi - b) * invDiff;
  64751. if (r == hi)
  64752. h = blue - green;
  64753. else if (g == hi)
  64754. h = 2.0f + red - blue;
  64755. else
  64756. h = 4.0f + green - red;
  64757. h *= 1.0f / 6.0f;
  64758. if (h < 0)
  64759. ++h;
  64760. }
  64761. else
  64762. {
  64763. h = 0;
  64764. }
  64765. }
  64766. else
  64767. {
  64768. s = 0;
  64769. h = 0;
  64770. }
  64771. v = hi / 255.0f;
  64772. }
  64773. float Colour::getHue() const throw()
  64774. {
  64775. float h, s, b;
  64776. getHSB (h, s, b);
  64777. return h;
  64778. }
  64779. const Colour Colour::withHue (const float hue) const throw()
  64780. {
  64781. float h, s, b;
  64782. getHSB (h, s, b);
  64783. return Colour (hue, s, b, getAlpha());
  64784. }
  64785. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64786. {
  64787. float h, s, b;
  64788. getHSB (h, s, b);
  64789. h += amountToRotate;
  64790. h -= std::floor (h);
  64791. return Colour (h, s, b, getAlpha());
  64792. }
  64793. float Colour::getSaturation() const throw()
  64794. {
  64795. float h, s, b;
  64796. getHSB (h, s, b);
  64797. return s;
  64798. }
  64799. const Colour Colour::withSaturation (const float saturation) const throw()
  64800. {
  64801. float h, s, b;
  64802. getHSB (h, s, b);
  64803. return Colour (h, saturation, b, getAlpha());
  64804. }
  64805. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64806. {
  64807. float h, s, b;
  64808. getHSB (h, s, b);
  64809. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64810. }
  64811. float Colour::getBrightness() const throw()
  64812. {
  64813. float h, s, b;
  64814. getHSB (h, s, b);
  64815. return b;
  64816. }
  64817. const Colour Colour::withBrightness (const float brightness) const throw()
  64818. {
  64819. float h, s, b;
  64820. getHSB (h, s, b);
  64821. return Colour (h, s, brightness, getAlpha());
  64822. }
  64823. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64824. {
  64825. float h, s, b;
  64826. getHSB (h, s, b);
  64827. b *= amount;
  64828. if (b > 1.0f)
  64829. b = 1.0f;
  64830. return Colour (h, s, b, getAlpha());
  64831. }
  64832. const Colour Colour::brighter (float amount) const throw()
  64833. {
  64834. amount = 1.0f / (1.0f + amount);
  64835. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  64836. (uint8) (255 - (amount * (255 - getGreen()))),
  64837. (uint8) (255 - (amount * (255 - getBlue()))),
  64838. getAlpha());
  64839. }
  64840. const Colour Colour::darker (float amount) const throw()
  64841. {
  64842. amount = 1.0f / (1.0f + amount);
  64843. return Colour ((uint8) (amount * getRed()),
  64844. (uint8) (amount * getGreen()),
  64845. (uint8) (amount * getBlue()),
  64846. getAlpha());
  64847. }
  64848. const Colour Colour::greyLevel (const float brightness) throw()
  64849. {
  64850. const uint8 level
  64851. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  64852. return Colour (level, level, level);
  64853. }
  64854. const Colour Colour::contrasting (const float amount) const throw()
  64855. {
  64856. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  64857. ? Colours::black
  64858. : Colours::white).withAlpha (amount));
  64859. }
  64860. const Colour Colour::contrasting (const Colour& colour1,
  64861. const Colour& colour2) throw()
  64862. {
  64863. const float b1 = colour1.getBrightness();
  64864. const float b2 = colour2.getBrightness();
  64865. float best = 0.0f;
  64866. float bestDist = 0.0f;
  64867. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  64868. {
  64869. const float d1 = std::abs (i - b1);
  64870. const float d2 = std::abs (i - b2);
  64871. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  64872. if (dist > bestDist)
  64873. {
  64874. best = i;
  64875. bestDist = dist;
  64876. }
  64877. }
  64878. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  64879. .withBrightness (best);
  64880. }
  64881. const String Colour::toString() const
  64882. {
  64883. return String::toHexString ((int) argb.getARGB());
  64884. }
  64885. const Colour Colour::fromString (const String& encodedColourString)
  64886. {
  64887. return Colour ((uint32) encodedColourString.getHexValue32());
  64888. }
  64889. const String Colour::toDisplayString (const bool includeAlphaValue) const
  64890. {
  64891. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  64892. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  64893. .toUpperCase();
  64894. }
  64895. END_JUCE_NAMESPACE
  64896. /*** End of inlined file: juce_Colour.cpp ***/
  64897. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  64898. BEGIN_JUCE_NAMESPACE
  64899. ColourGradient::ColourGradient() throw()
  64900. {
  64901. #if JUCE_DEBUG
  64902. point1.setX (987654.0f);
  64903. #endif
  64904. }
  64905. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  64906. const Colour& colour2, const float x2_, const float y2_,
  64907. const bool isRadial_)
  64908. : point1 (x1_, y1_),
  64909. point2 (x2_, y2_),
  64910. isRadial (isRadial_)
  64911. {
  64912. colours.add (ColourPoint (0.0, colour1));
  64913. colours.add (ColourPoint (1.0, colour2));
  64914. }
  64915. ColourGradient::~ColourGradient()
  64916. {
  64917. }
  64918. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  64919. {
  64920. return point1 == other.point1 && point2 == other.point2
  64921. && isRadial == other.isRadial
  64922. && colours == other.colours;
  64923. }
  64924. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  64925. {
  64926. return ! operator== (other);
  64927. }
  64928. void ColourGradient::clearColours()
  64929. {
  64930. colours.clear();
  64931. }
  64932. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  64933. {
  64934. // must be within the two end-points
  64935. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  64936. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  64937. int i;
  64938. for (i = 0; i < colours.size(); ++i)
  64939. if (colours.getReference(i).position > pos)
  64940. break;
  64941. colours.insert (i, ColourPoint (pos, colour));
  64942. return i;
  64943. }
  64944. void ColourGradient::removeColour (int index)
  64945. {
  64946. jassert (index > 0 && index < colours.size() - 1);
  64947. colours.remove (index);
  64948. }
  64949. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  64950. {
  64951. for (int i = 0; i < colours.size(); ++i)
  64952. {
  64953. Colour& c = colours.getReference(i).colour;
  64954. c = c.withMultipliedAlpha (multiplier);
  64955. }
  64956. }
  64957. int ColourGradient::getNumColours() const throw()
  64958. {
  64959. return colours.size();
  64960. }
  64961. double ColourGradient::getColourPosition (const int index) const throw()
  64962. {
  64963. if (isPositiveAndBelow (index, colours.size()))
  64964. return colours.getReference (index).position;
  64965. return 0;
  64966. }
  64967. const Colour ColourGradient::getColour (const int index) const throw()
  64968. {
  64969. if (isPositiveAndBelow (index, colours.size()))
  64970. return colours.getReference (index).colour;
  64971. return Colour();
  64972. }
  64973. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  64974. {
  64975. if (isPositiveAndBelow (index, colours.size()))
  64976. colours.getReference (index).colour = newColour;
  64977. }
  64978. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  64979. {
  64980. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64981. if (position <= 0 || colours.size() <= 1)
  64982. return colours.getReference(0).colour;
  64983. int i = colours.size() - 1;
  64984. while (position < colours.getReference(i).position)
  64985. --i;
  64986. const ColourPoint& p1 = colours.getReference (i);
  64987. if (i >= colours.size() - 1)
  64988. return p1.colour;
  64989. const ColourPoint& p2 = colours.getReference (i + 1);
  64990. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  64991. }
  64992. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  64993. {
  64994. #if JUCE_DEBUG
  64995. // trying to use the object without setting its co-ordinates? Have a careful read of
  64996. // the comments for the constructors.
  64997. jassert (point1.getX() != 987654.0f);
  64998. #endif
  64999. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65000. 3 * (int) point1.transformedBy (transform)
  65001. .getDistanceFrom (point2.transformedBy (transform)));
  65002. lookupTable.malloc (numEntries);
  65003. if (colours.size() >= 2)
  65004. {
  65005. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65006. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65007. int index = 0;
  65008. for (int j = 1; j < colours.size(); ++j)
  65009. {
  65010. const ColourPoint& p = colours.getReference (j);
  65011. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65012. const PixelARGB pix2 (p.colour.getPixelARGB());
  65013. for (int i = 0; i < numToDo; ++i)
  65014. {
  65015. jassert (index >= 0 && index < numEntries);
  65016. lookupTable[index] = pix1;
  65017. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65018. ++index;
  65019. }
  65020. pix1 = pix2;
  65021. }
  65022. while (index < numEntries)
  65023. lookupTable [index++] = pix1;
  65024. }
  65025. else
  65026. {
  65027. jassertfalse; // no colours specified!
  65028. }
  65029. return numEntries;
  65030. }
  65031. bool ColourGradient::isOpaque() const throw()
  65032. {
  65033. for (int i = 0; i < colours.size(); ++i)
  65034. if (! colours.getReference(i).colour.isOpaque())
  65035. return false;
  65036. return true;
  65037. }
  65038. bool ColourGradient::isInvisible() const throw()
  65039. {
  65040. for (int i = 0; i < colours.size(); ++i)
  65041. if (! colours.getReference(i).colour.isTransparent())
  65042. return false;
  65043. return true;
  65044. }
  65045. END_JUCE_NAMESPACE
  65046. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65047. /*** Start of inlined file: juce_Colours.cpp ***/
  65048. BEGIN_JUCE_NAMESPACE
  65049. const Colour Colours::transparentBlack (0);
  65050. const Colour Colours::transparentWhite (0x00ffffff);
  65051. const Colour Colours::aliceblue (0xfff0f8ff);
  65052. const Colour Colours::antiquewhite (0xfffaebd7);
  65053. const Colour Colours::aqua (0xff00ffff);
  65054. const Colour Colours::aquamarine (0xff7fffd4);
  65055. const Colour Colours::azure (0xfff0ffff);
  65056. const Colour Colours::beige (0xfff5f5dc);
  65057. const Colour Colours::bisque (0xffffe4c4);
  65058. const Colour Colours::black (0xff000000);
  65059. const Colour Colours::blanchedalmond (0xffffebcd);
  65060. const Colour Colours::blue (0xff0000ff);
  65061. const Colour Colours::blueviolet (0xff8a2be2);
  65062. const Colour Colours::brown (0xffa52a2a);
  65063. const Colour Colours::burlywood (0xffdeb887);
  65064. const Colour Colours::cadetblue (0xff5f9ea0);
  65065. const Colour Colours::chartreuse (0xff7fff00);
  65066. const Colour Colours::chocolate (0xffd2691e);
  65067. const Colour Colours::coral (0xffff7f50);
  65068. const Colour Colours::cornflowerblue (0xff6495ed);
  65069. const Colour Colours::cornsilk (0xfffff8dc);
  65070. const Colour Colours::crimson (0xffdc143c);
  65071. const Colour Colours::cyan (0xff00ffff);
  65072. const Colour Colours::darkblue (0xff00008b);
  65073. const Colour Colours::darkcyan (0xff008b8b);
  65074. const Colour Colours::darkgoldenrod (0xffb8860b);
  65075. const Colour Colours::darkgrey (0xff555555);
  65076. const Colour Colours::darkgreen (0xff006400);
  65077. const Colour Colours::darkkhaki (0xffbdb76b);
  65078. const Colour Colours::darkmagenta (0xff8b008b);
  65079. const Colour Colours::darkolivegreen (0xff556b2f);
  65080. const Colour Colours::darkorange (0xffff8c00);
  65081. const Colour Colours::darkorchid (0xff9932cc);
  65082. const Colour Colours::darkred (0xff8b0000);
  65083. const Colour Colours::darksalmon (0xffe9967a);
  65084. const Colour Colours::darkseagreen (0xff8fbc8f);
  65085. const Colour Colours::darkslateblue (0xff483d8b);
  65086. const Colour Colours::darkslategrey (0xff2f4f4f);
  65087. const Colour Colours::darkturquoise (0xff00ced1);
  65088. const Colour Colours::darkviolet (0xff9400d3);
  65089. const Colour Colours::deeppink (0xffff1493);
  65090. const Colour Colours::deepskyblue (0xff00bfff);
  65091. const Colour Colours::dimgrey (0xff696969);
  65092. const Colour Colours::dodgerblue (0xff1e90ff);
  65093. const Colour Colours::firebrick (0xffb22222);
  65094. const Colour Colours::floralwhite (0xfffffaf0);
  65095. const Colour Colours::forestgreen (0xff228b22);
  65096. const Colour Colours::fuchsia (0xffff00ff);
  65097. const Colour Colours::gainsboro (0xffdcdcdc);
  65098. const Colour Colours::gold (0xffffd700);
  65099. const Colour Colours::goldenrod (0xffdaa520);
  65100. const Colour Colours::grey (0xff808080);
  65101. const Colour Colours::green (0xff008000);
  65102. const Colour Colours::greenyellow (0xffadff2f);
  65103. const Colour Colours::honeydew (0xfff0fff0);
  65104. const Colour Colours::hotpink (0xffff69b4);
  65105. const Colour Colours::indianred (0xffcd5c5c);
  65106. const Colour Colours::indigo (0xff4b0082);
  65107. const Colour Colours::ivory (0xfffffff0);
  65108. const Colour Colours::khaki (0xfff0e68c);
  65109. const Colour Colours::lavender (0xffe6e6fa);
  65110. const Colour Colours::lavenderblush (0xfffff0f5);
  65111. const Colour Colours::lemonchiffon (0xfffffacd);
  65112. const Colour Colours::lightblue (0xffadd8e6);
  65113. const Colour Colours::lightcoral (0xfff08080);
  65114. const Colour Colours::lightcyan (0xffe0ffff);
  65115. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65116. const Colour Colours::lightgreen (0xff90ee90);
  65117. const Colour Colours::lightgrey (0xffd3d3d3);
  65118. const Colour Colours::lightpink (0xffffb6c1);
  65119. const Colour Colours::lightsalmon (0xffffa07a);
  65120. const Colour Colours::lightseagreen (0xff20b2aa);
  65121. const Colour Colours::lightskyblue (0xff87cefa);
  65122. const Colour Colours::lightslategrey (0xff778899);
  65123. const Colour Colours::lightsteelblue (0xffb0c4de);
  65124. const Colour Colours::lightyellow (0xffffffe0);
  65125. const Colour Colours::lime (0xff00ff00);
  65126. const Colour Colours::limegreen (0xff32cd32);
  65127. const Colour Colours::linen (0xfffaf0e6);
  65128. const Colour Colours::magenta (0xffff00ff);
  65129. const Colour Colours::maroon (0xff800000);
  65130. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65131. const Colour Colours::mediumblue (0xff0000cd);
  65132. const Colour Colours::mediumorchid (0xffba55d3);
  65133. const Colour Colours::mediumpurple (0xff9370db);
  65134. const Colour Colours::mediumseagreen (0xff3cb371);
  65135. const Colour Colours::mediumslateblue (0xff7b68ee);
  65136. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65137. const Colour Colours::mediumturquoise (0xff48d1cc);
  65138. const Colour Colours::mediumvioletred (0xffc71585);
  65139. const Colour Colours::midnightblue (0xff191970);
  65140. const Colour Colours::mintcream (0xfff5fffa);
  65141. const Colour Colours::mistyrose (0xffffe4e1);
  65142. const Colour Colours::navajowhite (0xffffdead);
  65143. const Colour Colours::navy (0xff000080);
  65144. const Colour Colours::oldlace (0xfffdf5e6);
  65145. const Colour Colours::olive (0xff808000);
  65146. const Colour Colours::olivedrab (0xff6b8e23);
  65147. const Colour Colours::orange (0xffffa500);
  65148. const Colour Colours::orangered (0xffff4500);
  65149. const Colour Colours::orchid (0xffda70d6);
  65150. const Colour Colours::palegoldenrod (0xffeee8aa);
  65151. const Colour Colours::palegreen (0xff98fb98);
  65152. const Colour Colours::paleturquoise (0xffafeeee);
  65153. const Colour Colours::palevioletred (0xffdb7093);
  65154. const Colour Colours::papayawhip (0xffffefd5);
  65155. const Colour Colours::peachpuff (0xffffdab9);
  65156. const Colour Colours::peru (0xffcd853f);
  65157. const Colour Colours::pink (0xffffc0cb);
  65158. const Colour Colours::plum (0xffdda0dd);
  65159. const Colour Colours::powderblue (0xffb0e0e6);
  65160. const Colour Colours::purple (0xff800080);
  65161. const Colour Colours::red (0xffff0000);
  65162. const Colour Colours::rosybrown (0xffbc8f8f);
  65163. const Colour Colours::royalblue (0xff4169e1);
  65164. const Colour Colours::saddlebrown (0xff8b4513);
  65165. const Colour Colours::salmon (0xfffa8072);
  65166. const Colour Colours::sandybrown (0xfff4a460);
  65167. const Colour Colours::seagreen (0xff2e8b57);
  65168. const Colour Colours::seashell (0xfffff5ee);
  65169. const Colour Colours::sienna (0xffa0522d);
  65170. const Colour Colours::silver (0xffc0c0c0);
  65171. const Colour Colours::skyblue (0xff87ceeb);
  65172. const Colour Colours::slateblue (0xff6a5acd);
  65173. const Colour Colours::slategrey (0xff708090);
  65174. const Colour Colours::snow (0xfffffafa);
  65175. const Colour Colours::springgreen (0xff00ff7f);
  65176. const Colour Colours::steelblue (0xff4682b4);
  65177. const Colour Colours::tan (0xffd2b48c);
  65178. const Colour Colours::teal (0xff008080);
  65179. const Colour Colours::thistle (0xffd8bfd8);
  65180. const Colour Colours::tomato (0xffff6347);
  65181. const Colour Colours::turquoise (0xff40e0d0);
  65182. const Colour Colours::violet (0xffee82ee);
  65183. const Colour Colours::wheat (0xfff5deb3);
  65184. const Colour Colours::white (0xffffffff);
  65185. const Colour Colours::whitesmoke (0xfff5f5f5);
  65186. const Colour Colours::yellow (0xffffff00);
  65187. const Colour Colours::yellowgreen (0xff9acd32);
  65188. const Colour Colours::findColourForName (const String& colourName,
  65189. const Colour& defaultColour)
  65190. {
  65191. static const int presets[] =
  65192. {
  65193. // (first value is the string's hashcode, second is ARGB)
  65194. 0x05978fff, 0xff000000, /* black */
  65195. 0x06bdcc29, 0xffffffff, /* white */
  65196. 0x002e305a, 0xff0000ff, /* blue */
  65197. 0x00308adf, 0xff808080, /* grey */
  65198. 0x05e0cf03, 0xff008000, /* green */
  65199. 0x0001b891, 0xffff0000, /* red */
  65200. 0xd43c6474, 0xffffff00, /* yellow */
  65201. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65202. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65203. 0x002dcebc, 0xff00ffff, /* aqua */
  65204. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65205. 0x0590228f, 0xfff0ffff, /* azure */
  65206. 0x05947fe4, 0xfff5f5dc, /* beige */
  65207. 0xad388e35, 0xffffe4c4, /* bisque */
  65208. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65209. 0x39129959, 0xff8a2be2, /* blueviolet */
  65210. 0x059a8136, 0xffa52a2a, /* brown */
  65211. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65212. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65213. 0x6b748956, 0xff7fff00, /* chartreuse */
  65214. 0x2903623c, 0xffd2691e, /* chocolate */
  65215. 0x05a74431, 0xffff7f50, /* coral */
  65216. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65217. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65218. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65219. 0x002ed323, 0xff00ffff, /* cyan */
  65220. 0x67cc74d0, 0xff00008b, /* darkblue */
  65221. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65222. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65223. 0x67cecf55, 0xff555555, /* darkgrey */
  65224. 0x920b194d, 0xff006400, /* darkgreen */
  65225. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65226. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65227. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65228. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65229. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65230. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65231. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65232. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65233. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65234. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65235. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65236. 0xc8769375, 0xff9400d3, /* darkviolet */
  65237. 0x25832862, 0xffff1493, /* deeppink */
  65238. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65239. 0x634c8b67, 0xff696969, /* dimgrey */
  65240. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65241. 0xef19e3cb, 0xffb22222, /* firebrick */
  65242. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65243. 0xd086fd06, 0xff228b22, /* forestgreen */
  65244. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65245. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65246. 0x00308060, 0xffffd700, /* gold */
  65247. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65248. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65249. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65250. 0x41892743, 0xffff69b4, /* hotpink */
  65251. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65252. 0xb969fed2, 0xff4b0082, /* indigo */
  65253. 0x05fef6a9, 0xfffffff0, /* ivory */
  65254. 0x06149302, 0xfff0e68c, /* khaki */
  65255. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65256. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65257. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65258. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65259. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65260. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65261. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65262. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65263. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65264. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65265. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65266. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65267. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65268. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65269. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65270. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65271. 0x0032afd5, 0xff00ff00, /* lime */
  65272. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65273. 0x06234efa, 0xfffaf0e6, /* linen */
  65274. 0x316858a9, 0xffff00ff, /* magenta */
  65275. 0xbf8ca470, 0xff800000, /* maroon */
  65276. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65277. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65278. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65279. 0x07556b71, 0xff9370db, /* mediumpurple */
  65280. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65281. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65282. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65283. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65284. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65285. 0x168eb32a, 0xff191970, /* midnightblue */
  65286. 0x4306b960, 0xfff5fffa, /* mintcream */
  65287. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65288. 0xe97218a6, 0xffffdead, /* navajowhite */
  65289. 0x00337bb6, 0xff000080, /* navy */
  65290. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65291. 0x064ee1db, 0xff808000, /* olive */
  65292. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65293. 0xc3de262e, 0xffffa500, /* orange */
  65294. 0x58bebba3, 0xffff4500, /* orangered */
  65295. 0xc3def8a3, 0xffda70d6, /* orchid */
  65296. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65297. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65298. 0x74022737, 0xffafeeee, /* paleturquoise */
  65299. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65300. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65301. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65302. 0x003472f8, 0xffcd853f, /* peru */
  65303. 0x00348176, 0xffffc0cb, /* pink */
  65304. 0x00348d94, 0xffdda0dd, /* plum */
  65305. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65306. 0xc5c507bc, 0xff800080, /* purple */
  65307. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65308. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65309. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65310. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65311. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65312. 0x34636c14, 0xff2e8b57, /* seagreen */
  65313. 0x3507fb41, 0xfffff5ee, /* seashell */
  65314. 0xca348772, 0xffa0522d, /* sienna */
  65315. 0xca37d30d, 0xffc0c0c0, /* silver */
  65316. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65317. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65318. 0x44ab37f8, 0xff708090, /* slategrey */
  65319. 0x0035f183, 0xfffffafa, /* snow */
  65320. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65321. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65322. 0x0001bfa1, 0xffd2b48c, /* tan */
  65323. 0x0036425c, 0xff008080, /* teal */
  65324. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65325. 0xcc41600a, 0xffff6347, /* tomato */
  65326. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65327. 0xcf57947f, 0xffee82ee, /* violet */
  65328. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65329. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65330. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65331. };
  65332. const int hash = colourName.trim().toLowerCase().hashCode();
  65333. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65334. if (presets [i] == hash)
  65335. return Colour (presets [i + 1]);
  65336. return defaultColour;
  65337. }
  65338. END_JUCE_NAMESPACE
  65339. /*** End of inlined file: juce_Colours.cpp ***/
  65340. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65341. BEGIN_JUCE_NAMESPACE
  65342. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65343. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65344. const Path& path, const AffineTransform& transform)
  65345. : bounds (bounds_),
  65346. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65347. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65348. needToCheckEmptinesss (true)
  65349. {
  65350. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65351. int* t = table;
  65352. for (int i = bounds.getHeight(); --i >= 0;)
  65353. {
  65354. *t = 0;
  65355. t += lineStrideElements;
  65356. }
  65357. const int topLimit = bounds.getY() << 8;
  65358. const int heightLimit = bounds.getHeight() << 8;
  65359. const int leftLimit = bounds.getX() << 8;
  65360. const int rightLimit = bounds.getRight() << 8;
  65361. PathFlatteningIterator iter (path, transform);
  65362. while (iter.next())
  65363. {
  65364. int y1 = roundToInt (iter.y1 * 256.0f);
  65365. int y2 = roundToInt (iter.y2 * 256.0f);
  65366. if (y1 != y2)
  65367. {
  65368. y1 -= topLimit;
  65369. y2 -= topLimit;
  65370. const int startY = y1;
  65371. int direction = -1;
  65372. if (y1 > y2)
  65373. {
  65374. swapVariables (y1, y2);
  65375. direction = 1;
  65376. }
  65377. if (y1 < 0)
  65378. y1 = 0;
  65379. if (y2 > heightLimit)
  65380. y2 = heightLimit;
  65381. if (y1 < y2)
  65382. {
  65383. const double startX = 256.0f * iter.x1;
  65384. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65385. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65386. do
  65387. {
  65388. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65389. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65390. if (x < leftLimit)
  65391. x = leftLimit;
  65392. else if (x >= rightLimit)
  65393. x = rightLimit - 1;
  65394. addEdgePoint (x, y1 >> 8, direction * step);
  65395. y1 += step;
  65396. }
  65397. while (y1 < y2);
  65398. }
  65399. }
  65400. }
  65401. sanitiseLevels (path.isUsingNonZeroWinding());
  65402. }
  65403. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65404. : bounds (rectangleToAdd),
  65405. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65406. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65407. needToCheckEmptinesss (true)
  65408. {
  65409. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65410. table[0] = 0;
  65411. const int x1 = rectangleToAdd.getX() << 8;
  65412. const int x2 = rectangleToAdd.getRight() << 8;
  65413. int* t = table;
  65414. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65415. {
  65416. t[0] = 2;
  65417. t[1] = x1;
  65418. t[2] = 255;
  65419. t[3] = x2;
  65420. t[4] = 0;
  65421. t += lineStrideElements;
  65422. }
  65423. }
  65424. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65425. : bounds (rectanglesToAdd.getBounds()),
  65426. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65427. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65428. needToCheckEmptinesss (true)
  65429. {
  65430. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65431. int* t = table;
  65432. for (int i = bounds.getHeight(); --i >= 0;)
  65433. {
  65434. *t = 0;
  65435. t += lineStrideElements;
  65436. }
  65437. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65438. {
  65439. const Rectangle<int>* const r = iter.getRectangle();
  65440. const int x1 = r->getX() << 8;
  65441. const int x2 = r->getRight() << 8;
  65442. int y = r->getY() - bounds.getY();
  65443. for (int j = r->getHeight(); --j >= 0;)
  65444. {
  65445. addEdgePoint (x1, y, 255);
  65446. addEdgePoint (x2, y, -255);
  65447. ++y;
  65448. }
  65449. }
  65450. sanitiseLevels (true);
  65451. }
  65452. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65453. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65454. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65455. 2 + (int) rectangleToAdd.getWidth(),
  65456. 2 + (int) rectangleToAdd.getHeight())),
  65457. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65458. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65459. needToCheckEmptinesss (true)
  65460. {
  65461. jassert (! rectangleToAdd.isEmpty());
  65462. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65463. table[0] = 0;
  65464. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65465. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65466. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65467. jassert (y1 < 256);
  65468. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65469. if (x2 <= x1 || y2 <= y1)
  65470. {
  65471. bounds.setHeight (0);
  65472. return;
  65473. }
  65474. int lineY = 0;
  65475. int* t = table;
  65476. if ((y1 >> 8) == (y2 >> 8))
  65477. {
  65478. t[0] = 2;
  65479. t[1] = x1;
  65480. t[2] = y2 - y1;
  65481. t[3] = x2;
  65482. t[4] = 0;
  65483. ++lineY;
  65484. t += lineStrideElements;
  65485. }
  65486. else
  65487. {
  65488. t[0] = 2;
  65489. t[1] = x1;
  65490. t[2] = 255 - (y1 & 255);
  65491. t[3] = x2;
  65492. t[4] = 0;
  65493. ++lineY;
  65494. t += lineStrideElements;
  65495. while (lineY < (y2 >> 8))
  65496. {
  65497. t[0] = 2;
  65498. t[1] = x1;
  65499. t[2] = 255;
  65500. t[3] = x2;
  65501. t[4] = 0;
  65502. ++lineY;
  65503. t += lineStrideElements;
  65504. }
  65505. jassert (lineY < bounds.getHeight());
  65506. t[0] = 2;
  65507. t[1] = x1;
  65508. t[2] = y2 & 255;
  65509. t[3] = x2;
  65510. t[4] = 0;
  65511. ++lineY;
  65512. t += lineStrideElements;
  65513. }
  65514. while (lineY < bounds.getHeight())
  65515. {
  65516. t[0] = 0;
  65517. t += lineStrideElements;
  65518. ++lineY;
  65519. }
  65520. }
  65521. EdgeTable::EdgeTable (const EdgeTable& other)
  65522. {
  65523. operator= (other);
  65524. }
  65525. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65526. {
  65527. bounds = other.bounds;
  65528. maxEdgesPerLine = other.maxEdgesPerLine;
  65529. lineStrideElements = other.lineStrideElements;
  65530. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65531. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65532. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65533. return *this;
  65534. }
  65535. EdgeTable::~EdgeTable()
  65536. {
  65537. }
  65538. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65539. {
  65540. while (--numLines >= 0)
  65541. {
  65542. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65543. src += srcLineStride;
  65544. dest += destLineStride;
  65545. }
  65546. }
  65547. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65548. {
  65549. // Convert the table from relative windings to absolute levels..
  65550. int* lineStart = table;
  65551. for (int i = bounds.getHeight(); --i >= 0;)
  65552. {
  65553. int* line = lineStart;
  65554. lineStart += lineStrideElements;
  65555. int num = *line;
  65556. if (num == 0)
  65557. continue;
  65558. int level = 0;
  65559. if (useNonZeroWinding)
  65560. {
  65561. while (--num > 0)
  65562. {
  65563. line += 2;
  65564. level += *line;
  65565. int corrected = abs (level);
  65566. if (corrected >> 8)
  65567. corrected = 255;
  65568. *line = corrected;
  65569. }
  65570. }
  65571. else
  65572. {
  65573. while (--num > 0)
  65574. {
  65575. line += 2;
  65576. level += *line;
  65577. int corrected = abs (level);
  65578. if (corrected >> 8)
  65579. {
  65580. corrected &= 511;
  65581. if (corrected >> 8)
  65582. corrected = 511 - corrected;
  65583. }
  65584. *line = corrected;
  65585. }
  65586. }
  65587. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65588. }
  65589. }
  65590. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65591. {
  65592. if (newNumEdgesPerLine != maxEdgesPerLine)
  65593. {
  65594. maxEdgesPerLine = newNumEdgesPerLine;
  65595. jassert (bounds.getHeight() > 0);
  65596. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65597. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65598. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65599. table.swapWith (newTable);
  65600. lineStrideElements = newLineStrideElements;
  65601. }
  65602. }
  65603. void EdgeTable::optimiseTable()
  65604. {
  65605. int maxLineElements = 0;
  65606. for (int i = bounds.getHeight(); --i >= 0;)
  65607. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65608. remapTableForNumEdges (maxLineElements);
  65609. }
  65610. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65611. {
  65612. jassert (y >= 0 && y < bounds.getHeight());
  65613. int* line = table + lineStrideElements * y;
  65614. const int numPoints = line[0];
  65615. int n = numPoints << 1;
  65616. if (n > 0)
  65617. {
  65618. while (n > 0)
  65619. {
  65620. const int cx = line [n - 1];
  65621. if (cx <= x)
  65622. {
  65623. if (cx == x)
  65624. {
  65625. line [n] += winding;
  65626. return;
  65627. }
  65628. break;
  65629. }
  65630. n -= 2;
  65631. }
  65632. if (numPoints >= maxEdgesPerLine)
  65633. {
  65634. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65635. jassert (numPoints < maxEdgesPerLine);
  65636. line = table + lineStrideElements * y;
  65637. }
  65638. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65639. }
  65640. line [n + 1] = x;
  65641. line [n + 2] = winding;
  65642. line[0]++;
  65643. }
  65644. void EdgeTable::translate (float dx, const int dy) throw()
  65645. {
  65646. bounds.translate ((int) std::floor (dx), dy);
  65647. int* lineStart = table;
  65648. const int intDx = (int) (dx * 256.0f);
  65649. for (int i = bounds.getHeight(); --i >= 0;)
  65650. {
  65651. int* line = lineStart;
  65652. lineStart += lineStrideElements;
  65653. int num = *line++;
  65654. while (--num >= 0)
  65655. {
  65656. *line += intDx;
  65657. line += 2;
  65658. }
  65659. }
  65660. }
  65661. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65662. {
  65663. jassert (y >= 0 && y < bounds.getHeight());
  65664. int* dest = table + lineStrideElements * y;
  65665. if (dest[0] == 0)
  65666. return;
  65667. int otherNumPoints = *otherLine;
  65668. if (otherNumPoints == 0)
  65669. {
  65670. *dest = 0;
  65671. return;
  65672. }
  65673. const int right = bounds.getRight() << 8;
  65674. // optimise for the common case where our line lies entirely within a
  65675. // single pair of points, as happens when clipping to a simple rect.
  65676. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65677. {
  65678. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65679. return;
  65680. }
  65681. ++otherLine;
  65682. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65683. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65684. memcpy (temp, dest, lineSizeBytes);
  65685. const int* src1 = temp;
  65686. int srcNum1 = *src1++;
  65687. int x1 = *src1++;
  65688. const int* src2 = otherLine;
  65689. int srcNum2 = otherNumPoints;
  65690. int x2 = *src2++;
  65691. int destIndex = 0, destTotal = 0;
  65692. int level1 = 0, level2 = 0;
  65693. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65694. while (srcNum1 > 0 && srcNum2 > 0)
  65695. {
  65696. int nextX;
  65697. if (x1 < x2)
  65698. {
  65699. nextX = x1;
  65700. level1 = *src1++;
  65701. x1 = *src1++;
  65702. --srcNum1;
  65703. }
  65704. else if (x1 == x2)
  65705. {
  65706. nextX = x1;
  65707. level1 = *src1++;
  65708. level2 = *src2++;
  65709. x1 = *src1++;
  65710. x2 = *src2++;
  65711. --srcNum1;
  65712. --srcNum2;
  65713. }
  65714. else
  65715. {
  65716. nextX = x2;
  65717. level2 = *src2++;
  65718. x2 = *src2++;
  65719. --srcNum2;
  65720. }
  65721. if (nextX > lastX)
  65722. {
  65723. if (nextX >= right)
  65724. break;
  65725. lastX = nextX;
  65726. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65727. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  65728. if (nextLevel != lastLevel)
  65729. {
  65730. if (destTotal >= maxEdgesPerLine)
  65731. {
  65732. dest[0] = destTotal;
  65733. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65734. dest = table + lineStrideElements * y;
  65735. }
  65736. ++destTotal;
  65737. lastLevel = nextLevel;
  65738. dest[++destIndex] = nextX;
  65739. dest[++destIndex] = nextLevel;
  65740. }
  65741. }
  65742. }
  65743. if (lastLevel > 0)
  65744. {
  65745. if (destTotal >= maxEdgesPerLine)
  65746. {
  65747. dest[0] = destTotal;
  65748. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65749. dest = table + lineStrideElements * y;
  65750. }
  65751. ++destTotal;
  65752. dest[++destIndex] = right;
  65753. dest[++destIndex] = 0;
  65754. }
  65755. dest[0] = destTotal;
  65756. #if JUCE_DEBUG
  65757. int last = std::numeric_limits<int>::min();
  65758. for (int i = 0; i < dest[0]; ++i)
  65759. {
  65760. jassert (dest[i * 2 + 1] > last);
  65761. last = dest[i * 2 + 1];
  65762. }
  65763. jassert (dest [dest[0] * 2] == 0);
  65764. #endif
  65765. }
  65766. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65767. {
  65768. int* lastItem = dest + (dest[0] * 2 - 1);
  65769. if (x2 < lastItem[0])
  65770. {
  65771. if (x2 <= dest[1])
  65772. {
  65773. dest[0] = 0;
  65774. return;
  65775. }
  65776. while (x2 < lastItem[-2])
  65777. {
  65778. --(dest[0]);
  65779. lastItem -= 2;
  65780. }
  65781. lastItem[0] = x2;
  65782. lastItem[1] = 0;
  65783. }
  65784. if (x1 > dest[1])
  65785. {
  65786. while (lastItem[0] > x1)
  65787. lastItem -= 2;
  65788. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65789. if (itemsRemoved > 0)
  65790. {
  65791. dest[0] -= itemsRemoved;
  65792. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65793. }
  65794. dest[1] = x1;
  65795. }
  65796. }
  65797. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  65798. {
  65799. const Rectangle<int> clipped (r.getIntersection (bounds));
  65800. if (clipped.isEmpty())
  65801. {
  65802. needToCheckEmptinesss = false;
  65803. bounds.setHeight (0);
  65804. }
  65805. else
  65806. {
  65807. const int top = clipped.getY() - bounds.getY();
  65808. const int bottom = clipped.getBottom() - bounds.getY();
  65809. if (bottom < bounds.getHeight())
  65810. bounds.setHeight (bottom);
  65811. if (clipped.getRight() < bounds.getRight())
  65812. bounds.setRight (clipped.getRight());
  65813. for (int i = top; --i >= 0;)
  65814. table [lineStrideElements * i] = 0;
  65815. if (clipped.getX() > bounds.getX())
  65816. {
  65817. const int x1 = clipped.getX() << 8;
  65818. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65819. int* line = table + lineStrideElements * top;
  65820. for (int i = bottom - top; --i >= 0;)
  65821. {
  65822. if (line[0] != 0)
  65823. clipEdgeTableLineToRange (line, x1, x2);
  65824. line += lineStrideElements;
  65825. }
  65826. }
  65827. needToCheckEmptinesss = true;
  65828. }
  65829. }
  65830. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  65831. {
  65832. const Rectangle<int> clipped (r.getIntersection (bounds));
  65833. if (! clipped.isEmpty())
  65834. {
  65835. const int top = clipped.getY() - bounds.getY();
  65836. const int bottom = clipped.getBottom() - bounds.getY();
  65837. //XXX optimise here by shortening the table if it fills top or bottom
  65838. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  65839. clipped.getX() << 8, 0,
  65840. clipped.getRight() << 8, 255,
  65841. std::numeric_limits<int>::max(), 0 };
  65842. for (int i = top; i < bottom; ++i)
  65843. intersectWithEdgeTableLine (i, rectLine);
  65844. needToCheckEmptinesss = true;
  65845. }
  65846. }
  65847. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  65848. {
  65849. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  65850. if (clipped.isEmpty())
  65851. {
  65852. needToCheckEmptinesss = false;
  65853. bounds.setHeight (0);
  65854. }
  65855. else
  65856. {
  65857. const int top = clipped.getY() - bounds.getY();
  65858. const int bottom = clipped.getBottom() - bounds.getY();
  65859. if (bottom < bounds.getHeight())
  65860. bounds.setHeight (bottom);
  65861. if (clipped.getRight() < bounds.getRight())
  65862. bounds.setRight (clipped.getRight());
  65863. int i = 0;
  65864. for (i = top; --i >= 0;)
  65865. table [lineStrideElements * i] = 0;
  65866. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  65867. for (i = top; i < bottom; ++i)
  65868. {
  65869. intersectWithEdgeTableLine (i, otherLine);
  65870. otherLine += other.lineStrideElements;
  65871. }
  65872. needToCheckEmptinesss = true;
  65873. }
  65874. }
  65875. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  65876. {
  65877. y -= bounds.getY();
  65878. if (y < 0 || y >= bounds.getHeight())
  65879. return;
  65880. needToCheckEmptinesss = true;
  65881. if (numPixels <= 0)
  65882. {
  65883. table [lineStrideElements * y] = 0;
  65884. return;
  65885. }
  65886. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  65887. int destIndex = 0, lastLevel = 0;
  65888. while (--numPixels >= 0)
  65889. {
  65890. const int alpha = *mask;
  65891. mask += maskStride;
  65892. if (alpha != lastLevel)
  65893. {
  65894. tempLine[++destIndex] = (x << 8);
  65895. tempLine[++destIndex] = alpha;
  65896. lastLevel = alpha;
  65897. }
  65898. ++x;
  65899. }
  65900. if (lastLevel > 0)
  65901. {
  65902. tempLine[++destIndex] = (x << 8);
  65903. tempLine[++destIndex] = 0;
  65904. }
  65905. tempLine[0] = destIndex >> 1;
  65906. intersectWithEdgeTableLine (y, tempLine);
  65907. }
  65908. bool EdgeTable::isEmpty() throw()
  65909. {
  65910. if (needToCheckEmptinesss)
  65911. {
  65912. needToCheckEmptinesss = false;
  65913. int* t = table;
  65914. for (int i = bounds.getHeight(); --i >= 0;)
  65915. {
  65916. if (t[0] > 1)
  65917. return false;
  65918. t += lineStrideElements;
  65919. }
  65920. bounds.setHeight (0);
  65921. }
  65922. return bounds.getHeight() == 0;
  65923. }
  65924. END_JUCE_NAMESPACE
  65925. /*** End of inlined file: juce_EdgeTable.cpp ***/
  65926. /*** Start of inlined file: juce_FillType.cpp ***/
  65927. BEGIN_JUCE_NAMESPACE
  65928. FillType::FillType() throw()
  65929. : colour (0xff000000), image (0)
  65930. {
  65931. }
  65932. FillType::FillType (const Colour& colour_) throw()
  65933. : colour (colour_), image (0)
  65934. {
  65935. }
  65936. FillType::FillType (const ColourGradient& gradient_)
  65937. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  65938. {
  65939. }
  65940. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  65941. : colour (0xff000000), image (image_), transform (transform_)
  65942. {
  65943. }
  65944. FillType::FillType (const FillType& other)
  65945. : colour (other.colour),
  65946. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  65947. image (other.image), transform (other.transform)
  65948. {
  65949. }
  65950. FillType& FillType::operator= (const FillType& other)
  65951. {
  65952. if (this != &other)
  65953. {
  65954. colour = other.colour;
  65955. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  65956. image = other.image;
  65957. transform = other.transform;
  65958. }
  65959. return *this;
  65960. }
  65961. FillType::~FillType() throw()
  65962. {
  65963. }
  65964. bool FillType::operator== (const FillType& other) const
  65965. {
  65966. return colour == other.colour && image == other.image
  65967. && transform == other.transform
  65968. && (gradient == other.gradient
  65969. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  65970. }
  65971. bool FillType::operator!= (const FillType& other) const
  65972. {
  65973. return ! operator== (other);
  65974. }
  65975. void FillType::setColour (const Colour& newColour) throw()
  65976. {
  65977. gradient = 0;
  65978. image = Image::null;
  65979. colour = newColour;
  65980. }
  65981. void FillType::setGradient (const ColourGradient& newGradient)
  65982. {
  65983. if (gradient != 0)
  65984. {
  65985. *gradient = newGradient;
  65986. }
  65987. else
  65988. {
  65989. image = Image::null;
  65990. gradient = new ColourGradient (newGradient);
  65991. colour = Colours::black;
  65992. }
  65993. }
  65994. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  65995. {
  65996. gradient = 0;
  65997. image = image_;
  65998. transform = transform_;
  65999. colour = Colours::black;
  66000. }
  66001. void FillType::setOpacity (const float newOpacity) throw()
  66002. {
  66003. colour = colour.withAlpha (newOpacity);
  66004. }
  66005. bool FillType::isInvisible() const throw()
  66006. {
  66007. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66008. }
  66009. END_JUCE_NAMESPACE
  66010. /*** End of inlined file: juce_FillType.cpp ***/
  66011. /*** Start of inlined file: juce_Graphics.cpp ***/
  66012. BEGIN_JUCE_NAMESPACE
  66013. namespace
  66014. {
  66015. template <typename Type>
  66016. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66017. {
  66018. const int maxVal = 0x3fffffff;
  66019. return (int) x >= -maxVal && (int) x <= maxVal
  66020. && (int) y >= -maxVal && (int) y <= maxVal
  66021. && (int) w >= -maxVal && (int) w <= maxVal
  66022. && (int) h >= -maxVal && (int) h <= maxVal;
  66023. }
  66024. }
  66025. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66026. {
  66027. }
  66028. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66029. {
  66030. }
  66031. Graphics::Graphics (const Image& imageToDrawOnto)
  66032. : context (imageToDrawOnto.createLowLevelContext()),
  66033. contextToDelete (context),
  66034. saveStatePending (false)
  66035. {
  66036. }
  66037. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66038. : context (internalContext),
  66039. saveStatePending (false)
  66040. {
  66041. }
  66042. Graphics::~Graphics()
  66043. {
  66044. }
  66045. void Graphics::resetToDefaultState()
  66046. {
  66047. saveStateIfPending();
  66048. context->setFill (FillType());
  66049. context->setFont (Font());
  66050. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66051. }
  66052. bool Graphics::isVectorDevice() const
  66053. {
  66054. return context->isVectorDevice();
  66055. }
  66056. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66057. {
  66058. saveStateIfPending();
  66059. return context->clipToRectangle (area);
  66060. }
  66061. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66062. {
  66063. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66064. }
  66065. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66066. {
  66067. saveStateIfPending();
  66068. return context->clipToRectangleList (clipRegion);
  66069. }
  66070. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66071. {
  66072. saveStateIfPending();
  66073. context->clipToPath (path, transform);
  66074. return ! context->isClipEmpty();
  66075. }
  66076. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66077. {
  66078. saveStateIfPending();
  66079. context->clipToImageAlpha (image, transform);
  66080. return ! context->isClipEmpty();
  66081. }
  66082. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66083. {
  66084. saveStateIfPending();
  66085. context->excludeClipRectangle (rectangleToExclude);
  66086. }
  66087. bool Graphics::isClipEmpty() const
  66088. {
  66089. return context->isClipEmpty();
  66090. }
  66091. const Rectangle<int> Graphics::getClipBounds() const
  66092. {
  66093. return context->getClipBounds();
  66094. }
  66095. void Graphics::saveState()
  66096. {
  66097. saveStateIfPending();
  66098. saveStatePending = true;
  66099. }
  66100. void Graphics::restoreState()
  66101. {
  66102. if (saveStatePending)
  66103. saveStatePending = false;
  66104. else
  66105. context->restoreState();
  66106. }
  66107. void Graphics::saveStateIfPending()
  66108. {
  66109. if (saveStatePending)
  66110. {
  66111. saveStatePending = false;
  66112. context->saveState();
  66113. }
  66114. }
  66115. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66116. {
  66117. saveStateIfPending();
  66118. context->setOrigin (newOriginX, newOriginY);
  66119. }
  66120. void Graphics::addTransform (const AffineTransform& transform)
  66121. {
  66122. saveStateIfPending();
  66123. context->addTransform (transform);
  66124. }
  66125. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66126. {
  66127. return context->clipRegionIntersects (area);
  66128. }
  66129. void Graphics::beginTransparencyLayer (float layerOpacity)
  66130. {
  66131. saveStateIfPending();
  66132. context->beginTransparencyLayer (layerOpacity);
  66133. }
  66134. void Graphics::endTransparencyLayer()
  66135. {
  66136. context->endTransparencyLayer();
  66137. }
  66138. void Graphics::setColour (const Colour& newColour)
  66139. {
  66140. saveStateIfPending();
  66141. context->setFill (newColour);
  66142. }
  66143. void Graphics::setOpacity (const float newOpacity)
  66144. {
  66145. saveStateIfPending();
  66146. context->setOpacity (newOpacity);
  66147. }
  66148. void Graphics::setGradientFill (const ColourGradient& gradient)
  66149. {
  66150. setFillType (gradient);
  66151. }
  66152. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66153. {
  66154. saveStateIfPending();
  66155. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66156. context->setOpacity (opacity);
  66157. }
  66158. void Graphics::setFillType (const FillType& newFill)
  66159. {
  66160. saveStateIfPending();
  66161. context->setFill (newFill);
  66162. }
  66163. void Graphics::setFont (const Font& newFont)
  66164. {
  66165. saveStateIfPending();
  66166. context->setFont (newFont);
  66167. }
  66168. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66169. {
  66170. saveStateIfPending();
  66171. Font f (context->getFont());
  66172. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66173. context->setFont (f);
  66174. }
  66175. const Font Graphics::getCurrentFont() const
  66176. {
  66177. return context->getFont();
  66178. }
  66179. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66180. {
  66181. if (text.isNotEmpty()
  66182. && startX < context->getClipBounds().getRight())
  66183. {
  66184. GlyphArrangement arr;
  66185. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66186. arr.draw (*this);
  66187. }
  66188. }
  66189. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66190. {
  66191. if (text.isNotEmpty())
  66192. {
  66193. GlyphArrangement arr;
  66194. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66195. arr.draw (*this, transform);
  66196. }
  66197. }
  66198. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66199. {
  66200. if (text.isNotEmpty()
  66201. && startX < context->getClipBounds().getRight())
  66202. {
  66203. GlyphArrangement arr;
  66204. arr.addJustifiedText (context->getFont(), text,
  66205. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66206. Justification::left);
  66207. arr.draw (*this);
  66208. }
  66209. }
  66210. void Graphics::drawText (const String& text,
  66211. const int x, const int y, const int width, const int height,
  66212. const Justification& justificationType,
  66213. const bool useEllipsesIfTooBig) const
  66214. {
  66215. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66216. {
  66217. GlyphArrangement arr;
  66218. arr.addCurtailedLineOfText (context->getFont(), text,
  66219. 0.0f, 0.0f, (float) width,
  66220. useEllipsesIfTooBig);
  66221. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66222. (float) x, (float) y, (float) width, (float) height,
  66223. justificationType);
  66224. arr.draw (*this);
  66225. }
  66226. }
  66227. void Graphics::drawFittedText (const String& text,
  66228. const int x, const int y, const int width, const int height,
  66229. const Justification& justification,
  66230. const int maximumNumberOfLines,
  66231. const float minimumHorizontalScale) const
  66232. {
  66233. if (text.isNotEmpty()
  66234. && width > 0 && height > 0
  66235. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66236. {
  66237. GlyphArrangement arr;
  66238. arr.addFittedText (context->getFont(), text,
  66239. (float) x, (float) y, (float) width, (float) height,
  66240. justification,
  66241. maximumNumberOfLines,
  66242. minimumHorizontalScale);
  66243. arr.draw (*this);
  66244. }
  66245. }
  66246. void Graphics::fillRect (int x, int y, int width, int height) const
  66247. {
  66248. // passing in a silly number can cause maths problems in rendering!
  66249. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66250. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66251. }
  66252. void Graphics::fillRect (const Rectangle<int>& r) const
  66253. {
  66254. context->fillRect (r, false);
  66255. }
  66256. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66257. {
  66258. // passing in a silly number can cause maths problems in rendering!
  66259. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66260. Path p;
  66261. p.addRectangle (x, y, width, height);
  66262. fillPath (p);
  66263. }
  66264. void Graphics::setPixel (int x, int y) const
  66265. {
  66266. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66267. }
  66268. void Graphics::fillAll() const
  66269. {
  66270. fillRect (context->getClipBounds());
  66271. }
  66272. void Graphics::fillAll (const Colour& colourToUse) const
  66273. {
  66274. if (! colourToUse.isTransparent())
  66275. {
  66276. const Rectangle<int> clip (context->getClipBounds());
  66277. context->saveState();
  66278. context->setFill (colourToUse);
  66279. context->fillRect (clip, false);
  66280. context->restoreState();
  66281. }
  66282. }
  66283. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66284. {
  66285. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66286. context->fillPath (path, transform);
  66287. }
  66288. void Graphics::strokePath (const Path& path,
  66289. const PathStrokeType& strokeType,
  66290. const AffineTransform& transform) const
  66291. {
  66292. Path stroke;
  66293. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66294. fillPath (stroke);
  66295. }
  66296. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66297. const int lineThickness) const
  66298. {
  66299. // passing in a silly number can cause maths problems in rendering!
  66300. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66301. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66302. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66303. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66304. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66305. }
  66306. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66307. {
  66308. // passing in a silly number can cause maths problems in rendering!
  66309. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66310. Path p;
  66311. p.addRectangle (x, y, width, lineThickness);
  66312. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66313. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66314. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66315. fillPath (p);
  66316. }
  66317. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66318. {
  66319. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66320. }
  66321. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66322. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66323. const bool useGradient, const bool sharpEdgeOnOutside) const
  66324. {
  66325. // passing in a silly number can cause maths problems in rendering!
  66326. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66327. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66328. {
  66329. context->saveState();
  66330. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66331. const float ramp = oldOpacity / bevelThickness;
  66332. for (int i = bevelThickness; --i >= 0;)
  66333. {
  66334. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66335. : oldOpacity;
  66336. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66337. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66338. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66339. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66340. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66341. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66342. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66343. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66344. }
  66345. context->restoreState();
  66346. }
  66347. }
  66348. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66349. {
  66350. // passing in a silly number can cause maths problems in rendering!
  66351. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66352. Path p;
  66353. p.addEllipse (x, y, width, height);
  66354. fillPath (p);
  66355. }
  66356. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66357. const float lineThickness) const
  66358. {
  66359. // passing in a silly number can cause maths problems in rendering!
  66360. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66361. Path p;
  66362. p.addEllipse (x, y, width, height);
  66363. strokePath (p, PathStrokeType (lineThickness));
  66364. }
  66365. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66366. {
  66367. // passing in a silly number can cause maths problems in rendering!
  66368. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66369. Path p;
  66370. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66371. fillPath (p);
  66372. }
  66373. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66374. {
  66375. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66376. }
  66377. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66378. const float cornerSize, const float lineThickness) const
  66379. {
  66380. // passing in a silly number can cause maths problems in rendering!
  66381. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66382. Path p;
  66383. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66384. strokePath (p, PathStrokeType (lineThickness));
  66385. }
  66386. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66387. {
  66388. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66389. }
  66390. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66391. {
  66392. Path p;
  66393. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66394. fillPath (p);
  66395. }
  66396. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66397. const int checkWidth, const int checkHeight,
  66398. const Colour& colour1, const Colour& colour2) const
  66399. {
  66400. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66401. if (checkWidth > 0 && checkHeight > 0)
  66402. {
  66403. context->saveState();
  66404. if (colour1 == colour2)
  66405. {
  66406. context->setFill (colour1);
  66407. context->fillRect (area, false);
  66408. }
  66409. else
  66410. {
  66411. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66412. if (! clipped.isEmpty())
  66413. {
  66414. context->clipToRectangle (clipped);
  66415. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66416. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66417. const int startX = area.getX() + checkNumX * checkWidth;
  66418. const int startY = area.getY() + checkNumY * checkHeight;
  66419. const int right = clipped.getRight();
  66420. const int bottom = clipped.getBottom();
  66421. for (int i = 0; i < 2; ++i)
  66422. {
  66423. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66424. int cy = i;
  66425. for (int y = startY; y < bottom; y += checkHeight)
  66426. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66427. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66428. }
  66429. }
  66430. }
  66431. context->restoreState();
  66432. }
  66433. }
  66434. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66435. {
  66436. context->drawVerticalLine (x, top, bottom);
  66437. }
  66438. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66439. {
  66440. context->drawHorizontalLine (y, left, right);
  66441. }
  66442. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66443. {
  66444. context->drawLine (Line<float> (x1, y1, x2, y2));
  66445. }
  66446. void Graphics::drawLine (const float startX, const float startY,
  66447. const float endX, const float endY,
  66448. const float lineThickness) const
  66449. {
  66450. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66451. }
  66452. void Graphics::drawLine (const Line<float>& line) const
  66453. {
  66454. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66455. }
  66456. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66457. {
  66458. Path p;
  66459. p.addLineSegment (line, lineThickness);
  66460. fillPath (p);
  66461. }
  66462. void Graphics::drawDashedLine (const float startX, const float startY,
  66463. const float endX, const float endY,
  66464. const float* const dashLengths,
  66465. const int numDashLengths,
  66466. const float lineThickness) const
  66467. {
  66468. const double dx = endX - startX;
  66469. const double dy = endY - startY;
  66470. const double totalLen = juce_hypot (dx, dy);
  66471. if (totalLen >= 0.5)
  66472. {
  66473. const double onePixAlpha = 1.0 / totalLen;
  66474. double alpha = 0.0;
  66475. float x = startX;
  66476. float y = startY;
  66477. int n = 0;
  66478. while (alpha < 1.0f)
  66479. {
  66480. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66481. n = n % numDashLengths;
  66482. const float oldX = x;
  66483. const float oldY = y;
  66484. x = (float) (startX + dx * alpha);
  66485. y = (float) (startY + dy * alpha);
  66486. if ((n & 1) != 0)
  66487. {
  66488. if (lineThickness != 1.0f)
  66489. drawLine (oldX, oldY, x, y, lineThickness);
  66490. else
  66491. drawLine (oldX, oldY, x, y);
  66492. }
  66493. }
  66494. }
  66495. }
  66496. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66497. {
  66498. saveStateIfPending();
  66499. context->setInterpolationQuality (newQuality);
  66500. }
  66501. void Graphics::drawImageAt (const Image& imageToDraw,
  66502. const int topLeftX, const int topLeftY,
  66503. const bool fillAlphaChannelWithCurrentBrush) const
  66504. {
  66505. const int imageW = imageToDraw.getWidth();
  66506. const int imageH = imageToDraw.getHeight();
  66507. drawImage (imageToDraw,
  66508. topLeftX, topLeftY, imageW, imageH,
  66509. 0, 0, imageW, imageH,
  66510. fillAlphaChannelWithCurrentBrush);
  66511. }
  66512. void Graphics::drawImageWithin (const Image& imageToDraw,
  66513. const int destX, const int destY,
  66514. const int destW, const int destH,
  66515. const RectanglePlacement& placementWithinTarget,
  66516. const bool fillAlphaChannelWithCurrentBrush) const
  66517. {
  66518. // passing in a silly number can cause maths problems in rendering!
  66519. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66520. if (imageToDraw.isValid())
  66521. {
  66522. const int imageW = imageToDraw.getWidth();
  66523. const int imageH = imageToDraw.getHeight();
  66524. if (imageW > 0 && imageH > 0)
  66525. {
  66526. double newX = 0.0, newY = 0.0;
  66527. double newW = imageW;
  66528. double newH = imageH;
  66529. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66530. destX, destY, destW, destH);
  66531. if (newW > 0 && newH > 0)
  66532. {
  66533. drawImage (imageToDraw,
  66534. roundToInt (newX), roundToInt (newY),
  66535. roundToInt (newW), roundToInt (newH),
  66536. 0, 0, imageW, imageH,
  66537. fillAlphaChannelWithCurrentBrush);
  66538. }
  66539. }
  66540. }
  66541. }
  66542. void Graphics::drawImage (const Image& imageToDraw,
  66543. int dx, int dy, int dw, int dh,
  66544. int sx, int sy, int sw, int sh,
  66545. const bool fillAlphaChannelWithCurrentBrush) const
  66546. {
  66547. // passing in a silly number can cause maths problems in rendering!
  66548. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66549. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66550. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66551. {
  66552. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66553. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66554. .translated ((float) dx, (float) dy),
  66555. fillAlphaChannelWithCurrentBrush);
  66556. }
  66557. }
  66558. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66559. const AffineTransform& transform,
  66560. const bool fillAlphaChannelWithCurrentBrush) const
  66561. {
  66562. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66563. {
  66564. if (fillAlphaChannelWithCurrentBrush)
  66565. {
  66566. context->saveState();
  66567. context->clipToImageAlpha (imageToDraw, transform);
  66568. fillAll();
  66569. context->restoreState();
  66570. }
  66571. else
  66572. {
  66573. context->drawImage (imageToDraw, transform, false);
  66574. }
  66575. }
  66576. }
  66577. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  66578. : context (g)
  66579. {
  66580. context.saveState();
  66581. }
  66582. Graphics::ScopedSaveState::~ScopedSaveState()
  66583. {
  66584. context.restoreState();
  66585. }
  66586. END_JUCE_NAMESPACE
  66587. /*** End of inlined file: juce_Graphics.cpp ***/
  66588. /*** Start of inlined file: juce_Justification.cpp ***/
  66589. BEGIN_JUCE_NAMESPACE
  66590. Justification::Justification (const Justification& other) throw()
  66591. : flags (other.flags)
  66592. {
  66593. }
  66594. Justification& Justification::operator= (const Justification& other) throw()
  66595. {
  66596. flags = other.flags;
  66597. return *this;
  66598. }
  66599. int Justification::getOnlyVerticalFlags() const throw()
  66600. {
  66601. return flags & (top | bottom | verticallyCentred);
  66602. }
  66603. int Justification::getOnlyHorizontalFlags() const throw()
  66604. {
  66605. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66606. }
  66607. void Justification::applyToRectangle (int& x, int& y,
  66608. const int w, const int h,
  66609. const int spaceX, const int spaceY,
  66610. const int spaceW, const int spaceH) const throw()
  66611. {
  66612. if ((flags & horizontallyCentred) != 0)
  66613. x = spaceX + ((spaceW - w) >> 1);
  66614. else if ((flags & right) != 0)
  66615. x = spaceX + spaceW - w;
  66616. else
  66617. x = spaceX;
  66618. if ((flags & verticallyCentred) != 0)
  66619. y = spaceY + ((spaceH - h) >> 1);
  66620. else if ((flags & bottom) != 0)
  66621. y = spaceY + spaceH - h;
  66622. else
  66623. y = spaceY;
  66624. }
  66625. END_JUCE_NAMESPACE
  66626. /*** End of inlined file: juce_Justification.cpp ***/
  66627. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66628. BEGIN_JUCE_NAMESPACE
  66629. // this will throw an assertion if you try to draw something that's not
  66630. // possible in postscript
  66631. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66632. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66633. #define notPossibleInPostscriptAssert jassertfalse
  66634. #else
  66635. #define notPossibleInPostscriptAssert
  66636. #endif
  66637. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66638. const String& documentTitle,
  66639. const int totalWidth_,
  66640. const int totalHeight_)
  66641. : out (resultingPostScript),
  66642. totalWidth (totalWidth_),
  66643. totalHeight (totalHeight_),
  66644. needToClip (true)
  66645. {
  66646. stateStack.add (new SavedState());
  66647. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66648. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66649. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66650. "\n%%BoundingBox: 0 0 600 824"
  66651. "\n%%Pages: 0"
  66652. "\n%%Creator: Raw Material Software JUCE"
  66653. "\n%%Title: " << documentTitle <<
  66654. "\n%%CreationDate: none"
  66655. "\n%%LanguageLevel: 2"
  66656. "\n%%EndComments"
  66657. "\n%%BeginProlog"
  66658. "\n%%BeginResource: JRes"
  66659. "\n/bd {bind def} bind def"
  66660. "\n/c {setrgbcolor} bd"
  66661. "\n/m {moveto} bd"
  66662. "\n/l {lineto} bd"
  66663. "\n/rl {rlineto} bd"
  66664. "\n/ct {curveto} bd"
  66665. "\n/cp {closepath} bd"
  66666. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66667. "\n/doclip {initclip newpath} bd"
  66668. "\n/endclip {clip newpath} bd"
  66669. "\n%%EndResource"
  66670. "\n%%EndProlog"
  66671. "\n%%BeginSetup"
  66672. "\n%%EndSetup"
  66673. "\n%%Page: 1 1"
  66674. "\n%%BeginPageSetup"
  66675. "\n%%EndPageSetup\n\n"
  66676. << "40 800 translate\n"
  66677. << scale << ' ' << scale << " scale\n\n";
  66678. }
  66679. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66680. {
  66681. }
  66682. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66683. {
  66684. return true;
  66685. }
  66686. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66687. {
  66688. if (x != 0 || y != 0)
  66689. {
  66690. stateStack.getLast()->xOffset += x;
  66691. stateStack.getLast()->yOffset += y;
  66692. needToClip = true;
  66693. }
  66694. }
  66695. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66696. {
  66697. //xxx
  66698. jassertfalse;
  66699. }
  66700. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  66701. {
  66702. jassertfalse; //xxx
  66703. return 1.0f;
  66704. }
  66705. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66706. {
  66707. needToClip = true;
  66708. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66709. }
  66710. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66711. {
  66712. needToClip = true;
  66713. return stateStack.getLast()->clip.clipTo (clipRegion);
  66714. }
  66715. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66716. {
  66717. needToClip = true;
  66718. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66719. }
  66720. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66721. {
  66722. writeClip();
  66723. Path p (path);
  66724. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66725. writePath (p);
  66726. out << "clip\n";
  66727. }
  66728. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66729. {
  66730. needToClip = true;
  66731. jassertfalse; // xxx
  66732. }
  66733. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66734. {
  66735. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66736. }
  66737. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66738. {
  66739. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66740. -stateStack.getLast()->yOffset);
  66741. }
  66742. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66743. {
  66744. return stateStack.getLast()->clip.isEmpty();
  66745. }
  66746. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66747. : xOffset (0),
  66748. yOffset (0)
  66749. {
  66750. }
  66751. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66752. {
  66753. }
  66754. void LowLevelGraphicsPostScriptRenderer::saveState()
  66755. {
  66756. stateStack.add (new SavedState (*stateStack.getLast()));
  66757. }
  66758. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66759. {
  66760. jassert (stateStack.size() > 0);
  66761. if (stateStack.size() > 0)
  66762. stateStack.removeLast();
  66763. }
  66764. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  66765. {
  66766. }
  66767. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  66768. {
  66769. }
  66770. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66771. {
  66772. if (needToClip)
  66773. {
  66774. needToClip = false;
  66775. out << "doclip ";
  66776. int itemsOnLine = 0;
  66777. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66778. {
  66779. if (++itemsOnLine == 6)
  66780. {
  66781. itemsOnLine = 0;
  66782. out << '\n';
  66783. }
  66784. const Rectangle<int>& r = *i.getRectangle();
  66785. out << r.getX() << ' ' << -r.getY() << ' '
  66786. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66787. }
  66788. out << "endclip\n";
  66789. }
  66790. }
  66791. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66792. {
  66793. Colour c (Colours::white.overlaidWith (colour));
  66794. if (lastColour != c)
  66795. {
  66796. lastColour = c;
  66797. out << String (c.getFloatRed(), 3) << ' '
  66798. << String (c.getFloatGreen(), 3) << ' '
  66799. << String (c.getFloatBlue(), 3) << " c\n";
  66800. }
  66801. }
  66802. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66803. {
  66804. out << String (x, 2) << ' '
  66805. << String (-y, 2) << ' ';
  66806. }
  66807. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66808. {
  66809. out << "newpath ";
  66810. float lastX = 0.0f;
  66811. float lastY = 0.0f;
  66812. int itemsOnLine = 0;
  66813. Path::Iterator i (path);
  66814. while (i.next())
  66815. {
  66816. if (++itemsOnLine == 4)
  66817. {
  66818. itemsOnLine = 0;
  66819. out << '\n';
  66820. }
  66821. switch (i.elementType)
  66822. {
  66823. case Path::Iterator::startNewSubPath:
  66824. writeXY (i.x1, i.y1);
  66825. lastX = i.x1;
  66826. lastY = i.y1;
  66827. out << "m ";
  66828. break;
  66829. case Path::Iterator::lineTo:
  66830. writeXY (i.x1, i.y1);
  66831. lastX = i.x1;
  66832. lastY = i.y1;
  66833. out << "l ";
  66834. break;
  66835. case Path::Iterator::quadraticTo:
  66836. {
  66837. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66838. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66839. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66840. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66841. writeXY (cp1x, cp1y);
  66842. writeXY (cp2x, cp2y);
  66843. writeXY (i.x2, i.y2);
  66844. out << "ct ";
  66845. lastX = i.x2;
  66846. lastY = i.y2;
  66847. }
  66848. break;
  66849. case Path::Iterator::cubicTo:
  66850. writeXY (i.x1, i.y1);
  66851. writeXY (i.x2, i.y2);
  66852. writeXY (i.x3, i.y3);
  66853. out << "ct ";
  66854. lastX = i.x3;
  66855. lastY = i.y3;
  66856. break;
  66857. case Path::Iterator::closePath:
  66858. out << "cp ";
  66859. break;
  66860. default:
  66861. jassertfalse;
  66862. break;
  66863. }
  66864. }
  66865. out << '\n';
  66866. }
  66867. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  66868. {
  66869. out << "[ "
  66870. << trans.mat00 << ' '
  66871. << trans.mat10 << ' '
  66872. << trans.mat01 << ' '
  66873. << trans.mat11 << ' '
  66874. << trans.mat02 << ' '
  66875. << trans.mat12 << " ] concat ";
  66876. }
  66877. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  66878. {
  66879. stateStack.getLast()->fillType = fillType;
  66880. }
  66881. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  66882. {
  66883. }
  66884. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  66885. {
  66886. }
  66887. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  66888. {
  66889. if (stateStack.getLast()->fillType.isColour())
  66890. {
  66891. writeClip();
  66892. writeColour (stateStack.getLast()->fillType.colour);
  66893. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66894. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  66895. }
  66896. else
  66897. {
  66898. Path p;
  66899. p.addRectangle (r);
  66900. fillPath (p, AffineTransform::identity);
  66901. }
  66902. }
  66903. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  66904. {
  66905. if (stateStack.getLast()->fillType.isColour())
  66906. {
  66907. writeClip();
  66908. Path p (path);
  66909. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  66910. (float) stateStack.getLast()->yOffset));
  66911. writePath (p);
  66912. writeColour (stateStack.getLast()->fillType.colour);
  66913. out << "fill\n";
  66914. }
  66915. else if (stateStack.getLast()->fillType.isGradient())
  66916. {
  66917. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  66918. // postscript can't do semi-transparent ones.
  66919. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  66920. writeClip();
  66921. out << "gsave ";
  66922. {
  66923. Path p (path);
  66924. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66925. writePath (p);
  66926. out << "clip\n";
  66927. }
  66928. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  66929. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  66930. // time-being, this just fills it with the average colour..
  66931. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  66932. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  66933. out << "grestore\n";
  66934. }
  66935. }
  66936. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  66937. const int sx, const int sy,
  66938. const int maxW, const int maxH) const
  66939. {
  66940. out << "{<\n";
  66941. const int w = jmin (maxW, im.getWidth());
  66942. const int h = jmin (maxH, im.getHeight());
  66943. int charsOnLine = 0;
  66944. const Image::BitmapData srcData (im, 0, 0, w, h);
  66945. Colour pixel;
  66946. for (int y = h; --y >= 0;)
  66947. {
  66948. for (int x = 0; x < w; ++x)
  66949. {
  66950. const uint8* pixelData = srcData.getPixelPointer (x, y);
  66951. if (x >= sx && y >= sy)
  66952. {
  66953. if (im.isARGB())
  66954. {
  66955. PixelARGB p (*(const PixelARGB*) pixelData);
  66956. p.unpremultiply();
  66957. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  66958. }
  66959. else if (im.isRGB())
  66960. {
  66961. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  66962. }
  66963. else
  66964. {
  66965. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  66966. }
  66967. }
  66968. else
  66969. {
  66970. pixel = Colours::transparentWhite;
  66971. }
  66972. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  66973. out << String::toHexString (pixelValues, 3, 0);
  66974. charsOnLine += 3;
  66975. if (charsOnLine > 100)
  66976. {
  66977. out << '\n';
  66978. charsOnLine = 0;
  66979. }
  66980. }
  66981. }
  66982. out << "\n>}\n";
  66983. }
  66984. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  66985. {
  66986. const int w = sourceImage.getWidth();
  66987. const int h = sourceImage.getHeight();
  66988. writeClip();
  66989. out << "gsave ";
  66990. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  66991. .scaled (1.0f, -1.0f));
  66992. RectangleList imageClip;
  66993. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  66994. out << "newpath ";
  66995. int itemsOnLine = 0;
  66996. for (RectangleList::Iterator i (imageClip); i.next();)
  66997. {
  66998. if (++itemsOnLine == 6)
  66999. {
  67000. out << '\n';
  67001. itemsOnLine = 0;
  67002. }
  67003. const Rectangle<int>& r = *i.getRectangle();
  67004. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67005. }
  67006. out << " clip newpath\n";
  67007. out << w << ' ' << h << " scale\n";
  67008. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67009. writeImage (sourceImage, 0, 0, w, h);
  67010. out << "false 3 colorimage grestore\n";
  67011. needToClip = true;
  67012. }
  67013. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67014. {
  67015. Path p;
  67016. p.addLineSegment (line, 1.0f);
  67017. fillPath (p, AffineTransform::identity);
  67018. }
  67019. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67020. {
  67021. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67022. }
  67023. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67024. {
  67025. drawLine (Line<float> (left, (float) y, right, (float) y));
  67026. }
  67027. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67028. {
  67029. stateStack.getLast()->font = newFont;
  67030. }
  67031. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67032. {
  67033. return stateStack.getLast()->font;
  67034. }
  67035. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67036. {
  67037. Path p;
  67038. Font& font = stateStack.getLast()->font;
  67039. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67040. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67041. }
  67042. END_JUCE_NAMESPACE
  67043. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67044. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67045. BEGIN_JUCE_NAMESPACE
  67046. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67047. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67048. #endif
  67049. #if JUCE_MSVC
  67050. #pragma warning (push)
  67051. #pragma warning (disable: 4127) // "expression is constant" warning
  67052. #if JUCE_DEBUG
  67053. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67054. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67055. #endif
  67056. #endif
  67057. namespace SoftwareRendererClasses
  67058. {
  67059. template <class PixelType, bool replaceExisting = false>
  67060. class SolidColourEdgeTableRenderer
  67061. {
  67062. public:
  67063. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67064. : data (data_),
  67065. sourceColour (colour)
  67066. {
  67067. if (sizeof (PixelType) == 3)
  67068. {
  67069. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67070. && sourceColour.getGreen() == sourceColour.getBlue();
  67071. filler[0].set (sourceColour);
  67072. filler[1].set (sourceColour);
  67073. filler[2].set (sourceColour);
  67074. filler[3].set (sourceColour);
  67075. }
  67076. }
  67077. forcedinline void setEdgeTableYPos (const int y) throw()
  67078. {
  67079. linePixels = (PixelType*) data.getLinePointer (y);
  67080. }
  67081. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67082. {
  67083. if (replaceExisting)
  67084. linePixels[x].set (sourceColour);
  67085. else
  67086. linePixels[x].blend (sourceColour, alphaLevel);
  67087. }
  67088. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67089. {
  67090. if (replaceExisting)
  67091. linePixels[x].set (sourceColour);
  67092. else
  67093. linePixels[x].blend (sourceColour);
  67094. }
  67095. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67096. {
  67097. PixelARGB p (sourceColour);
  67098. p.multiplyAlpha (alphaLevel);
  67099. PixelType* dest = linePixels + x;
  67100. if (replaceExisting || p.getAlpha() >= 0xff)
  67101. replaceLine (dest, p, width);
  67102. else
  67103. blendLine (dest, p, width);
  67104. }
  67105. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67106. {
  67107. PixelType* dest = linePixels + x;
  67108. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67109. replaceLine (dest, sourceColour, width);
  67110. else
  67111. blendLine (dest, sourceColour, width);
  67112. }
  67113. private:
  67114. const Image::BitmapData& data;
  67115. PixelType* linePixels;
  67116. PixelARGB sourceColour;
  67117. PixelRGB filler [4];
  67118. bool areRGBComponentsEqual;
  67119. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67120. {
  67121. do
  67122. {
  67123. dest->blend (colour);
  67124. ++dest;
  67125. } while (--width > 0);
  67126. }
  67127. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67128. {
  67129. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67130. {
  67131. memset (dest, colour.getRed(), width * 3);
  67132. }
  67133. else
  67134. {
  67135. if (width >> 5)
  67136. {
  67137. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67138. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67139. {
  67140. dest->set (colour);
  67141. ++dest;
  67142. --width;
  67143. }
  67144. while (width > 4)
  67145. {
  67146. int* d = reinterpret_cast<int*> (dest);
  67147. *d++ = intFiller[0];
  67148. *d++ = intFiller[1];
  67149. *d++ = intFiller[2];
  67150. dest = reinterpret_cast<PixelRGB*> (d);
  67151. width -= 4;
  67152. }
  67153. }
  67154. while (--width >= 0)
  67155. {
  67156. dest->set (colour);
  67157. ++dest;
  67158. }
  67159. }
  67160. }
  67161. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67162. {
  67163. memset (dest, colour.getAlpha(), width);
  67164. }
  67165. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67166. {
  67167. do
  67168. {
  67169. dest->set (colour);
  67170. ++dest;
  67171. } while (--width > 0);
  67172. }
  67173. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67174. };
  67175. class LinearGradientPixelGenerator
  67176. {
  67177. public:
  67178. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67179. : lookupTable (lookupTable_), numEntries (numEntries_)
  67180. {
  67181. jassert (numEntries_ >= 0);
  67182. Point<float> p1 (gradient.point1);
  67183. Point<float> p2 (gradient.point2);
  67184. if (! transform.isIdentity())
  67185. {
  67186. const Line<float> l (p2, p1);
  67187. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67188. p1.applyTransform (transform);
  67189. p2.applyTransform (transform);
  67190. p3.applyTransform (transform);
  67191. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67192. }
  67193. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67194. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67195. if (vertical)
  67196. {
  67197. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67198. start = roundToInt (p1.getY() * scale);
  67199. }
  67200. else if (horizontal)
  67201. {
  67202. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67203. start = roundToInt (p1.getX() * scale);
  67204. }
  67205. else
  67206. {
  67207. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67208. yTerm = p1.getY() - p1.getX() / grad;
  67209. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67210. grad *= scale;
  67211. }
  67212. }
  67213. forcedinline void setY (const int y) throw()
  67214. {
  67215. if (vertical)
  67216. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67217. else if (! horizontal)
  67218. start = roundToInt ((y - yTerm) * grad);
  67219. }
  67220. inline const PixelARGB getPixel (const int x) const throw()
  67221. {
  67222. return vertical ? linePix
  67223. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67224. }
  67225. private:
  67226. const PixelARGB* const lookupTable;
  67227. const int numEntries;
  67228. PixelARGB linePix;
  67229. int start, scale;
  67230. double grad, yTerm;
  67231. bool vertical, horizontal;
  67232. enum { numScaleBits = 12 };
  67233. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67234. };
  67235. class RadialGradientPixelGenerator
  67236. {
  67237. public:
  67238. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67239. const PixelARGB* const lookupTable_, const int numEntries_)
  67240. : lookupTable (lookupTable_),
  67241. numEntries (numEntries_),
  67242. gx1 (gradient.point1.getX()),
  67243. gy1 (gradient.point1.getY())
  67244. {
  67245. jassert (numEntries_ >= 0);
  67246. const Point<float> diff (gradient.point1 - gradient.point2);
  67247. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67248. invScale = numEntries / std::sqrt (maxDist);
  67249. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67250. }
  67251. forcedinline void setY (const int y) throw()
  67252. {
  67253. dy = y - gy1;
  67254. dy *= dy;
  67255. }
  67256. inline const PixelARGB getPixel (const int px) const throw()
  67257. {
  67258. double x = px - gx1;
  67259. x *= x;
  67260. x += dy;
  67261. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67262. }
  67263. protected:
  67264. const PixelARGB* const lookupTable;
  67265. const int numEntries;
  67266. const double gx1, gy1;
  67267. double maxDist, invScale, dy;
  67268. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67269. };
  67270. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67271. {
  67272. public:
  67273. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67274. const PixelARGB* const lookupTable_, const int numEntries_)
  67275. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67276. inverseTransform (transform.inverted())
  67277. {
  67278. tM10 = inverseTransform.mat10;
  67279. tM00 = inverseTransform.mat00;
  67280. }
  67281. forcedinline void setY (const int y) throw()
  67282. {
  67283. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67284. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67285. }
  67286. inline const PixelARGB getPixel (const int px) const throw()
  67287. {
  67288. double x = px;
  67289. const double y = tM10 * x + lineYM11;
  67290. x = tM00 * x + lineYM01;
  67291. x *= x;
  67292. x += y * y;
  67293. if (x >= maxDist)
  67294. return lookupTable [numEntries];
  67295. else
  67296. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67297. }
  67298. private:
  67299. double tM10, tM00, lineYM01, lineYM11;
  67300. const AffineTransform inverseTransform;
  67301. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67302. };
  67303. template <class PixelType, class GradientType>
  67304. class GradientEdgeTableRenderer : public GradientType
  67305. {
  67306. public:
  67307. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67308. const PixelARGB* const lookupTable_, const int numEntries_)
  67309. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67310. destData (destData_)
  67311. {
  67312. }
  67313. forcedinline void setEdgeTableYPos (const int y) throw()
  67314. {
  67315. linePixels = (PixelType*) destData.getLinePointer (y);
  67316. GradientType::setY (y);
  67317. }
  67318. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67319. {
  67320. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67321. }
  67322. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67323. {
  67324. linePixels[x].blend (GradientType::getPixel (x));
  67325. }
  67326. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67327. {
  67328. PixelType* dest = linePixels + x;
  67329. if (alphaLevel < 0xff)
  67330. {
  67331. do
  67332. {
  67333. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67334. } while (--width > 0);
  67335. }
  67336. else
  67337. {
  67338. do
  67339. {
  67340. (dest++)->blend (GradientType::getPixel (x++));
  67341. } while (--width > 0);
  67342. }
  67343. }
  67344. void handleEdgeTableLineFull (int x, int width) const throw()
  67345. {
  67346. PixelType* dest = linePixels + x;
  67347. do
  67348. {
  67349. (dest++)->blend (GradientType::getPixel (x++));
  67350. } while (--width > 0);
  67351. }
  67352. private:
  67353. const Image::BitmapData& destData;
  67354. PixelType* linePixels;
  67355. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67356. };
  67357. namespace RenderingHelpers
  67358. {
  67359. forcedinline int safeModulo (int n, const int divisor) throw()
  67360. {
  67361. jassert (divisor > 0);
  67362. n %= divisor;
  67363. return (n < 0) ? (n + divisor) : n;
  67364. }
  67365. }
  67366. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67367. class ImageFillEdgeTableRenderer
  67368. {
  67369. public:
  67370. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67371. const Image::BitmapData& srcData_,
  67372. const int extraAlpha_,
  67373. const int x, const int y)
  67374. : destData (destData_),
  67375. srcData (srcData_),
  67376. extraAlpha (extraAlpha_ + 1),
  67377. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67378. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67379. {
  67380. }
  67381. forcedinline void setEdgeTableYPos (int y) throw()
  67382. {
  67383. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67384. y -= yOffset;
  67385. if (repeatPattern)
  67386. {
  67387. jassert (y >= 0);
  67388. y %= srcData.height;
  67389. }
  67390. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67391. }
  67392. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67393. {
  67394. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67395. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67396. }
  67397. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67398. {
  67399. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67400. }
  67401. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67402. {
  67403. DestPixelType* dest = linePixels + x;
  67404. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67405. x -= xOffset;
  67406. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67407. if (alphaLevel < 0xfe)
  67408. {
  67409. do
  67410. {
  67411. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67412. } while (--width > 0);
  67413. }
  67414. else
  67415. {
  67416. if (repeatPattern)
  67417. {
  67418. do
  67419. {
  67420. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67421. } while (--width > 0);
  67422. }
  67423. else
  67424. {
  67425. copyRow (dest, sourceLineStart + x, width);
  67426. }
  67427. }
  67428. }
  67429. void handleEdgeTableLineFull (int x, int width) const throw()
  67430. {
  67431. DestPixelType* dest = linePixels + x;
  67432. x -= xOffset;
  67433. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67434. if (extraAlpha < 0xfe)
  67435. {
  67436. do
  67437. {
  67438. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67439. } while (--width > 0);
  67440. }
  67441. else
  67442. {
  67443. if (repeatPattern)
  67444. {
  67445. do
  67446. {
  67447. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67448. } while (--width > 0);
  67449. }
  67450. else
  67451. {
  67452. copyRow (dest, sourceLineStart + x, width);
  67453. }
  67454. }
  67455. }
  67456. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67457. {
  67458. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67459. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67460. uint8* mask = (uint8*) (s + x - xOffset);
  67461. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67462. mask += PixelARGB::indexA;
  67463. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67464. }
  67465. private:
  67466. const Image::BitmapData& destData;
  67467. const Image::BitmapData& srcData;
  67468. const int extraAlpha, xOffset, yOffset;
  67469. DestPixelType* linePixels;
  67470. SrcPixelType* sourceLineStart;
  67471. template <class PixelType1, class PixelType2>
  67472. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67473. {
  67474. do
  67475. {
  67476. dest++ ->blend (*src++);
  67477. } while (--width > 0);
  67478. }
  67479. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67480. {
  67481. memcpy (dest, src, width * sizeof (PixelRGB));
  67482. }
  67483. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67484. };
  67485. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67486. class TransformedImageFillEdgeTableRenderer
  67487. {
  67488. public:
  67489. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67490. const Image::BitmapData& srcData_,
  67491. const AffineTransform& transform,
  67492. const int extraAlpha_,
  67493. const bool betterQuality_)
  67494. : interpolator (transform,
  67495. betterQuality_ ? 0.5f : 0.0f,
  67496. betterQuality_ ? -128 : 0),
  67497. destData (destData_),
  67498. srcData (srcData_),
  67499. extraAlpha (extraAlpha_ + 1),
  67500. betterQuality (betterQuality_),
  67501. maxX (srcData_.width - 1),
  67502. maxY (srcData_.height - 1),
  67503. scratchSize (2048)
  67504. {
  67505. scratchBuffer.malloc (scratchSize);
  67506. }
  67507. forcedinline void setEdgeTableYPos (const int newY) throw()
  67508. {
  67509. y = newY;
  67510. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67511. }
  67512. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67513. {
  67514. SrcPixelType p;
  67515. generate (&p, x, 1);
  67516. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67517. }
  67518. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67519. {
  67520. SrcPixelType p;
  67521. generate (&p, x, 1);
  67522. linePixels[x].blend (p, extraAlpha);
  67523. }
  67524. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67525. {
  67526. if (width > scratchSize)
  67527. {
  67528. scratchSize = width;
  67529. scratchBuffer.malloc (scratchSize);
  67530. }
  67531. SrcPixelType* span = scratchBuffer;
  67532. generate (span, x, width);
  67533. DestPixelType* dest = linePixels + x;
  67534. alphaLevel *= extraAlpha;
  67535. alphaLevel >>= 8;
  67536. if (alphaLevel < 0xfe)
  67537. {
  67538. do
  67539. {
  67540. dest++ ->blend (*span++, alphaLevel);
  67541. } while (--width > 0);
  67542. }
  67543. else
  67544. {
  67545. do
  67546. {
  67547. dest++ ->blend (*span++);
  67548. } while (--width > 0);
  67549. }
  67550. }
  67551. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67552. {
  67553. handleEdgeTableLine (x, width, 255);
  67554. }
  67555. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67556. {
  67557. if (width > scratchSize)
  67558. {
  67559. scratchSize = width;
  67560. scratchBuffer.malloc (scratchSize);
  67561. }
  67562. y = y_;
  67563. generate (static_cast <SrcPixelType*> (scratchBuffer), x, width);
  67564. et.clipLineToMask (x, y_,
  67565. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67566. sizeof (SrcPixelType), width);
  67567. }
  67568. private:
  67569. template <class PixelType>
  67570. void generate (PixelType* dest, const int x, int numPixels) throw()
  67571. {
  67572. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67573. do
  67574. {
  67575. int hiResX, hiResY;
  67576. this->interpolator.next (hiResX, hiResY);
  67577. int loResX = hiResX >> 8;
  67578. int loResY = hiResY >> 8;
  67579. if (repeatPattern)
  67580. {
  67581. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67582. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67583. }
  67584. if (betterQuality)
  67585. {
  67586. if (isPositiveAndBelow (loResX, maxX))
  67587. {
  67588. if (isPositiveAndBelow (loResY, maxY))
  67589. {
  67590. // In the centre of the image..
  67591. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67592. hiResX & 255, hiResY & 255);
  67593. ++dest;
  67594. continue;
  67595. }
  67596. else
  67597. {
  67598. // At a top or bottom edge..
  67599. if (! repeatPattern)
  67600. {
  67601. if (loResY < 0)
  67602. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67603. else
  67604. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67605. ++dest;
  67606. continue;
  67607. }
  67608. }
  67609. }
  67610. else
  67611. {
  67612. if (isPositiveAndBelow (loResY, maxY))
  67613. {
  67614. // At a left or right hand edge..
  67615. if (! repeatPattern)
  67616. {
  67617. if (loResX < 0)
  67618. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67619. else
  67620. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67621. ++dest;
  67622. continue;
  67623. }
  67624. }
  67625. }
  67626. }
  67627. if (! repeatPattern)
  67628. {
  67629. if (loResX < 0) loResX = 0;
  67630. if (loResY < 0) loResY = 0;
  67631. if (loResX > maxX) loResX = maxX;
  67632. if (loResY > maxY) loResY = maxY;
  67633. }
  67634. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67635. ++dest;
  67636. } while (--numPixels > 0);
  67637. }
  67638. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67639. {
  67640. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67641. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67642. c[0] += weight * src[0];
  67643. c[1] += weight * src[1];
  67644. c[2] += weight * src[2];
  67645. c[3] += weight * src[3];
  67646. weight = subPixelX * (256 - subPixelY);
  67647. c[0] += weight * src[4];
  67648. c[1] += weight * src[5];
  67649. c[2] += weight * src[6];
  67650. c[3] += weight * src[7];
  67651. src += this->srcData.lineStride;
  67652. weight = (256 - subPixelX) * subPixelY;
  67653. c[0] += weight * src[0];
  67654. c[1] += weight * src[1];
  67655. c[2] += weight * src[2];
  67656. c[3] += weight * src[3];
  67657. weight = subPixelX * subPixelY;
  67658. c[0] += weight * src[4];
  67659. c[1] += weight * src[5];
  67660. c[2] += weight * src[6];
  67661. c[3] += weight * src[7];
  67662. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67663. (uint8) (c[PixelARGB::indexR] >> 16),
  67664. (uint8) (c[PixelARGB::indexG] >> 16),
  67665. (uint8) (c[PixelARGB::indexB] >> 16));
  67666. }
  67667. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67668. {
  67669. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67670. uint32 weight = (256 - subPixelX) * alpha;
  67671. c[0] += weight * src[0];
  67672. c[1] += weight * src[1];
  67673. c[2] += weight * src[2];
  67674. c[3] += weight * src[3];
  67675. weight = subPixelX * alpha;
  67676. c[0] += weight * src[4];
  67677. c[1] += weight * src[5];
  67678. c[2] += weight * src[6];
  67679. c[3] += weight * src[7];
  67680. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67681. (uint8) (c[PixelARGB::indexR] >> 16),
  67682. (uint8) (c[PixelARGB::indexG] >> 16),
  67683. (uint8) (c[PixelARGB::indexB] >> 16));
  67684. }
  67685. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67686. {
  67687. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67688. uint32 weight = (256 - subPixelY) * alpha;
  67689. c[0] += weight * src[0];
  67690. c[1] += weight * src[1];
  67691. c[2] += weight * src[2];
  67692. c[3] += weight * src[3];
  67693. src += this->srcData.lineStride;
  67694. weight = subPixelY * alpha;
  67695. c[0] += weight * src[0];
  67696. c[1] += weight * src[1];
  67697. c[2] += weight * src[2];
  67698. c[3] += weight * src[3];
  67699. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67700. (uint8) (c[PixelARGB::indexR] >> 16),
  67701. (uint8) (c[PixelARGB::indexG] >> 16),
  67702. (uint8) (c[PixelARGB::indexB] >> 16));
  67703. }
  67704. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67705. {
  67706. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67707. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67708. c[0] += weight * src[0];
  67709. c[1] += weight * src[1];
  67710. c[2] += weight * src[2];
  67711. weight = subPixelX * (256 - subPixelY);
  67712. c[0] += weight * src[3];
  67713. c[1] += weight * src[4];
  67714. c[2] += weight * src[5];
  67715. src += this->srcData.lineStride;
  67716. weight = (256 - subPixelX) * subPixelY;
  67717. c[0] += weight * src[0];
  67718. c[1] += weight * src[1];
  67719. c[2] += weight * src[2];
  67720. weight = subPixelX * subPixelY;
  67721. c[0] += weight * src[3];
  67722. c[1] += weight * src[4];
  67723. c[2] += weight * src[5];
  67724. dest->setARGB ((uint8) 255,
  67725. (uint8) (c[PixelRGB::indexR] >> 16),
  67726. (uint8) (c[PixelRGB::indexG] >> 16),
  67727. (uint8) (c[PixelRGB::indexB] >> 16));
  67728. }
  67729. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67730. {
  67731. uint32 c[3] = { 128, 128, 128 };
  67732. uint32 weight = (256 - subPixelX);
  67733. c[0] += weight * src[0];
  67734. c[1] += weight * src[1];
  67735. c[2] += weight * src[2];
  67736. c[0] += subPixelX * src[3];
  67737. c[1] += subPixelX * src[4];
  67738. c[2] += subPixelX * src[5];
  67739. dest->setARGB ((uint8) 255,
  67740. (uint8) (c[PixelRGB::indexR] >> 8),
  67741. (uint8) (c[PixelRGB::indexG] >> 8),
  67742. (uint8) (c[PixelRGB::indexB] >> 8));
  67743. }
  67744. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  67745. {
  67746. uint32 c[3] = { 128, 128, 128 };
  67747. uint32 weight = (256 - subPixelY);
  67748. c[0] += weight * src[0];
  67749. c[1] += weight * src[1];
  67750. c[2] += weight * src[2];
  67751. src += this->srcData.lineStride;
  67752. c[0] += subPixelY * src[0];
  67753. c[1] += subPixelY * src[1];
  67754. c[2] += subPixelY * src[2];
  67755. dest->setARGB ((uint8) 255,
  67756. (uint8) (c[PixelRGB::indexR] >> 8),
  67757. (uint8) (c[PixelRGB::indexG] >> 8),
  67758. (uint8) (c[PixelRGB::indexB] >> 8));
  67759. }
  67760. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67761. {
  67762. uint32 c = 256 * 128;
  67763. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  67764. c += src[1] * (subPixelX * (256 - subPixelY));
  67765. src += this->srcData.lineStride;
  67766. c += src[0] * ((256 - subPixelX) * subPixelY);
  67767. c += src[1] * (subPixelX * subPixelY);
  67768. *((uint8*) dest) = (uint8) (c >> 16);
  67769. }
  67770. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67771. {
  67772. uint32 c = 256 * 128;
  67773. c += src[0] * (256 - subPixelX) * alpha;
  67774. c += src[1] * subPixelX * alpha;
  67775. *((uint8*) dest) = (uint8) (c >> 16);
  67776. }
  67777. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67778. {
  67779. uint32 c = 256 * 128;
  67780. c += src[0] * (256 - subPixelY) * alpha;
  67781. src += this->srcData.lineStride;
  67782. c += src[0] * subPixelY * alpha;
  67783. *((uint8*) dest) = (uint8) (c >> 16);
  67784. }
  67785. class TransformedImageSpanInterpolator
  67786. {
  67787. public:
  67788. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  67789. : inverseTransform (transform.inverted()),
  67790. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  67791. {}
  67792. void setStartOfLine (float x, float y, const int numPixels) throw()
  67793. {
  67794. jassert (numPixels > 0);
  67795. x += pixelOffset;
  67796. y += pixelOffset;
  67797. float x1 = x, y1 = y;
  67798. x += numPixels;
  67799. inverseTransform.transformPoints (x1, y1, x, y);
  67800. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  67801. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  67802. }
  67803. void next (int& x, int& y) throw()
  67804. {
  67805. x = xBresenham.n;
  67806. xBresenham.stepToNext();
  67807. y = yBresenham.n;
  67808. yBresenham.stepToNext();
  67809. }
  67810. private:
  67811. class BresenhamInterpolator
  67812. {
  67813. public:
  67814. BresenhamInterpolator() throw() {}
  67815. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  67816. {
  67817. numSteps = numSteps_;
  67818. step = (n2 - n1) / numSteps;
  67819. remainder = modulo = (n2 - n1) % numSteps;
  67820. n = n1 + pixelOffsetInt;
  67821. if (modulo <= 0)
  67822. {
  67823. modulo += numSteps;
  67824. remainder += numSteps;
  67825. --step;
  67826. }
  67827. modulo -= numSteps;
  67828. }
  67829. forcedinline void stepToNext() throw()
  67830. {
  67831. modulo += remainder;
  67832. n += step;
  67833. if (modulo > 0)
  67834. {
  67835. modulo -= numSteps;
  67836. ++n;
  67837. }
  67838. }
  67839. int n;
  67840. private:
  67841. int numSteps, step, modulo, remainder;
  67842. };
  67843. const AffineTransform inverseTransform;
  67844. BresenhamInterpolator xBresenham, yBresenham;
  67845. const float pixelOffset;
  67846. const int pixelOffsetInt;
  67847. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  67848. };
  67849. TransformedImageSpanInterpolator interpolator;
  67850. const Image::BitmapData& destData;
  67851. const Image::BitmapData& srcData;
  67852. const int extraAlpha;
  67853. const bool betterQuality;
  67854. const int maxX, maxY;
  67855. int y;
  67856. DestPixelType* linePixels;
  67857. HeapBlock <SrcPixelType> scratchBuffer;
  67858. int scratchSize;
  67859. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  67860. };
  67861. class ClipRegionBase : public ReferenceCountedObject
  67862. {
  67863. public:
  67864. ClipRegionBase() {}
  67865. virtual ~ClipRegionBase() {}
  67866. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  67867. virtual const Ptr clone() const = 0;
  67868. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  67869. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  67870. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  67871. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  67872. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  67873. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  67874. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  67875. virtual const Ptr translated (const Point<int>& delta) = 0;
  67876. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  67877. virtual const Rectangle<int> getClipBounds() const = 0;
  67878. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  67879. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  67880. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  67881. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  67882. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  67883. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  67884. protected:
  67885. template <class Iterator>
  67886. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  67887. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  67888. {
  67889. switch (destData.pixelFormat)
  67890. {
  67891. case Image::ARGB:
  67892. switch (srcData.pixelFormat)
  67893. {
  67894. case Image::ARGB:
  67895. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67896. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67897. break;
  67898. case Image::RGB:
  67899. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67900. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67901. break;
  67902. default:
  67903. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67904. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67905. break;
  67906. }
  67907. break;
  67908. case Image::RGB:
  67909. switch (srcData.pixelFormat)
  67910. {
  67911. case Image::ARGB:
  67912. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67913. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67914. break;
  67915. case Image::RGB:
  67916. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67917. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67918. break;
  67919. default:
  67920. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67921. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67922. break;
  67923. }
  67924. break;
  67925. default:
  67926. switch (srcData.pixelFormat)
  67927. {
  67928. case Image::ARGB:
  67929. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67930. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67931. break;
  67932. case Image::RGB:
  67933. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67934. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67935. break;
  67936. default:
  67937. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67938. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67939. break;
  67940. }
  67941. break;
  67942. }
  67943. }
  67944. template <class Iterator>
  67945. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  67946. {
  67947. switch (destData.pixelFormat)
  67948. {
  67949. case Image::ARGB:
  67950. switch (srcData.pixelFormat)
  67951. {
  67952. case Image::ARGB:
  67953. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67954. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67955. break;
  67956. case Image::RGB:
  67957. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67958. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67959. break;
  67960. default:
  67961. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67962. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67963. break;
  67964. }
  67965. break;
  67966. case Image::RGB:
  67967. switch (srcData.pixelFormat)
  67968. {
  67969. case Image::ARGB:
  67970. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67971. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67972. break;
  67973. case Image::RGB:
  67974. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67975. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67976. break;
  67977. default:
  67978. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67979. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67980. break;
  67981. }
  67982. break;
  67983. default:
  67984. switch (srcData.pixelFormat)
  67985. {
  67986. case Image::ARGB:
  67987. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67988. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67989. break;
  67990. case Image::RGB:
  67991. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67992. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67993. break;
  67994. default:
  67995. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67996. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67997. break;
  67998. }
  67999. break;
  68000. }
  68001. }
  68002. template <class Iterator, class DestPixelType>
  68003. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68004. {
  68005. jassert (destData.pixelStride == sizeof (DestPixelType));
  68006. if (replaceContents)
  68007. {
  68008. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68009. iter.iterate (r);
  68010. }
  68011. else
  68012. {
  68013. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68014. iter.iterate (r);
  68015. }
  68016. }
  68017. template <class Iterator, class DestPixelType>
  68018. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68019. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68020. {
  68021. jassert (destData.pixelStride == sizeof (DestPixelType));
  68022. if (g.isRadial)
  68023. {
  68024. if (isIdentity)
  68025. {
  68026. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68027. iter.iterate (renderer);
  68028. }
  68029. else
  68030. {
  68031. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68032. iter.iterate (renderer);
  68033. }
  68034. }
  68035. else
  68036. {
  68037. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68038. iter.iterate (renderer);
  68039. }
  68040. }
  68041. };
  68042. class ClipRegion_EdgeTable : public ClipRegionBase
  68043. {
  68044. public:
  68045. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68046. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68047. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68048. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68049. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68050. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68051. ~ClipRegion_EdgeTable() {}
  68052. const Ptr clone() const
  68053. {
  68054. return new ClipRegion_EdgeTable (*this);
  68055. }
  68056. const Ptr applyClipTo (const Ptr& target) const
  68057. {
  68058. return target->clipToEdgeTable (edgeTable);
  68059. }
  68060. const Ptr clipToRectangle (const Rectangle<int>& r)
  68061. {
  68062. edgeTable.clipToRectangle (r);
  68063. return edgeTable.isEmpty() ? 0 : this;
  68064. }
  68065. const Ptr clipToRectangleList (const RectangleList& r)
  68066. {
  68067. RectangleList inverse (edgeTable.getMaximumBounds());
  68068. if (inverse.subtract (r))
  68069. for (RectangleList::Iterator iter (inverse); iter.next();)
  68070. edgeTable.excludeRectangle (*iter.getRectangle());
  68071. return edgeTable.isEmpty() ? 0 : this;
  68072. }
  68073. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68074. {
  68075. edgeTable.excludeRectangle (r);
  68076. return edgeTable.isEmpty() ? 0 : this;
  68077. }
  68078. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68079. {
  68080. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68081. edgeTable.clipToEdgeTable (et);
  68082. return edgeTable.isEmpty() ? 0 : this;
  68083. }
  68084. const Ptr clipToEdgeTable (const EdgeTable& et)
  68085. {
  68086. edgeTable.clipToEdgeTable (et);
  68087. return edgeTable.isEmpty() ? 0 : this;
  68088. }
  68089. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68090. {
  68091. const Image::BitmapData srcData (image, false);
  68092. if (transform.isOnlyTranslation())
  68093. {
  68094. // If our translation doesn't involve any distortion, just use a simple blit..
  68095. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68096. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68097. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68098. {
  68099. const int imageX = ((tx + 128) >> 8);
  68100. const int imageY = ((ty + 128) >> 8);
  68101. if (image.getFormat() == Image::ARGB)
  68102. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68103. else
  68104. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68105. return edgeTable.isEmpty() ? 0 : this;
  68106. }
  68107. }
  68108. if (transform.isSingularity())
  68109. return 0;
  68110. {
  68111. Path p;
  68112. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68113. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68114. edgeTable.clipToEdgeTable (et2);
  68115. }
  68116. if (! edgeTable.isEmpty())
  68117. {
  68118. if (image.getFormat() == Image::ARGB)
  68119. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68120. else
  68121. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68122. }
  68123. return edgeTable.isEmpty() ? 0 : this;
  68124. }
  68125. const Ptr translated (const Point<int>& delta)
  68126. {
  68127. edgeTable.translate ((float) delta.getX(), delta.getY());
  68128. return edgeTable.isEmpty() ? 0 : this;
  68129. }
  68130. bool clipRegionIntersects (const Rectangle<int>& r) const
  68131. {
  68132. return edgeTable.getMaximumBounds().intersects (r);
  68133. }
  68134. const Rectangle<int> getClipBounds() const
  68135. {
  68136. return edgeTable.getMaximumBounds();
  68137. }
  68138. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68139. {
  68140. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68141. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68142. if (! clipped.isEmpty())
  68143. {
  68144. ClipRegion_EdgeTable et (clipped);
  68145. et.edgeTable.clipToEdgeTable (edgeTable);
  68146. et.fillAllWithColour (destData, colour, replaceContents);
  68147. }
  68148. }
  68149. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68150. {
  68151. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68152. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68153. if (! clipped.isEmpty())
  68154. {
  68155. ClipRegion_EdgeTable et (clipped);
  68156. et.edgeTable.clipToEdgeTable (edgeTable);
  68157. et.fillAllWithColour (destData, colour, false);
  68158. }
  68159. }
  68160. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68161. {
  68162. switch (destData.pixelFormat)
  68163. {
  68164. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68165. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68166. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68167. }
  68168. }
  68169. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68170. {
  68171. HeapBlock <PixelARGB> lookupTable;
  68172. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68173. jassert (numLookupEntries > 0);
  68174. switch (destData.pixelFormat)
  68175. {
  68176. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68177. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68178. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68179. }
  68180. }
  68181. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68182. {
  68183. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68184. }
  68185. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68186. {
  68187. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68188. }
  68189. EdgeTable edgeTable;
  68190. private:
  68191. template <class SrcPixelType>
  68192. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68193. {
  68194. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68195. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68196. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68197. edgeTable.getMaximumBounds().getWidth());
  68198. }
  68199. template <class SrcPixelType>
  68200. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68201. {
  68202. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68203. edgeTable.clipToRectangle (r);
  68204. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68205. for (int y = 0; y < r.getHeight(); ++y)
  68206. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68207. }
  68208. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68209. };
  68210. class ClipRegion_RectangleList : public ClipRegionBase
  68211. {
  68212. public:
  68213. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68214. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68215. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68216. ~ClipRegion_RectangleList() {}
  68217. const Ptr clone() const
  68218. {
  68219. return new ClipRegion_RectangleList (*this);
  68220. }
  68221. const Ptr applyClipTo (const Ptr& target) const
  68222. {
  68223. return target->clipToRectangleList (clip);
  68224. }
  68225. const Ptr clipToRectangle (const Rectangle<int>& r)
  68226. {
  68227. clip.clipTo (r);
  68228. return clip.isEmpty() ? 0 : this;
  68229. }
  68230. const Ptr clipToRectangleList (const RectangleList& r)
  68231. {
  68232. clip.clipTo (r);
  68233. return clip.isEmpty() ? 0 : this;
  68234. }
  68235. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68236. {
  68237. clip.subtract (r);
  68238. return clip.isEmpty() ? 0 : this;
  68239. }
  68240. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68241. {
  68242. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68243. }
  68244. const Ptr clipToEdgeTable (const EdgeTable& et)
  68245. {
  68246. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68247. }
  68248. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68249. {
  68250. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68251. }
  68252. const Ptr translated (const Point<int>& delta)
  68253. {
  68254. clip.offsetAll (delta.getX(), delta.getY());
  68255. return clip.isEmpty() ? 0 : this;
  68256. }
  68257. bool clipRegionIntersects (const Rectangle<int>& r) const
  68258. {
  68259. return clip.intersects (r);
  68260. }
  68261. const Rectangle<int> getClipBounds() const
  68262. {
  68263. return clip.getBounds();
  68264. }
  68265. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68266. {
  68267. SubRectangleIterator iter (clip, area);
  68268. switch (destData.pixelFormat)
  68269. {
  68270. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68271. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68272. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68273. }
  68274. }
  68275. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68276. {
  68277. SubRectangleIteratorFloat iter (clip, area);
  68278. switch (destData.pixelFormat)
  68279. {
  68280. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68281. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68282. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68283. }
  68284. }
  68285. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68286. {
  68287. switch (destData.pixelFormat)
  68288. {
  68289. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68290. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68291. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68292. }
  68293. }
  68294. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68295. {
  68296. HeapBlock <PixelARGB> lookupTable;
  68297. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68298. jassert (numLookupEntries > 0);
  68299. switch (destData.pixelFormat)
  68300. {
  68301. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68302. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68303. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68304. }
  68305. }
  68306. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68307. {
  68308. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68309. }
  68310. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68311. {
  68312. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68313. }
  68314. RectangleList clip;
  68315. template <class Renderer>
  68316. void iterate (Renderer& r) const throw()
  68317. {
  68318. RectangleList::Iterator iter (clip);
  68319. while (iter.next())
  68320. {
  68321. const Rectangle<int> rect (*iter.getRectangle());
  68322. const int x = rect.getX();
  68323. const int w = rect.getWidth();
  68324. jassert (w > 0);
  68325. const int bottom = rect.getBottom();
  68326. for (int y = rect.getY(); y < bottom; ++y)
  68327. {
  68328. r.setEdgeTableYPos (y);
  68329. r.handleEdgeTableLineFull (x, w);
  68330. }
  68331. }
  68332. }
  68333. private:
  68334. class SubRectangleIterator
  68335. {
  68336. public:
  68337. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68338. : clip (clip_), area (area_)
  68339. {
  68340. }
  68341. template <class Renderer>
  68342. void iterate (Renderer& r) const throw()
  68343. {
  68344. RectangleList::Iterator iter (clip);
  68345. while (iter.next())
  68346. {
  68347. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68348. if (! rect.isEmpty())
  68349. {
  68350. const int x = rect.getX();
  68351. const int w = rect.getWidth();
  68352. const int bottom = rect.getBottom();
  68353. for (int y = rect.getY(); y < bottom; ++y)
  68354. {
  68355. r.setEdgeTableYPos (y);
  68356. r.handleEdgeTableLineFull (x, w);
  68357. }
  68358. }
  68359. }
  68360. }
  68361. private:
  68362. const RectangleList& clip;
  68363. const Rectangle<int> area;
  68364. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68365. };
  68366. class SubRectangleIteratorFloat
  68367. {
  68368. public:
  68369. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68370. : clip (clip_), area (area_)
  68371. {
  68372. }
  68373. template <class Renderer>
  68374. void iterate (Renderer& r) const throw()
  68375. {
  68376. int left = roundToInt (area.getX() * 256.0f);
  68377. int top = roundToInt (area.getY() * 256.0f);
  68378. int right = roundToInt (area.getRight() * 256.0f);
  68379. int bottom = roundToInt (area.getBottom() * 256.0f);
  68380. int totalTop, totalLeft, totalBottom, totalRight;
  68381. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68382. if ((top >> 8) == (bottom >> 8))
  68383. {
  68384. topAlpha = bottom - top;
  68385. bottomAlpha = 0;
  68386. totalTop = top >> 8;
  68387. totalBottom = bottom = top = totalTop + 1;
  68388. }
  68389. else
  68390. {
  68391. if ((top & 255) == 0)
  68392. {
  68393. topAlpha = 0;
  68394. top = totalTop = (top >> 8);
  68395. }
  68396. else
  68397. {
  68398. topAlpha = 255 - (top & 255);
  68399. totalTop = (top >> 8);
  68400. top = totalTop + 1;
  68401. }
  68402. bottomAlpha = bottom & 255;
  68403. bottom >>= 8;
  68404. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68405. }
  68406. if ((left >> 8) == (right >> 8))
  68407. {
  68408. leftAlpha = right - left;
  68409. rightAlpha = 0;
  68410. totalLeft = (left >> 8);
  68411. totalRight = right = left = totalLeft + 1;
  68412. }
  68413. else
  68414. {
  68415. if ((left & 255) == 0)
  68416. {
  68417. leftAlpha = 0;
  68418. left = totalLeft = (left >> 8);
  68419. }
  68420. else
  68421. {
  68422. leftAlpha = 255 - (left & 255);
  68423. totalLeft = (left >> 8);
  68424. left = totalLeft + 1;
  68425. }
  68426. rightAlpha = right & 255;
  68427. right >>= 8;
  68428. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68429. }
  68430. RectangleList::Iterator iter (clip);
  68431. while (iter.next())
  68432. {
  68433. const int clipLeft = iter.getRectangle()->getX();
  68434. const int clipRight = iter.getRectangle()->getRight();
  68435. const int clipTop = iter.getRectangle()->getY();
  68436. const int clipBottom = iter.getRectangle()->getBottom();
  68437. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68438. {
  68439. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68440. {
  68441. if (topAlpha != 0 && totalTop >= clipTop)
  68442. {
  68443. r.setEdgeTableYPos (totalTop);
  68444. r.handleEdgeTablePixel (left, topAlpha);
  68445. }
  68446. const int endY = jmin (bottom, clipBottom);
  68447. for (int y = jmax (clipTop, top); y < endY; ++y)
  68448. {
  68449. r.setEdgeTableYPos (y);
  68450. r.handleEdgeTablePixelFull (left);
  68451. }
  68452. if (bottomAlpha != 0 && bottom < clipBottom)
  68453. {
  68454. r.setEdgeTableYPos (bottom);
  68455. r.handleEdgeTablePixel (left, bottomAlpha);
  68456. }
  68457. }
  68458. else
  68459. {
  68460. const int clippedLeft = jmax (left, clipLeft);
  68461. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68462. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68463. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68464. if (topAlpha != 0 && totalTop >= clipTop)
  68465. {
  68466. r.setEdgeTableYPos (totalTop);
  68467. if (doLeftAlpha)
  68468. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68469. if (clippedWidth > 0)
  68470. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68471. if (doRightAlpha)
  68472. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68473. }
  68474. const int endY = jmin (bottom, clipBottom);
  68475. for (int y = jmax (clipTop, top); y < endY; ++y)
  68476. {
  68477. r.setEdgeTableYPos (y);
  68478. if (doLeftAlpha)
  68479. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68480. if (clippedWidth > 0)
  68481. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68482. if (doRightAlpha)
  68483. r.handleEdgeTablePixel (right, rightAlpha);
  68484. }
  68485. if (bottomAlpha != 0 && bottom < clipBottom)
  68486. {
  68487. r.setEdgeTableYPos (bottom);
  68488. if (doLeftAlpha)
  68489. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68490. if (clippedWidth > 0)
  68491. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68492. if (doRightAlpha)
  68493. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68494. }
  68495. }
  68496. }
  68497. }
  68498. }
  68499. private:
  68500. const RectangleList& clip;
  68501. const Rectangle<float>& area;
  68502. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68503. };
  68504. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68505. };
  68506. }
  68507. class LowLevelGraphicsSoftwareRenderer::SavedState
  68508. {
  68509. public:
  68510. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68511. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68512. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68513. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68514. {
  68515. }
  68516. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68517. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68518. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68519. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68520. {
  68521. }
  68522. SavedState (const SavedState& other)
  68523. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68524. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68525. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68526. interpolationQuality (other.interpolationQuality)
  68527. {
  68528. }
  68529. void setOrigin (const int x, const int y) throw()
  68530. {
  68531. if (isOnlyTranslated)
  68532. {
  68533. xOffset += x;
  68534. yOffset += y;
  68535. }
  68536. else
  68537. {
  68538. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68539. }
  68540. }
  68541. void addTransform (const AffineTransform& t)
  68542. {
  68543. if ((! isOnlyTranslated)
  68544. || (! t.isOnlyTranslation())
  68545. || (int) (t.getTranslationX() * 256.0f) != 0
  68546. || (int) (t.getTranslationY() * 256.0f) != 0)
  68547. {
  68548. complexTransform = getTransformWith (t);
  68549. isOnlyTranslated = false;
  68550. }
  68551. else
  68552. {
  68553. xOffset += (int) t.getTranslationX();
  68554. yOffset += (int) t.getTranslationY();
  68555. }
  68556. }
  68557. float getScaleFactor() const
  68558. {
  68559. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  68560. }
  68561. bool clipToRectangle (const Rectangle<int>& r)
  68562. {
  68563. if (clip != 0)
  68564. {
  68565. if (isOnlyTranslated)
  68566. {
  68567. cloneClipIfMultiplyReferenced();
  68568. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68569. }
  68570. else
  68571. {
  68572. Path p;
  68573. p.addRectangle (r);
  68574. clipToPath (p, AffineTransform::identity);
  68575. }
  68576. }
  68577. return clip != 0;
  68578. }
  68579. bool clipToRectangleList (const RectangleList& r)
  68580. {
  68581. if (clip != 0)
  68582. {
  68583. if (isOnlyTranslated)
  68584. {
  68585. cloneClipIfMultiplyReferenced();
  68586. RectangleList offsetList (r);
  68587. offsetList.offsetAll (xOffset, yOffset);
  68588. clip = clip->clipToRectangleList (offsetList);
  68589. }
  68590. else
  68591. {
  68592. clipToPath (r.toPath(), AffineTransform::identity);
  68593. }
  68594. }
  68595. return clip != 0;
  68596. }
  68597. bool excludeClipRectangle (const Rectangle<int>& r)
  68598. {
  68599. if (clip != 0)
  68600. {
  68601. cloneClipIfMultiplyReferenced();
  68602. if (isOnlyTranslated)
  68603. {
  68604. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68605. }
  68606. else
  68607. {
  68608. Path p;
  68609. p.addRectangle (r.toFloat());
  68610. p.applyTransform (complexTransform);
  68611. p.addRectangle (clip->getClipBounds().toFloat());
  68612. p.setUsingNonZeroWinding (false);
  68613. clip = clip->clipToPath (p, AffineTransform::identity);
  68614. }
  68615. }
  68616. return clip != 0;
  68617. }
  68618. void clipToPath (const Path& p, const AffineTransform& transform)
  68619. {
  68620. if (clip != 0)
  68621. {
  68622. cloneClipIfMultiplyReferenced();
  68623. clip = clip->clipToPath (p, getTransformWith (transform));
  68624. }
  68625. }
  68626. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68627. {
  68628. if (clip != 0)
  68629. {
  68630. if (image.hasAlphaChannel())
  68631. {
  68632. cloneClipIfMultiplyReferenced();
  68633. clip = clip->clipToImageAlpha (image, getTransformWith (t),
  68634. interpolationQuality != Graphics::lowResamplingQuality);
  68635. }
  68636. else
  68637. {
  68638. Path p;
  68639. p.addRectangle (image.getBounds());
  68640. clipToPath (p, t);
  68641. }
  68642. }
  68643. }
  68644. bool clipRegionIntersects (const Rectangle<int>& r) const
  68645. {
  68646. if (clip != 0)
  68647. {
  68648. if (isOnlyTranslated)
  68649. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68650. else
  68651. return getClipBounds().intersects (r);
  68652. }
  68653. return false;
  68654. }
  68655. const Rectangle<int> getUntransformedClipBounds() const
  68656. {
  68657. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68658. }
  68659. const Rectangle<int> getClipBounds() const
  68660. {
  68661. if (clip != 0)
  68662. {
  68663. if (isOnlyTranslated)
  68664. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68665. else
  68666. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68667. }
  68668. return Rectangle<int>();
  68669. }
  68670. SavedState* beginTransparencyLayer (float opacity)
  68671. {
  68672. const Rectangle<int> clip (getUntransformedClipBounds());
  68673. SavedState* s = new SavedState (*this);
  68674. s->image = Image (Image::ARGB, clip.getWidth(), clip.getHeight(), true);
  68675. s->compositionAlpha = opacity;
  68676. if (s->isOnlyTranslated)
  68677. {
  68678. s->xOffset -= clip.getX();
  68679. s->yOffset -= clip.getY();
  68680. }
  68681. else
  68682. {
  68683. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -clip.getX(),
  68684. (float) -clip.getY()));
  68685. }
  68686. s->cloneClipIfMultiplyReferenced();
  68687. s->clip = s->clip->translated (-clip.getPosition());
  68688. return s;
  68689. }
  68690. void endTransparencyLayer (SavedState& layerState)
  68691. {
  68692. const Rectangle<int> clip (getUntransformedClipBounds());
  68693. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68694. g->setOpacity (layerState.compositionAlpha);
  68695. g->drawImage (layerState.image, AffineTransform::translation ((float) clip.getX(),
  68696. (float) clip.getY()), false);
  68697. }
  68698. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68699. {
  68700. if (clip != 0)
  68701. {
  68702. if (isOnlyTranslated)
  68703. {
  68704. if (fillType.isColour())
  68705. {
  68706. Image::BitmapData destData (image, true);
  68707. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68708. }
  68709. else
  68710. {
  68711. const Rectangle<int> totalClip (clip->getClipBounds());
  68712. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68713. if (! clipped.isEmpty())
  68714. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68715. }
  68716. }
  68717. else
  68718. {
  68719. Path p;
  68720. p.addRectangle (r);
  68721. fillPath (p, AffineTransform::identity);
  68722. }
  68723. }
  68724. }
  68725. void fillRect (const Rectangle<float>& r)
  68726. {
  68727. if (clip != 0)
  68728. {
  68729. if (isOnlyTranslated)
  68730. {
  68731. if (fillType.isColour())
  68732. {
  68733. Image::BitmapData destData (image, true);
  68734. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68735. }
  68736. else
  68737. {
  68738. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68739. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68740. if (! clipped.isEmpty())
  68741. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68742. }
  68743. }
  68744. else
  68745. {
  68746. Path p;
  68747. p.addRectangle (r);
  68748. fillPath (p, AffineTransform::identity);
  68749. }
  68750. }
  68751. }
  68752. void fillPath (const Path& path, const AffineTransform& transform)
  68753. {
  68754. if (clip != 0)
  68755. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  68756. }
  68757. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  68758. {
  68759. jassert (isOnlyTranslated);
  68760. if (clip != 0)
  68761. {
  68762. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68763. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68764. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68765. fillShape (shapeToFill, false);
  68766. }
  68767. }
  68768. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68769. {
  68770. jassert (clip != 0);
  68771. shapeToFill = clip->applyClipTo (shapeToFill);
  68772. if (shapeToFill != 0)
  68773. {
  68774. Image::BitmapData destData (image, true);
  68775. if (fillType.isGradient())
  68776. {
  68777. jassert (! replaceContents); // that option is just for solid colours
  68778. ColourGradient g2 (*(fillType.gradient));
  68779. g2.multiplyOpacity (fillType.getOpacity());
  68780. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  68781. const bool isIdentity = transform.isOnlyTranslation();
  68782. if (isIdentity)
  68783. {
  68784. // If our translation doesn't involve any distortion, we can speed it up..
  68785. g2.point1.applyTransform (transform);
  68786. g2.point2.applyTransform (transform);
  68787. transform = AffineTransform::identity;
  68788. }
  68789. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68790. }
  68791. else if (fillType.isTiledImage())
  68792. {
  68793. renderImage (fillType.image, fillType.transform, shapeToFill);
  68794. }
  68795. else
  68796. {
  68797. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68798. }
  68799. }
  68800. }
  68801. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68802. {
  68803. const AffineTransform transform (getTransformWith (t));
  68804. const Image::BitmapData destData (image, true);
  68805. const Image::BitmapData srcData (sourceImage, false);
  68806. const int alpha = fillType.colour.getAlpha();
  68807. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68808. if (transform.isOnlyTranslation())
  68809. {
  68810. // If our translation doesn't involve any distortion, just use a simple blit..
  68811. int tx = (int) (transform.getTranslationX() * 256.0f);
  68812. int ty = (int) (transform.getTranslationY() * 256.0f);
  68813. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68814. {
  68815. tx = ((tx + 128) >> 8);
  68816. ty = ((ty + 128) >> 8);
  68817. if (tiledFillClipRegion != 0)
  68818. {
  68819. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68820. }
  68821. else
  68822. {
  68823. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  68824. c = clip->applyClipTo (c);
  68825. if (c != 0)
  68826. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68827. }
  68828. return;
  68829. }
  68830. }
  68831. if (transform.isSingularity())
  68832. return;
  68833. if (tiledFillClipRegion != 0)
  68834. {
  68835. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68836. }
  68837. else
  68838. {
  68839. Path p;
  68840. p.addRectangle (sourceImage.getBounds());
  68841. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68842. c = c->clipToPath (p, transform);
  68843. if (c != 0)
  68844. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68845. }
  68846. }
  68847. Image image;
  68848. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68849. private:
  68850. AffineTransform complexTransform;
  68851. int xOffset, yOffset;
  68852. float compositionAlpha;
  68853. public:
  68854. bool isOnlyTranslated;
  68855. Font font;
  68856. FillType fillType;
  68857. Graphics::ResamplingQuality interpolationQuality;
  68858. private:
  68859. void cloneClipIfMultiplyReferenced()
  68860. {
  68861. if (clip->getReferenceCount() > 1)
  68862. clip = clip->clone();
  68863. }
  68864. const AffineTransform getTransform() const
  68865. {
  68866. if (isOnlyTranslated)
  68867. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  68868. return complexTransform;
  68869. }
  68870. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  68871. {
  68872. if (isOnlyTranslated)
  68873. return userTransform.translated ((float) xOffset, (float) yOffset);
  68874. return userTransform.followedBy (complexTransform);
  68875. }
  68876. SavedState& operator= (const SavedState&);
  68877. };
  68878. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68879. : image (image_),
  68880. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  68881. {
  68882. }
  68883. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68884. const RectangleList& initialClip)
  68885. : image (image_),
  68886. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  68887. {
  68888. }
  68889. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68890. {
  68891. }
  68892. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68893. {
  68894. return false;
  68895. }
  68896. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68897. {
  68898. currentState->setOrigin (x, y);
  68899. }
  68900. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  68901. {
  68902. currentState->addTransform (transform);
  68903. }
  68904. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  68905. {
  68906. return currentState->getScaleFactor();
  68907. }
  68908. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68909. {
  68910. return currentState->clipToRectangle (r);
  68911. }
  68912. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68913. {
  68914. return currentState->clipToRectangleList (clipRegion);
  68915. }
  68916. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68917. {
  68918. currentState->excludeClipRectangle (r);
  68919. }
  68920. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68921. {
  68922. currentState->clipToPath (path, transform);
  68923. }
  68924. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  68925. {
  68926. currentState->clipToImageAlpha (sourceImage, transform);
  68927. }
  68928. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  68929. {
  68930. return currentState->clipRegionIntersects (r);
  68931. }
  68932. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  68933. {
  68934. return currentState->getClipBounds();
  68935. }
  68936. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  68937. {
  68938. return currentState->clip == 0;
  68939. }
  68940. void LowLevelGraphicsSoftwareRenderer::saveState()
  68941. {
  68942. stateStack.add (new SavedState (*currentState));
  68943. }
  68944. void LowLevelGraphicsSoftwareRenderer::restoreState()
  68945. {
  68946. SavedState* const top = stateStack.getLast();
  68947. if (top != 0)
  68948. {
  68949. currentState = top;
  68950. stateStack.removeLast (1, false);
  68951. }
  68952. else
  68953. {
  68954. jassertfalse; // trying to pop with an empty stack!
  68955. }
  68956. }
  68957. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  68958. {
  68959. saveState();
  68960. currentState = currentState->beginTransparencyLayer (opacity);
  68961. }
  68962. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  68963. {
  68964. const ScopedPointer<SavedState> layer (currentState);
  68965. restoreState();
  68966. currentState->endTransparencyLayer (*layer);
  68967. }
  68968. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  68969. {
  68970. currentState->fillType = fillType;
  68971. }
  68972. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  68973. {
  68974. currentState->fillType.setOpacity (newOpacity);
  68975. }
  68976. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  68977. {
  68978. currentState->interpolationQuality = quality;
  68979. }
  68980. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  68981. {
  68982. currentState->fillRect (r, replaceExistingContents);
  68983. }
  68984. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  68985. {
  68986. currentState->fillPath (path, transform);
  68987. }
  68988. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  68989. {
  68990. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  68991. }
  68992. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  68993. {
  68994. Path p;
  68995. p.addLineSegment (line, 1.0f);
  68996. fillPath (p, AffineTransform::identity);
  68997. }
  68998. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  68999. {
  69000. if (bottom > top)
  69001. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69002. }
  69003. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69004. {
  69005. if (right > left)
  69006. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69007. }
  69008. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69009. {
  69010. public:
  69011. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69012. ~CachedGlyph() {}
  69013. void draw (SavedState& state, const float x, const float y) const
  69014. {
  69015. if (edgeTable != 0)
  69016. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69017. }
  69018. void generate (const Font& newFont, const int glyphNumber)
  69019. {
  69020. font = newFont;
  69021. glyph = glyphNumber;
  69022. edgeTable = 0;
  69023. Path glyphPath;
  69024. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69025. if (! glyphPath.isEmpty())
  69026. {
  69027. const float fontHeight = font.getHeight();
  69028. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69029. #if JUCE_MAC || JUCE_IOS
  69030. .translated (0.0f, -0.5f)
  69031. #endif
  69032. );
  69033. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69034. glyphPath, transform);
  69035. }
  69036. }
  69037. int glyph, lastAccessCount;
  69038. Font font;
  69039. private:
  69040. ScopedPointer <EdgeTable> edgeTable;
  69041. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69042. };
  69043. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69044. {
  69045. public:
  69046. GlyphCache()
  69047. : accessCounter (0), hits (0), misses (0)
  69048. {
  69049. for (int i = 120; --i >= 0;)
  69050. glyphs.add (new CachedGlyph());
  69051. }
  69052. ~GlyphCache()
  69053. {
  69054. clearSingletonInstance();
  69055. }
  69056. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69057. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69058. {
  69059. ++accessCounter;
  69060. int oldestCounter = std::numeric_limits<int>::max();
  69061. CachedGlyph* oldest = 0;
  69062. for (int i = glyphs.size(); --i >= 0;)
  69063. {
  69064. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69065. if (glyph->glyph == glyphNumber && glyph->font == font)
  69066. {
  69067. ++hits;
  69068. glyph->lastAccessCount = accessCounter;
  69069. glyph->draw (state, x, y);
  69070. return;
  69071. }
  69072. if (glyph->lastAccessCount <= oldestCounter)
  69073. {
  69074. oldestCounter = glyph->lastAccessCount;
  69075. oldest = glyph;
  69076. }
  69077. }
  69078. if (hits + ++misses > (glyphs.size() << 4))
  69079. {
  69080. if (misses * 2 > hits)
  69081. {
  69082. for (int i = 32; --i >= 0;)
  69083. glyphs.add (new CachedGlyph());
  69084. }
  69085. hits = misses = 0;
  69086. oldest = glyphs.getLast();
  69087. }
  69088. jassert (oldest != 0);
  69089. oldest->lastAccessCount = accessCounter;
  69090. oldest->generate (font, glyphNumber);
  69091. oldest->draw (state, x, y);
  69092. }
  69093. private:
  69094. friend class OwnedArray <CachedGlyph>;
  69095. OwnedArray <CachedGlyph> glyphs;
  69096. int accessCounter, hits, misses;
  69097. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69098. };
  69099. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69100. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69101. {
  69102. currentState->font = newFont;
  69103. }
  69104. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69105. {
  69106. return currentState->font;
  69107. }
  69108. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69109. {
  69110. Font& f = currentState->font;
  69111. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69112. {
  69113. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69114. transform.getTranslationX(),
  69115. transform.getTranslationY());
  69116. }
  69117. else
  69118. {
  69119. Path p;
  69120. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69121. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69122. }
  69123. }
  69124. #if JUCE_MSVC
  69125. #pragma warning (pop)
  69126. #if JUCE_DEBUG
  69127. #pragma optimize ("", on) // resets optimisations to the project defaults
  69128. #endif
  69129. #endif
  69130. END_JUCE_NAMESPACE
  69131. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69132. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69133. BEGIN_JUCE_NAMESPACE
  69134. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69135. : flags (other.flags)
  69136. {
  69137. }
  69138. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69139. {
  69140. flags = other.flags;
  69141. return *this;
  69142. }
  69143. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69144. const double dx, const double dy, const double dw, const double dh) const throw()
  69145. {
  69146. if (w == 0 || h == 0)
  69147. return;
  69148. if ((flags & stretchToFit) != 0)
  69149. {
  69150. x = dx;
  69151. y = dy;
  69152. w = dw;
  69153. h = dh;
  69154. }
  69155. else
  69156. {
  69157. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69158. : jmin (dw / w, dh / h);
  69159. if ((flags & onlyReduceInSize) != 0)
  69160. scale = jmin (scale, 1.0);
  69161. if ((flags & onlyIncreaseInSize) != 0)
  69162. scale = jmax (scale, 1.0);
  69163. w *= scale;
  69164. h *= scale;
  69165. if ((flags & xLeft) != 0)
  69166. x = dx;
  69167. else if ((flags & xRight) != 0)
  69168. x = dx + dw - w;
  69169. else
  69170. x = dx + (dw - w) * 0.5;
  69171. if ((flags & yTop) != 0)
  69172. y = dy;
  69173. else if ((flags & yBottom) != 0)
  69174. y = dy + dh - h;
  69175. else
  69176. y = dy + (dh - h) * 0.5;
  69177. }
  69178. }
  69179. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69180. {
  69181. if (source.isEmpty())
  69182. return AffineTransform::identity;
  69183. float newX = destination.getX();
  69184. float newY = destination.getY();
  69185. float scaleX = destination.getWidth() / source.getWidth();
  69186. float scaleY = destination.getHeight() / source.getHeight();
  69187. if ((flags & stretchToFit) == 0)
  69188. {
  69189. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69190. : jmin (scaleX, scaleY);
  69191. if ((flags & onlyReduceInSize) != 0)
  69192. scaleX = jmin (scaleX, 1.0f);
  69193. if ((flags & onlyIncreaseInSize) != 0)
  69194. scaleX = jmax (scaleX, 1.0f);
  69195. scaleY = scaleX;
  69196. if ((flags & xRight) != 0)
  69197. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69198. else if ((flags & xLeft) == 0)
  69199. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69200. if ((flags & yBottom) != 0)
  69201. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69202. else if ((flags & yTop) == 0)
  69203. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69204. }
  69205. return AffineTransform::translation (-source.getX(), -source.getY())
  69206. .scaled (scaleX, scaleY)
  69207. .translated (newX, newY);
  69208. }
  69209. END_JUCE_NAMESPACE
  69210. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69211. /*** Start of inlined file: juce_Drawable.cpp ***/
  69212. BEGIN_JUCE_NAMESPACE
  69213. Drawable::Drawable()
  69214. {
  69215. setInterceptsMouseClicks (false, false);
  69216. setPaintingIsUnclipped (true);
  69217. }
  69218. Drawable::~Drawable()
  69219. {
  69220. }
  69221. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69222. {
  69223. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69224. }
  69225. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69226. {
  69227. Graphics::ScopedSaveState ss (g);
  69228. const float oldOpacity = getAlpha();
  69229. setAlpha (opacity);
  69230. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69231. (float) -originRelativeToComponent.getY())
  69232. .followedBy (getTransform())
  69233. .followedBy (transform));
  69234. if (! g.isClipEmpty())
  69235. paintEntireComponent (g, false);
  69236. setAlpha (oldOpacity);
  69237. }
  69238. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69239. {
  69240. draw (g, opacity, AffineTransform::translation (x, y));
  69241. }
  69242. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69243. {
  69244. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69245. }
  69246. DrawableComposite* Drawable::getParent() const
  69247. {
  69248. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69249. }
  69250. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69251. {
  69252. g.setOrigin (originRelativeToComponent.getX(),
  69253. originRelativeToComponent.getY());
  69254. }
  69255. void Drawable::markerHasMoved()
  69256. {
  69257. }
  69258. void Drawable::parentHierarchyChanged()
  69259. {
  69260. setBoundsToEnclose (getDrawableBounds());
  69261. }
  69262. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69263. {
  69264. Drawable* const parent = getParent();
  69265. Point<int> parentOrigin;
  69266. if (parent != 0)
  69267. parentOrigin = parent->originRelativeToComponent;
  69268. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69269. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69270. setBounds (newBounds);
  69271. }
  69272. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69273. {
  69274. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69275. }
  69276. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69277. {
  69278. if (! area.isEmpty())
  69279. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69280. }
  69281. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69282. {
  69283. Drawable* result = 0;
  69284. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69285. if (image.isValid())
  69286. {
  69287. DrawableImage* const di = new DrawableImage();
  69288. di->setImage (image);
  69289. result = di;
  69290. }
  69291. else
  69292. {
  69293. const String asString (String::createStringFromData (data, (int) numBytes));
  69294. XmlDocument doc (asString);
  69295. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69296. if (outer != 0 && outer->hasTagName ("svg"))
  69297. {
  69298. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69299. if (svg != 0)
  69300. result = Drawable::createFromSVG (*svg);
  69301. }
  69302. }
  69303. return result;
  69304. }
  69305. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69306. {
  69307. MemoryOutputStream mo;
  69308. mo.writeFromInputStream (dataSource, -1);
  69309. return createFromImageData (mo.getData(), mo.getDataSize());
  69310. }
  69311. Drawable* Drawable::createFromImageFile (const File& file)
  69312. {
  69313. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69314. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69315. }
  69316. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69317. {
  69318. return createChildFromValueTree (0, tree, imageProvider);
  69319. }
  69320. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69321. {
  69322. const Identifier type (tree.getType());
  69323. Drawable* d = 0;
  69324. if (type == DrawablePath::valueTreeType) d = new DrawablePath();
  69325. else if (type == DrawableComposite::valueTreeType) d = new DrawableComposite();
  69326. else if (type == DrawableRectangle::valueTreeType) d = new DrawableRectangle();
  69327. else if (type == DrawableImage::valueTreeType) d = new DrawableImage();
  69328. else if (type == DrawableText::valueTreeType) d = new DrawableText();
  69329. if (d != 0)
  69330. {
  69331. if (parent != 0)
  69332. parent->insertDrawable (d);
  69333. d->refreshFromValueTree (tree, imageProvider);
  69334. }
  69335. return d;
  69336. }
  69337. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69338. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69339. : state (state_)
  69340. {
  69341. }
  69342. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69343. {
  69344. }
  69345. const String Drawable::ValueTreeWrapperBase::getID() const
  69346. {
  69347. return state [idProperty];
  69348. }
  69349. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69350. {
  69351. if (newID.isEmpty())
  69352. state.removeProperty (idProperty, undoManager);
  69353. else
  69354. state.setProperty (idProperty, newID, undoManager);
  69355. }
  69356. END_JUCE_NAMESPACE
  69357. /*** End of inlined file: juce_Drawable.cpp ***/
  69358. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69359. BEGIN_JUCE_NAMESPACE
  69360. DrawableShape::DrawableShape()
  69361. : strokeType (0.0f),
  69362. mainFill (Colours::black),
  69363. strokeFill (Colours::black)
  69364. {
  69365. }
  69366. DrawableShape::DrawableShape (const DrawableShape& other)
  69367. : strokeType (other.strokeType),
  69368. mainFill (other.mainFill),
  69369. strokeFill (other.strokeFill)
  69370. {
  69371. }
  69372. DrawableShape::~DrawableShape()
  69373. {
  69374. }
  69375. void DrawableShape::setFill (const FillType& newFill)
  69376. {
  69377. mainFill = newFill;
  69378. }
  69379. void DrawableShape::setStrokeFill (const FillType& newFill)
  69380. {
  69381. strokeFill = newFill;
  69382. }
  69383. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69384. {
  69385. strokeType = newStrokeType;
  69386. strokeChanged();
  69387. }
  69388. void DrawableShape::setStrokeThickness (const float newThickness)
  69389. {
  69390. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69391. }
  69392. bool DrawableShape::isStrokeVisible() const throw()
  69393. {
  69394. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69395. }
  69396. bool DrawableShape::refreshFillTypes (const FillAndStrokeState& newState,
  69397. Expression::EvaluationContext* /*nameFinder*/,
  69398. ImageProvider* imageProvider)
  69399. {
  69400. bool hasChanged = false;
  69401. {
  69402. const FillType f (newState.getMainFill (getParent(), imageProvider));
  69403. if (mainFill != f)
  69404. {
  69405. hasChanged = true;
  69406. mainFill = f;
  69407. }
  69408. }
  69409. {
  69410. const FillType f (newState.getStrokeFill (getParent(), imageProvider));
  69411. if (strokeFill != f)
  69412. {
  69413. hasChanged = true;
  69414. strokeFill = f;
  69415. }
  69416. }
  69417. return hasChanged;
  69418. }
  69419. void DrawableShape::writeTo (FillAndStrokeState& state, ImageProvider* imageProvider, UndoManager* undoManager) const
  69420. {
  69421. state.setMainFill (mainFill, 0, 0, 0, imageProvider, undoManager);
  69422. state.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, undoManager);
  69423. state.setStrokeType (strokeType, undoManager);
  69424. }
  69425. void DrawableShape::paint (Graphics& g)
  69426. {
  69427. transformContextToCorrectOrigin (g);
  69428. g.setFillType (mainFill);
  69429. g.fillPath (path);
  69430. if (isStrokeVisible())
  69431. {
  69432. g.setFillType (strokeFill);
  69433. g.fillPath (strokePath);
  69434. }
  69435. }
  69436. void DrawableShape::pathChanged()
  69437. {
  69438. strokeChanged();
  69439. }
  69440. void DrawableShape::strokeChanged()
  69441. {
  69442. strokePath.clear();
  69443. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69444. setBoundsToEnclose (getDrawableBounds());
  69445. repaint();
  69446. }
  69447. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69448. {
  69449. if (isStrokeVisible())
  69450. return strokePath.getBounds();
  69451. else
  69452. return path.getBounds();
  69453. }
  69454. bool DrawableShape::hitTest (int x, int y) const
  69455. {
  69456. const float globalX = (float) (x - originRelativeToComponent.getX());
  69457. const float globalY = (float) (y - originRelativeToComponent.getY());
  69458. return path.contains (globalX, globalY)
  69459. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69460. }
  69461. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69462. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69463. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69464. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69465. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69466. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69467. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69468. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69469. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69470. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69471. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69472. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69473. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69474. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69475. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69476. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69477. : Drawable::ValueTreeWrapperBase (state_)
  69478. {
  69479. }
  69480. const FillType DrawableShape::FillAndStrokeState::getMainFill (Expression::EvaluationContext* nameFinder,
  69481. ImageProvider* imageProvider) const
  69482. {
  69483. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69484. }
  69485. ValueTree DrawableShape::FillAndStrokeState::getMainFillState()
  69486. {
  69487. ValueTree v (state.getChildWithName (fill));
  69488. if (v.isValid())
  69489. return v;
  69490. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69491. return getMainFillState();
  69492. }
  69493. void DrawableShape::FillAndStrokeState::setMainFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69494. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69495. {
  69496. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69497. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69498. }
  69499. const FillType DrawableShape::FillAndStrokeState::getStrokeFill (Expression::EvaluationContext* nameFinder,
  69500. ImageProvider* imageProvider) const
  69501. {
  69502. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69503. }
  69504. ValueTree DrawableShape::FillAndStrokeState::getStrokeFillState()
  69505. {
  69506. ValueTree v (state.getChildWithName (stroke));
  69507. if (v.isValid())
  69508. return v;
  69509. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69510. return getStrokeFillState();
  69511. }
  69512. void DrawableShape::FillAndStrokeState::setStrokeFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69513. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69514. {
  69515. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69516. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69517. }
  69518. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69519. {
  69520. const String jointStyleString (state [jointStyle].toString());
  69521. const String capStyleString (state [capStyle].toString());
  69522. return PathStrokeType (state [strokeWidth],
  69523. jointStyleString == "curved" ? PathStrokeType::curved
  69524. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69525. : PathStrokeType::mitered),
  69526. capStyleString == "square" ? PathStrokeType::square
  69527. : (capStyleString == "round" ? PathStrokeType::rounded
  69528. : PathStrokeType::butt));
  69529. }
  69530. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69531. {
  69532. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69533. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69534. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69535. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69536. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69537. }
  69538. const FillType DrawableShape::FillAndStrokeState::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69539. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69540. {
  69541. const String newType (v[type].toString());
  69542. if (newType == "solid")
  69543. {
  69544. const String colourString (v [colour].toString());
  69545. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69546. : (uint32) colourString.getHexValue32()));
  69547. }
  69548. else if (newType == "gradient")
  69549. {
  69550. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69551. ColourGradient g;
  69552. if (gp1 != 0) *gp1 = p1;
  69553. if (gp2 != 0) *gp2 = p2;
  69554. if (gp3 != 0) *gp3 = p3;
  69555. g.point1 = p1.resolve (nameFinder);
  69556. g.point2 = p2.resolve (nameFinder);
  69557. g.isRadial = v[radial];
  69558. StringArray colourSteps;
  69559. colourSteps.addTokens (v[colours].toString(), false);
  69560. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69561. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69562. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69563. FillType fillType (g);
  69564. if (g.isRadial)
  69565. {
  69566. const Point<float> point3 (p3.resolve (nameFinder));
  69567. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69568. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69569. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69570. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69571. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69572. }
  69573. return fillType;
  69574. }
  69575. else if (newType == "image")
  69576. {
  69577. Image im;
  69578. if (imageProvider != 0)
  69579. im = imageProvider->getImageForIdentifier (v[imageId]);
  69580. FillType f (im, AffineTransform::identity);
  69581. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69582. return f;
  69583. }
  69584. jassert (! v.isValid());
  69585. return FillType();
  69586. }
  69587. namespace DrawableShapeHelpers
  69588. {
  69589. const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69590. {
  69591. const ColourGradient& g = *fillType.gradient;
  69592. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69593. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69594. return point3Source.transformedBy (fillType.transform);
  69595. }
  69596. }
  69597. void DrawableShape::FillAndStrokeState::writeFillType (ValueTree& v, const FillType& fillType,
  69598. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69599. ImageProvider* imageProvider, UndoManager* const undoManager)
  69600. {
  69601. if (fillType.isColour())
  69602. {
  69603. v.setProperty (type, "solid", undoManager);
  69604. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69605. }
  69606. else if (fillType.isGradient())
  69607. {
  69608. v.setProperty (type, "gradient", undoManager);
  69609. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69610. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69611. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : DrawableShapeHelpers::calcThirdGradientPoint (fillType).toString(), undoManager);
  69612. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69613. String s;
  69614. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69615. s << ' ' << fillType.gradient->getColourPosition (i)
  69616. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69617. v.setProperty (colours, s.trimStart(), undoManager);
  69618. }
  69619. else if (fillType.isTiledImage())
  69620. {
  69621. v.setProperty (type, "image", undoManager);
  69622. if (imageProvider != 0)
  69623. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69624. if (fillType.getOpacity() < 1.0f)
  69625. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69626. else
  69627. v.removeProperty (imageOpacity, undoManager);
  69628. }
  69629. else
  69630. {
  69631. jassertfalse;
  69632. }
  69633. }
  69634. END_JUCE_NAMESPACE
  69635. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69636. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69637. BEGIN_JUCE_NAMESPACE
  69638. DrawableComposite::DrawableComposite()
  69639. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69640. updateBoundsReentrant (false)
  69641. {
  69642. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69643. RelativeCoordinate (100.0),
  69644. RelativeCoordinate (0.0),
  69645. RelativeCoordinate (100.0)));
  69646. }
  69647. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69648. : bounds (other.bounds),
  69649. updateBoundsReentrant (false)
  69650. {
  69651. for (int i = 0; i < other.getNumDrawables(); ++i)
  69652. insertDrawable (other.getDrawable(i)->createCopy());
  69653. markersX.addCopiesOf (other.markersX);
  69654. markersY.addCopiesOf (other.markersY);
  69655. }
  69656. DrawableComposite::~DrawableComposite()
  69657. {
  69658. deleteAllChildren();
  69659. }
  69660. int DrawableComposite::getNumDrawables() const throw()
  69661. {
  69662. return getNumChildComponents();
  69663. }
  69664. Drawable* DrawableComposite::getDrawable (int index) const
  69665. {
  69666. return dynamic_cast <Drawable*> (getChildComponent (index));
  69667. }
  69668. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69669. {
  69670. if (drawable != 0)
  69671. addAndMakeVisible (drawable, index);
  69672. }
  69673. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69674. {
  69675. insertDrawable (drawable.createCopy(), index);
  69676. }
  69677. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69678. {
  69679. Drawable* const d = getDrawable (index);
  69680. if (deleteDrawable)
  69681. delete d;
  69682. else
  69683. removeChildComponent (d);
  69684. }
  69685. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69686. {
  69687. for (int i = getNumChildComponents(); --i >= 0;)
  69688. if (getChildComponent(i)->getName() == name)
  69689. return getDrawable (i);
  69690. return 0;
  69691. }
  69692. void DrawableComposite::bringToFront (const int index)
  69693. {
  69694. Drawable* d = getDrawable (index);
  69695. if (d != 0)
  69696. d->toFront (false);
  69697. }
  69698. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  69699. {
  69700. Rectangle<float> r;
  69701. for (int i = getNumDrawables(); --i >= 0;)
  69702. {
  69703. Drawable* const d = getDrawable(i);
  69704. if (d != 0)
  69705. {
  69706. if (d->isTransformed())
  69707. r = r.getUnion (d->getDrawableBounds().transformed (d->getTransform()));
  69708. else
  69709. r = r.getUnion (d->getDrawableBounds());
  69710. }
  69711. }
  69712. return r;
  69713. }
  69714. void DrawableComposite::markerHasMoved()
  69715. {
  69716. for (int i = getNumDrawables(); --i >= 0;)
  69717. {
  69718. Drawable* const d = getDrawable(i);
  69719. if (d != 0)
  69720. d->markerHasMoved();
  69721. }
  69722. }
  69723. const RelativeRectangle DrawableComposite::getContentArea() const
  69724. {
  69725. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69726. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69727. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69728. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69729. }
  69730. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69731. {
  69732. setMarker (contentLeftMarkerName, true, newArea.left);
  69733. setMarker (contentRightMarkerName, true, newArea.right);
  69734. setMarker (contentTopMarkerName, false, newArea.top);
  69735. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69736. refreshTransformFromBounds();
  69737. }
  69738. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69739. {
  69740. bounds = newBoundingBox;
  69741. refreshTransformFromBounds();
  69742. }
  69743. void DrawableComposite::resetBoundingBoxToContentArea()
  69744. {
  69745. const RelativeRectangle content (getContentArea());
  69746. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69747. RelativePoint (content.right, content.top),
  69748. RelativePoint (content.left, content.bottom)));
  69749. }
  69750. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69751. {
  69752. const Rectangle<float> activeArea (getDrawableBounds());
  69753. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  69754. RelativeCoordinate (activeArea.getRight()),
  69755. RelativeCoordinate (activeArea.getY()),
  69756. RelativeCoordinate (activeArea.getBottom())));
  69757. resetBoundingBoxToContentArea();
  69758. }
  69759. void DrawableComposite::refreshTransformFromBounds()
  69760. {
  69761. Point<float> resolved[3];
  69762. bounds.resolveThreePoints (resolved, getParent());
  69763. const Rectangle<float> content (getContentArea().resolve (getParent()));
  69764. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69765. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69766. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  69767. if (t.isSingularity())
  69768. t = AffineTransform::identity;
  69769. setTransform (t);
  69770. }
  69771. void DrawableComposite::parentHierarchyChanged()
  69772. {
  69773. DrawableComposite* parent = getParent();
  69774. if (parent != 0)
  69775. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  69776. }
  69777. void DrawableComposite::childBoundsChanged (Component*)
  69778. {
  69779. updateBoundsToFitChildren();
  69780. }
  69781. void DrawableComposite::childrenChanged()
  69782. {
  69783. updateBoundsToFitChildren();
  69784. }
  69785. struct RentrancyCheckSetter
  69786. {
  69787. RentrancyCheckSetter (bool& b_) : b (b_) { b_ = true; }
  69788. ~RentrancyCheckSetter() { b = false; }
  69789. private:
  69790. bool& b;
  69791. JUCE_DECLARE_NON_COPYABLE (RentrancyCheckSetter);
  69792. };
  69793. void DrawableComposite::updateBoundsToFitChildren()
  69794. {
  69795. if (! updateBoundsReentrant)
  69796. {
  69797. const RentrancyCheckSetter checkSetter (updateBoundsReentrant);
  69798. Rectangle<int> childArea;
  69799. for (int i = getNumChildComponents(); --i >= 0;)
  69800. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  69801. const Point<int> delta (childArea.getPosition());
  69802. childArea += getPosition();
  69803. if (childArea != getBounds())
  69804. {
  69805. if (! delta.isOrigin())
  69806. {
  69807. originRelativeToComponent -= delta;
  69808. for (int i = getNumChildComponents(); --i >= 0;)
  69809. {
  69810. Component* const c = getChildComponent(i);
  69811. if (c != 0)
  69812. c->setBounds (c->getBounds() - delta);
  69813. }
  69814. }
  69815. setBounds (childArea);
  69816. }
  69817. }
  69818. }
  69819. const char* const DrawableComposite::contentLeftMarkerName = "left";
  69820. const char* const DrawableComposite::contentRightMarkerName = "right";
  69821. const char* const DrawableComposite::contentTopMarkerName = "top";
  69822. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  69823. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69824. : name (other.name), position (other.position)
  69825. {
  69826. }
  69827. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69828. : name (name_), position (position_)
  69829. {
  69830. }
  69831. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69832. {
  69833. return name != other.name || position != other.position;
  69834. }
  69835. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69836. {
  69837. return (xAxis ? markersX : markersY).size();
  69838. }
  69839. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69840. {
  69841. return (xAxis ? markersX : markersY) [index];
  69842. }
  69843. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69844. {
  69845. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69846. for (int i = 0; i < markers.size(); ++i)
  69847. {
  69848. Marker* const m = markers.getUnchecked(i);
  69849. if (m->name == name)
  69850. {
  69851. if (m->position != position)
  69852. {
  69853. m->position = position;
  69854. markerHasMoved();
  69855. }
  69856. return;
  69857. }
  69858. }
  69859. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69860. markerHasMoved();
  69861. }
  69862. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69863. {
  69864. jassert (index >= 2);
  69865. if (index >= 2)
  69866. (xAxis ? markersX : markersY).remove (index);
  69867. }
  69868. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69869. {
  69870. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69871. int i;
  69872. for (i = 0; i < markersX.size(); ++i)
  69873. {
  69874. Marker* const m = markersX.getUnchecked(i);
  69875. if (m->name == symbol)
  69876. return m->position.getExpression();
  69877. }
  69878. for (i = 0; i < markersY.size(); ++i)
  69879. {
  69880. Marker* const m = markersY.getUnchecked(i);
  69881. if (m->name == symbol)
  69882. return m->position.getExpression();
  69883. }
  69884. throw Expression::EvaluationError (symbol, member);
  69885. }
  69886. Drawable* DrawableComposite::createCopy() const
  69887. {
  69888. return new DrawableComposite (*this);
  69889. }
  69890. const Identifier DrawableComposite::valueTreeType ("Group");
  69891. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69892. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69893. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69894. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69895. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69896. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69897. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69898. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69899. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69900. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69901. : ValueTreeWrapperBase (state_)
  69902. {
  69903. jassert (state.hasType (valueTreeType));
  69904. }
  69905. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69906. {
  69907. return state.getChildWithName (childGroupTag);
  69908. }
  69909. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69910. {
  69911. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69912. }
  69913. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69914. {
  69915. return getChildList().getNumChildren();
  69916. }
  69917. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69918. {
  69919. return getChildList().getChild (index);
  69920. }
  69921. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69922. {
  69923. if (getID() == objectId)
  69924. return state;
  69925. if (! recursive)
  69926. {
  69927. return getChildList().getChildWithProperty (idProperty, objectId);
  69928. }
  69929. else
  69930. {
  69931. const ValueTree childList (getChildList());
  69932. for (int i = getNumDrawables(); --i >= 0;)
  69933. {
  69934. const ValueTree& child = childList.getChild (i);
  69935. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69936. return child;
  69937. if (child.hasType (DrawableComposite::valueTreeType))
  69938. {
  69939. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69940. if (v.isValid())
  69941. return v;
  69942. }
  69943. }
  69944. return ValueTree::invalid;
  69945. }
  69946. }
  69947. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69948. {
  69949. return getChildList().indexOf (item);
  69950. }
  69951. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69952. {
  69953. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69954. }
  69955. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69956. {
  69957. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69958. }
  69959. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69960. {
  69961. getChildList().removeChild (child, undoManager);
  69962. }
  69963. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69964. {
  69965. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69966. state.getProperty (topRight, "100, 0"),
  69967. state.getProperty (bottomLeft, "0, 100"));
  69968. }
  69969. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69970. {
  69971. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69972. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69973. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69974. }
  69975. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69976. {
  69977. const RelativeRectangle content (getContentArea());
  69978. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69979. RelativePoint (content.right, content.top),
  69980. RelativePoint (content.left, content.bottom)), undoManager);
  69981. }
  69982. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69983. {
  69984. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69985. getMarker (true, getMarkerState (true, 1)).position,
  69986. getMarker (false, getMarkerState (false, 0)).position,
  69987. getMarker (false, getMarkerState (false, 1)).position);
  69988. }
  69989. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69990. {
  69991. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69992. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69993. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69994. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69995. }
  69996. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69997. {
  69998. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69999. }
  70000. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70001. {
  70002. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70003. }
  70004. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  70005. {
  70006. return getMarkerList (xAxis).getNumChildren();
  70007. }
  70008. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  70009. {
  70010. return getMarkerList (xAxis).getChild (index);
  70011. }
  70012. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  70013. {
  70014. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  70015. }
  70016. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  70017. {
  70018. return state.isAChildOf (getMarkerList (xAxis));
  70019. }
  70020. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70021. {
  70022. (void) xAxis;
  70023. jassert (containsMarker (xAxis, state));
  70024. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70025. }
  70026. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70027. {
  70028. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70029. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70030. if (marker.isValid())
  70031. {
  70032. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70033. }
  70034. else
  70035. {
  70036. marker = ValueTree (markerTag);
  70037. marker.setProperty (nameProperty, m.name, 0);
  70038. marker.setProperty (posProperty, m.position.toString(), 0);
  70039. markerList.addChild (marker, -1, undoManager);
  70040. }
  70041. }
  70042. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70043. {
  70044. if (state [nameProperty].toString() != contentLeftMarkerName
  70045. && state [nameProperty].toString() != contentRightMarkerName
  70046. && state [nameProperty].toString() != contentTopMarkerName
  70047. && state [nameProperty].toString() != contentBottomMarkerName)
  70048. getMarkerList (xAxis).removeChild (state, undoManager);
  70049. }
  70050. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70051. {
  70052. const ValueTreeWrapper wrapper (tree);
  70053. setName (wrapper.getID());
  70054. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70055. if (bounds != newBounds)
  70056. bounds = newBounds;
  70057. const int numMarkersX = wrapper.getNumMarkers (true);
  70058. const int numMarkersY = wrapper.getNumMarkers (false);
  70059. // Remove deleted markers...
  70060. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70061. {
  70062. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70063. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70064. }
  70065. // Update markers and add new ones..
  70066. int i;
  70067. for (i = 0; i < numMarkersX; ++i)
  70068. {
  70069. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70070. Marker* m = markersX[i];
  70071. if (m == 0)
  70072. markersX.add (new Marker (newMarker));
  70073. else if (newMarker != *m)
  70074. *m = newMarker;
  70075. }
  70076. for (i = 0; i < numMarkersY; ++i)
  70077. {
  70078. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70079. Marker* m = markersY[i];
  70080. if (m == 0)
  70081. markersY.add (new Marker (newMarker));
  70082. else if (newMarker != *m)
  70083. *m = newMarker;
  70084. }
  70085. // Remove deleted drawables..
  70086. for (i = getNumDrawables(); --i >= wrapper.getNumDrawables();)
  70087. delete getDrawable(i);
  70088. // Update drawables and add new ones..
  70089. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70090. {
  70091. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70092. Drawable* d = getDrawable(i);
  70093. if (d != 0)
  70094. {
  70095. if (newDrawable.hasType (d->getValueTreeType()))
  70096. {
  70097. d->refreshFromValueTree (newDrawable, imageProvider);
  70098. }
  70099. else
  70100. {
  70101. delete d;
  70102. d = 0;
  70103. }
  70104. }
  70105. if (d == 0)
  70106. {
  70107. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70108. addAndMakeVisible (d, i);
  70109. }
  70110. }
  70111. refreshTransformFromBounds();
  70112. }
  70113. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70114. {
  70115. ValueTree tree (valueTreeType);
  70116. ValueTreeWrapper v (tree);
  70117. v.setID (getName(), 0);
  70118. v.setBoundingBox (bounds, 0);
  70119. int i;
  70120. for (i = 0; i < getNumDrawables(); ++i)
  70121. v.addDrawable (getDrawable(i)->createValueTree (imageProvider), -1, 0);
  70122. for (i = 0; i < markersX.size(); ++i)
  70123. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70124. for (i = 0; i < markersY.size(); ++i)
  70125. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70126. return tree;
  70127. }
  70128. END_JUCE_NAMESPACE
  70129. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70130. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70131. BEGIN_JUCE_NAMESPACE
  70132. DrawableImage::DrawableImage()
  70133. : image (0),
  70134. opacity (1.0f),
  70135. overlayColour (0x00000000)
  70136. {
  70137. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70138. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70139. }
  70140. DrawableImage::DrawableImage (const DrawableImage& other)
  70141. : image (other.image),
  70142. opacity (other.opacity),
  70143. overlayColour (other.overlayColour),
  70144. bounds (other.bounds)
  70145. {
  70146. }
  70147. DrawableImage::~DrawableImage()
  70148. {
  70149. }
  70150. void DrawableImage::setImage (const Image& imageToUse)
  70151. {
  70152. image = imageToUse;
  70153. setBounds (imageToUse.getBounds());
  70154. if (image.isValid())
  70155. {
  70156. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70157. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70158. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70159. }
  70160. refreshTransformFromBounds();
  70161. }
  70162. void DrawableImage::setOpacity (const float newOpacity)
  70163. {
  70164. opacity = newOpacity;
  70165. }
  70166. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70167. {
  70168. overlayColour = newOverlayColour;
  70169. }
  70170. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70171. {
  70172. bounds = newBounds;
  70173. refreshTransformFromBounds();
  70174. }
  70175. void DrawableImage::refreshTransformFromBounds()
  70176. {
  70177. if (! image.isNull())
  70178. {
  70179. Point<float> resolved[3];
  70180. bounds.resolveThreePoints (resolved, getParent());
  70181. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70182. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70183. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70184. tr.getX(), tr.getY(),
  70185. bl.getX(), bl.getY()));
  70186. if (! t.isSingularity())
  70187. setTransform (t);
  70188. }
  70189. }
  70190. void DrawableImage::paint (Graphics& g)
  70191. {
  70192. if (image.isValid())
  70193. {
  70194. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70195. {
  70196. g.setOpacity (opacity);
  70197. g.drawImageAt (image, 0, 0, false);
  70198. }
  70199. if (! overlayColour.isTransparent())
  70200. {
  70201. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70202. g.drawImageAt (image, 0, 0, true);
  70203. }
  70204. }
  70205. }
  70206. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70207. {
  70208. return image.getBounds().toFloat();
  70209. }
  70210. bool DrawableImage::hitTest (int x, int y) const
  70211. {
  70212. return (! image.isNull())
  70213. && image.getPixelAt (x, y).getAlpha() >= 127;
  70214. }
  70215. Drawable* DrawableImage::createCopy() const
  70216. {
  70217. return new DrawableImage (*this);
  70218. }
  70219. const Identifier DrawableImage::valueTreeType ("Image");
  70220. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70221. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70222. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70223. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70224. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70225. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70226. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70227. : ValueTreeWrapperBase (state_)
  70228. {
  70229. jassert (state.hasType (valueTreeType));
  70230. }
  70231. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70232. {
  70233. return state [image];
  70234. }
  70235. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70236. {
  70237. return state.getPropertyAsValue (image, undoManager);
  70238. }
  70239. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70240. {
  70241. state.setProperty (image, newIdentifier, undoManager);
  70242. }
  70243. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70244. {
  70245. return (float) state.getProperty (opacity, 1.0);
  70246. }
  70247. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70248. {
  70249. if (! state.hasProperty (opacity))
  70250. state.setProperty (opacity, 1.0, undoManager);
  70251. return state.getPropertyAsValue (opacity, undoManager);
  70252. }
  70253. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70254. {
  70255. state.setProperty (opacity, newOpacity, undoManager);
  70256. }
  70257. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70258. {
  70259. return Colour (state [overlay].toString().getHexValue32());
  70260. }
  70261. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70262. {
  70263. if (newColour.isTransparent())
  70264. state.removeProperty (overlay, undoManager);
  70265. else
  70266. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70267. }
  70268. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70269. {
  70270. return state.getPropertyAsValue (overlay, undoManager);
  70271. }
  70272. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70273. {
  70274. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70275. state.getProperty (topRight, "100, 0"),
  70276. state.getProperty (bottomLeft, "0, 100"));
  70277. }
  70278. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70279. {
  70280. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70281. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70282. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70283. }
  70284. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70285. {
  70286. const ValueTreeWrapper controller (tree);
  70287. setName (controller.getID());
  70288. const float newOpacity = controller.getOpacity();
  70289. const Colour newOverlayColour (controller.getOverlayColour());
  70290. Image newImage;
  70291. const var imageIdentifier (controller.getImageIdentifier());
  70292. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70293. if (imageProvider != 0)
  70294. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70295. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70296. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage)
  70297. {
  70298. repaint();
  70299. opacity = newOpacity;
  70300. overlayColour = newOverlayColour;
  70301. bounds = newBounds;
  70302. setImage (newImage);
  70303. }
  70304. }
  70305. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70306. {
  70307. ValueTree tree (valueTreeType);
  70308. ValueTreeWrapper v (tree);
  70309. v.setID (getName(), 0);
  70310. v.setOpacity (opacity, 0);
  70311. v.setOverlayColour (overlayColour, 0);
  70312. v.setBoundingBox (bounds, 0);
  70313. if (image.isValid())
  70314. {
  70315. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70316. if (imageProvider != 0)
  70317. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70318. }
  70319. return tree;
  70320. }
  70321. END_JUCE_NAMESPACE
  70322. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70323. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70324. BEGIN_JUCE_NAMESPACE
  70325. DrawablePath::DrawablePath()
  70326. {
  70327. }
  70328. DrawablePath::DrawablePath (const DrawablePath& other)
  70329. : DrawableShape (other)
  70330. {
  70331. if (other.relativePath != 0)
  70332. relativePath = new RelativePointPath (*other.relativePath);
  70333. else
  70334. setPath (other.path);
  70335. }
  70336. DrawablePath::~DrawablePath()
  70337. {
  70338. }
  70339. Drawable* DrawablePath::createCopy() const
  70340. {
  70341. return new DrawablePath (*this);
  70342. }
  70343. void DrawablePath::setPath (const Path& newPath)
  70344. {
  70345. path = newPath;
  70346. pathChanged();
  70347. }
  70348. const Path& DrawablePath::getPath() const
  70349. {
  70350. return path;
  70351. }
  70352. const Path& DrawablePath::getStrokePath() const
  70353. {
  70354. return strokePath;
  70355. }
  70356. bool DrawablePath::rebuildPath (Path& path) const
  70357. {
  70358. if (relativePath != 0)
  70359. {
  70360. path.clear();
  70361. relativePath->createPath (path, getParent());
  70362. return true;
  70363. }
  70364. return false;
  70365. }
  70366. const Identifier DrawablePath::valueTreeType ("Path");
  70367. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70368. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70369. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70370. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70371. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70372. : FillAndStrokeState (state_)
  70373. {
  70374. jassert (state.hasType (valueTreeType));
  70375. }
  70376. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70377. {
  70378. return state.getOrCreateChildWithName (path, 0);
  70379. }
  70380. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70381. {
  70382. return state [nonZeroWinding];
  70383. }
  70384. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70385. {
  70386. state.setProperty (nonZeroWinding, b, undoManager);
  70387. }
  70388. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70389. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70390. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70391. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70392. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70393. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70394. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70395. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70396. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70397. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70398. : state (state_)
  70399. {
  70400. }
  70401. DrawablePath::ValueTreeWrapper::Element::~Element()
  70402. {
  70403. }
  70404. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70405. {
  70406. return ValueTreeWrapper (state.getParent().getParent());
  70407. }
  70408. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70409. {
  70410. return Element (state.getSibling (-1));
  70411. }
  70412. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70413. {
  70414. const Identifier i (state.getType());
  70415. if (i == startSubPathElement || i == lineToElement) return 1;
  70416. if (i == quadraticToElement) return 2;
  70417. if (i == cubicToElement) return 3;
  70418. return 0;
  70419. }
  70420. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70421. {
  70422. jassert (index >= 0 && index < getNumControlPoints());
  70423. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70424. }
  70425. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70426. {
  70427. jassert (index >= 0 && index < getNumControlPoints());
  70428. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70429. }
  70430. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70431. {
  70432. jassert (index >= 0 && index < getNumControlPoints());
  70433. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70434. }
  70435. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70436. {
  70437. const Identifier i (state.getType());
  70438. if (i == startSubPathElement)
  70439. return getControlPoint (0);
  70440. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70441. return getPreviousElement().getEndPoint();
  70442. }
  70443. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70444. {
  70445. const Identifier i (state.getType());
  70446. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70447. if (i == quadraticToElement) return getControlPoint (1);
  70448. if (i == cubicToElement) return getControlPoint (2);
  70449. jassert (i == closeSubPathElement);
  70450. return RelativePoint();
  70451. }
  70452. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70453. {
  70454. const Identifier i (state.getType());
  70455. if (i == lineToElement || i == closeSubPathElement)
  70456. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70457. if (i == cubicToElement)
  70458. {
  70459. Path p;
  70460. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70461. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70462. return p.getLength();
  70463. }
  70464. if (i == quadraticToElement)
  70465. {
  70466. Path p;
  70467. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70468. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70469. return p.getLength();
  70470. }
  70471. jassert (i == startSubPathElement);
  70472. return 0;
  70473. }
  70474. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70475. {
  70476. return state [mode].toString();
  70477. }
  70478. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70479. {
  70480. if (state.hasType (cubicToElement))
  70481. state.setProperty (mode, newMode, undoManager);
  70482. }
  70483. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70484. {
  70485. const Identifier i (state.getType());
  70486. if (i == quadraticToElement || i == cubicToElement)
  70487. {
  70488. ValueTree newState (lineToElement);
  70489. Element e (newState);
  70490. e.setControlPoint (0, getEndPoint(), undoManager);
  70491. state = newState;
  70492. }
  70493. }
  70494. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70495. {
  70496. const Identifier i (state.getType());
  70497. if (i == lineToElement || i == quadraticToElement)
  70498. {
  70499. ValueTree newState (cubicToElement);
  70500. Element e (newState);
  70501. const RelativePoint start (getStartPoint());
  70502. const RelativePoint end (getEndPoint());
  70503. const Point<float> startResolved (start.resolve (nameFinder));
  70504. const Point<float> endResolved (end.resolve (nameFinder));
  70505. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70506. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70507. e.setControlPoint (2, end, undoManager);
  70508. state = newState;
  70509. }
  70510. }
  70511. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70512. {
  70513. const Identifier i (state.getType());
  70514. if (i != startSubPathElement)
  70515. {
  70516. ValueTree newState (startSubPathElement);
  70517. Element e (newState);
  70518. e.setControlPoint (0, getEndPoint(), undoManager);
  70519. state = newState;
  70520. }
  70521. }
  70522. namespace DrawablePathHelpers
  70523. {
  70524. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70525. {
  70526. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70527. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70528. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70529. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70530. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70531. return newCp1 + (newCp2 - newCp1) * proportion;
  70532. }
  70533. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70534. {
  70535. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70536. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70537. return mid1 + (mid2 - mid1) * proportion;
  70538. }
  70539. }
  70540. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70541. {
  70542. using namespace DrawablePathHelpers;
  70543. const Identifier i (state.getType());
  70544. float bestProp = 0;
  70545. if (i == cubicToElement)
  70546. {
  70547. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70548. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70549. float bestDistance = std::numeric_limits<float>::max();
  70550. for (int i = 110; --i >= 0;)
  70551. {
  70552. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70553. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70554. const float distance = centre.getDistanceFrom (targetPoint);
  70555. if (distance < bestDistance)
  70556. {
  70557. bestProp = prop;
  70558. bestDistance = distance;
  70559. }
  70560. }
  70561. }
  70562. else if (i == quadraticToElement)
  70563. {
  70564. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70565. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70566. float bestDistance = std::numeric_limits<float>::max();
  70567. for (int i = 110; --i >= 0;)
  70568. {
  70569. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70570. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70571. const float distance = centre.getDistanceFrom (targetPoint);
  70572. if (distance < bestDistance)
  70573. {
  70574. bestProp = prop;
  70575. bestDistance = distance;
  70576. }
  70577. }
  70578. }
  70579. else if (i == lineToElement)
  70580. {
  70581. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70582. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70583. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70584. }
  70585. return bestProp;
  70586. }
  70587. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70588. {
  70589. ValueTree newTree;
  70590. const Identifier i (state.getType());
  70591. if (i == cubicToElement)
  70592. {
  70593. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70594. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70595. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70596. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70597. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70598. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70599. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70600. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70601. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70602. setControlPoint (0, mid1, undoManager);
  70603. setControlPoint (1, newCp1, undoManager);
  70604. setControlPoint (2, newCentre, undoManager);
  70605. setModeOfEndPoint (roundedMode, undoManager);
  70606. Element newElement (newTree = ValueTree (cubicToElement));
  70607. newElement.setControlPoint (0, newCp2, 0);
  70608. newElement.setControlPoint (1, mid3, 0);
  70609. newElement.setControlPoint (2, rp4, 0);
  70610. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70611. }
  70612. else if (i == quadraticToElement)
  70613. {
  70614. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70615. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70616. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70617. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70618. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70619. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70620. setControlPoint (0, mid1, undoManager);
  70621. setControlPoint (1, newCentre, undoManager);
  70622. setModeOfEndPoint (roundedMode, undoManager);
  70623. Element newElement (newTree = ValueTree (quadraticToElement));
  70624. newElement.setControlPoint (0, mid2, 0);
  70625. newElement.setControlPoint (1, rp3, 0);
  70626. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70627. }
  70628. else if (i == lineToElement)
  70629. {
  70630. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70631. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70632. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70633. setControlPoint (0, newPoint, undoManager);
  70634. Element newElement (newTree = ValueTree (lineToElement));
  70635. newElement.setControlPoint (0, rp2, 0);
  70636. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70637. }
  70638. else if (i == closeSubPathElement)
  70639. {
  70640. }
  70641. return newTree;
  70642. }
  70643. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70644. {
  70645. state.getParent().removeChild (state, undoManager);
  70646. }
  70647. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70648. {
  70649. ValueTreeWrapper v (tree);
  70650. setName (v.getID());
  70651. if (refreshFillTypes (v, getParent(), imageProvider))
  70652. repaint();
  70653. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70654. Path newPath;
  70655. newRelativePath->createPath (newPath, getParent());
  70656. if (! newRelativePath->containsAnyDynamicPoints())
  70657. newRelativePath = 0;
  70658. const PathStrokeType newStroke (v.getStrokeType());
  70659. if (strokeType != newStroke || path != newPath)
  70660. {
  70661. path.swapWithPath (newPath);
  70662. strokeType = newStroke;
  70663. pathChanged();
  70664. }
  70665. relativePath = newRelativePath;
  70666. }
  70667. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70668. {
  70669. ValueTree tree (valueTreeType);
  70670. ValueTreeWrapper v (tree);
  70671. v.setID (getName(), 0);
  70672. writeTo (v, imageProvider, 0);
  70673. if (relativePath != 0)
  70674. {
  70675. relativePath->writeTo (tree, 0);
  70676. }
  70677. else
  70678. {
  70679. RelativePointPath rp (path);
  70680. rp.writeTo (tree, 0);
  70681. }
  70682. return tree;
  70683. }
  70684. END_JUCE_NAMESPACE
  70685. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70686. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70687. BEGIN_JUCE_NAMESPACE
  70688. DrawableRectangle::DrawableRectangle()
  70689. {
  70690. }
  70691. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70692. : DrawableShape (other)
  70693. {
  70694. }
  70695. DrawableRectangle::~DrawableRectangle()
  70696. {
  70697. }
  70698. Drawable* DrawableRectangle::createCopy() const
  70699. {
  70700. return new DrawableRectangle (*this);
  70701. }
  70702. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70703. {
  70704. bounds = newBounds;
  70705. pathChanged();
  70706. strokeChanged();
  70707. }
  70708. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70709. {
  70710. cornerSize = newSize;
  70711. pathChanged();
  70712. strokeChanged();
  70713. }
  70714. bool DrawableRectangle::rebuildPath (Path& path) const
  70715. {
  70716. Point<float> points[3];
  70717. bounds.resolveThreePoints (points, getParent());
  70718. const float w = Line<float> (points[0], points[1]).getLength();
  70719. const float h = Line<float> (points[0], points[2]).getLength();
  70720. const float cornerSizeX = (float) cornerSize.x.resolve (getParent());
  70721. const float cornerSizeY = (float) cornerSize.y.resolve (getParent());
  70722. path.clear();
  70723. if (cornerSizeX > 0 && cornerSizeY > 0)
  70724. path.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70725. else
  70726. path.addRectangle (0, 0, w, h);
  70727. path.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70728. w, 0, points[1].getX(), points[1].getY(),
  70729. 0, h, points[2].getX(), points[2].getY()));
  70730. return true;
  70731. }
  70732. const AffineTransform DrawableRectangle::calculateTransform() const
  70733. {
  70734. Point<float> resolved[3];
  70735. bounds.resolveThreePoints (resolved, getParent());
  70736. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70737. resolved[1].getX(), resolved[1].getY(),
  70738. resolved[2].getX(), resolved[2].getY());
  70739. }
  70740. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70741. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70742. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70743. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70744. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70745. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70746. : FillAndStrokeState (state_)
  70747. {
  70748. jassert (state.hasType (valueTreeType));
  70749. }
  70750. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70751. {
  70752. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70753. state.getProperty (topRight, "100, 0"),
  70754. state.getProperty (bottomLeft, "0, 100"));
  70755. }
  70756. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70757. {
  70758. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70759. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70760. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70761. }
  70762. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70763. {
  70764. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70765. }
  70766. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70767. {
  70768. return RelativePoint (state [cornerSize]);
  70769. }
  70770. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70771. {
  70772. return state.getPropertyAsValue (cornerSize, undoManager);
  70773. }
  70774. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70775. {
  70776. ValueTreeWrapper v (tree);
  70777. setName (v.getID());
  70778. if (refreshFillTypes (v, getParent(), imageProvider))
  70779. repaint();
  70780. RelativeParallelogram newBounds (v.getRectangle());
  70781. const PathStrokeType newStroke (v.getStrokeType());
  70782. const RelativePoint newCornerSize (v.getCornerSize());
  70783. if (strokeType != newStroke || newBounds != bounds || newCornerSize != cornerSize)
  70784. {
  70785. repaint();
  70786. bounds = newBounds;
  70787. strokeType = newStroke;
  70788. cornerSize = newCornerSize;
  70789. pathChanged();
  70790. }
  70791. }
  70792. const ValueTree DrawableRectangle::createValueTree (ImageProvider* imageProvider) const
  70793. {
  70794. ValueTree tree (valueTreeType);
  70795. ValueTreeWrapper v (tree);
  70796. v.setID (getName(), 0);
  70797. writeTo (v, imageProvider, 0);
  70798. v.setRectangle (bounds, 0);
  70799. v.setCornerSize (cornerSize, 0);
  70800. return tree;
  70801. }
  70802. END_JUCE_NAMESPACE
  70803. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  70804. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70805. BEGIN_JUCE_NAMESPACE
  70806. DrawableText::DrawableText()
  70807. : colour (Colours::black),
  70808. justification (Justification::centredLeft)
  70809. {
  70810. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70811. RelativePoint (50.0f, 0.0f),
  70812. RelativePoint (0.0f, 20.0f)));
  70813. setFont (Font (15.0f), true);
  70814. }
  70815. DrawableText::DrawableText (const DrawableText& other)
  70816. : bounds (other.bounds),
  70817. fontSizeControlPoint (other.fontSizeControlPoint),
  70818. font (other.font),
  70819. text (other.text),
  70820. colour (other.colour),
  70821. justification (other.justification)
  70822. {
  70823. }
  70824. DrawableText::~DrawableText()
  70825. {
  70826. }
  70827. void DrawableText::refreshBounds()
  70828. {
  70829. setBoundsToEnclose (getDrawableBounds());
  70830. repaint();
  70831. }
  70832. void DrawableText::setText (const String& newText)
  70833. {
  70834. text = newText;
  70835. refreshBounds();
  70836. }
  70837. void DrawableText::setColour (const Colour& newColour)
  70838. {
  70839. colour = newColour;
  70840. repaint();
  70841. }
  70842. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70843. {
  70844. font = newFont;
  70845. if (applySizeAndScale)
  70846. {
  70847. Point<float> corners[3];
  70848. bounds.resolveThreePoints (corners, getParent());
  70849. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70850. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70851. }
  70852. refreshBounds();
  70853. }
  70854. void DrawableText::setJustification (const Justification& newJustification)
  70855. {
  70856. justification = newJustification;
  70857. repaint();
  70858. }
  70859. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70860. {
  70861. bounds = newBounds;
  70862. refreshBounds();
  70863. }
  70864. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70865. {
  70866. fontSizeControlPoint = newPoint;
  70867. refreshBounds();
  70868. }
  70869. void DrawableText::paint (Graphics& g)
  70870. {
  70871. transformContextToCorrectOrigin (g);
  70872. Point<float> points[3];
  70873. bounds.resolveThreePoints (points, getParent());
  70874. const float w = Line<float> (points[0], points[1]).getLength();
  70875. const float h = Line<float> (points[0], points[2]).getLength();
  70876. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (getParent())));
  70877. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  70878. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  70879. Font f (font);
  70880. f.setHeight (fontHeight);
  70881. f.setHorizontalScale (fontWidth / fontHeight);
  70882. g.setColour (colour);
  70883. GlyphArrangement ga;
  70884. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70885. ga.draw (g, AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70886. w, 0, points[1].getX(), points[1].getY(),
  70887. 0, h, points[2].getX(), points[2].getY()));
  70888. }
  70889. const Rectangle<float> DrawableText::getDrawableBounds() const
  70890. {
  70891. return bounds.getBounds (getParent());
  70892. }
  70893. Drawable* DrawableText::createCopy() const
  70894. {
  70895. return new DrawableText (*this);
  70896. }
  70897. const Identifier DrawableText::valueTreeType ("Text");
  70898. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70899. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70900. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70901. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70902. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70903. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70904. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70905. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70906. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70907. : ValueTreeWrapperBase (state_)
  70908. {
  70909. jassert (state.hasType (valueTreeType));
  70910. }
  70911. const String DrawableText::ValueTreeWrapper::getText() const
  70912. {
  70913. return state [text].toString();
  70914. }
  70915. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70916. {
  70917. state.setProperty (text, newText, undoManager);
  70918. }
  70919. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70920. {
  70921. return state.getPropertyAsValue (text, undoManager);
  70922. }
  70923. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70924. {
  70925. return Colour::fromString (state [colour].toString());
  70926. }
  70927. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70928. {
  70929. state.setProperty (colour, newColour.toString(), undoManager);
  70930. }
  70931. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70932. {
  70933. return Justification ((int) state [justification]);
  70934. }
  70935. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  70936. {
  70937. state.setProperty (justification, newJustification.getFlags(), undoManager);
  70938. }
  70939. const Font DrawableText::ValueTreeWrapper::getFont() const
  70940. {
  70941. return Font::fromString (state [font]);
  70942. }
  70943. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  70944. {
  70945. state.setProperty (font, newFont.toString(), undoManager);
  70946. }
  70947. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  70948. {
  70949. return state.getPropertyAsValue (font, undoManager);
  70950. }
  70951. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  70952. {
  70953. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  70954. }
  70955. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70956. {
  70957. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70958. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70959. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70960. }
  70961. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  70962. {
  70963. return state [fontSizeAnchor].toString();
  70964. }
  70965. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  70966. {
  70967. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  70968. }
  70969. void DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  70970. {
  70971. ValueTreeWrapper v (tree);
  70972. setName (v.getID());
  70973. const RelativeParallelogram newBounds (v.getBoundingBox());
  70974. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  70975. const Colour newColour (v.getColour());
  70976. const Justification newJustification (v.getJustification());
  70977. const String newText (v.getText());
  70978. const Font newFont (v.getFont());
  70979. if (text != newText || font != newFont || justification != newJustification
  70980. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  70981. {
  70982. repaint();
  70983. setBoundingBox (newBounds);
  70984. setFontSizeControlPoint (newFontPoint);
  70985. setColour (newColour);
  70986. setFont (newFont, false);
  70987. setJustification (newJustification);
  70988. setText (newText);
  70989. }
  70990. }
  70991. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  70992. {
  70993. ValueTree tree (valueTreeType);
  70994. ValueTreeWrapper v (tree);
  70995. v.setID (getName(), 0);
  70996. v.setText (text, 0);
  70997. v.setFont (font, 0);
  70998. v.setJustification (justification, 0);
  70999. v.setColour (colour, 0);
  71000. v.setBoundingBox (bounds, 0);
  71001. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71002. return tree;
  71003. }
  71004. END_JUCE_NAMESPACE
  71005. /*** End of inlined file: juce_DrawableText.cpp ***/
  71006. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71007. BEGIN_JUCE_NAMESPACE
  71008. class SVGState
  71009. {
  71010. public:
  71011. SVGState (const XmlElement* const topLevel)
  71012. : topLevelXml (topLevel),
  71013. elementX (0), elementY (0),
  71014. width (512), height (512),
  71015. viewBoxW (0), viewBoxH (0)
  71016. {
  71017. }
  71018. ~SVGState()
  71019. {
  71020. }
  71021. Drawable* parseSVGElement (const XmlElement& xml)
  71022. {
  71023. if (! xml.hasTagName ("svg"))
  71024. return 0;
  71025. DrawableComposite* const drawable = new DrawableComposite();
  71026. drawable->setName (xml.getStringAttribute ("id"));
  71027. SVGState newState (*this);
  71028. if (xml.hasAttribute ("transform"))
  71029. newState.addTransform (xml);
  71030. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71031. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71032. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71033. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71034. if (xml.hasAttribute ("viewBox"))
  71035. {
  71036. const String viewParams (xml.getStringAttribute ("viewBox"));
  71037. int i = 0;
  71038. float vx, vy, vw, vh;
  71039. if (parseCoords (viewParams, vx, vy, i, true)
  71040. && parseCoords (viewParams, vw, vh, i, true)
  71041. && vw > 0
  71042. && vh > 0)
  71043. {
  71044. newState.viewBoxW = vw;
  71045. newState.viewBoxH = vh;
  71046. int placementFlags = 0;
  71047. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71048. if (aspect.containsIgnoreCase ("none"))
  71049. {
  71050. placementFlags = RectanglePlacement::stretchToFit;
  71051. }
  71052. else
  71053. {
  71054. if (aspect.containsIgnoreCase ("slice"))
  71055. placementFlags |= RectanglePlacement::fillDestination;
  71056. if (aspect.containsIgnoreCase ("xMin"))
  71057. placementFlags |= RectanglePlacement::xLeft;
  71058. else if (aspect.containsIgnoreCase ("xMax"))
  71059. placementFlags |= RectanglePlacement::xRight;
  71060. else
  71061. placementFlags |= RectanglePlacement::xMid;
  71062. if (aspect.containsIgnoreCase ("yMin"))
  71063. placementFlags |= RectanglePlacement::yTop;
  71064. else if (aspect.containsIgnoreCase ("yMax"))
  71065. placementFlags |= RectanglePlacement::yBottom;
  71066. else
  71067. placementFlags |= RectanglePlacement::yMid;
  71068. }
  71069. const RectanglePlacement placement (placementFlags);
  71070. newState.transform
  71071. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71072. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71073. .followedBy (newState.transform);
  71074. }
  71075. }
  71076. else
  71077. {
  71078. if (viewBoxW == 0)
  71079. newState.viewBoxW = newState.width;
  71080. if (viewBoxH == 0)
  71081. newState.viewBoxH = newState.height;
  71082. }
  71083. newState.parseSubElements (xml, drawable);
  71084. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71085. return drawable;
  71086. }
  71087. private:
  71088. const XmlElement* const topLevelXml;
  71089. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71090. AffineTransform transform;
  71091. String cssStyleText;
  71092. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71093. {
  71094. forEachXmlChildElement (xml, e)
  71095. {
  71096. Drawable* d = 0;
  71097. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71098. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71099. else if (e->hasTagName ("path")) d = parsePath (*e);
  71100. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71101. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71102. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71103. else if (e->hasTagName ("line")) d = parseLine (*e);
  71104. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71105. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71106. else if (e->hasTagName ("text")) d = parseText (*e);
  71107. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71108. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71109. parentDrawable->insertDrawable (d);
  71110. }
  71111. }
  71112. DrawableComposite* parseSwitch (const XmlElement& xml)
  71113. {
  71114. const XmlElement* const group = xml.getChildByName ("g");
  71115. if (group != 0)
  71116. return parseGroupElement (*group);
  71117. return 0;
  71118. }
  71119. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71120. {
  71121. DrawableComposite* const drawable = new DrawableComposite();
  71122. drawable->setName (xml.getStringAttribute ("id"));
  71123. if (xml.hasAttribute ("transform"))
  71124. {
  71125. SVGState newState (*this);
  71126. newState.addTransform (xml);
  71127. newState.parseSubElements (xml, drawable);
  71128. }
  71129. else
  71130. {
  71131. parseSubElements (xml, drawable);
  71132. }
  71133. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71134. return drawable;
  71135. }
  71136. Drawable* parsePath (const XmlElement& xml) const
  71137. {
  71138. const String d (xml.getStringAttribute ("d").trimStart());
  71139. Path path;
  71140. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71141. path.setUsingNonZeroWinding (false);
  71142. int index = 0;
  71143. float lastX = 0, lastY = 0;
  71144. float lastX2 = 0, lastY2 = 0;
  71145. juce_wchar lastCommandChar = 0;
  71146. bool isRelative = true;
  71147. bool carryOn = true;
  71148. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71149. while (d[index] != 0)
  71150. {
  71151. float x, y, x2, y2, x3, y3;
  71152. if (validCommandChars.containsChar (d[index]))
  71153. {
  71154. lastCommandChar = d [index++];
  71155. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71156. }
  71157. switch (lastCommandChar)
  71158. {
  71159. case 'M':
  71160. case 'm':
  71161. case 'L':
  71162. case 'l':
  71163. if (parseCoords (d, x, y, index, false))
  71164. {
  71165. if (isRelative)
  71166. {
  71167. x += lastX;
  71168. y += lastY;
  71169. }
  71170. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71171. {
  71172. path.startNewSubPath (x, y);
  71173. lastCommandChar = 'l';
  71174. }
  71175. else
  71176. path.lineTo (x, y);
  71177. lastX2 = lastX;
  71178. lastY2 = lastY;
  71179. lastX = x;
  71180. lastY = y;
  71181. }
  71182. else
  71183. {
  71184. ++index;
  71185. }
  71186. break;
  71187. case 'H':
  71188. case 'h':
  71189. if (parseCoord (d, x, index, false, true))
  71190. {
  71191. if (isRelative)
  71192. x += lastX;
  71193. path.lineTo (x, lastY);
  71194. lastX2 = lastX;
  71195. lastX = x;
  71196. }
  71197. else
  71198. {
  71199. ++index;
  71200. }
  71201. break;
  71202. case 'V':
  71203. case 'v':
  71204. if (parseCoord (d, y, index, false, false))
  71205. {
  71206. if (isRelative)
  71207. y += lastY;
  71208. path.lineTo (lastX, y);
  71209. lastY2 = lastY;
  71210. lastY = y;
  71211. }
  71212. else
  71213. {
  71214. ++index;
  71215. }
  71216. break;
  71217. case 'C':
  71218. case 'c':
  71219. if (parseCoords (d, x, y, index, false)
  71220. && parseCoords (d, x2, y2, index, false)
  71221. && parseCoords (d, x3, y3, index, false))
  71222. {
  71223. if (isRelative)
  71224. {
  71225. x += lastX;
  71226. y += lastY;
  71227. x2 += lastX;
  71228. y2 += lastY;
  71229. x3 += lastX;
  71230. y3 += lastY;
  71231. }
  71232. path.cubicTo (x, y, x2, y2, x3, y3);
  71233. lastX2 = x2;
  71234. lastY2 = y2;
  71235. lastX = x3;
  71236. lastY = y3;
  71237. }
  71238. else
  71239. {
  71240. ++index;
  71241. }
  71242. break;
  71243. case 'S':
  71244. case 's':
  71245. if (parseCoords (d, x, y, index, false)
  71246. && parseCoords (d, x3, y3, index, false))
  71247. {
  71248. if (isRelative)
  71249. {
  71250. x += lastX;
  71251. y += lastY;
  71252. x3 += lastX;
  71253. y3 += lastY;
  71254. }
  71255. x2 = lastX + (lastX - lastX2);
  71256. y2 = lastY + (lastY - lastY2);
  71257. path.cubicTo (x2, y2, x, y, x3, y3);
  71258. lastX2 = x;
  71259. lastY2 = y;
  71260. lastX = x3;
  71261. lastY = y3;
  71262. }
  71263. else
  71264. {
  71265. ++index;
  71266. }
  71267. break;
  71268. case 'Q':
  71269. case 'q':
  71270. if (parseCoords (d, x, y, index, false)
  71271. && parseCoords (d, x2, y2, index, false))
  71272. {
  71273. if (isRelative)
  71274. {
  71275. x += lastX;
  71276. y += lastY;
  71277. x2 += lastX;
  71278. y2 += lastY;
  71279. }
  71280. path.quadraticTo (x, y, x2, y2);
  71281. lastX2 = x;
  71282. lastY2 = y;
  71283. lastX = x2;
  71284. lastY = y2;
  71285. }
  71286. else
  71287. {
  71288. ++index;
  71289. }
  71290. break;
  71291. case 'T':
  71292. case 't':
  71293. if (parseCoords (d, x, y, index, false))
  71294. {
  71295. if (isRelative)
  71296. {
  71297. x += lastX;
  71298. y += lastY;
  71299. }
  71300. x2 = lastX + (lastX - lastX2);
  71301. y2 = lastY + (lastY - lastY2);
  71302. path.quadraticTo (x2, y2, x, y);
  71303. lastX2 = x2;
  71304. lastY2 = y2;
  71305. lastX = x;
  71306. lastY = y;
  71307. }
  71308. else
  71309. {
  71310. ++index;
  71311. }
  71312. break;
  71313. case 'A':
  71314. case 'a':
  71315. if (parseCoords (d, x, y, index, false))
  71316. {
  71317. String num;
  71318. if (parseNextNumber (d, num, index, false))
  71319. {
  71320. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71321. if (parseNextNumber (d, num, index, false))
  71322. {
  71323. const bool largeArc = num.getIntValue() != 0;
  71324. if (parseNextNumber (d, num, index, false))
  71325. {
  71326. const bool sweep = num.getIntValue() != 0;
  71327. if (parseCoords (d, x2, y2, index, false))
  71328. {
  71329. if (isRelative)
  71330. {
  71331. x2 += lastX;
  71332. y2 += lastY;
  71333. }
  71334. if (lastX != x2 || lastY != y2)
  71335. {
  71336. double centreX, centreY, startAngle, deltaAngle;
  71337. double rx = x, ry = y;
  71338. endpointToCentreParameters (lastX, lastY, x2, y2,
  71339. angle, largeArc, sweep,
  71340. rx, ry, centreX, centreY,
  71341. startAngle, deltaAngle);
  71342. path.addCentredArc ((float) centreX, (float) centreY,
  71343. (float) rx, (float) ry,
  71344. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71345. false);
  71346. path.lineTo (x2, y2);
  71347. }
  71348. lastX2 = lastX;
  71349. lastY2 = lastY;
  71350. lastX = x2;
  71351. lastY = y2;
  71352. }
  71353. }
  71354. }
  71355. }
  71356. }
  71357. else
  71358. {
  71359. ++index;
  71360. }
  71361. break;
  71362. case 'Z':
  71363. case 'z':
  71364. path.closeSubPath();
  71365. while (CharacterFunctions::isWhitespace (d [index]))
  71366. ++index;
  71367. break;
  71368. default:
  71369. carryOn = false;
  71370. break;
  71371. }
  71372. if (! carryOn)
  71373. break;
  71374. }
  71375. return parseShape (xml, path);
  71376. }
  71377. Drawable* parseRect (const XmlElement& xml) const
  71378. {
  71379. Path rect;
  71380. const bool hasRX = xml.hasAttribute ("rx");
  71381. const bool hasRY = xml.hasAttribute ("ry");
  71382. if (hasRX || hasRY)
  71383. {
  71384. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71385. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71386. if (! hasRX)
  71387. rx = ry;
  71388. else if (! hasRY)
  71389. ry = rx;
  71390. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71391. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71392. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71393. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71394. rx, ry);
  71395. }
  71396. else
  71397. {
  71398. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71399. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71400. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71401. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71402. }
  71403. return parseShape (xml, rect);
  71404. }
  71405. Drawable* parseCircle (const XmlElement& xml) const
  71406. {
  71407. Path circle;
  71408. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71409. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71410. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71411. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71412. return parseShape (xml, circle);
  71413. }
  71414. Drawable* parseEllipse (const XmlElement& xml) const
  71415. {
  71416. Path ellipse;
  71417. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71418. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71419. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71420. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71421. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71422. return parseShape (xml, ellipse);
  71423. }
  71424. Drawable* parseLine (const XmlElement& xml) const
  71425. {
  71426. Path line;
  71427. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71428. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71429. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71430. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71431. line.startNewSubPath (x1, y1);
  71432. line.lineTo (x2, y2);
  71433. return parseShape (xml, line);
  71434. }
  71435. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71436. {
  71437. const String points (xml.getStringAttribute ("points"));
  71438. Path path;
  71439. int index = 0;
  71440. float x, y;
  71441. if (parseCoords (points, x, y, index, true))
  71442. {
  71443. float firstX = x;
  71444. float firstY = y;
  71445. float lastX = 0, lastY = 0;
  71446. path.startNewSubPath (x, y);
  71447. while (parseCoords (points, x, y, index, true))
  71448. {
  71449. lastX = x;
  71450. lastY = y;
  71451. path.lineTo (x, y);
  71452. }
  71453. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71454. path.closeSubPath();
  71455. }
  71456. return parseShape (xml, path);
  71457. }
  71458. Drawable* parseShape (const XmlElement& xml, Path& path,
  71459. const bool shouldParseTransform = true) const
  71460. {
  71461. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71462. {
  71463. SVGState newState (*this);
  71464. newState.addTransform (xml);
  71465. return newState.parseShape (xml, path, false);
  71466. }
  71467. DrawablePath* dp = new DrawablePath();
  71468. dp->setName (xml.getStringAttribute ("id"));
  71469. dp->setFill (Colours::transparentBlack);
  71470. path.applyTransform (transform);
  71471. dp->setPath (path);
  71472. Path::Iterator iter (path);
  71473. bool containsClosedSubPath = false;
  71474. while (iter.next())
  71475. {
  71476. if (iter.elementType == Path::Iterator::closePath)
  71477. {
  71478. containsClosedSubPath = true;
  71479. break;
  71480. }
  71481. }
  71482. dp->setFill (getPathFillType (path,
  71483. getStyleAttribute (&xml, "fill"),
  71484. getStyleAttribute (&xml, "fill-opacity"),
  71485. getStyleAttribute (&xml, "opacity"),
  71486. containsClosedSubPath ? Colours::black
  71487. : Colours::transparentBlack));
  71488. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71489. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71490. {
  71491. dp->setStrokeFill (getPathFillType (path, strokeType,
  71492. getStyleAttribute (&xml, "stroke-opacity"),
  71493. getStyleAttribute (&xml, "opacity"),
  71494. Colours::transparentBlack));
  71495. dp->setStrokeType (getStrokeFor (&xml));
  71496. }
  71497. return dp;
  71498. }
  71499. const XmlElement* findLinkedElement (const XmlElement* e) const
  71500. {
  71501. const String id (e->getStringAttribute ("xlink:href"));
  71502. if (! id.startsWithChar ('#'))
  71503. return 0;
  71504. return findElementForId (topLevelXml, id.substring (1));
  71505. }
  71506. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71507. {
  71508. if (fillXml == 0)
  71509. return;
  71510. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71511. {
  71512. int index = 0;
  71513. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71514. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71515. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71516. double offset = e->getDoubleAttribute ("offset");
  71517. if (e->getStringAttribute ("offset").containsChar ('%'))
  71518. offset *= 0.01;
  71519. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71520. }
  71521. }
  71522. const FillType getPathFillType (const Path& path,
  71523. const String& fill,
  71524. const String& fillOpacity,
  71525. const String& overallOpacity,
  71526. const Colour& defaultColour) const
  71527. {
  71528. float opacity = 1.0f;
  71529. if (overallOpacity.isNotEmpty())
  71530. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71531. if (fillOpacity.isNotEmpty())
  71532. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71533. if (fill.startsWithIgnoreCase ("url"))
  71534. {
  71535. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71536. .upToLastOccurrenceOf (")", false, false).trim());
  71537. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71538. if (fillXml != 0
  71539. && (fillXml->hasTagName ("linearGradient")
  71540. || fillXml->hasTagName ("radialGradient")))
  71541. {
  71542. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71543. ColourGradient gradient;
  71544. addGradientStopsIn (gradient, inheritedFrom);
  71545. addGradientStopsIn (gradient, fillXml);
  71546. if (gradient.getNumColours() > 0)
  71547. {
  71548. gradient.addColour (0.0, gradient.getColour (0));
  71549. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71550. }
  71551. else
  71552. {
  71553. gradient.addColour (0.0, Colours::black);
  71554. gradient.addColour (1.0, Colours::black);
  71555. }
  71556. if (overallOpacity.isNotEmpty())
  71557. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71558. jassert (gradient.getNumColours() > 0);
  71559. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71560. float gradientWidth = viewBoxW;
  71561. float gradientHeight = viewBoxH;
  71562. float dx = 0.0f;
  71563. float dy = 0.0f;
  71564. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71565. if (! userSpace)
  71566. {
  71567. const Rectangle<float> bounds (path.getBounds());
  71568. dx = bounds.getX();
  71569. dy = bounds.getY();
  71570. gradientWidth = bounds.getWidth();
  71571. gradientHeight = bounds.getHeight();
  71572. }
  71573. if (gradient.isRadial)
  71574. {
  71575. if (userSpace)
  71576. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71577. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71578. else
  71579. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71580. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71581. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71582. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71583. //xxx (the fx, fy focal point isn't handled properly here..)
  71584. }
  71585. else
  71586. {
  71587. if (userSpace)
  71588. {
  71589. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71590. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71591. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71592. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71593. }
  71594. else
  71595. {
  71596. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71597. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71598. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71599. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71600. }
  71601. if (gradient.point1 == gradient.point2)
  71602. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71603. }
  71604. FillType type (gradient);
  71605. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71606. .followedBy (transform);
  71607. return type;
  71608. }
  71609. }
  71610. if (fill.equalsIgnoreCase ("none"))
  71611. return Colours::transparentBlack;
  71612. int i = 0;
  71613. const Colour colour (parseColour (fill, i, defaultColour));
  71614. return colour.withMultipliedAlpha (opacity);
  71615. }
  71616. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71617. {
  71618. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71619. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71620. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71621. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71622. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71623. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71624. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71625. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71626. if (join.equalsIgnoreCase ("round"))
  71627. joinStyle = PathStrokeType::curved;
  71628. else if (join.equalsIgnoreCase ("bevel"))
  71629. joinStyle = PathStrokeType::beveled;
  71630. if (cap.equalsIgnoreCase ("round"))
  71631. capStyle = PathStrokeType::rounded;
  71632. else if (cap.equalsIgnoreCase ("square"))
  71633. capStyle = PathStrokeType::square;
  71634. float ox = 0.0f, oy = 0.0f;
  71635. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71636. transform.transformPoints (ox, oy, x, y);
  71637. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  71638. joinStyle, capStyle);
  71639. }
  71640. Drawable* parseText (const XmlElement& xml)
  71641. {
  71642. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71643. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71644. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71645. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71646. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71647. //xxx not done text yet!
  71648. forEachXmlChildElement (xml, e)
  71649. {
  71650. if (e->isTextElement())
  71651. {
  71652. const String text (e->getText());
  71653. Path path;
  71654. Drawable* s = parseShape (*e, path);
  71655. delete s; // xxx not finished!
  71656. }
  71657. else if (e->hasTagName ("tspan"))
  71658. {
  71659. Drawable* s = parseText (*e);
  71660. delete s; // xxx not finished!
  71661. }
  71662. }
  71663. return 0;
  71664. }
  71665. void addTransform (const XmlElement& xml)
  71666. {
  71667. transform = parseTransform (xml.getStringAttribute ("transform"))
  71668. .followedBy (transform);
  71669. }
  71670. bool parseCoord (const String& s, float& value, int& index,
  71671. const bool allowUnits, const bool isX) const
  71672. {
  71673. String number;
  71674. if (! parseNextNumber (s, number, index, allowUnits))
  71675. {
  71676. value = 0;
  71677. return false;
  71678. }
  71679. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71680. return true;
  71681. }
  71682. bool parseCoords (const String& s, float& x, float& y,
  71683. int& index, const bool allowUnits) const
  71684. {
  71685. return parseCoord (s, x, index, allowUnits, true)
  71686. && parseCoord (s, y, index, allowUnits, false);
  71687. }
  71688. float getCoordLength (const String& s, const float sizeForProportions) const
  71689. {
  71690. float n = s.getFloatValue();
  71691. const int len = s.length();
  71692. if (len > 2)
  71693. {
  71694. const float dpi = 96.0f;
  71695. const juce_wchar n1 = s [len - 2];
  71696. const juce_wchar n2 = s [len - 1];
  71697. if (n1 == 'i' && n2 == 'n')
  71698. n *= dpi;
  71699. else if (n1 == 'm' && n2 == 'm')
  71700. n *= dpi / 25.4f;
  71701. else if (n1 == 'c' && n2 == 'm')
  71702. n *= dpi / 2.54f;
  71703. else if (n1 == 'p' && n2 == 'c')
  71704. n *= 15.0f;
  71705. else if (n2 == '%')
  71706. n *= 0.01f * sizeForProportions;
  71707. }
  71708. return n;
  71709. }
  71710. void getCoordList (Array <float>& coords, const String& list,
  71711. const bool allowUnits, const bool isX) const
  71712. {
  71713. int index = 0;
  71714. float value;
  71715. while (parseCoord (list, value, index, allowUnits, isX))
  71716. coords.add (value);
  71717. }
  71718. void parseCSSStyle (const XmlElement& xml)
  71719. {
  71720. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71721. }
  71722. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71723. const String& defaultValue = String::empty) const
  71724. {
  71725. if (xml->hasAttribute (attributeName))
  71726. return xml->getStringAttribute (attributeName, defaultValue);
  71727. const String styleAtt (xml->getStringAttribute ("style"));
  71728. if (styleAtt.isNotEmpty())
  71729. {
  71730. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71731. if (value.isNotEmpty())
  71732. return value;
  71733. }
  71734. else if (xml->hasAttribute ("class"))
  71735. {
  71736. const String className ("." + xml->getStringAttribute ("class"));
  71737. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71738. if (index < 0)
  71739. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71740. if (index >= 0)
  71741. {
  71742. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71743. if (openBracket > index)
  71744. {
  71745. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71746. if (closeBracket > openBracket)
  71747. {
  71748. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71749. if (value.isNotEmpty())
  71750. return value;
  71751. }
  71752. }
  71753. }
  71754. }
  71755. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71756. if (xml != 0)
  71757. return getStyleAttribute (xml, attributeName, defaultValue);
  71758. return defaultValue;
  71759. }
  71760. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71761. {
  71762. if (xml->hasAttribute (attributeName))
  71763. return xml->getStringAttribute (attributeName);
  71764. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71765. if (xml != 0)
  71766. return getInheritedAttribute (xml, attributeName);
  71767. return String::empty;
  71768. }
  71769. static bool isIdentifierChar (const juce_wchar c)
  71770. {
  71771. return CharacterFunctions::isLetter (c) || c == '-';
  71772. }
  71773. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71774. {
  71775. int i = 0;
  71776. for (;;)
  71777. {
  71778. i = list.indexOf (i, attributeName);
  71779. if (i < 0)
  71780. break;
  71781. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71782. && ! isIdentifierChar (list [i + attributeName.length()]))
  71783. {
  71784. i = list.indexOfChar (i, ':');
  71785. if (i < 0)
  71786. break;
  71787. int end = list.indexOfChar (i, ';');
  71788. if (end < 0)
  71789. end = 0x7ffff;
  71790. return list.substring (i + 1, end).trim();
  71791. }
  71792. ++i;
  71793. }
  71794. return defaultValue;
  71795. }
  71796. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71797. {
  71798. const juce_wchar* const s = source;
  71799. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71800. ++index;
  71801. int start = index;
  71802. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71803. ++index;
  71804. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71805. ++index;
  71806. if ((s[index] == 'e' || s[index] == 'E')
  71807. && (CharacterFunctions::isDigit (s[index + 1])
  71808. || s[index + 1] == '-'
  71809. || s[index + 1] == '+'))
  71810. {
  71811. index += 2;
  71812. while (CharacterFunctions::isDigit (s[index]))
  71813. ++index;
  71814. }
  71815. if (allowUnits)
  71816. {
  71817. while (CharacterFunctions::isLetter (s[index]))
  71818. ++index;
  71819. }
  71820. if (index == start)
  71821. return false;
  71822. value = String (s + start, index - start);
  71823. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71824. ++index;
  71825. return true;
  71826. }
  71827. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71828. {
  71829. if (s [index] == '#')
  71830. {
  71831. uint32 hex [6];
  71832. zeromem (hex, sizeof (hex));
  71833. int numChars = 0;
  71834. for (int i = 6; --i >= 0;)
  71835. {
  71836. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71837. if (hexValue >= 0)
  71838. hex [numChars++] = hexValue;
  71839. else
  71840. break;
  71841. }
  71842. if (numChars <= 3)
  71843. return Colour ((uint8) (hex [0] * 0x11),
  71844. (uint8) (hex [1] * 0x11),
  71845. (uint8) (hex [2] * 0x11));
  71846. else
  71847. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71848. (uint8) ((hex [2] << 4) + hex [3]),
  71849. (uint8) ((hex [4] << 4) + hex [5]));
  71850. }
  71851. else if (s [index] == 'r'
  71852. && s [index + 1] == 'g'
  71853. && s [index + 2] == 'b')
  71854. {
  71855. const int openBracket = s.indexOfChar (index, '(');
  71856. const int closeBracket = s.indexOfChar (openBracket, ')');
  71857. if (openBracket >= 3 && closeBracket > openBracket)
  71858. {
  71859. index = closeBracket;
  71860. StringArray tokens;
  71861. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71862. tokens.trim();
  71863. tokens.removeEmptyStrings();
  71864. if (tokens[0].containsChar ('%'))
  71865. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71866. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71867. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71868. else
  71869. return Colour ((uint8) tokens[0].getIntValue(),
  71870. (uint8) tokens[1].getIntValue(),
  71871. (uint8) tokens[2].getIntValue());
  71872. }
  71873. }
  71874. return Colours::findColourForName (s, defaultColour);
  71875. }
  71876. static const AffineTransform parseTransform (String t)
  71877. {
  71878. AffineTransform result;
  71879. while (t.isNotEmpty())
  71880. {
  71881. StringArray tokens;
  71882. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71883. .upToFirstOccurrenceOf (")", false, false),
  71884. ", ", String::empty);
  71885. tokens.removeEmptyStrings (true);
  71886. float numbers [6];
  71887. for (int i = 0; i < 6; ++i)
  71888. numbers[i] = tokens[i].getFloatValue();
  71889. AffineTransform trans;
  71890. if (t.startsWithIgnoreCase ("matrix"))
  71891. {
  71892. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71893. numbers[1], numbers[3], numbers[5]);
  71894. }
  71895. else if (t.startsWithIgnoreCase ("translate"))
  71896. {
  71897. jassert (tokens.size() == 2);
  71898. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71899. }
  71900. else if (t.startsWithIgnoreCase ("scale"))
  71901. {
  71902. if (tokens.size() == 1)
  71903. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71904. else
  71905. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71906. }
  71907. else if (t.startsWithIgnoreCase ("rotate"))
  71908. {
  71909. if (tokens.size() != 3)
  71910. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71911. else
  71912. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71913. numbers[1], numbers[2]);
  71914. }
  71915. else if (t.startsWithIgnoreCase ("skewX"))
  71916. {
  71917. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71918. 0.0f, 1.0f, 0.0f);
  71919. }
  71920. else if (t.startsWithIgnoreCase ("skewY"))
  71921. {
  71922. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71923. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71924. }
  71925. result = trans.followedBy (result);
  71926. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71927. }
  71928. return result;
  71929. }
  71930. static void endpointToCentreParameters (const double x1, const double y1,
  71931. const double x2, const double y2,
  71932. const double angle,
  71933. const bool largeArc, const bool sweep,
  71934. double& rx, double& ry,
  71935. double& centreX, double& centreY,
  71936. double& startAngle, double& deltaAngle)
  71937. {
  71938. const double midX = (x1 - x2) * 0.5;
  71939. const double midY = (y1 - y2) * 0.5;
  71940. const double cosAngle = cos (angle);
  71941. const double sinAngle = sin (angle);
  71942. const double xp = cosAngle * midX + sinAngle * midY;
  71943. const double yp = cosAngle * midY - sinAngle * midX;
  71944. const double xp2 = xp * xp;
  71945. const double yp2 = yp * yp;
  71946. double rx2 = rx * rx;
  71947. double ry2 = ry * ry;
  71948. const double s = (xp2 / rx2) + (yp2 / ry2);
  71949. double c;
  71950. if (s <= 1.0)
  71951. {
  71952. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  71953. / (( rx2 * yp2) + (ry2 * xp2))));
  71954. if (largeArc == sweep)
  71955. c = -c;
  71956. }
  71957. else
  71958. {
  71959. const double s2 = std::sqrt (s);
  71960. rx *= s2;
  71961. ry *= s2;
  71962. rx2 = rx * rx;
  71963. ry2 = ry * ry;
  71964. c = 0;
  71965. }
  71966. const double cpx = ((rx * yp) / ry) * c;
  71967. const double cpy = ((-ry * xp) / rx) * c;
  71968. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  71969. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  71970. const double ux = (xp - cpx) / rx;
  71971. const double uy = (yp - cpy) / ry;
  71972. const double vx = (-xp - cpx) / rx;
  71973. const double vy = (-yp - cpy) / ry;
  71974. const double length = juce_hypot (ux, uy);
  71975. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  71976. if (uy < 0)
  71977. startAngle = -startAngle;
  71978. startAngle += double_Pi * 0.5;
  71979. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  71980. / (length * juce_hypot (vx, vy))));
  71981. if ((ux * vy) - (uy * vx) < 0)
  71982. deltaAngle = -deltaAngle;
  71983. if (sweep)
  71984. {
  71985. if (deltaAngle < 0)
  71986. deltaAngle += double_Pi * 2.0;
  71987. }
  71988. else
  71989. {
  71990. if (deltaAngle > 0)
  71991. deltaAngle -= double_Pi * 2.0;
  71992. }
  71993. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  71994. }
  71995. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  71996. {
  71997. forEachXmlChildElement (*parent, e)
  71998. {
  71999. if (e->compareAttribute ("id", id))
  72000. return e;
  72001. const XmlElement* const found = findElementForId (e, id);
  72002. if (found != 0)
  72003. return found;
  72004. }
  72005. return 0;
  72006. }
  72007. SVGState& operator= (const SVGState&);
  72008. };
  72009. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72010. {
  72011. SVGState state (&svgDocument);
  72012. return state.parseSVGElement (svgDocument);
  72013. }
  72014. END_JUCE_NAMESPACE
  72015. /*** End of inlined file: juce_SVGParser.cpp ***/
  72016. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72017. BEGIN_JUCE_NAMESPACE
  72018. #if JUCE_MSVC && JUCE_DEBUG
  72019. #pragma optimize ("t", on)
  72020. #endif
  72021. DropShadowEffect::DropShadowEffect()
  72022. : offsetX (0),
  72023. offsetY (0),
  72024. radius (4),
  72025. opacity (0.6f)
  72026. {
  72027. }
  72028. DropShadowEffect::~DropShadowEffect()
  72029. {
  72030. }
  72031. void DropShadowEffect::setShadowProperties (const float newRadius,
  72032. const float newOpacity,
  72033. const int newShadowOffsetX,
  72034. const int newShadowOffsetY)
  72035. {
  72036. radius = jmax (1.1f, newRadius);
  72037. offsetX = newShadowOffsetX;
  72038. offsetY = newShadowOffsetY;
  72039. opacity = newOpacity;
  72040. }
  72041. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72042. {
  72043. const int w = image.getWidth();
  72044. const int h = image.getHeight();
  72045. Image shadowImage (Image::SingleChannel, w, h, false);
  72046. const Image::BitmapData srcData (image, false);
  72047. const Image::BitmapData destData (shadowImage, true);
  72048. const int filter = roundToInt (63.0f / radius);
  72049. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72050. for (int x = w; --x >= 0;)
  72051. {
  72052. int shadowAlpha = 0;
  72053. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72054. uint8* shadowPix = destData.data + x;
  72055. for (int y = h; --y >= 0;)
  72056. {
  72057. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72058. *shadowPix = (uint8) shadowAlpha;
  72059. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72060. shadowPix += destData.lineStride;
  72061. }
  72062. }
  72063. for (int y = h; --y >= 0;)
  72064. {
  72065. int shadowAlpha = 0;
  72066. uint8* shadowPix = destData.getLinePointer (y);
  72067. for (int x = w; --x >= 0;)
  72068. {
  72069. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72070. *shadowPix++ = (uint8) shadowAlpha;
  72071. }
  72072. }
  72073. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72074. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72075. g.setOpacity (alpha);
  72076. g.drawImageAt (image, 0, 0);
  72077. }
  72078. #if JUCE_MSVC && JUCE_DEBUG
  72079. #pragma optimize ("", on) // resets optimisations to the project defaults
  72080. #endif
  72081. END_JUCE_NAMESPACE
  72082. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72083. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72084. BEGIN_JUCE_NAMESPACE
  72085. GlowEffect::GlowEffect()
  72086. : radius (2.0f),
  72087. colour (Colours::white)
  72088. {
  72089. }
  72090. GlowEffect::~GlowEffect()
  72091. {
  72092. }
  72093. void GlowEffect::setGlowProperties (const float newRadius,
  72094. const Colour& newColour)
  72095. {
  72096. radius = newRadius;
  72097. colour = newColour;
  72098. }
  72099. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72100. {
  72101. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72102. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72103. blurKernel.createGaussianBlur (radius);
  72104. blurKernel.rescaleAllValues (radius);
  72105. blurKernel.applyToImage (temp, image, image.getBounds());
  72106. g.setColour (colour.withMultipliedAlpha (alpha));
  72107. g.drawImageAt (temp, 0, 0, true);
  72108. g.setOpacity (alpha);
  72109. g.drawImageAt (image, 0, 0, false);
  72110. }
  72111. END_JUCE_NAMESPACE
  72112. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72113. /*** Start of inlined file: juce_Font.cpp ***/
  72114. BEGIN_JUCE_NAMESPACE
  72115. namespace FontValues
  72116. {
  72117. float limitFontHeight (const float height) throw()
  72118. {
  72119. return jlimit (0.1f, 10000.0f, height);
  72120. }
  72121. const float defaultFontHeight = 14.0f;
  72122. String fallbackFont;
  72123. }
  72124. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72125. const float kerning_, const float ascent_, const int styleFlags_,
  72126. Typeface* const typeface_) throw()
  72127. : typefaceName (typefaceName_),
  72128. height (height_),
  72129. horizontalScale (horizontalScale_),
  72130. kerning (kerning_),
  72131. ascent (ascent_),
  72132. styleFlags (styleFlags_),
  72133. typeface (typeface_)
  72134. {
  72135. }
  72136. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72137. : typefaceName (other.typefaceName),
  72138. height (other.height),
  72139. horizontalScale (other.horizontalScale),
  72140. kerning (other.kerning),
  72141. ascent (other.ascent),
  72142. styleFlags (other.styleFlags),
  72143. typeface (other.typeface)
  72144. {
  72145. }
  72146. Font::Font()
  72147. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72148. 1.0f, 0, 0, Font::plain, 0))
  72149. {
  72150. }
  72151. Font::Font (const float fontHeight, const int styleFlags_)
  72152. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72153. 1.0f, 0, 0, styleFlags_, 0))
  72154. {
  72155. }
  72156. Font::Font (const String& typefaceName_,
  72157. const float fontHeight,
  72158. const int styleFlags_)
  72159. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72160. 1.0f, 0, 0, styleFlags_, 0))
  72161. {
  72162. }
  72163. Font::Font (const Font& other) throw()
  72164. : font (other.font)
  72165. {
  72166. }
  72167. Font& Font::operator= (const Font& other) throw()
  72168. {
  72169. font = other.font;
  72170. return *this;
  72171. }
  72172. Font::~Font() throw()
  72173. {
  72174. }
  72175. Font::Font (const Typeface::Ptr& typeface)
  72176. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72177. 1.0f, 0, 0, Font::plain, typeface))
  72178. {
  72179. }
  72180. bool Font::operator== (const Font& other) const throw()
  72181. {
  72182. return font == other.font
  72183. || (font->height == other.font->height
  72184. && font->styleFlags == other.font->styleFlags
  72185. && font->horizontalScale == other.font->horizontalScale
  72186. && font->kerning == other.font->kerning
  72187. && font->typefaceName == other.font->typefaceName);
  72188. }
  72189. bool Font::operator!= (const Font& other) const throw()
  72190. {
  72191. return ! operator== (other);
  72192. }
  72193. void Font::dupeInternalIfShared()
  72194. {
  72195. if (font->getReferenceCount() > 1)
  72196. font = new SharedFontInternal (*font);
  72197. }
  72198. const String Font::getDefaultSansSerifFontName()
  72199. {
  72200. static const String name ("<Sans-Serif>");
  72201. return name;
  72202. }
  72203. const String Font::getDefaultSerifFontName()
  72204. {
  72205. static const String name ("<Serif>");
  72206. return name;
  72207. }
  72208. const String Font::getDefaultMonospacedFontName()
  72209. {
  72210. static const String name ("<Monospaced>");
  72211. return name;
  72212. }
  72213. void Font::setTypefaceName (const String& faceName)
  72214. {
  72215. if (faceName != font->typefaceName)
  72216. {
  72217. dupeInternalIfShared();
  72218. font->typefaceName = faceName;
  72219. font->typeface = 0;
  72220. font->ascent = 0;
  72221. }
  72222. }
  72223. const String Font::getFallbackFontName()
  72224. {
  72225. return FontValues::fallbackFont;
  72226. }
  72227. void Font::setFallbackFontName (const String& name)
  72228. {
  72229. FontValues::fallbackFont = name;
  72230. }
  72231. void Font::setHeight (float newHeight)
  72232. {
  72233. newHeight = FontValues::limitFontHeight (newHeight);
  72234. if (font->height != newHeight)
  72235. {
  72236. dupeInternalIfShared();
  72237. font->height = newHeight;
  72238. }
  72239. }
  72240. void Font::setHeightWithoutChangingWidth (float newHeight)
  72241. {
  72242. newHeight = FontValues::limitFontHeight (newHeight);
  72243. if (font->height != newHeight)
  72244. {
  72245. dupeInternalIfShared();
  72246. font->horizontalScale *= (font->height / newHeight);
  72247. font->height = newHeight;
  72248. }
  72249. }
  72250. void Font::setStyleFlags (const int newFlags)
  72251. {
  72252. if (font->styleFlags != newFlags)
  72253. {
  72254. dupeInternalIfShared();
  72255. font->styleFlags = newFlags;
  72256. font->typeface = 0;
  72257. font->ascent = 0;
  72258. }
  72259. }
  72260. void Font::setSizeAndStyle (float newHeight,
  72261. const int newStyleFlags,
  72262. const float newHorizontalScale,
  72263. const float newKerningAmount)
  72264. {
  72265. newHeight = FontValues::limitFontHeight (newHeight);
  72266. if (font->height != newHeight
  72267. || font->horizontalScale != newHorizontalScale
  72268. || font->kerning != newKerningAmount)
  72269. {
  72270. dupeInternalIfShared();
  72271. font->height = newHeight;
  72272. font->horizontalScale = newHorizontalScale;
  72273. font->kerning = newKerningAmount;
  72274. }
  72275. setStyleFlags (newStyleFlags);
  72276. }
  72277. void Font::setHorizontalScale (const float scaleFactor)
  72278. {
  72279. dupeInternalIfShared();
  72280. font->horizontalScale = scaleFactor;
  72281. }
  72282. void Font::setExtraKerningFactor (const float extraKerning)
  72283. {
  72284. dupeInternalIfShared();
  72285. font->kerning = extraKerning;
  72286. }
  72287. void Font::setBold (const bool shouldBeBold)
  72288. {
  72289. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72290. : (font->styleFlags & ~bold));
  72291. }
  72292. const Font Font::boldened() const
  72293. {
  72294. Font f (*this);
  72295. f.setBold (true);
  72296. return f;
  72297. }
  72298. bool Font::isBold() const throw()
  72299. {
  72300. return (font->styleFlags & bold) != 0;
  72301. }
  72302. void Font::setItalic (const bool shouldBeItalic)
  72303. {
  72304. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72305. : (font->styleFlags & ~italic));
  72306. }
  72307. const Font Font::italicised() const
  72308. {
  72309. Font f (*this);
  72310. f.setItalic (true);
  72311. return f;
  72312. }
  72313. bool Font::isItalic() const throw()
  72314. {
  72315. return (font->styleFlags & italic) != 0;
  72316. }
  72317. void Font::setUnderline (const bool shouldBeUnderlined)
  72318. {
  72319. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72320. : (font->styleFlags & ~underlined));
  72321. }
  72322. bool Font::isUnderlined() const throw()
  72323. {
  72324. return (font->styleFlags & underlined) != 0;
  72325. }
  72326. float Font::getAscent() const
  72327. {
  72328. if (font->ascent == 0)
  72329. font->ascent = getTypeface()->getAscent();
  72330. return font->height * font->ascent;
  72331. }
  72332. float Font::getDescent() const
  72333. {
  72334. return font->height - getAscent();
  72335. }
  72336. int Font::getStringWidth (const String& text) const
  72337. {
  72338. return roundToInt (getStringWidthFloat (text));
  72339. }
  72340. float Font::getStringWidthFloat (const String& text) const
  72341. {
  72342. float w = getTypeface()->getStringWidth (text);
  72343. if (font->kerning != 0)
  72344. w += font->kerning * text.length();
  72345. return w * font->height * font->horizontalScale;
  72346. }
  72347. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72348. {
  72349. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72350. const float scale = font->height * font->horizontalScale;
  72351. const int num = xOffsets.size();
  72352. if (num > 0)
  72353. {
  72354. float* const x = &(xOffsets.getReference(0));
  72355. if (font->kerning != 0)
  72356. {
  72357. for (int i = 0; i < num; ++i)
  72358. x[i] = (x[i] + i * font->kerning) * scale;
  72359. }
  72360. else
  72361. {
  72362. for (int i = 0; i < num; ++i)
  72363. x[i] *= scale;
  72364. }
  72365. }
  72366. }
  72367. void Font::findFonts (Array<Font>& destArray)
  72368. {
  72369. const StringArray names (findAllTypefaceNames());
  72370. for (int i = 0; i < names.size(); ++i)
  72371. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72372. }
  72373. const String Font::toString() const
  72374. {
  72375. String s (getTypefaceName());
  72376. if (s == getDefaultSansSerifFontName())
  72377. s = String::empty;
  72378. else
  72379. s += "; ";
  72380. s += String (getHeight(), 1);
  72381. if (isBold())
  72382. s += " bold";
  72383. if (isItalic())
  72384. s += " italic";
  72385. return s;
  72386. }
  72387. const Font Font::fromString (const String& fontDescription)
  72388. {
  72389. String name;
  72390. const int separator = fontDescription.indexOfChar (';');
  72391. if (separator > 0)
  72392. name = fontDescription.substring (0, separator).trim();
  72393. if (name.isEmpty())
  72394. name = getDefaultSansSerifFontName();
  72395. String sizeAndStyle (fontDescription.substring (separator + 1));
  72396. float height = sizeAndStyle.getFloatValue();
  72397. if (height <= 0)
  72398. height = 10.0f;
  72399. int flags = Font::plain;
  72400. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72401. flags |= Font::bold;
  72402. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72403. flags |= Font::italic;
  72404. return Font (name, height, flags);
  72405. }
  72406. class TypefaceCache : public DeletedAtShutdown
  72407. {
  72408. public:
  72409. TypefaceCache (int numToCache = 10)
  72410. : counter (1)
  72411. {
  72412. while (--numToCache >= 0)
  72413. faces.add (new CachedFace());
  72414. }
  72415. ~TypefaceCache()
  72416. {
  72417. clearSingletonInstance();
  72418. }
  72419. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72420. const Typeface::Ptr findTypefaceFor (const Font& font)
  72421. {
  72422. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72423. const String faceName (font.getTypefaceName());
  72424. int i;
  72425. for (i = faces.size(); --i >= 0;)
  72426. {
  72427. CachedFace* const face = faces.getUnchecked(i);
  72428. if (face->flags == flags
  72429. && face->typefaceName == faceName)
  72430. {
  72431. face->lastUsageCount = ++counter;
  72432. return face->typeFace;
  72433. }
  72434. }
  72435. int replaceIndex = 0;
  72436. int bestLastUsageCount = std::numeric_limits<int>::max();
  72437. for (i = faces.size(); --i >= 0;)
  72438. {
  72439. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72440. if (bestLastUsageCount > lu)
  72441. {
  72442. bestLastUsageCount = lu;
  72443. replaceIndex = i;
  72444. }
  72445. }
  72446. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72447. face->typefaceName = faceName;
  72448. face->flags = flags;
  72449. face->lastUsageCount = ++counter;
  72450. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72451. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72452. return face->typeFace;
  72453. }
  72454. private:
  72455. struct CachedFace
  72456. {
  72457. CachedFace() throw()
  72458. : lastUsageCount (0), flags (-1)
  72459. {
  72460. }
  72461. String typefaceName;
  72462. int lastUsageCount;
  72463. int flags;
  72464. Typeface::Ptr typeFace;
  72465. };
  72466. int counter;
  72467. OwnedArray <CachedFace> faces;
  72468. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72469. };
  72470. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72471. Typeface* Font::getTypeface() const
  72472. {
  72473. if (font->typeface == 0)
  72474. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72475. return font->typeface;
  72476. }
  72477. END_JUCE_NAMESPACE
  72478. /*** End of inlined file: juce_Font.cpp ***/
  72479. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72480. BEGIN_JUCE_NAMESPACE
  72481. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72482. const juce_wchar character_, const int glyph_)
  72483. : x (x_),
  72484. y (y_),
  72485. w (w_),
  72486. font (font_),
  72487. character (character_),
  72488. glyph (glyph_)
  72489. {
  72490. }
  72491. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72492. : x (other.x),
  72493. y (other.y),
  72494. w (other.w),
  72495. font (other.font),
  72496. character (other.character),
  72497. glyph (other.glyph)
  72498. {
  72499. }
  72500. void PositionedGlyph::draw (const Graphics& g) const
  72501. {
  72502. if (! isWhitespace())
  72503. {
  72504. g.getInternalContext()->setFont (font);
  72505. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72506. }
  72507. }
  72508. void PositionedGlyph::draw (const Graphics& g,
  72509. const AffineTransform& transform) const
  72510. {
  72511. if (! isWhitespace())
  72512. {
  72513. g.getInternalContext()->setFont (font);
  72514. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72515. .followedBy (transform));
  72516. }
  72517. }
  72518. void PositionedGlyph::createPath (Path& path) const
  72519. {
  72520. if (! isWhitespace())
  72521. {
  72522. Typeface* const t = font.getTypeface();
  72523. if (t != 0)
  72524. {
  72525. Path p;
  72526. t->getOutlineForGlyph (glyph, p);
  72527. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72528. .translated (x, y));
  72529. }
  72530. }
  72531. }
  72532. bool PositionedGlyph::hitTest (float px, float py) const
  72533. {
  72534. if (getBounds().contains (px, py) && ! isWhitespace())
  72535. {
  72536. Typeface* const t = font.getTypeface();
  72537. if (t != 0)
  72538. {
  72539. Path p;
  72540. t->getOutlineForGlyph (glyph, p);
  72541. AffineTransform::translation (-x, -y)
  72542. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72543. .transformPoint (px, py);
  72544. return p.contains (px, py);
  72545. }
  72546. }
  72547. return false;
  72548. }
  72549. void PositionedGlyph::moveBy (const float deltaX,
  72550. const float deltaY)
  72551. {
  72552. x += deltaX;
  72553. y += deltaY;
  72554. }
  72555. GlyphArrangement::GlyphArrangement()
  72556. {
  72557. glyphs.ensureStorageAllocated (128);
  72558. }
  72559. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72560. {
  72561. addGlyphArrangement (other);
  72562. }
  72563. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72564. {
  72565. if (this != &other)
  72566. {
  72567. clear();
  72568. addGlyphArrangement (other);
  72569. }
  72570. return *this;
  72571. }
  72572. GlyphArrangement::~GlyphArrangement()
  72573. {
  72574. }
  72575. void GlyphArrangement::clear()
  72576. {
  72577. glyphs.clear();
  72578. }
  72579. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72580. {
  72581. jassert (isPositiveAndBelow (index, glyphs.size()));
  72582. return *glyphs [index];
  72583. }
  72584. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72585. {
  72586. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72587. glyphs.addCopiesOf (other.glyphs);
  72588. }
  72589. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72590. {
  72591. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72592. }
  72593. void GlyphArrangement::addLineOfText (const Font& font,
  72594. const String& text,
  72595. const float xOffset,
  72596. const float yOffset)
  72597. {
  72598. addCurtailedLineOfText (font, text,
  72599. xOffset, yOffset,
  72600. 1.0e10f, false);
  72601. }
  72602. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72603. const String& text,
  72604. float xOffset,
  72605. const float yOffset,
  72606. const float maxWidthPixels,
  72607. const bool useEllipsis)
  72608. {
  72609. if (text.isNotEmpty())
  72610. {
  72611. Array <int> newGlyphs;
  72612. Array <float> xOffsets;
  72613. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72614. const int textLen = newGlyphs.size();
  72615. const juce_wchar* const unicodeText = text;
  72616. for (int i = 0; i < textLen; ++i)
  72617. {
  72618. const float thisX = xOffsets.getUnchecked (i);
  72619. const float nextX = xOffsets.getUnchecked (i + 1);
  72620. if (nextX > maxWidthPixels + 1.0f)
  72621. {
  72622. // curtail the string if it's too wide..
  72623. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72624. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72625. break;
  72626. }
  72627. else
  72628. {
  72629. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72630. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72631. }
  72632. }
  72633. }
  72634. }
  72635. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72636. const int startIndex, int endIndex)
  72637. {
  72638. int numDeleted = 0;
  72639. if (glyphs.size() > 0)
  72640. {
  72641. Array<int> dotGlyphs;
  72642. Array<float> dotXs;
  72643. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72644. const float dx = dotXs[1];
  72645. float xOffset = 0.0f, yOffset = 0.0f;
  72646. while (endIndex > startIndex)
  72647. {
  72648. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72649. xOffset = pg->x;
  72650. yOffset = pg->y;
  72651. glyphs.remove (endIndex);
  72652. ++numDeleted;
  72653. if (xOffset + dx * 3 <= maxXPos)
  72654. break;
  72655. }
  72656. for (int i = 3; --i >= 0;)
  72657. {
  72658. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72659. font, '.', dotGlyphs.getFirst()));
  72660. --numDeleted;
  72661. xOffset += dx;
  72662. if (xOffset > maxXPos)
  72663. break;
  72664. }
  72665. }
  72666. return numDeleted;
  72667. }
  72668. void GlyphArrangement::addJustifiedText (const Font& font,
  72669. const String& text,
  72670. float x, float y,
  72671. const float maxLineWidth,
  72672. const Justification& horizontalLayout)
  72673. {
  72674. int lineStartIndex = glyphs.size();
  72675. addLineOfText (font, text, x, y);
  72676. const float originalY = y;
  72677. while (lineStartIndex < glyphs.size())
  72678. {
  72679. int i = lineStartIndex;
  72680. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72681. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72682. ++i;
  72683. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72684. int lastWordBreakIndex = -1;
  72685. while (i < glyphs.size())
  72686. {
  72687. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72688. const juce_wchar c = pg->getCharacter();
  72689. if (c == '\r' || c == '\n')
  72690. {
  72691. ++i;
  72692. if (c == '\r' && i < glyphs.size()
  72693. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72694. ++i;
  72695. break;
  72696. }
  72697. else if (pg->isWhitespace())
  72698. {
  72699. lastWordBreakIndex = i + 1;
  72700. }
  72701. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72702. {
  72703. if (lastWordBreakIndex >= 0)
  72704. i = lastWordBreakIndex;
  72705. break;
  72706. }
  72707. ++i;
  72708. }
  72709. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72710. float currentLineEndX = currentLineStartX;
  72711. for (int j = i; --j >= lineStartIndex;)
  72712. {
  72713. if (! glyphs.getUnchecked (j)->isWhitespace())
  72714. {
  72715. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72716. break;
  72717. }
  72718. }
  72719. float deltaX = 0.0f;
  72720. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72721. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72722. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72723. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72724. else if (horizontalLayout.testFlags (Justification::right))
  72725. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72726. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72727. x + deltaX - currentLineStartX, y - originalY);
  72728. lineStartIndex = i;
  72729. y += font.getHeight();
  72730. }
  72731. }
  72732. void GlyphArrangement::addFittedText (const Font& f,
  72733. const String& text,
  72734. const float x, const float y,
  72735. const float width, const float height,
  72736. const Justification& layout,
  72737. int maximumLines,
  72738. const float minimumHorizontalScale)
  72739. {
  72740. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72741. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72742. if (text.containsAnyOf ("\r\n"))
  72743. {
  72744. GlyphArrangement ga;
  72745. ga.addJustifiedText (f, text, x, y, width, layout);
  72746. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72747. float dy = y - bb.getY();
  72748. if (layout.testFlags (Justification::verticallyCentred))
  72749. dy += (height - bb.getHeight()) * 0.5f;
  72750. else if (layout.testFlags (Justification::bottom))
  72751. dy += height - bb.getHeight();
  72752. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72753. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72754. for (int i = 0; i < ga.glyphs.size(); ++i)
  72755. glyphs.add (ga.glyphs.getUnchecked (i));
  72756. ga.glyphs.clear (false);
  72757. return;
  72758. }
  72759. int startIndex = glyphs.size();
  72760. addLineOfText (f, text.trim(), x, y);
  72761. if (glyphs.size() > startIndex)
  72762. {
  72763. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72764. - glyphs.getUnchecked (startIndex)->getLeft();
  72765. if (lineWidth <= 0)
  72766. return;
  72767. if (lineWidth * minimumHorizontalScale < width)
  72768. {
  72769. if (lineWidth > width)
  72770. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72771. width / lineWidth);
  72772. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72773. x, y, width, height, layout);
  72774. }
  72775. else if (maximumLines <= 1)
  72776. {
  72777. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72778. x, y, width, height, f, layout, minimumHorizontalScale);
  72779. }
  72780. else
  72781. {
  72782. Font font (f);
  72783. String txt (text.trim());
  72784. const int length = txt.length();
  72785. const int originalStartIndex = startIndex;
  72786. int numLines = 1;
  72787. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72788. maximumLines = 1;
  72789. maximumLines = jmin (maximumLines, length);
  72790. while (numLines < maximumLines)
  72791. {
  72792. ++numLines;
  72793. const float newFontHeight = height / (float) numLines;
  72794. if (newFontHeight < font.getHeight())
  72795. {
  72796. font.setHeight (jmax (8.0f, newFontHeight));
  72797. removeRangeOfGlyphs (startIndex, -1);
  72798. addLineOfText (font, txt, x, y);
  72799. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72800. - glyphs.getUnchecked (startIndex)->getLeft();
  72801. }
  72802. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72803. break;
  72804. }
  72805. if (numLines < 1)
  72806. numLines = 1;
  72807. float lineY = y;
  72808. float widthPerLine = lineWidth / numLines;
  72809. int lastLineStartIndex = 0;
  72810. for (int line = 0; line < numLines; ++line)
  72811. {
  72812. int i = startIndex;
  72813. lastLineStartIndex = i;
  72814. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72815. if (line == numLines - 1)
  72816. {
  72817. widthPerLine = width;
  72818. i = glyphs.size();
  72819. }
  72820. else
  72821. {
  72822. while (i < glyphs.size())
  72823. {
  72824. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72825. if (lineWidth > widthPerLine)
  72826. {
  72827. // got to a point where the line's too long, so skip forward to find a
  72828. // good place to break it..
  72829. const int searchStartIndex = i;
  72830. while (i < glyphs.size())
  72831. {
  72832. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72833. {
  72834. if (glyphs.getUnchecked (i)->isWhitespace()
  72835. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72836. {
  72837. ++i;
  72838. break;
  72839. }
  72840. }
  72841. else
  72842. {
  72843. // can't find a suitable break, so try looking backwards..
  72844. i = searchStartIndex;
  72845. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72846. {
  72847. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72848. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72849. {
  72850. i -= back - 1;
  72851. break;
  72852. }
  72853. }
  72854. break;
  72855. }
  72856. ++i;
  72857. }
  72858. break;
  72859. }
  72860. ++i;
  72861. }
  72862. int wsStart = i;
  72863. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72864. --wsStart;
  72865. int wsEnd = i;
  72866. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72867. ++wsEnd;
  72868. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72869. i = jmax (wsStart, startIndex + 1);
  72870. }
  72871. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72872. x, lineY, width, font.getHeight(), font,
  72873. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72874. minimumHorizontalScale);
  72875. startIndex = i;
  72876. lineY += font.getHeight();
  72877. if (startIndex >= glyphs.size())
  72878. break;
  72879. }
  72880. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72881. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72882. }
  72883. }
  72884. }
  72885. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72886. const float dx, const float dy)
  72887. {
  72888. jassert (startIndex >= 0);
  72889. if (dx != 0.0f || dy != 0.0f)
  72890. {
  72891. if (num < 0 || startIndex + num > glyphs.size())
  72892. num = glyphs.size() - startIndex;
  72893. while (--num >= 0)
  72894. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72895. }
  72896. }
  72897. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72898. const Justification& justification, float minimumHorizontalScale)
  72899. {
  72900. int numDeleted = 0;
  72901. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72902. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72903. if (lineWidth > w)
  72904. {
  72905. if (minimumHorizontalScale < 1.0f)
  72906. {
  72907. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72908. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72909. }
  72910. if (lineWidth > w)
  72911. {
  72912. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72913. numGlyphs -= numDeleted;
  72914. }
  72915. }
  72916. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72917. return numDeleted;
  72918. }
  72919. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  72920. const float horizontalScaleFactor)
  72921. {
  72922. jassert (startIndex >= 0);
  72923. if (num < 0 || startIndex + num > glyphs.size())
  72924. num = glyphs.size() - startIndex;
  72925. if (num > 0)
  72926. {
  72927. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  72928. while (--num >= 0)
  72929. {
  72930. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72931. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  72932. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  72933. pg->w *= horizontalScaleFactor;
  72934. }
  72935. }
  72936. }
  72937. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  72938. {
  72939. jassert (startIndex >= 0);
  72940. if (num < 0 || startIndex + num > glyphs.size())
  72941. num = glyphs.size() - startIndex;
  72942. Rectangle<float> result;
  72943. while (--num >= 0)
  72944. {
  72945. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72946. if (includeWhitespace || ! pg->isWhitespace())
  72947. result = result.getUnion (pg->getBounds());
  72948. }
  72949. return result;
  72950. }
  72951. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  72952. const float x, const float y, const float width, const float height,
  72953. const Justification& justification)
  72954. {
  72955. jassert (num >= 0 && startIndex >= 0);
  72956. if (glyphs.size() > 0 && num > 0)
  72957. {
  72958. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  72959. | Justification::horizontallyCentred)));
  72960. float deltaX = 0.0f;
  72961. if (justification.testFlags (Justification::horizontallyJustified))
  72962. deltaX = x - bb.getX();
  72963. else if (justification.testFlags (Justification::horizontallyCentred))
  72964. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  72965. else if (justification.testFlags (Justification::right))
  72966. deltaX = (x + width) - bb.getRight();
  72967. else
  72968. deltaX = x - bb.getX();
  72969. float deltaY = 0.0f;
  72970. if (justification.testFlags (Justification::top))
  72971. deltaY = y - bb.getY();
  72972. else if (justification.testFlags (Justification::bottom))
  72973. deltaY = (y + height) - bb.getBottom();
  72974. else
  72975. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  72976. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  72977. if (justification.testFlags (Justification::horizontallyJustified))
  72978. {
  72979. int lineStart = 0;
  72980. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  72981. int i;
  72982. for (i = 0; i < num; ++i)
  72983. {
  72984. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  72985. if (glyphY != baseY)
  72986. {
  72987. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72988. lineStart = i;
  72989. baseY = glyphY;
  72990. }
  72991. }
  72992. if (i > lineStart)
  72993. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72994. }
  72995. }
  72996. }
  72997. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  72998. {
  72999. if (start + num < glyphs.size()
  73000. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73001. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73002. {
  73003. int numSpaces = 0;
  73004. int spacesAtEnd = 0;
  73005. for (int i = 0; i < num; ++i)
  73006. {
  73007. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73008. {
  73009. ++spacesAtEnd;
  73010. ++numSpaces;
  73011. }
  73012. else
  73013. {
  73014. spacesAtEnd = 0;
  73015. }
  73016. }
  73017. numSpaces -= spacesAtEnd;
  73018. if (numSpaces > 0)
  73019. {
  73020. const float startX = glyphs.getUnchecked (start)->getLeft();
  73021. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73022. const float extraPaddingBetweenWords
  73023. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73024. float deltaX = 0.0f;
  73025. for (int i = 0; i < num; ++i)
  73026. {
  73027. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73028. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73029. deltaX += extraPaddingBetweenWords;
  73030. }
  73031. }
  73032. }
  73033. }
  73034. void GlyphArrangement::draw (const Graphics& g) const
  73035. {
  73036. for (int i = 0; i < glyphs.size(); ++i)
  73037. {
  73038. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73039. if (pg->font.isUnderlined())
  73040. {
  73041. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73042. float nextX = pg->x + pg->w;
  73043. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73044. nextX = glyphs.getUnchecked (i + 1)->x;
  73045. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73046. nextX - pg->x, lineThickness);
  73047. }
  73048. pg->draw (g);
  73049. }
  73050. }
  73051. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73052. {
  73053. for (int i = 0; i < glyphs.size(); ++i)
  73054. {
  73055. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73056. if (pg->font.isUnderlined())
  73057. {
  73058. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73059. float nextX = pg->x + pg->w;
  73060. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73061. nextX = glyphs.getUnchecked (i + 1)->x;
  73062. Path p;
  73063. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73064. nextX, pg->y + lineThickness * 2.0f),
  73065. lineThickness);
  73066. g.fillPath (p, transform);
  73067. }
  73068. pg->draw (g, transform);
  73069. }
  73070. }
  73071. void GlyphArrangement::createPath (Path& path) const
  73072. {
  73073. for (int i = 0; i < glyphs.size(); ++i)
  73074. glyphs.getUnchecked (i)->createPath (path);
  73075. }
  73076. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73077. {
  73078. for (int i = 0; i < glyphs.size(); ++i)
  73079. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73080. return i;
  73081. return -1;
  73082. }
  73083. END_JUCE_NAMESPACE
  73084. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73085. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73086. BEGIN_JUCE_NAMESPACE
  73087. class TextLayout::Token
  73088. {
  73089. public:
  73090. Token (const String& t,
  73091. const Font& f,
  73092. const bool isWhitespace_)
  73093. : text (t),
  73094. font (f),
  73095. x(0),
  73096. y(0),
  73097. isWhitespace (isWhitespace_)
  73098. {
  73099. w = font.getStringWidth (t);
  73100. h = roundToInt (f.getHeight());
  73101. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73102. }
  73103. Token (const Token& other)
  73104. : text (other.text),
  73105. font (other.font),
  73106. x (other.x),
  73107. y (other.y),
  73108. w (other.w),
  73109. h (other.h),
  73110. line (other.line),
  73111. lineHeight (other.lineHeight),
  73112. isWhitespace (other.isWhitespace),
  73113. isNewLine (other.isNewLine)
  73114. {
  73115. }
  73116. void draw (Graphics& g,
  73117. const int xOffset,
  73118. const int yOffset)
  73119. {
  73120. if (! isWhitespace)
  73121. {
  73122. g.setFont (font);
  73123. g.drawSingleLineText (text.trimEnd(),
  73124. xOffset + x,
  73125. yOffset + y + (lineHeight - h)
  73126. + roundToInt (font.getAscent()));
  73127. }
  73128. }
  73129. String text;
  73130. Font font;
  73131. int x, y, w, h;
  73132. int line, lineHeight;
  73133. bool isWhitespace, isNewLine;
  73134. private:
  73135. JUCE_LEAK_DETECTOR (Token);
  73136. };
  73137. TextLayout::TextLayout()
  73138. : totalLines (0)
  73139. {
  73140. tokens.ensureStorageAllocated (64);
  73141. }
  73142. TextLayout::TextLayout (const String& text, const Font& font)
  73143. : totalLines (0)
  73144. {
  73145. tokens.ensureStorageAllocated (64);
  73146. appendText (text, font);
  73147. }
  73148. TextLayout::TextLayout (const TextLayout& other)
  73149. : totalLines (0)
  73150. {
  73151. *this = other;
  73152. }
  73153. TextLayout& TextLayout::operator= (const TextLayout& other)
  73154. {
  73155. if (this != &other)
  73156. {
  73157. clear();
  73158. totalLines = other.totalLines;
  73159. tokens.addCopiesOf (other.tokens);
  73160. }
  73161. return *this;
  73162. }
  73163. TextLayout::~TextLayout()
  73164. {
  73165. clear();
  73166. }
  73167. void TextLayout::clear()
  73168. {
  73169. tokens.clear();
  73170. totalLines = 0;
  73171. }
  73172. bool TextLayout::isEmpty() const
  73173. {
  73174. return tokens.size() == 0;
  73175. }
  73176. void TextLayout::appendText (const String& text, const Font& font)
  73177. {
  73178. const juce_wchar* t = text;
  73179. String currentString;
  73180. int lastCharType = 0;
  73181. for (;;)
  73182. {
  73183. const juce_wchar c = *t++;
  73184. if (c == 0)
  73185. break;
  73186. int charType;
  73187. if (c == '\r' || c == '\n')
  73188. {
  73189. charType = 0;
  73190. }
  73191. else if (CharacterFunctions::isWhitespace (c))
  73192. {
  73193. charType = 2;
  73194. }
  73195. else
  73196. {
  73197. charType = 1;
  73198. }
  73199. if (charType == 0 || charType != lastCharType)
  73200. {
  73201. if (currentString.isNotEmpty())
  73202. {
  73203. tokens.add (new Token (currentString, font,
  73204. lastCharType == 2 || lastCharType == 0));
  73205. }
  73206. currentString = String::charToString (c);
  73207. if (c == '\r' && *t == '\n')
  73208. currentString += *t++;
  73209. }
  73210. else
  73211. {
  73212. currentString += c;
  73213. }
  73214. lastCharType = charType;
  73215. }
  73216. if (currentString.isNotEmpty())
  73217. tokens.add (new Token (currentString, font, lastCharType == 2));
  73218. }
  73219. void TextLayout::setText (const String& text, const Font& font)
  73220. {
  73221. clear();
  73222. appendText (text, font);
  73223. }
  73224. void TextLayout::layout (int maxWidth,
  73225. const Justification& justification,
  73226. const bool attemptToBalanceLineLengths)
  73227. {
  73228. if (attemptToBalanceLineLengths)
  73229. {
  73230. const int originalW = maxWidth;
  73231. int bestWidth = maxWidth;
  73232. float bestLineProportion = 0.0f;
  73233. while (maxWidth > originalW / 2)
  73234. {
  73235. layout (maxWidth, justification, false);
  73236. if (getNumLines() <= 1)
  73237. return;
  73238. const int lastLineW = getLineWidth (getNumLines() - 1);
  73239. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73240. const float prop = lastLineW / (float) lastButOneLineW;
  73241. if (prop > 0.9f)
  73242. return;
  73243. if (prop > bestLineProportion)
  73244. {
  73245. bestLineProportion = prop;
  73246. bestWidth = maxWidth;
  73247. }
  73248. maxWidth -= 10;
  73249. }
  73250. layout (bestWidth, justification, false);
  73251. }
  73252. else
  73253. {
  73254. int x = 0;
  73255. int y = 0;
  73256. int h = 0;
  73257. totalLines = 0;
  73258. int i;
  73259. for (i = 0; i < tokens.size(); ++i)
  73260. {
  73261. Token* const t = tokens.getUnchecked(i);
  73262. t->x = x;
  73263. t->y = y;
  73264. t->line = totalLines;
  73265. x += t->w;
  73266. h = jmax (h, t->h);
  73267. const Token* nextTok = tokens [i + 1];
  73268. if (nextTok == 0)
  73269. break;
  73270. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73271. {
  73272. // finished a line, so go back and update the heights of the things on it
  73273. for (int j = i; j >= 0; --j)
  73274. {
  73275. Token* const tok = tokens.getUnchecked(j);
  73276. if (tok->line == totalLines)
  73277. tok->lineHeight = h;
  73278. else
  73279. break;
  73280. }
  73281. x = 0;
  73282. y += h;
  73283. h = 0;
  73284. ++totalLines;
  73285. }
  73286. }
  73287. // finished a line, so go back and update the heights of the things on it
  73288. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73289. {
  73290. Token* const t = tokens.getUnchecked(j);
  73291. if (t->line == totalLines)
  73292. t->lineHeight = h;
  73293. else
  73294. break;
  73295. }
  73296. ++totalLines;
  73297. if (! justification.testFlags (Justification::left))
  73298. {
  73299. int totalW = getWidth();
  73300. for (i = totalLines; --i >= 0;)
  73301. {
  73302. const int lineW = getLineWidth (i);
  73303. int dx = 0;
  73304. if (justification.testFlags (Justification::horizontallyCentred))
  73305. dx = (totalW - lineW) / 2;
  73306. else if (justification.testFlags (Justification::right))
  73307. dx = totalW - lineW;
  73308. for (int j = tokens.size(); --j >= 0;)
  73309. {
  73310. Token* const t = tokens.getUnchecked(j);
  73311. if (t->line == i)
  73312. t->x += dx;
  73313. }
  73314. }
  73315. }
  73316. }
  73317. }
  73318. int TextLayout::getLineWidth (const int lineNumber) const
  73319. {
  73320. int maxW = 0;
  73321. for (int i = tokens.size(); --i >= 0;)
  73322. {
  73323. const Token* const t = tokens.getUnchecked(i);
  73324. if (t->line == lineNumber && ! t->isWhitespace)
  73325. maxW = jmax (maxW, t->x + t->w);
  73326. }
  73327. return maxW;
  73328. }
  73329. int TextLayout::getWidth() const
  73330. {
  73331. int maxW = 0;
  73332. for (int i = tokens.size(); --i >= 0;)
  73333. {
  73334. const Token* const t = tokens.getUnchecked(i);
  73335. if (! t->isWhitespace)
  73336. maxW = jmax (maxW, t->x + t->w);
  73337. }
  73338. return maxW;
  73339. }
  73340. int TextLayout::getHeight() const
  73341. {
  73342. int maxH = 0;
  73343. for (int i = tokens.size(); --i >= 0;)
  73344. {
  73345. const Token* const t = tokens.getUnchecked(i);
  73346. if (! t->isWhitespace)
  73347. maxH = jmax (maxH, t->y + t->h);
  73348. }
  73349. return maxH;
  73350. }
  73351. void TextLayout::draw (Graphics& g,
  73352. const int xOffset,
  73353. const int yOffset) const
  73354. {
  73355. for (int i = tokens.size(); --i >= 0;)
  73356. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73357. }
  73358. void TextLayout::drawWithin (Graphics& g,
  73359. int x, int y, int w, int h,
  73360. const Justification& justification) const
  73361. {
  73362. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73363. x, y, w, h);
  73364. draw (g, x, y);
  73365. }
  73366. END_JUCE_NAMESPACE
  73367. /*** End of inlined file: juce_TextLayout.cpp ***/
  73368. /*** Start of inlined file: juce_Typeface.cpp ***/
  73369. BEGIN_JUCE_NAMESPACE
  73370. Typeface::Typeface (const String& name_) throw()
  73371. : name (name_), isFallbackFont (false)
  73372. {
  73373. }
  73374. Typeface::~Typeface()
  73375. {
  73376. }
  73377. const Typeface::Ptr Typeface::getFallbackTypeface()
  73378. {
  73379. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73380. Typeface* t = fallbackFont.getTypeface();
  73381. t->isFallbackFont = true;
  73382. return t;
  73383. }
  73384. class CustomTypeface::GlyphInfo
  73385. {
  73386. public:
  73387. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73388. : character (character_), path (path_), width (width_)
  73389. {
  73390. }
  73391. struct KerningPair
  73392. {
  73393. juce_wchar character2;
  73394. float kerningAmount;
  73395. };
  73396. void addKerningPair (const juce_wchar subsequentCharacter,
  73397. const float extraKerningAmount) throw()
  73398. {
  73399. KerningPair kp;
  73400. kp.character2 = subsequentCharacter;
  73401. kp.kerningAmount = extraKerningAmount;
  73402. kerningPairs.add (kp);
  73403. }
  73404. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73405. {
  73406. if (subsequentCharacter != 0)
  73407. {
  73408. for (int i = kerningPairs.size(); --i >= 0;)
  73409. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73410. return width + kerningPairs.getReference(i).kerningAmount;
  73411. }
  73412. return width;
  73413. }
  73414. const juce_wchar character;
  73415. const Path path;
  73416. float width;
  73417. Array <KerningPair> kerningPairs;
  73418. private:
  73419. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73420. };
  73421. CustomTypeface::CustomTypeface()
  73422. : Typeface (String::empty)
  73423. {
  73424. clear();
  73425. }
  73426. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73427. : Typeface (String::empty)
  73428. {
  73429. clear();
  73430. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73431. BufferedInputStream in (gzin, 32768);
  73432. name = in.readString();
  73433. isBold = in.readBool();
  73434. isItalic = in.readBool();
  73435. ascent = in.readFloat();
  73436. defaultCharacter = (juce_wchar) in.readShort();
  73437. int i, numChars = in.readInt();
  73438. for (i = 0; i < numChars; ++i)
  73439. {
  73440. const juce_wchar c = (juce_wchar) in.readShort();
  73441. const float width = in.readFloat();
  73442. Path p;
  73443. p.loadPathFromStream (in);
  73444. addGlyph (c, p, width);
  73445. }
  73446. const int numKerningPairs = in.readInt();
  73447. for (i = 0; i < numKerningPairs; ++i)
  73448. {
  73449. const juce_wchar char1 = (juce_wchar) in.readShort();
  73450. const juce_wchar char2 = (juce_wchar) in.readShort();
  73451. addKerningPair (char1, char2, in.readFloat());
  73452. }
  73453. }
  73454. CustomTypeface::~CustomTypeface()
  73455. {
  73456. }
  73457. void CustomTypeface::clear()
  73458. {
  73459. defaultCharacter = 0;
  73460. ascent = 1.0f;
  73461. isBold = isItalic = false;
  73462. zeromem (lookupTable, sizeof (lookupTable));
  73463. glyphs.clear();
  73464. }
  73465. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73466. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73467. {
  73468. name = name_;
  73469. defaultCharacter = defaultCharacter_;
  73470. ascent = ascent_;
  73471. isBold = isBold_;
  73472. isItalic = isItalic_;
  73473. }
  73474. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73475. {
  73476. // Check that you're not trying to add the same character twice..
  73477. jassert (findGlyph (character, false) == 0);
  73478. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  73479. lookupTable [character] = (short) glyphs.size();
  73480. glyphs.add (new GlyphInfo (character, path, width));
  73481. }
  73482. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73483. {
  73484. if (extraAmount != 0)
  73485. {
  73486. GlyphInfo* const g = findGlyph (char1, true);
  73487. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73488. if (g != 0)
  73489. g->addKerningPair (char2, extraAmount);
  73490. }
  73491. }
  73492. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73493. {
  73494. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  73495. return glyphs [(int) lookupTable [(int) character]];
  73496. for (int i = 0; i < glyphs.size(); ++i)
  73497. {
  73498. GlyphInfo* const g = glyphs.getUnchecked(i);
  73499. if (g->character == character)
  73500. return g;
  73501. }
  73502. if (loadIfNeeded && loadGlyphIfPossible (character))
  73503. return findGlyph (character, false);
  73504. return 0;
  73505. }
  73506. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73507. {
  73508. GlyphInfo* glyph = findGlyph (character, true);
  73509. if (glyph == 0)
  73510. {
  73511. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73512. glyph = findGlyph (L' ', true);
  73513. if (glyph == 0)
  73514. {
  73515. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73516. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73517. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73518. {
  73519. Path path;
  73520. fallbackTypeface->getOutlineForGlyph (character, path);
  73521. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73522. }
  73523. if (glyph == 0)
  73524. glyph = findGlyph (defaultCharacter, true);
  73525. }
  73526. }
  73527. return glyph;
  73528. }
  73529. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73530. {
  73531. return false;
  73532. }
  73533. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73534. {
  73535. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73536. for (int i = 0; i < numCharacters; ++i)
  73537. {
  73538. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73539. Array <int> glyphIndexes;
  73540. Array <float> offsets;
  73541. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73542. const int glyphIndex = glyphIndexes.getFirst();
  73543. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73544. {
  73545. const float glyphWidth = offsets[1];
  73546. Path p;
  73547. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73548. addGlyph (c, p, glyphWidth);
  73549. for (int j = glyphs.size() - 1; --j >= 0;)
  73550. {
  73551. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73552. glyphIndexes.clearQuick();
  73553. offsets.clearQuick();
  73554. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73555. if (offsets.size() > 1)
  73556. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73557. }
  73558. }
  73559. }
  73560. }
  73561. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73562. {
  73563. GZIPCompressorOutputStream out (&outputStream);
  73564. out.writeString (name);
  73565. out.writeBool (isBold);
  73566. out.writeBool (isItalic);
  73567. out.writeFloat (ascent);
  73568. out.writeShort ((short) (unsigned short) defaultCharacter);
  73569. out.writeInt (glyphs.size());
  73570. int i, numKerningPairs = 0;
  73571. for (i = 0; i < glyphs.size(); ++i)
  73572. {
  73573. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73574. out.writeShort ((short) (unsigned short) g->character);
  73575. out.writeFloat (g->width);
  73576. g->path.writePathToStream (out);
  73577. numKerningPairs += g->kerningPairs.size();
  73578. }
  73579. out.writeInt (numKerningPairs);
  73580. for (i = 0; i < glyphs.size(); ++i)
  73581. {
  73582. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73583. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73584. {
  73585. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73586. out.writeShort ((short) (unsigned short) g->character);
  73587. out.writeShort ((short) (unsigned short) p.character2);
  73588. out.writeFloat (p.kerningAmount);
  73589. }
  73590. }
  73591. return true;
  73592. }
  73593. float CustomTypeface::getAscent() const
  73594. {
  73595. return ascent;
  73596. }
  73597. float CustomTypeface::getDescent() const
  73598. {
  73599. return 1.0f - ascent;
  73600. }
  73601. float CustomTypeface::getStringWidth (const String& text)
  73602. {
  73603. float x = 0;
  73604. const juce_wchar* t = text;
  73605. while (*t != 0)
  73606. {
  73607. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73608. if (glyph == 0 && ! isFallbackFont)
  73609. {
  73610. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73611. if (fallbackTypeface != 0)
  73612. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73613. }
  73614. if (glyph != 0)
  73615. x += glyph->getHorizontalSpacing (*t);
  73616. }
  73617. return x;
  73618. }
  73619. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73620. {
  73621. xOffsets.add (0);
  73622. float x = 0;
  73623. const juce_wchar* t = text;
  73624. while (*t != 0)
  73625. {
  73626. const juce_wchar c = *t++;
  73627. const GlyphInfo* const glyph = findGlyph (c, true);
  73628. if (glyph == 0 && ! isFallbackFont)
  73629. {
  73630. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73631. if (fallbackTypeface != 0)
  73632. {
  73633. Array <int> subGlyphs;
  73634. Array <float> subOffsets;
  73635. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73636. if (subGlyphs.size() > 0)
  73637. {
  73638. resultGlyphs.add (subGlyphs.getFirst());
  73639. x += subOffsets[1];
  73640. xOffsets.add (x);
  73641. }
  73642. }
  73643. }
  73644. if (glyph != 0)
  73645. {
  73646. x += glyph->getHorizontalSpacing (*t);
  73647. resultGlyphs.add ((int) glyph->character);
  73648. xOffsets.add (x);
  73649. }
  73650. }
  73651. }
  73652. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73653. {
  73654. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73655. if (glyph == 0 && ! isFallbackFont)
  73656. {
  73657. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73658. if (fallbackTypeface != 0)
  73659. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73660. }
  73661. if (glyph != 0)
  73662. {
  73663. path = glyph->path;
  73664. return true;
  73665. }
  73666. return false;
  73667. }
  73668. END_JUCE_NAMESPACE
  73669. /*** End of inlined file: juce_Typeface.cpp ***/
  73670. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73671. BEGIN_JUCE_NAMESPACE
  73672. AffineTransform::AffineTransform() throw()
  73673. : mat00 (1.0f), mat01 (0), mat02 (0),
  73674. mat10 (0), mat11 (1.0f), mat12 (0)
  73675. {
  73676. }
  73677. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73678. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73679. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73680. {
  73681. }
  73682. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73683. const float mat10_, const float mat11_, const float mat12_) throw()
  73684. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73685. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73686. {
  73687. }
  73688. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73689. {
  73690. mat00 = other.mat00;
  73691. mat01 = other.mat01;
  73692. mat02 = other.mat02;
  73693. mat10 = other.mat10;
  73694. mat11 = other.mat11;
  73695. mat12 = other.mat12;
  73696. return *this;
  73697. }
  73698. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73699. {
  73700. return mat00 == other.mat00
  73701. && mat01 == other.mat01
  73702. && mat02 == other.mat02
  73703. && mat10 == other.mat10
  73704. && mat11 == other.mat11
  73705. && mat12 == other.mat12;
  73706. }
  73707. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73708. {
  73709. return ! operator== (other);
  73710. }
  73711. bool AffineTransform::isIdentity() const throw()
  73712. {
  73713. return (mat01 == 0)
  73714. && (mat02 == 0)
  73715. && (mat10 == 0)
  73716. && (mat12 == 0)
  73717. && (mat00 == 1.0f)
  73718. && (mat11 == 1.0f);
  73719. }
  73720. const AffineTransform AffineTransform::identity;
  73721. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73722. {
  73723. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73724. other.mat00 * mat01 + other.mat01 * mat11,
  73725. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73726. other.mat10 * mat00 + other.mat11 * mat10,
  73727. other.mat10 * mat01 + other.mat11 * mat11,
  73728. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73729. }
  73730. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  73731. {
  73732. return AffineTransform (mat00, mat01, mat02 + dx,
  73733. mat10, mat11, mat12 + dy);
  73734. }
  73735. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  73736. {
  73737. return AffineTransform (1.0f, 0, dx,
  73738. 0, 1.0f, dy);
  73739. }
  73740. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73741. {
  73742. const float cosRad = std::cos (rad);
  73743. const float sinRad = std::sin (rad);
  73744. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  73745. cosRad * mat01 + -sinRad * mat11,
  73746. cosRad * mat02 + -sinRad * mat12,
  73747. sinRad * mat00 + cosRad * mat10,
  73748. sinRad * mat01 + cosRad * mat11,
  73749. sinRad * mat02 + cosRad * mat12);
  73750. }
  73751. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73752. {
  73753. const float cosRad = std::cos (rad);
  73754. const float sinRad = std::sin (rad);
  73755. return AffineTransform (cosRad, -sinRad, 0,
  73756. sinRad, cosRad, 0);
  73757. }
  73758. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  73759. {
  73760. const float cosRad = std::cos (rad);
  73761. const float sinRad = std::sin (rad);
  73762. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  73763. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  73764. }
  73765. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  73766. {
  73767. return followedBy (rotation (angle, pivotX, pivotY));
  73768. }
  73769. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  73770. {
  73771. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73772. factorY * mat10, factorY * mat11, factorY * mat12);
  73773. }
  73774. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  73775. {
  73776. return AffineTransform (factorX, 0, 0,
  73777. 0, factorY, 0);
  73778. }
  73779. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  73780. const float pivotX, const float pivotY) const throw()
  73781. {
  73782. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  73783. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  73784. }
  73785. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  73786. const float pivotX, const float pivotY) throw()
  73787. {
  73788. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  73789. 0, factorY, pivotY * (1.0f - factorY));
  73790. }
  73791. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  73792. {
  73793. return AffineTransform (1.0f, shearX, 0,
  73794. shearY, 1.0f, 0);
  73795. }
  73796. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  73797. {
  73798. return AffineTransform (mat00 + shearX * mat10,
  73799. mat01 + shearX * mat11,
  73800. mat02 + shearX * mat12,
  73801. shearY * mat00 + mat10,
  73802. shearY * mat01 + mat11,
  73803. shearY * mat02 + mat12);
  73804. }
  73805. const AffineTransform AffineTransform::inverted() const throw()
  73806. {
  73807. double determinant = (mat00 * mat11 - mat10 * mat01);
  73808. if (determinant != 0.0)
  73809. {
  73810. determinant = 1.0 / determinant;
  73811. const float dst00 = (float) (mat11 * determinant);
  73812. const float dst10 = (float) (-mat10 * determinant);
  73813. const float dst01 = (float) (-mat01 * determinant);
  73814. const float dst11 = (float) (mat00 * determinant);
  73815. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73816. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73817. }
  73818. else
  73819. {
  73820. // singularity..
  73821. return *this;
  73822. }
  73823. }
  73824. bool AffineTransform::isSingularity() const throw()
  73825. {
  73826. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73827. }
  73828. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73829. const float x10, const float y10,
  73830. const float x01, const float y01) throw()
  73831. {
  73832. return AffineTransform (x10 - x00, x01 - x00, x00,
  73833. y10 - y00, y01 - y00, y00);
  73834. }
  73835. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73836. const float sx2, const float sy2, const float tx2, const float ty2,
  73837. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73838. {
  73839. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73840. .inverted()
  73841. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73842. }
  73843. bool AffineTransform::isOnlyTranslation() const throw()
  73844. {
  73845. return (mat01 == 0)
  73846. && (mat10 == 0)
  73847. && (mat00 == 1.0f)
  73848. && (mat11 == 1.0f);
  73849. }
  73850. float AffineTransform::getScaleFactor() const throw()
  73851. {
  73852. return juce_hypot (mat00 + mat01, mat10 + mat11);
  73853. }
  73854. END_JUCE_NAMESPACE
  73855. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73856. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73857. BEGIN_JUCE_NAMESPACE
  73858. BorderSize::BorderSize() throw()
  73859. : top (0),
  73860. left (0),
  73861. bottom (0),
  73862. right (0)
  73863. {
  73864. }
  73865. BorderSize::BorderSize (const BorderSize& other) throw()
  73866. : top (other.top),
  73867. left (other.left),
  73868. bottom (other.bottom),
  73869. right (other.right)
  73870. {
  73871. }
  73872. BorderSize::BorderSize (const int topGap,
  73873. const int leftGap,
  73874. const int bottomGap,
  73875. const int rightGap) throw()
  73876. : top (topGap),
  73877. left (leftGap),
  73878. bottom (bottomGap),
  73879. right (rightGap)
  73880. {
  73881. }
  73882. BorderSize::BorderSize (const int allGaps) throw()
  73883. : top (allGaps),
  73884. left (allGaps),
  73885. bottom (allGaps),
  73886. right (allGaps)
  73887. {
  73888. }
  73889. BorderSize::~BorderSize() throw()
  73890. {
  73891. }
  73892. void BorderSize::setTop (const int newTopGap) throw()
  73893. {
  73894. top = newTopGap;
  73895. }
  73896. void BorderSize::setLeft (const int newLeftGap) throw()
  73897. {
  73898. left = newLeftGap;
  73899. }
  73900. void BorderSize::setBottom (const int newBottomGap) throw()
  73901. {
  73902. bottom = newBottomGap;
  73903. }
  73904. void BorderSize::setRight (const int newRightGap) throw()
  73905. {
  73906. right = newRightGap;
  73907. }
  73908. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73909. {
  73910. return Rectangle<int> (r.getX() + left,
  73911. r.getY() + top,
  73912. r.getWidth() - (left + right),
  73913. r.getHeight() - (top + bottom));
  73914. }
  73915. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73916. {
  73917. r.setBounds (r.getX() + left,
  73918. r.getY() + top,
  73919. r.getWidth() - (left + right),
  73920. r.getHeight() - (top + bottom));
  73921. }
  73922. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73923. {
  73924. return Rectangle<int> (r.getX() - left,
  73925. r.getY() - top,
  73926. r.getWidth() + (left + right),
  73927. r.getHeight() + (top + bottom));
  73928. }
  73929. void BorderSize::addTo (Rectangle<int>& r) const throw()
  73930. {
  73931. r.setBounds (r.getX() - left,
  73932. r.getY() - top,
  73933. r.getWidth() + (left + right),
  73934. r.getHeight() + (top + bottom));
  73935. }
  73936. bool BorderSize::operator== (const BorderSize& other) const throw()
  73937. {
  73938. return top == other.top
  73939. && left == other.left
  73940. && bottom == other.bottom
  73941. && right == other.right;
  73942. }
  73943. bool BorderSize::operator!= (const BorderSize& other) const throw()
  73944. {
  73945. return ! operator== (other);
  73946. }
  73947. END_JUCE_NAMESPACE
  73948. /*** End of inlined file: juce_BorderSize.cpp ***/
  73949. /*** Start of inlined file: juce_Path.cpp ***/
  73950. BEGIN_JUCE_NAMESPACE
  73951. // tests that some co-ords aren't NaNs
  73952. #define CHECK_COORDS_ARE_VALID(x, y) \
  73953. jassert (x == x && y == y);
  73954. namespace PathHelpers
  73955. {
  73956. const float ellipseAngularIncrement = 0.05f;
  73957. const String nextToken (const juce_wchar*& t)
  73958. {
  73959. while (CharacterFunctions::isWhitespace (*t))
  73960. ++t;
  73961. const juce_wchar* const start = t;
  73962. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  73963. ++t;
  73964. return String (start, (int) (t - start));
  73965. }
  73966. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  73967. {
  73968. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  73969. }
  73970. }
  73971. const float Path::lineMarker = 100001.0f;
  73972. const float Path::moveMarker = 100002.0f;
  73973. const float Path::quadMarker = 100003.0f;
  73974. const float Path::cubicMarker = 100004.0f;
  73975. const float Path::closeSubPathMarker = 100005.0f;
  73976. Path::Path()
  73977. : numElements (0),
  73978. pathXMin (0),
  73979. pathXMax (0),
  73980. pathYMin (0),
  73981. pathYMax (0),
  73982. useNonZeroWinding (true)
  73983. {
  73984. }
  73985. Path::~Path()
  73986. {
  73987. }
  73988. Path::Path (const Path& other)
  73989. : numElements (other.numElements),
  73990. pathXMin (other.pathXMin),
  73991. pathXMax (other.pathXMax),
  73992. pathYMin (other.pathYMin),
  73993. pathYMax (other.pathYMax),
  73994. useNonZeroWinding (other.useNonZeroWinding)
  73995. {
  73996. if (numElements > 0)
  73997. {
  73998. data.setAllocatedSize ((int) numElements);
  73999. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74000. }
  74001. }
  74002. Path& Path::operator= (const Path& other)
  74003. {
  74004. if (this != &other)
  74005. {
  74006. data.ensureAllocatedSize ((int) other.numElements);
  74007. numElements = other.numElements;
  74008. pathXMin = other.pathXMin;
  74009. pathXMax = other.pathXMax;
  74010. pathYMin = other.pathYMin;
  74011. pathYMax = other.pathYMax;
  74012. useNonZeroWinding = other.useNonZeroWinding;
  74013. if (numElements > 0)
  74014. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74015. }
  74016. return *this;
  74017. }
  74018. bool Path::operator== (const Path& other) const throw()
  74019. {
  74020. return ! operator!= (other);
  74021. }
  74022. bool Path::operator!= (const Path& other) const throw()
  74023. {
  74024. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74025. return true;
  74026. for (size_t i = 0; i < numElements; ++i)
  74027. if (data.elements[i] != other.data.elements[i])
  74028. return true;
  74029. return false;
  74030. }
  74031. void Path::clear() throw()
  74032. {
  74033. numElements = 0;
  74034. pathXMin = 0;
  74035. pathYMin = 0;
  74036. pathYMax = 0;
  74037. pathXMax = 0;
  74038. }
  74039. void Path::swapWithPath (Path& other) throw()
  74040. {
  74041. data.swapWith (other.data);
  74042. swapVariables <size_t> (numElements, other.numElements);
  74043. swapVariables <float> (pathXMin, other.pathXMin);
  74044. swapVariables <float> (pathXMax, other.pathXMax);
  74045. swapVariables <float> (pathYMin, other.pathYMin);
  74046. swapVariables <float> (pathYMax, other.pathYMax);
  74047. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74048. }
  74049. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74050. {
  74051. useNonZeroWinding = isNonZero;
  74052. }
  74053. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74054. const bool preserveProportions) throw()
  74055. {
  74056. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74057. }
  74058. bool Path::isEmpty() const throw()
  74059. {
  74060. size_t i = 0;
  74061. while (i < numElements)
  74062. {
  74063. const float type = data.elements [i++];
  74064. if (type == moveMarker)
  74065. {
  74066. i += 2;
  74067. }
  74068. else if (type == lineMarker
  74069. || type == quadMarker
  74070. || type == cubicMarker)
  74071. {
  74072. return false;
  74073. }
  74074. }
  74075. return true;
  74076. }
  74077. const Rectangle<float> Path::getBounds() const throw()
  74078. {
  74079. return Rectangle<float> (pathXMin, pathYMin,
  74080. pathXMax - pathXMin,
  74081. pathYMax - pathYMin);
  74082. }
  74083. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74084. {
  74085. return getBounds().transformed (transform);
  74086. }
  74087. void Path::startNewSubPath (const float x, const float y)
  74088. {
  74089. CHECK_COORDS_ARE_VALID (x, y);
  74090. if (numElements == 0)
  74091. {
  74092. pathXMin = pathXMax = x;
  74093. pathYMin = pathYMax = y;
  74094. }
  74095. else
  74096. {
  74097. pathXMin = jmin (pathXMin, x);
  74098. pathXMax = jmax (pathXMax, x);
  74099. pathYMin = jmin (pathYMin, y);
  74100. pathYMax = jmax (pathYMax, y);
  74101. }
  74102. data.ensureAllocatedSize ((int) numElements + 3);
  74103. data.elements [numElements++] = moveMarker;
  74104. data.elements [numElements++] = x;
  74105. data.elements [numElements++] = y;
  74106. }
  74107. void Path::startNewSubPath (const Point<float>& start)
  74108. {
  74109. startNewSubPath (start.getX(), start.getY());
  74110. }
  74111. void Path::lineTo (const float x, const float y)
  74112. {
  74113. CHECK_COORDS_ARE_VALID (x, y);
  74114. if (numElements == 0)
  74115. startNewSubPath (0, 0);
  74116. data.ensureAllocatedSize ((int) numElements + 3);
  74117. data.elements [numElements++] = lineMarker;
  74118. data.elements [numElements++] = x;
  74119. data.elements [numElements++] = y;
  74120. pathXMin = jmin (pathXMin, x);
  74121. pathXMax = jmax (pathXMax, x);
  74122. pathYMin = jmin (pathYMin, y);
  74123. pathYMax = jmax (pathYMax, y);
  74124. }
  74125. void Path::lineTo (const Point<float>& end)
  74126. {
  74127. lineTo (end.getX(), end.getY());
  74128. }
  74129. void Path::quadraticTo (const float x1, const float y1,
  74130. const float x2, const float y2)
  74131. {
  74132. CHECK_COORDS_ARE_VALID (x1, y1);
  74133. CHECK_COORDS_ARE_VALID (x2, y2);
  74134. if (numElements == 0)
  74135. startNewSubPath (0, 0);
  74136. data.ensureAllocatedSize ((int) numElements + 5);
  74137. data.elements [numElements++] = quadMarker;
  74138. data.elements [numElements++] = x1;
  74139. data.elements [numElements++] = y1;
  74140. data.elements [numElements++] = x2;
  74141. data.elements [numElements++] = y2;
  74142. pathXMin = jmin (pathXMin, x1, x2);
  74143. pathXMax = jmax (pathXMax, x1, x2);
  74144. pathYMin = jmin (pathYMin, y1, y2);
  74145. pathYMax = jmax (pathYMax, y1, y2);
  74146. }
  74147. void Path::quadraticTo (const Point<float>& controlPoint,
  74148. const Point<float>& endPoint)
  74149. {
  74150. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74151. endPoint.getX(), endPoint.getY());
  74152. }
  74153. void Path::cubicTo (const float x1, const float y1,
  74154. const float x2, const float y2,
  74155. const float x3, const float y3)
  74156. {
  74157. CHECK_COORDS_ARE_VALID (x1, y1);
  74158. CHECK_COORDS_ARE_VALID (x2, y2);
  74159. CHECK_COORDS_ARE_VALID (x3, y3);
  74160. if (numElements == 0)
  74161. startNewSubPath (0, 0);
  74162. data.ensureAllocatedSize ((int) numElements + 7);
  74163. data.elements [numElements++] = cubicMarker;
  74164. data.elements [numElements++] = x1;
  74165. data.elements [numElements++] = y1;
  74166. data.elements [numElements++] = x2;
  74167. data.elements [numElements++] = y2;
  74168. data.elements [numElements++] = x3;
  74169. data.elements [numElements++] = y3;
  74170. pathXMin = jmin (pathXMin, x1, x2, x3);
  74171. pathXMax = jmax (pathXMax, x1, x2, x3);
  74172. pathYMin = jmin (pathYMin, y1, y2, y3);
  74173. pathYMax = jmax (pathYMax, y1, y2, y3);
  74174. }
  74175. void Path::cubicTo (const Point<float>& controlPoint1,
  74176. const Point<float>& controlPoint2,
  74177. const Point<float>& endPoint)
  74178. {
  74179. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74180. controlPoint2.getX(), controlPoint2.getY(),
  74181. endPoint.getX(), endPoint.getY());
  74182. }
  74183. void Path::closeSubPath()
  74184. {
  74185. if (numElements > 0
  74186. && data.elements [numElements - 1] != closeSubPathMarker)
  74187. {
  74188. data.ensureAllocatedSize ((int) numElements + 1);
  74189. data.elements [numElements++] = closeSubPathMarker;
  74190. }
  74191. }
  74192. const Point<float> Path::getCurrentPosition() const
  74193. {
  74194. size_t i = numElements - 1;
  74195. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74196. {
  74197. while (i >= 0)
  74198. {
  74199. if (data.elements[i] == moveMarker)
  74200. {
  74201. i += 2;
  74202. break;
  74203. }
  74204. --i;
  74205. }
  74206. }
  74207. if (i > 0)
  74208. return Point<float> (data.elements [i - 1], data.elements [i]);
  74209. return Point<float>();
  74210. }
  74211. void Path::addRectangle (const float x, const float y,
  74212. const float w, const float h)
  74213. {
  74214. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74215. if (w < 0)
  74216. swapVariables (x1, x2);
  74217. if (h < 0)
  74218. swapVariables (y1, y2);
  74219. data.ensureAllocatedSize ((int) numElements + 13);
  74220. if (numElements == 0)
  74221. {
  74222. pathXMin = x1;
  74223. pathXMax = x2;
  74224. pathYMin = y1;
  74225. pathYMax = y2;
  74226. }
  74227. else
  74228. {
  74229. pathXMin = jmin (pathXMin, x1);
  74230. pathXMax = jmax (pathXMax, x2);
  74231. pathYMin = jmin (pathYMin, y1);
  74232. pathYMax = jmax (pathYMax, y2);
  74233. }
  74234. data.elements [numElements++] = moveMarker;
  74235. data.elements [numElements++] = x1;
  74236. data.elements [numElements++] = y2;
  74237. data.elements [numElements++] = lineMarker;
  74238. data.elements [numElements++] = x1;
  74239. data.elements [numElements++] = y1;
  74240. data.elements [numElements++] = lineMarker;
  74241. data.elements [numElements++] = x2;
  74242. data.elements [numElements++] = y1;
  74243. data.elements [numElements++] = lineMarker;
  74244. data.elements [numElements++] = x2;
  74245. data.elements [numElements++] = y2;
  74246. data.elements [numElements++] = closeSubPathMarker;
  74247. }
  74248. void Path::addRoundedRectangle (const float x, const float y,
  74249. const float w, const float h,
  74250. float csx,
  74251. float csy)
  74252. {
  74253. csx = jmin (csx, w * 0.5f);
  74254. csy = jmin (csy, h * 0.5f);
  74255. const float cs45x = csx * 0.45f;
  74256. const float cs45y = csy * 0.45f;
  74257. const float x2 = x + w;
  74258. const float y2 = y + h;
  74259. startNewSubPath (x + csx, y);
  74260. lineTo (x2 - csx, y);
  74261. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74262. lineTo (x2, y2 - csy);
  74263. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74264. lineTo (x + csx, y2);
  74265. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74266. lineTo (x, y + csy);
  74267. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74268. closeSubPath();
  74269. }
  74270. void Path::addRoundedRectangle (const float x, const float y,
  74271. const float w, const float h,
  74272. float cs)
  74273. {
  74274. addRoundedRectangle (x, y, w, h, cs, cs);
  74275. }
  74276. void Path::addTriangle (const float x1, const float y1,
  74277. const float x2, const float y2,
  74278. const float x3, const float y3)
  74279. {
  74280. startNewSubPath (x1, y1);
  74281. lineTo (x2, y2);
  74282. lineTo (x3, y3);
  74283. closeSubPath();
  74284. }
  74285. void Path::addQuadrilateral (const float x1, const float y1,
  74286. const float x2, const float y2,
  74287. const float x3, const float y3,
  74288. const float x4, const float y4)
  74289. {
  74290. startNewSubPath (x1, y1);
  74291. lineTo (x2, y2);
  74292. lineTo (x3, y3);
  74293. lineTo (x4, y4);
  74294. closeSubPath();
  74295. }
  74296. void Path::addEllipse (const float x, const float y,
  74297. const float w, const float h)
  74298. {
  74299. const float hw = w * 0.5f;
  74300. const float hw55 = hw * 0.55f;
  74301. const float hh = h * 0.5f;
  74302. const float hh55 = hh * 0.55f;
  74303. const float cx = x + hw;
  74304. const float cy = y + hh;
  74305. startNewSubPath (cx, cy - hh);
  74306. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74307. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74308. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74309. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74310. closeSubPath();
  74311. }
  74312. void Path::addArc (const float x, const float y,
  74313. const float w, const float h,
  74314. const float fromRadians,
  74315. const float toRadians,
  74316. const bool startAsNewSubPath)
  74317. {
  74318. const float radiusX = w / 2.0f;
  74319. const float radiusY = h / 2.0f;
  74320. addCentredArc (x + radiusX,
  74321. y + radiusY,
  74322. radiusX, radiusY,
  74323. 0.0f,
  74324. fromRadians, toRadians,
  74325. startAsNewSubPath);
  74326. }
  74327. void Path::addCentredArc (const float centreX, const float centreY,
  74328. const float radiusX, const float radiusY,
  74329. const float rotationOfEllipse,
  74330. const float fromRadians,
  74331. const float toRadians,
  74332. const bool startAsNewSubPath)
  74333. {
  74334. if (radiusX > 0.0f && radiusY > 0.0f)
  74335. {
  74336. const Point<float> centre (centreX, centreY);
  74337. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74338. float angle = fromRadians;
  74339. if (startAsNewSubPath)
  74340. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74341. if (fromRadians < toRadians)
  74342. {
  74343. if (startAsNewSubPath)
  74344. angle += PathHelpers::ellipseAngularIncrement;
  74345. while (angle < toRadians)
  74346. {
  74347. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74348. angle += PathHelpers::ellipseAngularIncrement;
  74349. }
  74350. }
  74351. else
  74352. {
  74353. if (startAsNewSubPath)
  74354. angle -= PathHelpers::ellipseAngularIncrement;
  74355. while (angle > toRadians)
  74356. {
  74357. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74358. angle -= PathHelpers::ellipseAngularIncrement;
  74359. }
  74360. }
  74361. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74362. }
  74363. }
  74364. void Path::addPieSegment (const float x, const float y,
  74365. const float width, const float height,
  74366. const float fromRadians,
  74367. const float toRadians,
  74368. const float innerCircleProportionalSize)
  74369. {
  74370. float radiusX = width * 0.5f;
  74371. float radiusY = height * 0.5f;
  74372. const Point<float> centre (x + radiusX, y + radiusY);
  74373. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74374. addArc (x, y, width, height, fromRadians, toRadians);
  74375. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74376. {
  74377. closeSubPath();
  74378. if (innerCircleProportionalSize > 0)
  74379. {
  74380. radiusX *= innerCircleProportionalSize;
  74381. radiusY *= innerCircleProportionalSize;
  74382. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74383. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74384. }
  74385. }
  74386. else
  74387. {
  74388. if (innerCircleProportionalSize > 0)
  74389. {
  74390. radiusX *= innerCircleProportionalSize;
  74391. radiusY *= innerCircleProportionalSize;
  74392. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74393. }
  74394. else
  74395. {
  74396. lineTo (centre);
  74397. }
  74398. }
  74399. closeSubPath();
  74400. }
  74401. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74402. {
  74403. const Line<float> reversed (line.reversed());
  74404. lineThickness *= 0.5f;
  74405. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74406. lineTo (line.getPointAlongLine (0, -lineThickness));
  74407. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74408. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74409. closeSubPath();
  74410. }
  74411. void Path::addArrow (const Line<float>& line, float lineThickness,
  74412. float arrowheadWidth, float arrowheadLength)
  74413. {
  74414. const Line<float> reversed (line.reversed());
  74415. lineThickness *= 0.5f;
  74416. arrowheadWidth *= 0.5f;
  74417. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74418. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74419. lineTo (line.getPointAlongLine (0, -lineThickness));
  74420. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74421. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74422. lineTo (line.getEnd());
  74423. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74424. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74425. closeSubPath();
  74426. }
  74427. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74428. const float radius, const float startAngle)
  74429. {
  74430. jassert (numberOfSides > 1); // this would be silly.
  74431. if (numberOfSides > 1)
  74432. {
  74433. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74434. for (int i = 0; i < numberOfSides; ++i)
  74435. {
  74436. const float angle = startAngle + i * angleBetweenPoints;
  74437. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74438. if (i == 0)
  74439. startNewSubPath (p);
  74440. else
  74441. lineTo (p);
  74442. }
  74443. closeSubPath();
  74444. }
  74445. }
  74446. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74447. const float innerRadius, const float outerRadius, const float startAngle)
  74448. {
  74449. jassert (numberOfPoints > 1); // this would be silly.
  74450. if (numberOfPoints > 1)
  74451. {
  74452. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74453. for (int i = 0; i < numberOfPoints; ++i)
  74454. {
  74455. const float angle = startAngle + i * angleBetweenPoints;
  74456. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74457. if (i == 0)
  74458. startNewSubPath (p);
  74459. else
  74460. lineTo (p);
  74461. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74462. }
  74463. closeSubPath();
  74464. }
  74465. }
  74466. void Path::addBubble (float x, float y,
  74467. float w, float h,
  74468. float cs,
  74469. float tipX,
  74470. float tipY,
  74471. int whichSide,
  74472. float arrowPos,
  74473. float arrowWidth)
  74474. {
  74475. if (w > 1.0f && h > 1.0f)
  74476. {
  74477. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74478. const float cs2 = 2.0f * cs;
  74479. startNewSubPath (x + cs, y);
  74480. if (whichSide == 0)
  74481. {
  74482. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74483. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74484. lineTo (arrowX1, y);
  74485. lineTo (tipX, tipY);
  74486. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74487. }
  74488. lineTo (x + w - cs, y);
  74489. if (cs > 0.0f)
  74490. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74491. if (whichSide == 3)
  74492. {
  74493. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74494. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74495. lineTo (x + w, arrowY1);
  74496. lineTo (tipX, tipY);
  74497. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74498. }
  74499. lineTo (x + w, y + h - cs);
  74500. if (cs > 0.0f)
  74501. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74502. if (whichSide == 2)
  74503. {
  74504. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74505. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74506. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74507. lineTo (tipX, tipY);
  74508. lineTo (arrowX1, y + h);
  74509. }
  74510. lineTo (x + cs, y + h);
  74511. if (cs > 0.0f)
  74512. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74513. if (whichSide == 1)
  74514. {
  74515. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74516. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74517. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74518. lineTo (tipX, tipY);
  74519. lineTo (x, arrowY1);
  74520. }
  74521. lineTo (x, y + cs);
  74522. if (cs > 0.0f)
  74523. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74524. closeSubPath();
  74525. }
  74526. }
  74527. void Path::addPath (const Path& other)
  74528. {
  74529. size_t i = 0;
  74530. while (i < other.numElements)
  74531. {
  74532. const float type = other.data.elements [i++];
  74533. if (type == moveMarker)
  74534. {
  74535. startNewSubPath (other.data.elements [i],
  74536. other.data.elements [i + 1]);
  74537. i += 2;
  74538. }
  74539. else if (type == lineMarker)
  74540. {
  74541. lineTo (other.data.elements [i],
  74542. other.data.elements [i + 1]);
  74543. i += 2;
  74544. }
  74545. else if (type == quadMarker)
  74546. {
  74547. quadraticTo (other.data.elements [i],
  74548. other.data.elements [i + 1],
  74549. other.data.elements [i + 2],
  74550. other.data.elements [i + 3]);
  74551. i += 4;
  74552. }
  74553. else if (type == cubicMarker)
  74554. {
  74555. cubicTo (other.data.elements [i],
  74556. other.data.elements [i + 1],
  74557. other.data.elements [i + 2],
  74558. other.data.elements [i + 3],
  74559. other.data.elements [i + 4],
  74560. other.data.elements [i + 5]);
  74561. i += 6;
  74562. }
  74563. else if (type == closeSubPathMarker)
  74564. {
  74565. closeSubPath();
  74566. }
  74567. else
  74568. {
  74569. // something's gone wrong with the element list!
  74570. jassertfalse;
  74571. }
  74572. }
  74573. }
  74574. void Path::addPath (const Path& other,
  74575. const AffineTransform& transformToApply)
  74576. {
  74577. size_t i = 0;
  74578. while (i < other.numElements)
  74579. {
  74580. const float type = other.data.elements [i++];
  74581. if (type == closeSubPathMarker)
  74582. {
  74583. closeSubPath();
  74584. }
  74585. else
  74586. {
  74587. float x = other.data.elements [i++];
  74588. float y = other.data.elements [i++];
  74589. transformToApply.transformPoint (x, y);
  74590. if (type == moveMarker)
  74591. {
  74592. startNewSubPath (x, y);
  74593. }
  74594. else if (type == lineMarker)
  74595. {
  74596. lineTo (x, y);
  74597. }
  74598. else if (type == quadMarker)
  74599. {
  74600. float x2 = other.data.elements [i++];
  74601. float y2 = other.data.elements [i++];
  74602. transformToApply.transformPoint (x2, y2);
  74603. quadraticTo (x, y, x2, y2);
  74604. }
  74605. else if (type == cubicMarker)
  74606. {
  74607. float x2 = other.data.elements [i++];
  74608. float y2 = other.data.elements [i++];
  74609. float x3 = other.data.elements [i++];
  74610. float y3 = other.data.elements [i++];
  74611. transformToApply.transformPoints (x2, y2, x3, y3);
  74612. cubicTo (x, y, x2, y2, x3, y3);
  74613. }
  74614. else
  74615. {
  74616. // something's gone wrong with the element list!
  74617. jassertfalse;
  74618. }
  74619. }
  74620. }
  74621. }
  74622. void Path::applyTransform (const AffineTransform& transform) throw()
  74623. {
  74624. size_t i = 0;
  74625. pathYMin = pathXMin = 0;
  74626. pathYMax = pathXMax = 0;
  74627. bool setMaxMin = false;
  74628. while (i < numElements)
  74629. {
  74630. const float type = data.elements [i++];
  74631. if (type == moveMarker)
  74632. {
  74633. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74634. if (setMaxMin)
  74635. {
  74636. pathXMin = jmin (pathXMin, data.elements [i]);
  74637. pathXMax = jmax (pathXMax, data.elements [i]);
  74638. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74639. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74640. }
  74641. else
  74642. {
  74643. pathXMin = pathXMax = data.elements [i];
  74644. pathYMin = pathYMax = data.elements [i + 1];
  74645. setMaxMin = true;
  74646. }
  74647. i += 2;
  74648. }
  74649. else if (type == lineMarker)
  74650. {
  74651. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74652. pathXMin = jmin (pathXMin, data.elements [i]);
  74653. pathXMax = jmax (pathXMax, data.elements [i]);
  74654. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74655. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74656. i += 2;
  74657. }
  74658. else if (type == quadMarker)
  74659. {
  74660. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74661. data.elements [i + 2], data.elements [i + 3]);
  74662. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74663. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74664. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74665. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74666. i += 4;
  74667. }
  74668. else if (type == cubicMarker)
  74669. {
  74670. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74671. data.elements [i + 2], data.elements [i + 3],
  74672. data.elements [i + 4], data.elements [i + 5]);
  74673. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74674. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74675. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74676. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74677. i += 6;
  74678. }
  74679. }
  74680. }
  74681. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74682. const float w, const float h,
  74683. const bool preserveProportions,
  74684. const Justification& justification) const
  74685. {
  74686. Rectangle<float> bounds (getBounds());
  74687. if (preserveProportions)
  74688. {
  74689. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74690. return AffineTransform::identity;
  74691. float newW, newH;
  74692. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74693. if (srcRatio > h / w)
  74694. {
  74695. newW = h / srcRatio;
  74696. newH = h;
  74697. }
  74698. else
  74699. {
  74700. newW = w;
  74701. newH = w * srcRatio;
  74702. }
  74703. float newXCentre = x;
  74704. float newYCentre = y;
  74705. if (justification.testFlags (Justification::left))
  74706. newXCentre += newW * 0.5f;
  74707. else if (justification.testFlags (Justification::right))
  74708. newXCentre += w - newW * 0.5f;
  74709. else
  74710. newXCentre += w * 0.5f;
  74711. if (justification.testFlags (Justification::top))
  74712. newYCentre += newH * 0.5f;
  74713. else if (justification.testFlags (Justification::bottom))
  74714. newYCentre += h - newH * 0.5f;
  74715. else
  74716. newYCentre += h * 0.5f;
  74717. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74718. bounds.getHeight() * -0.5f - bounds.getY())
  74719. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74720. .translated (newXCentre, newYCentre);
  74721. }
  74722. else
  74723. {
  74724. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74725. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74726. .translated (x, y);
  74727. }
  74728. }
  74729. bool Path::contains (const float x, const float y, const float tolerance) const
  74730. {
  74731. if (x <= pathXMin || x >= pathXMax
  74732. || y <= pathYMin || y >= pathYMax)
  74733. return false;
  74734. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74735. int positiveCrossings = 0;
  74736. int negativeCrossings = 0;
  74737. while (i.next())
  74738. {
  74739. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74740. {
  74741. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74742. if (intersectX <= x)
  74743. {
  74744. if (i.y1 < i.y2)
  74745. ++positiveCrossings;
  74746. else
  74747. ++negativeCrossings;
  74748. }
  74749. }
  74750. }
  74751. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74752. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74753. }
  74754. bool Path::contains (const Point<float>& point, const float tolerance) const
  74755. {
  74756. return contains (point.getX(), point.getY(), tolerance);
  74757. }
  74758. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  74759. {
  74760. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74761. Point<float> intersection;
  74762. while (i.next())
  74763. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74764. return true;
  74765. return false;
  74766. }
  74767. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74768. {
  74769. Line<float> result (line);
  74770. const bool startInside = contains (line.getStart());
  74771. const bool endInside = contains (line.getEnd());
  74772. if (startInside == endInside)
  74773. {
  74774. if (keepSectionOutsidePath == startInside)
  74775. result = Line<float>();
  74776. }
  74777. else
  74778. {
  74779. PathFlatteningIterator i (*this, AffineTransform::identity);
  74780. Point<float> intersection;
  74781. while (i.next())
  74782. {
  74783. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74784. {
  74785. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74786. result.setStart (intersection);
  74787. else
  74788. result.setEnd (intersection);
  74789. }
  74790. }
  74791. }
  74792. return result;
  74793. }
  74794. float Path::getLength (const AffineTransform& transform) const
  74795. {
  74796. float length = 0;
  74797. PathFlatteningIterator i (*this, transform);
  74798. while (i.next())
  74799. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74800. return length;
  74801. }
  74802. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74803. {
  74804. PathFlatteningIterator i (*this, transform);
  74805. while (i.next())
  74806. {
  74807. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74808. const float lineLength = line.getLength();
  74809. if (distanceFromStart <= lineLength)
  74810. return line.getPointAlongLine (distanceFromStart);
  74811. distanceFromStart -= lineLength;
  74812. }
  74813. return Point<float> (i.x2, i.y2);
  74814. }
  74815. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74816. const AffineTransform& transform) const
  74817. {
  74818. PathFlatteningIterator i (*this, transform);
  74819. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74820. float length = 0;
  74821. Point<float> pointOnLine;
  74822. while (i.next())
  74823. {
  74824. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74825. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74826. if (distance < bestDistance)
  74827. {
  74828. bestDistance = distance;
  74829. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74830. pointOnPath = pointOnLine;
  74831. }
  74832. length += line.getLength();
  74833. }
  74834. return bestPosition;
  74835. }
  74836. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74837. {
  74838. if (cornerRadius <= 0.01f)
  74839. return *this;
  74840. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74841. size_t n = 0;
  74842. bool lastWasLine = false, firstWasLine = false;
  74843. Path p;
  74844. while (n < numElements)
  74845. {
  74846. const float type = data.elements [n++];
  74847. if (type == moveMarker)
  74848. {
  74849. indexOfPathStart = p.numElements;
  74850. indexOfPathStartThis = n - 1;
  74851. const float x = data.elements [n++];
  74852. const float y = data.elements [n++];
  74853. p.startNewSubPath (x, y);
  74854. lastWasLine = false;
  74855. firstWasLine = (data.elements [n] == lineMarker);
  74856. }
  74857. else if (type == lineMarker || type == closeSubPathMarker)
  74858. {
  74859. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74860. if (type == lineMarker)
  74861. {
  74862. endX = data.elements [n++];
  74863. endY = data.elements [n++];
  74864. if (n > 8)
  74865. {
  74866. startX = data.elements [n - 8];
  74867. startY = data.elements [n - 7];
  74868. joinX = data.elements [n - 5];
  74869. joinY = data.elements [n - 4];
  74870. }
  74871. }
  74872. else
  74873. {
  74874. endX = data.elements [indexOfPathStartThis + 1];
  74875. endY = data.elements [indexOfPathStartThis + 2];
  74876. if (n > 6)
  74877. {
  74878. startX = data.elements [n - 6];
  74879. startY = data.elements [n - 5];
  74880. joinX = data.elements [n - 3];
  74881. joinY = data.elements [n - 2];
  74882. }
  74883. }
  74884. if (lastWasLine)
  74885. {
  74886. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74887. if (len1 > 0)
  74888. {
  74889. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74890. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74891. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74892. }
  74893. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74894. if (len2 > 0)
  74895. {
  74896. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74897. p.quadraticTo (joinX, joinY,
  74898. (float) (joinX + (endX - joinX) * propNeeded),
  74899. (float) (joinY + (endY - joinY) * propNeeded));
  74900. }
  74901. p.lineTo (endX, endY);
  74902. }
  74903. else if (type == lineMarker)
  74904. {
  74905. p.lineTo (endX, endY);
  74906. lastWasLine = true;
  74907. }
  74908. if (type == closeSubPathMarker)
  74909. {
  74910. if (firstWasLine)
  74911. {
  74912. startX = data.elements [n - 3];
  74913. startY = data.elements [n - 2];
  74914. joinX = endX;
  74915. joinY = endY;
  74916. endX = data.elements [indexOfPathStartThis + 4];
  74917. endY = data.elements [indexOfPathStartThis + 5];
  74918. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74919. if (len1 > 0)
  74920. {
  74921. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74922. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74923. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74924. }
  74925. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74926. if (len2 > 0)
  74927. {
  74928. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74929. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74930. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74931. p.quadraticTo (joinX, joinY, endX, endY);
  74932. p.data.elements [indexOfPathStart + 1] = endX;
  74933. p.data.elements [indexOfPathStart + 2] = endY;
  74934. }
  74935. }
  74936. p.closeSubPath();
  74937. }
  74938. }
  74939. else if (type == quadMarker)
  74940. {
  74941. lastWasLine = false;
  74942. const float x1 = data.elements [n++];
  74943. const float y1 = data.elements [n++];
  74944. const float x2 = data.elements [n++];
  74945. const float y2 = data.elements [n++];
  74946. p.quadraticTo (x1, y1, x2, y2);
  74947. }
  74948. else if (type == cubicMarker)
  74949. {
  74950. lastWasLine = false;
  74951. const float x1 = data.elements [n++];
  74952. const float y1 = data.elements [n++];
  74953. const float x2 = data.elements [n++];
  74954. const float y2 = data.elements [n++];
  74955. const float x3 = data.elements [n++];
  74956. const float y3 = data.elements [n++];
  74957. p.cubicTo (x1, y1, x2, y2, x3, y3);
  74958. }
  74959. }
  74960. return p;
  74961. }
  74962. void Path::loadPathFromStream (InputStream& source)
  74963. {
  74964. while (! source.isExhausted())
  74965. {
  74966. switch (source.readByte())
  74967. {
  74968. case 'm':
  74969. {
  74970. const float x = source.readFloat();
  74971. const float y = source.readFloat();
  74972. startNewSubPath (x, y);
  74973. break;
  74974. }
  74975. case 'l':
  74976. {
  74977. const float x = source.readFloat();
  74978. const float y = source.readFloat();
  74979. lineTo (x, y);
  74980. break;
  74981. }
  74982. case 'q':
  74983. {
  74984. const float x1 = source.readFloat();
  74985. const float y1 = source.readFloat();
  74986. const float x2 = source.readFloat();
  74987. const float y2 = source.readFloat();
  74988. quadraticTo (x1, y1, x2, y2);
  74989. break;
  74990. }
  74991. case 'b':
  74992. {
  74993. const float x1 = source.readFloat();
  74994. const float y1 = source.readFloat();
  74995. const float x2 = source.readFloat();
  74996. const float y2 = source.readFloat();
  74997. const float x3 = source.readFloat();
  74998. const float y3 = source.readFloat();
  74999. cubicTo (x1, y1, x2, y2, x3, y3);
  75000. break;
  75001. }
  75002. case 'c':
  75003. closeSubPath();
  75004. break;
  75005. case 'n':
  75006. useNonZeroWinding = true;
  75007. break;
  75008. case 'z':
  75009. useNonZeroWinding = false;
  75010. break;
  75011. case 'e':
  75012. return; // end of path marker
  75013. default:
  75014. jassertfalse; // illegal char in the stream
  75015. break;
  75016. }
  75017. }
  75018. }
  75019. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75020. {
  75021. MemoryInputStream in (pathData, numberOfBytes, false);
  75022. loadPathFromStream (in);
  75023. }
  75024. void Path::writePathToStream (OutputStream& dest) const
  75025. {
  75026. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75027. size_t i = 0;
  75028. while (i < numElements)
  75029. {
  75030. const float type = data.elements [i++];
  75031. if (type == moveMarker)
  75032. {
  75033. dest.writeByte ('m');
  75034. dest.writeFloat (data.elements [i++]);
  75035. dest.writeFloat (data.elements [i++]);
  75036. }
  75037. else if (type == lineMarker)
  75038. {
  75039. dest.writeByte ('l');
  75040. dest.writeFloat (data.elements [i++]);
  75041. dest.writeFloat (data.elements [i++]);
  75042. }
  75043. else if (type == quadMarker)
  75044. {
  75045. dest.writeByte ('q');
  75046. dest.writeFloat (data.elements [i++]);
  75047. dest.writeFloat (data.elements [i++]);
  75048. dest.writeFloat (data.elements [i++]);
  75049. dest.writeFloat (data.elements [i++]);
  75050. }
  75051. else if (type == cubicMarker)
  75052. {
  75053. dest.writeByte ('b');
  75054. dest.writeFloat (data.elements [i++]);
  75055. dest.writeFloat (data.elements [i++]);
  75056. dest.writeFloat (data.elements [i++]);
  75057. dest.writeFloat (data.elements [i++]);
  75058. dest.writeFloat (data.elements [i++]);
  75059. dest.writeFloat (data.elements [i++]);
  75060. }
  75061. else if (type == closeSubPathMarker)
  75062. {
  75063. dest.writeByte ('c');
  75064. }
  75065. }
  75066. dest.writeByte ('e'); // marks the end-of-path
  75067. }
  75068. const String Path::toString() const
  75069. {
  75070. MemoryOutputStream s (2048);
  75071. if (! useNonZeroWinding)
  75072. s << 'a';
  75073. size_t i = 0;
  75074. float lastMarker = 0.0f;
  75075. while (i < numElements)
  75076. {
  75077. const float marker = data.elements [i++];
  75078. char markerChar = 0;
  75079. int numCoords = 0;
  75080. if (marker == moveMarker)
  75081. {
  75082. markerChar = 'm';
  75083. numCoords = 2;
  75084. }
  75085. else if (marker == lineMarker)
  75086. {
  75087. markerChar = 'l';
  75088. numCoords = 2;
  75089. }
  75090. else if (marker == quadMarker)
  75091. {
  75092. markerChar = 'q';
  75093. numCoords = 4;
  75094. }
  75095. else if (marker == cubicMarker)
  75096. {
  75097. markerChar = 'c';
  75098. numCoords = 6;
  75099. }
  75100. else
  75101. {
  75102. jassert (marker == closeSubPathMarker);
  75103. markerChar = 'z';
  75104. }
  75105. if (marker != lastMarker)
  75106. {
  75107. if (s.getDataSize() != 0)
  75108. s << ' ';
  75109. s << markerChar;
  75110. lastMarker = marker;
  75111. }
  75112. while (--numCoords >= 0 && i < numElements)
  75113. {
  75114. String coord (data.elements [i++], 3);
  75115. while (coord.endsWithChar ('0') && coord != "0")
  75116. coord = coord.dropLastCharacters (1);
  75117. if (coord.endsWithChar ('.'))
  75118. coord = coord.dropLastCharacters (1);
  75119. if (s.getDataSize() != 0)
  75120. s << ' ';
  75121. s << coord;
  75122. }
  75123. }
  75124. return s.toUTF8();
  75125. }
  75126. void Path::restoreFromString (const String& stringVersion)
  75127. {
  75128. clear();
  75129. setUsingNonZeroWinding (true);
  75130. const juce_wchar* t = stringVersion;
  75131. juce_wchar marker = 'm';
  75132. int numValues = 2;
  75133. float values [6];
  75134. for (;;)
  75135. {
  75136. const String token (PathHelpers::nextToken (t));
  75137. const juce_wchar firstChar = token[0];
  75138. int startNum = 0;
  75139. if (firstChar == 0)
  75140. break;
  75141. if (firstChar == 'm' || firstChar == 'l')
  75142. {
  75143. marker = firstChar;
  75144. numValues = 2;
  75145. }
  75146. else if (firstChar == 'q')
  75147. {
  75148. marker = firstChar;
  75149. numValues = 4;
  75150. }
  75151. else if (firstChar == 'c')
  75152. {
  75153. marker = firstChar;
  75154. numValues = 6;
  75155. }
  75156. else if (firstChar == 'z')
  75157. {
  75158. marker = firstChar;
  75159. numValues = 0;
  75160. }
  75161. else if (firstChar == 'a')
  75162. {
  75163. setUsingNonZeroWinding (false);
  75164. continue;
  75165. }
  75166. else
  75167. {
  75168. ++startNum;
  75169. values [0] = token.getFloatValue();
  75170. }
  75171. for (int i = startNum; i < numValues; ++i)
  75172. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75173. switch (marker)
  75174. {
  75175. case 'm': startNewSubPath (values[0], values[1]); break;
  75176. case 'l': lineTo (values[0], values[1]); break;
  75177. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75178. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75179. case 'z': closeSubPath(); break;
  75180. default: jassertfalse; break; // illegal string format?
  75181. }
  75182. }
  75183. }
  75184. Path::Iterator::Iterator (const Path& path_)
  75185. : path (path_),
  75186. index (0)
  75187. {
  75188. }
  75189. Path::Iterator::~Iterator()
  75190. {
  75191. }
  75192. bool Path::Iterator::next()
  75193. {
  75194. const float* const elements = path.data.elements;
  75195. if (index < path.numElements)
  75196. {
  75197. const float type = elements [index++];
  75198. if (type == moveMarker)
  75199. {
  75200. elementType = startNewSubPath;
  75201. x1 = elements [index++];
  75202. y1 = elements [index++];
  75203. }
  75204. else if (type == lineMarker)
  75205. {
  75206. elementType = lineTo;
  75207. x1 = elements [index++];
  75208. y1 = elements [index++];
  75209. }
  75210. else if (type == quadMarker)
  75211. {
  75212. elementType = quadraticTo;
  75213. x1 = elements [index++];
  75214. y1 = elements [index++];
  75215. x2 = elements [index++];
  75216. y2 = elements [index++];
  75217. }
  75218. else if (type == cubicMarker)
  75219. {
  75220. elementType = cubicTo;
  75221. x1 = elements [index++];
  75222. y1 = elements [index++];
  75223. x2 = elements [index++];
  75224. y2 = elements [index++];
  75225. x3 = elements [index++];
  75226. y3 = elements [index++];
  75227. }
  75228. else if (type == closeSubPathMarker)
  75229. {
  75230. elementType = closePath;
  75231. }
  75232. return true;
  75233. }
  75234. return false;
  75235. }
  75236. END_JUCE_NAMESPACE
  75237. /*** End of inlined file: juce_Path.cpp ***/
  75238. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75239. BEGIN_JUCE_NAMESPACE
  75240. #if JUCE_MSVC && JUCE_DEBUG
  75241. #pragma optimize ("t", on)
  75242. #endif
  75243. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75244. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75245. const AffineTransform& transform_,
  75246. const float tolerance)
  75247. : x2 (0),
  75248. y2 (0),
  75249. closesSubPath (false),
  75250. subPathIndex (-1),
  75251. path (path_),
  75252. transform (transform_),
  75253. points (path_.data.elements),
  75254. toleranceSquared (tolerance * tolerance),
  75255. subPathCloseX (0),
  75256. subPathCloseY (0),
  75257. isIdentityTransform (transform_.isIdentity()),
  75258. stackBase (32),
  75259. index (0),
  75260. stackSize (32)
  75261. {
  75262. stackPos = stackBase;
  75263. }
  75264. PathFlatteningIterator::~PathFlatteningIterator()
  75265. {
  75266. }
  75267. bool PathFlatteningIterator::next()
  75268. {
  75269. x1 = x2;
  75270. y1 = y2;
  75271. float x3 = 0;
  75272. float y3 = 0;
  75273. float x4 = 0;
  75274. float y4 = 0;
  75275. float type;
  75276. for (;;)
  75277. {
  75278. if (stackPos == stackBase)
  75279. {
  75280. if (index >= path.numElements)
  75281. {
  75282. return false;
  75283. }
  75284. else
  75285. {
  75286. type = points [index++];
  75287. if (type != Path::closeSubPathMarker)
  75288. {
  75289. x2 = points [index++];
  75290. y2 = points [index++];
  75291. if (type == Path::quadMarker)
  75292. {
  75293. x3 = points [index++];
  75294. y3 = points [index++];
  75295. if (! isIdentityTransform)
  75296. transform.transformPoints (x2, y2, x3, y3);
  75297. }
  75298. else if (type == Path::cubicMarker)
  75299. {
  75300. x3 = points [index++];
  75301. y3 = points [index++];
  75302. x4 = points [index++];
  75303. y4 = points [index++];
  75304. if (! isIdentityTransform)
  75305. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75306. }
  75307. else
  75308. {
  75309. if (! isIdentityTransform)
  75310. transform.transformPoint (x2, y2);
  75311. }
  75312. }
  75313. }
  75314. }
  75315. else
  75316. {
  75317. type = *--stackPos;
  75318. if (type != Path::closeSubPathMarker)
  75319. {
  75320. x2 = *--stackPos;
  75321. y2 = *--stackPos;
  75322. if (type == Path::quadMarker)
  75323. {
  75324. x3 = *--stackPos;
  75325. y3 = *--stackPos;
  75326. }
  75327. else if (type == Path::cubicMarker)
  75328. {
  75329. x3 = *--stackPos;
  75330. y3 = *--stackPos;
  75331. x4 = *--stackPos;
  75332. y4 = *--stackPos;
  75333. }
  75334. }
  75335. }
  75336. if (type == Path::lineMarker)
  75337. {
  75338. ++subPathIndex;
  75339. closesSubPath = (stackPos == stackBase)
  75340. && (index < path.numElements)
  75341. && (points [index] == Path::closeSubPathMarker)
  75342. && x2 == subPathCloseX
  75343. && y2 == subPathCloseY;
  75344. return true;
  75345. }
  75346. else if (type == Path::quadMarker)
  75347. {
  75348. const size_t offset = (size_t) (stackPos - stackBase);
  75349. if (offset >= stackSize - 10)
  75350. {
  75351. stackSize <<= 1;
  75352. stackBase.realloc (stackSize);
  75353. stackPos = stackBase + offset;
  75354. }
  75355. const float m1x = (x1 + x2) * 0.5f;
  75356. const float m1y = (y1 + y2) * 0.5f;
  75357. const float m2x = (x2 + x3) * 0.5f;
  75358. const float m2y = (y2 + y3) * 0.5f;
  75359. const float m3x = (m1x + m2x) * 0.5f;
  75360. const float m3y = (m1y + m2y) * 0.5f;
  75361. const float errorX = m3x - x2;
  75362. const float errorY = m3y - y2;
  75363. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75364. {
  75365. *stackPos++ = y3;
  75366. *stackPos++ = x3;
  75367. *stackPos++ = m2y;
  75368. *stackPos++ = m2x;
  75369. *stackPos++ = Path::quadMarker;
  75370. *stackPos++ = m3y;
  75371. *stackPos++ = m3x;
  75372. *stackPos++ = m1y;
  75373. *stackPos++ = m1x;
  75374. *stackPos++ = Path::quadMarker;
  75375. }
  75376. else
  75377. {
  75378. *stackPos++ = y3;
  75379. *stackPos++ = x3;
  75380. *stackPos++ = Path::lineMarker;
  75381. *stackPos++ = m3y;
  75382. *stackPos++ = m3x;
  75383. *stackPos++ = Path::lineMarker;
  75384. }
  75385. jassert (stackPos < stackBase + stackSize);
  75386. }
  75387. else if (type == Path::cubicMarker)
  75388. {
  75389. const size_t offset = (size_t) (stackPos - stackBase);
  75390. if (offset >= stackSize - 16)
  75391. {
  75392. stackSize <<= 1;
  75393. stackBase.realloc (stackSize);
  75394. stackPos = stackBase + offset;
  75395. }
  75396. const float m1x = (x1 + x2) * 0.5f;
  75397. const float m1y = (y1 + y2) * 0.5f;
  75398. const float m2x = (x3 + x2) * 0.5f;
  75399. const float m2y = (y3 + y2) * 0.5f;
  75400. const float m3x = (x3 + x4) * 0.5f;
  75401. const float m3y = (y3 + y4) * 0.5f;
  75402. const float m4x = (m1x + m2x) * 0.5f;
  75403. const float m4y = (m1y + m2y) * 0.5f;
  75404. const float m5x = (m3x + m2x) * 0.5f;
  75405. const float m5y = (m3y + m2y) * 0.5f;
  75406. const float error1X = m4x - x2;
  75407. const float error1Y = m4y - y2;
  75408. const float error2X = m5x - x3;
  75409. const float error2Y = m5y - y3;
  75410. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75411. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75412. {
  75413. *stackPos++ = y4;
  75414. *stackPos++ = x4;
  75415. *stackPos++ = m3y;
  75416. *stackPos++ = m3x;
  75417. *stackPos++ = m5y;
  75418. *stackPos++ = m5x;
  75419. *stackPos++ = Path::cubicMarker;
  75420. *stackPos++ = (m4y + m5y) * 0.5f;
  75421. *stackPos++ = (m4x + m5x) * 0.5f;
  75422. *stackPos++ = m4y;
  75423. *stackPos++ = m4x;
  75424. *stackPos++ = m1y;
  75425. *stackPos++ = m1x;
  75426. *stackPos++ = Path::cubicMarker;
  75427. }
  75428. else
  75429. {
  75430. *stackPos++ = y4;
  75431. *stackPos++ = x4;
  75432. *stackPos++ = Path::lineMarker;
  75433. *stackPos++ = m5y;
  75434. *stackPos++ = m5x;
  75435. *stackPos++ = Path::lineMarker;
  75436. *stackPos++ = m4y;
  75437. *stackPos++ = m4x;
  75438. *stackPos++ = Path::lineMarker;
  75439. }
  75440. }
  75441. else if (type == Path::closeSubPathMarker)
  75442. {
  75443. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75444. {
  75445. x1 = x2;
  75446. y1 = y2;
  75447. x2 = subPathCloseX;
  75448. y2 = subPathCloseY;
  75449. closesSubPath = true;
  75450. return true;
  75451. }
  75452. }
  75453. else
  75454. {
  75455. jassert (type == Path::moveMarker);
  75456. subPathIndex = -1;
  75457. subPathCloseX = x1 = x2;
  75458. subPathCloseY = y1 = y2;
  75459. }
  75460. }
  75461. }
  75462. #if JUCE_MSVC && JUCE_DEBUG
  75463. #pragma optimize ("", on) // resets optimisations to the project defaults
  75464. #endif
  75465. END_JUCE_NAMESPACE
  75466. /*** End of inlined file: juce_PathIterator.cpp ***/
  75467. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75468. BEGIN_JUCE_NAMESPACE
  75469. PathStrokeType::PathStrokeType (const float strokeThickness,
  75470. const JointStyle jointStyle_,
  75471. const EndCapStyle endStyle_) throw()
  75472. : thickness (strokeThickness),
  75473. jointStyle (jointStyle_),
  75474. endStyle (endStyle_)
  75475. {
  75476. }
  75477. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75478. : thickness (other.thickness),
  75479. jointStyle (other.jointStyle),
  75480. endStyle (other.endStyle)
  75481. {
  75482. }
  75483. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75484. {
  75485. thickness = other.thickness;
  75486. jointStyle = other.jointStyle;
  75487. endStyle = other.endStyle;
  75488. return *this;
  75489. }
  75490. PathStrokeType::~PathStrokeType() throw()
  75491. {
  75492. }
  75493. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75494. {
  75495. return thickness == other.thickness
  75496. && jointStyle == other.jointStyle
  75497. && endStyle == other.endStyle;
  75498. }
  75499. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75500. {
  75501. return ! operator== (other);
  75502. }
  75503. namespace PathStrokeHelpers
  75504. {
  75505. bool lineIntersection (const float x1, const float y1,
  75506. const float x2, const float y2,
  75507. const float x3, const float y3,
  75508. const float x4, const float y4,
  75509. float& intersectionX,
  75510. float& intersectionY,
  75511. float& distanceBeyondLine1EndSquared) throw()
  75512. {
  75513. if (x2 != x3 || y2 != y3)
  75514. {
  75515. const float dx1 = x2 - x1;
  75516. const float dy1 = y2 - y1;
  75517. const float dx2 = x4 - x3;
  75518. const float dy2 = y4 - y3;
  75519. const float divisor = dx1 * dy2 - dx2 * dy1;
  75520. if (divisor == 0)
  75521. {
  75522. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75523. {
  75524. if (dy1 == 0 && dy2 != 0)
  75525. {
  75526. const float along = (y1 - y3) / dy2;
  75527. intersectionX = x3 + along * dx2;
  75528. intersectionY = y1;
  75529. distanceBeyondLine1EndSquared = intersectionX - x2;
  75530. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75531. if ((x2 > x1) == (intersectionX < x2))
  75532. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75533. return along >= 0 && along <= 1.0f;
  75534. }
  75535. else if (dy2 == 0 && dy1 != 0)
  75536. {
  75537. const float along = (y3 - y1) / dy1;
  75538. intersectionX = x1 + along * dx1;
  75539. intersectionY = y3;
  75540. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75541. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75542. if (along < 1.0f)
  75543. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75544. return along >= 0 && along <= 1.0f;
  75545. }
  75546. else if (dx1 == 0 && dx2 != 0)
  75547. {
  75548. const float along = (x1 - x3) / dx2;
  75549. intersectionX = x1;
  75550. intersectionY = y3 + along * dy2;
  75551. distanceBeyondLine1EndSquared = intersectionY - y2;
  75552. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75553. if ((y2 > y1) == (intersectionY < y2))
  75554. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75555. return along >= 0 && along <= 1.0f;
  75556. }
  75557. else if (dx2 == 0 && dx1 != 0)
  75558. {
  75559. const float along = (x3 - x1) / dx1;
  75560. intersectionX = x3;
  75561. intersectionY = y1 + along * dy1;
  75562. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75563. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75564. if (along < 1.0f)
  75565. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75566. return along >= 0 && along <= 1.0f;
  75567. }
  75568. }
  75569. intersectionX = 0.5f * (x2 + x3);
  75570. intersectionY = 0.5f * (y2 + y3);
  75571. distanceBeyondLine1EndSquared = 0.0f;
  75572. return false;
  75573. }
  75574. else
  75575. {
  75576. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75577. intersectionX = x1 + along1 * dx1;
  75578. intersectionY = y1 + along1 * dy1;
  75579. if (along1 >= 0 && along1 <= 1.0f)
  75580. {
  75581. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75582. if (along2 >= 0 && along2 <= divisor)
  75583. {
  75584. distanceBeyondLine1EndSquared = 0.0f;
  75585. return true;
  75586. }
  75587. }
  75588. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75589. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75590. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75591. if (along1 < 1.0f)
  75592. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75593. return false;
  75594. }
  75595. }
  75596. intersectionX = x2;
  75597. intersectionY = y2;
  75598. distanceBeyondLine1EndSquared = 0.0f;
  75599. return true;
  75600. }
  75601. void addEdgeAndJoint (Path& destPath,
  75602. const PathStrokeType::JointStyle style,
  75603. const float maxMiterExtensionSquared, const float width,
  75604. const float x1, const float y1,
  75605. const float x2, const float y2,
  75606. const float x3, const float y3,
  75607. const float x4, const float y4,
  75608. const float midX, const float midY)
  75609. {
  75610. if (style == PathStrokeType::beveled
  75611. || (x3 == x4 && y3 == y4)
  75612. || (x1 == x2 && y1 == y2))
  75613. {
  75614. destPath.lineTo (x2, y2);
  75615. destPath.lineTo (x3, y3);
  75616. }
  75617. else
  75618. {
  75619. float jx, jy, distanceBeyondLine1EndSquared;
  75620. // if they intersect, use this point..
  75621. if (lineIntersection (x1, y1, x2, y2,
  75622. x3, y3, x4, y4,
  75623. jx, jy, distanceBeyondLine1EndSquared))
  75624. {
  75625. destPath.lineTo (jx, jy);
  75626. }
  75627. else
  75628. {
  75629. if (style == PathStrokeType::mitered)
  75630. {
  75631. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75632. && distanceBeyondLine1EndSquared > 0.0f)
  75633. {
  75634. destPath.lineTo (jx, jy);
  75635. }
  75636. else
  75637. {
  75638. // the end sticks out too far, so just use a blunt joint
  75639. destPath.lineTo (x2, y2);
  75640. destPath.lineTo (x3, y3);
  75641. }
  75642. }
  75643. else
  75644. {
  75645. // curved joints
  75646. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75647. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75648. const float angleIncrement = 0.1f;
  75649. destPath.lineTo (x2, y2);
  75650. if (std::abs (angle1 - angle2) > angleIncrement)
  75651. {
  75652. if (angle2 > angle1 + float_Pi
  75653. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75654. {
  75655. if (angle2 > angle1)
  75656. angle2 -= float_Pi * 2.0f;
  75657. jassert (angle1 <= angle2 + float_Pi);
  75658. angle1 -= angleIncrement;
  75659. while (angle1 > angle2)
  75660. {
  75661. destPath.lineTo (midX + width * std::sin (angle1),
  75662. midY + width * std::cos (angle1));
  75663. angle1 -= angleIncrement;
  75664. }
  75665. }
  75666. else
  75667. {
  75668. if (angle1 > angle2)
  75669. angle1 -= float_Pi * 2.0f;
  75670. jassert (angle1 >= angle2 - float_Pi);
  75671. angle1 += angleIncrement;
  75672. while (angle1 < angle2)
  75673. {
  75674. destPath.lineTo (midX + width * std::sin (angle1),
  75675. midY + width * std::cos (angle1));
  75676. angle1 += angleIncrement;
  75677. }
  75678. }
  75679. }
  75680. destPath.lineTo (x3, y3);
  75681. }
  75682. }
  75683. }
  75684. }
  75685. void addLineEnd (Path& destPath,
  75686. const PathStrokeType::EndCapStyle style,
  75687. const float x1, const float y1,
  75688. const float x2, const float y2,
  75689. const float width)
  75690. {
  75691. if (style == PathStrokeType::butt)
  75692. {
  75693. destPath.lineTo (x2, y2);
  75694. }
  75695. else
  75696. {
  75697. float offx1, offy1, offx2, offy2;
  75698. float dx = x2 - x1;
  75699. float dy = y2 - y1;
  75700. const float len = juce_hypot (dx, dy);
  75701. if (len == 0)
  75702. {
  75703. offx1 = offx2 = x1;
  75704. offy1 = offy2 = y1;
  75705. }
  75706. else
  75707. {
  75708. const float offset = width / len;
  75709. dx *= offset;
  75710. dy *= offset;
  75711. offx1 = x1 + dy;
  75712. offy1 = y1 - dx;
  75713. offx2 = x2 + dy;
  75714. offy2 = y2 - dx;
  75715. }
  75716. if (style == PathStrokeType::square)
  75717. {
  75718. // sqaure ends
  75719. destPath.lineTo (offx1, offy1);
  75720. destPath.lineTo (offx2, offy2);
  75721. destPath.lineTo (x2, y2);
  75722. }
  75723. else
  75724. {
  75725. // rounded ends
  75726. const float midx = (offx1 + offx2) * 0.5f;
  75727. const float midy = (offy1 + offy2) * 0.5f;
  75728. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75729. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75730. midx, midy);
  75731. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75732. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75733. x2, y2);
  75734. }
  75735. }
  75736. }
  75737. struct Arrowhead
  75738. {
  75739. float startWidth, startLength;
  75740. float endWidth, endLength;
  75741. };
  75742. void addArrowhead (Path& destPath,
  75743. const float x1, const float y1,
  75744. const float x2, const float y2,
  75745. const float tipX, const float tipY,
  75746. const float width,
  75747. const float arrowheadWidth)
  75748. {
  75749. Line<float> line (x1, y1, x2, y2);
  75750. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75751. destPath.lineTo (tipX, tipY);
  75752. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75753. destPath.lineTo (x2, y2);
  75754. }
  75755. struct LineSection
  75756. {
  75757. float x1, y1, x2, y2; // original line
  75758. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75759. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75760. };
  75761. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75762. {
  75763. while (amountAtEnd > 0 && subPath.size() > 0)
  75764. {
  75765. LineSection& l = subPath.getReference (subPath.size() - 1);
  75766. float dx = l.rx2 - l.rx1;
  75767. float dy = l.ry2 - l.ry1;
  75768. const float len = juce_hypot (dx, dy);
  75769. if (len <= amountAtEnd && subPath.size() > 1)
  75770. {
  75771. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75772. prev.x2 = l.x2;
  75773. prev.y2 = l.y2;
  75774. subPath.removeLast();
  75775. amountAtEnd -= len;
  75776. }
  75777. else
  75778. {
  75779. const float prop = jmin (0.9999f, amountAtEnd / len);
  75780. dx *= prop;
  75781. dy *= prop;
  75782. l.rx1 += dx;
  75783. l.ry1 += dy;
  75784. l.lx2 += dx;
  75785. l.ly2 += dy;
  75786. break;
  75787. }
  75788. }
  75789. while (amountAtStart > 0 && subPath.size() > 0)
  75790. {
  75791. LineSection& l = subPath.getReference (0);
  75792. float dx = l.rx2 - l.rx1;
  75793. float dy = l.ry2 - l.ry1;
  75794. const float len = juce_hypot (dx, dy);
  75795. if (len <= amountAtStart && subPath.size() > 1)
  75796. {
  75797. LineSection& next = subPath.getReference (1);
  75798. next.x1 = l.x1;
  75799. next.y1 = l.y1;
  75800. subPath.remove (0);
  75801. amountAtStart -= len;
  75802. }
  75803. else
  75804. {
  75805. const float prop = jmin (0.9999f, amountAtStart / len);
  75806. dx *= prop;
  75807. dy *= prop;
  75808. l.rx2 -= dx;
  75809. l.ry2 -= dy;
  75810. l.lx1 -= dx;
  75811. l.ly1 -= dy;
  75812. break;
  75813. }
  75814. }
  75815. }
  75816. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75817. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75818. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75819. const Arrowhead* const arrowhead)
  75820. {
  75821. jassert (subPath.size() > 0);
  75822. if (arrowhead != 0)
  75823. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75824. const LineSection& firstLine = subPath.getReference (0);
  75825. float lastX1 = firstLine.lx1;
  75826. float lastY1 = firstLine.ly1;
  75827. float lastX2 = firstLine.lx2;
  75828. float lastY2 = firstLine.ly2;
  75829. if (isClosed)
  75830. {
  75831. destPath.startNewSubPath (lastX1, lastY1);
  75832. }
  75833. else
  75834. {
  75835. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75836. if (arrowhead != 0)
  75837. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75838. width, arrowhead->startWidth);
  75839. else
  75840. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75841. }
  75842. int i;
  75843. for (i = 1; i < subPath.size(); ++i)
  75844. {
  75845. const LineSection& l = subPath.getReference (i);
  75846. addEdgeAndJoint (destPath, jointStyle,
  75847. maxMiterExtensionSquared, width,
  75848. lastX1, lastY1, lastX2, lastY2,
  75849. l.lx1, l.ly1, l.lx2, l.ly2,
  75850. l.x1, l.y1);
  75851. lastX1 = l.lx1;
  75852. lastY1 = l.ly1;
  75853. lastX2 = l.lx2;
  75854. lastY2 = l.ly2;
  75855. }
  75856. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75857. if (isClosed)
  75858. {
  75859. const LineSection& l = subPath.getReference (0);
  75860. addEdgeAndJoint (destPath, jointStyle,
  75861. maxMiterExtensionSquared, width,
  75862. lastX1, lastY1, lastX2, lastY2,
  75863. l.lx1, l.ly1, l.lx2, l.ly2,
  75864. l.x1, l.y1);
  75865. destPath.closeSubPath();
  75866. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75867. }
  75868. else
  75869. {
  75870. destPath.lineTo (lastX2, lastY2);
  75871. if (arrowhead != 0)
  75872. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75873. width, arrowhead->endWidth);
  75874. else
  75875. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75876. }
  75877. lastX1 = lastLine.rx1;
  75878. lastY1 = lastLine.ry1;
  75879. lastX2 = lastLine.rx2;
  75880. lastY2 = lastLine.ry2;
  75881. for (i = subPath.size() - 1; --i >= 0;)
  75882. {
  75883. const LineSection& l = subPath.getReference (i);
  75884. addEdgeAndJoint (destPath, jointStyle,
  75885. maxMiterExtensionSquared, width,
  75886. lastX1, lastY1, lastX2, lastY2,
  75887. l.rx1, l.ry1, l.rx2, l.ry2,
  75888. l.x2, l.y2);
  75889. lastX1 = l.rx1;
  75890. lastY1 = l.ry1;
  75891. lastX2 = l.rx2;
  75892. lastY2 = l.ry2;
  75893. }
  75894. if (isClosed)
  75895. {
  75896. addEdgeAndJoint (destPath, jointStyle,
  75897. maxMiterExtensionSquared, width,
  75898. lastX1, lastY1, lastX2, lastY2,
  75899. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75900. lastLine.x2, lastLine.y2);
  75901. }
  75902. else
  75903. {
  75904. // do the last line
  75905. destPath.lineTo (lastX2, lastY2);
  75906. }
  75907. destPath.closeSubPath();
  75908. }
  75909. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75910. const PathStrokeType::EndCapStyle endStyle,
  75911. Path& destPath, const Path& source,
  75912. const AffineTransform& transform,
  75913. const float extraAccuracy, const Arrowhead* const arrowhead)
  75914. {
  75915. jassert (extraAccuracy > 0);
  75916. if (thickness <= 0)
  75917. {
  75918. destPath.clear();
  75919. return;
  75920. }
  75921. const Path* sourcePath = &source;
  75922. Path temp;
  75923. if (sourcePath == &destPath)
  75924. {
  75925. destPath.swapWithPath (temp);
  75926. sourcePath = &temp;
  75927. }
  75928. else
  75929. {
  75930. destPath.clear();
  75931. }
  75932. destPath.setUsingNonZeroWinding (true);
  75933. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75934. const float width = 0.5f * thickness;
  75935. // Iterate the path, creating a list of the
  75936. // left/right-hand lines along either side of it...
  75937. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  75938. Array <LineSection> subPath;
  75939. subPath.ensureStorageAllocated (512);
  75940. LineSection l;
  75941. l.x1 = 0;
  75942. l.y1 = 0;
  75943. const float minSegmentLength = 0.0001f;
  75944. while (it.next())
  75945. {
  75946. if (it.subPathIndex == 0)
  75947. {
  75948. if (subPath.size() > 0)
  75949. {
  75950. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75951. subPath.clearQuick();
  75952. }
  75953. l.x1 = it.x1;
  75954. l.y1 = it.y1;
  75955. }
  75956. l.x2 = it.x2;
  75957. l.y2 = it.y2;
  75958. float dx = l.x2 - l.x1;
  75959. float dy = l.y2 - l.y1;
  75960. const float hypotSquared = dx*dx + dy*dy;
  75961. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  75962. {
  75963. const float len = std::sqrt (hypotSquared);
  75964. if (len == 0)
  75965. {
  75966. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  75967. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  75968. }
  75969. else
  75970. {
  75971. const float offset = width / len;
  75972. dx *= offset;
  75973. dy *= offset;
  75974. l.rx2 = l.x1 - dy;
  75975. l.ry2 = l.y1 + dx;
  75976. l.lx1 = l.x1 + dy;
  75977. l.ly1 = l.y1 - dx;
  75978. l.lx2 = l.x2 + dy;
  75979. l.ly2 = l.y2 - dx;
  75980. l.rx1 = l.x2 - dy;
  75981. l.ry1 = l.y2 + dx;
  75982. }
  75983. subPath.add (l);
  75984. if (it.closesSubPath)
  75985. {
  75986. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75987. subPath.clearQuick();
  75988. }
  75989. else
  75990. {
  75991. l.x1 = it.x2;
  75992. l.y1 = it.y2;
  75993. }
  75994. }
  75995. }
  75996. if (subPath.size() > 0)
  75997. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75998. }
  75999. }
  76000. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76001. const AffineTransform& transform, const float extraAccuracy) const
  76002. {
  76003. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76004. transform, extraAccuracy, 0);
  76005. }
  76006. void PathStrokeType::createDashedStroke (Path& destPath,
  76007. const Path& sourcePath,
  76008. const float* dashLengths,
  76009. int numDashLengths,
  76010. const AffineTransform& transform,
  76011. const float extraAccuracy) const
  76012. {
  76013. jassert (extraAccuracy > 0);
  76014. if (thickness <= 0)
  76015. return;
  76016. // this should really be an even number..
  76017. jassert ((numDashLengths & 1) == 0);
  76018. Path newDestPath;
  76019. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76020. bool first = true;
  76021. int dashNum = 0;
  76022. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76023. float dx = 0.0f, dy = 0.0f;
  76024. for (;;)
  76025. {
  76026. const bool isSolid = ((dashNum & 1) == 0);
  76027. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76028. jassert (dashLen > 0); // must be a positive increment!
  76029. if (dashLen <= 0)
  76030. break;
  76031. pos += dashLen;
  76032. while (pos > lineEndPos)
  76033. {
  76034. if (! it.next())
  76035. {
  76036. if (isSolid && ! first)
  76037. newDestPath.lineTo (it.x2, it.y2);
  76038. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76039. return;
  76040. }
  76041. if (isSolid && ! first)
  76042. newDestPath.lineTo (it.x1, it.y1);
  76043. else
  76044. newDestPath.startNewSubPath (it.x1, it.y1);
  76045. dx = it.x2 - it.x1;
  76046. dy = it.y2 - it.y1;
  76047. lineLen = juce_hypot (dx, dy);
  76048. lineEndPos += lineLen;
  76049. first = it.closesSubPath;
  76050. }
  76051. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76052. if (isSolid)
  76053. newDestPath.lineTo (it.x1 + dx * alpha,
  76054. it.y1 + dy * alpha);
  76055. else
  76056. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76057. it.y1 + dy * alpha);
  76058. }
  76059. }
  76060. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76061. const Path& sourcePath,
  76062. const float arrowheadStartWidth, const float arrowheadStartLength,
  76063. const float arrowheadEndWidth, const float arrowheadEndLength,
  76064. const AffineTransform& transform,
  76065. const float extraAccuracy) const
  76066. {
  76067. PathStrokeHelpers::Arrowhead head;
  76068. head.startWidth = arrowheadStartWidth;
  76069. head.startLength = arrowheadStartLength;
  76070. head.endWidth = arrowheadEndWidth;
  76071. head.endLength = arrowheadEndLength;
  76072. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76073. destPath, sourcePath, transform, extraAccuracy, &head);
  76074. }
  76075. END_JUCE_NAMESPACE
  76076. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76077. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76078. BEGIN_JUCE_NAMESPACE
  76079. PositionedRectangle::PositionedRectangle() throw()
  76080. : x (0.0),
  76081. y (0.0),
  76082. w (0.0),
  76083. h (0.0),
  76084. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76085. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76086. wMode (absoluteSize),
  76087. hMode (absoluteSize)
  76088. {
  76089. }
  76090. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76091. : x (other.x),
  76092. y (other.y),
  76093. w (other.w),
  76094. h (other.h),
  76095. xMode (other.xMode),
  76096. yMode (other.yMode),
  76097. wMode (other.wMode),
  76098. hMode (other.hMode)
  76099. {
  76100. }
  76101. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76102. {
  76103. x = other.x;
  76104. y = other.y;
  76105. w = other.w;
  76106. h = other.h;
  76107. xMode = other.xMode;
  76108. yMode = other.yMode;
  76109. wMode = other.wMode;
  76110. hMode = other.hMode;
  76111. return *this;
  76112. }
  76113. PositionedRectangle::~PositionedRectangle() throw()
  76114. {
  76115. }
  76116. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76117. {
  76118. return x == other.x
  76119. && y == other.y
  76120. && w == other.w
  76121. && h == other.h
  76122. && xMode == other.xMode
  76123. && yMode == other.yMode
  76124. && wMode == other.wMode
  76125. && hMode == other.hMode;
  76126. }
  76127. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76128. {
  76129. return ! operator== (other);
  76130. }
  76131. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76132. {
  76133. StringArray tokens;
  76134. tokens.addTokens (stringVersion, false);
  76135. decodePosString (tokens [0], xMode, x);
  76136. decodePosString (tokens [1], yMode, y);
  76137. decodeSizeString (tokens [2], wMode, w);
  76138. decodeSizeString (tokens [3], hMode, h);
  76139. }
  76140. const String PositionedRectangle::toString() const throw()
  76141. {
  76142. String s;
  76143. s.preallocateStorage (12);
  76144. addPosDescription (s, xMode, x);
  76145. s << ' ';
  76146. addPosDescription (s, yMode, y);
  76147. s << ' ';
  76148. addSizeDescription (s, wMode, w);
  76149. s << ' ';
  76150. addSizeDescription (s, hMode, h);
  76151. return s;
  76152. }
  76153. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76154. {
  76155. jassert (! target.isEmpty());
  76156. double x_, y_, w_, h_;
  76157. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76158. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76159. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76160. roundToInt (w_), roundToInt (h_));
  76161. }
  76162. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76163. double& x_, double& y_,
  76164. double& w_, double& h_) const throw()
  76165. {
  76166. jassert (! target.isEmpty());
  76167. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76168. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76169. }
  76170. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76171. {
  76172. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76173. }
  76174. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76175. const Rectangle<int>& target) throw()
  76176. {
  76177. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76178. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76179. }
  76180. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76181. const double newW, const double newH,
  76182. const Rectangle<int>& target) throw()
  76183. {
  76184. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76185. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76186. }
  76187. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76188. {
  76189. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76190. updateFrom (comp.getBounds(), Rectangle<int>());
  76191. else
  76192. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76193. }
  76194. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76195. {
  76196. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76197. }
  76198. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76199. {
  76200. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76201. | absoluteFromParentBottomRight
  76202. | absoluteFromParentCentre
  76203. | proportionOfParentSize));
  76204. }
  76205. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76206. {
  76207. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76208. }
  76209. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76210. {
  76211. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76212. | absoluteFromParentBottomRight
  76213. | absoluteFromParentCentre
  76214. | proportionOfParentSize));
  76215. }
  76216. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76217. {
  76218. return (SizeMode) wMode;
  76219. }
  76220. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76221. {
  76222. return (SizeMode) hMode;
  76223. }
  76224. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76225. const PositionMode xMode_,
  76226. const AnchorPoint yAnchor,
  76227. const PositionMode yMode_,
  76228. const SizeMode widthMode,
  76229. const SizeMode heightMode,
  76230. const Rectangle<int>& target) throw()
  76231. {
  76232. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76233. {
  76234. double tx, tw;
  76235. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76236. xMode = (uint8) (xAnchor | xMode_);
  76237. wMode = (uint8) widthMode;
  76238. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76239. }
  76240. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76241. {
  76242. double ty, th;
  76243. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76244. yMode = (uint8) (yAnchor | yMode_);
  76245. hMode = (uint8) heightMode;
  76246. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76247. }
  76248. }
  76249. bool PositionedRectangle::isPositionAbsolute() const throw()
  76250. {
  76251. return xMode == absoluteFromParentTopLeft
  76252. && yMode == absoluteFromParentTopLeft
  76253. && wMode == absoluteSize
  76254. && hMode == absoluteSize;
  76255. }
  76256. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76257. {
  76258. if ((mode & proportionOfParentSize) != 0)
  76259. {
  76260. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76261. }
  76262. else
  76263. {
  76264. s << (roundToInt (value * 100.0) / 100.0);
  76265. if ((mode & absoluteFromParentBottomRight) != 0)
  76266. s << 'R';
  76267. else if ((mode & absoluteFromParentCentre) != 0)
  76268. s << 'C';
  76269. }
  76270. if ((mode & anchorAtRightOrBottom) != 0)
  76271. s << 'r';
  76272. else if ((mode & anchorAtCentre) != 0)
  76273. s << 'c';
  76274. }
  76275. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76276. {
  76277. if (mode == proportionalSize)
  76278. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76279. else if (mode == parentSizeMinusAbsolute)
  76280. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76281. else
  76282. s << (roundToInt (value * 100.0) / 100.0);
  76283. }
  76284. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76285. {
  76286. if (s.containsChar ('r'))
  76287. mode = anchorAtRightOrBottom;
  76288. else if (s.containsChar ('c'))
  76289. mode = anchorAtCentre;
  76290. else
  76291. mode = anchorAtLeftOrTop;
  76292. if (s.containsChar ('%'))
  76293. {
  76294. mode |= proportionOfParentSize;
  76295. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76296. }
  76297. else
  76298. {
  76299. if (s.containsChar ('R'))
  76300. mode |= absoluteFromParentBottomRight;
  76301. else if (s.containsChar ('C'))
  76302. mode |= absoluteFromParentCentre;
  76303. else
  76304. mode |= absoluteFromParentTopLeft;
  76305. value = s.removeCharacters ("rcRC").getDoubleValue();
  76306. }
  76307. }
  76308. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76309. {
  76310. if (s.containsChar ('%'))
  76311. {
  76312. mode = proportionalSize;
  76313. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76314. }
  76315. else if (s.containsChar ('M'))
  76316. {
  76317. mode = parentSizeMinusAbsolute;
  76318. value = s.getDoubleValue();
  76319. }
  76320. else
  76321. {
  76322. mode = absoluteSize;
  76323. value = s.getDoubleValue();
  76324. }
  76325. }
  76326. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76327. const double x_, const double w_,
  76328. const uint8 xMode_, const uint8 wMode_,
  76329. const int parentPos,
  76330. const int parentSize) const throw()
  76331. {
  76332. if (wMode_ == proportionalSize)
  76333. wOut = roundToInt (w_ * parentSize);
  76334. else if (wMode_ == parentSizeMinusAbsolute)
  76335. wOut = jmax (0, parentSize - roundToInt (w_));
  76336. else
  76337. wOut = roundToInt (w_);
  76338. if ((xMode_ & proportionOfParentSize) != 0)
  76339. xOut = parentPos + x_ * parentSize;
  76340. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76341. xOut = (parentPos + parentSize) - x_;
  76342. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76343. xOut = x_ + (parentPos + parentSize / 2);
  76344. else
  76345. xOut = x_ + parentPos;
  76346. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76347. xOut -= wOut;
  76348. else if ((xMode_ & anchorAtCentre) != 0)
  76349. xOut -= wOut / 2;
  76350. }
  76351. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76352. double x_, const double w_,
  76353. const uint8 xMode_, const uint8 wMode_,
  76354. const int parentPos,
  76355. const int parentSize) const throw()
  76356. {
  76357. if (wMode_ == proportionalSize)
  76358. {
  76359. if (parentSize > 0)
  76360. wOut = w_ / parentSize;
  76361. }
  76362. else if (wMode_ == parentSizeMinusAbsolute)
  76363. wOut = parentSize - w_;
  76364. else
  76365. wOut = w_;
  76366. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76367. x_ += w_;
  76368. else if ((xMode_ & anchorAtCentre) != 0)
  76369. x_ += w_ / 2;
  76370. if ((xMode_ & proportionOfParentSize) != 0)
  76371. {
  76372. if (parentSize > 0)
  76373. xOut = (x_ - parentPos) / parentSize;
  76374. }
  76375. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76376. xOut = (parentPos + parentSize) - x_;
  76377. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76378. xOut = x_ - (parentPos + parentSize / 2);
  76379. else
  76380. xOut = x_ - parentPos;
  76381. }
  76382. END_JUCE_NAMESPACE
  76383. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76384. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76385. BEGIN_JUCE_NAMESPACE
  76386. RectangleList::RectangleList() throw()
  76387. {
  76388. }
  76389. RectangleList::RectangleList (const Rectangle<int>& rect)
  76390. {
  76391. if (! rect.isEmpty())
  76392. rects.add (rect);
  76393. }
  76394. RectangleList::RectangleList (const RectangleList& other)
  76395. : rects (other.rects)
  76396. {
  76397. }
  76398. RectangleList& RectangleList::operator= (const RectangleList& other)
  76399. {
  76400. rects = other.rects;
  76401. return *this;
  76402. }
  76403. RectangleList::~RectangleList()
  76404. {
  76405. }
  76406. void RectangleList::clear()
  76407. {
  76408. rects.clearQuick();
  76409. }
  76410. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76411. {
  76412. if (isPositiveAndBelow (index, rects.size()))
  76413. return rects.getReference (index);
  76414. return Rectangle<int>();
  76415. }
  76416. bool RectangleList::isEmpty() const throw()
  76417. {
  76418. return rects.size() == 0;
  76419. }
  76420. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76421. : current (0),
  76422. owner (list),
  76423. index (list.rects.size())
  76424. {
  76425. }
  76426. RectangleList::Iterator::~Iterator()
  76427. {
  76428. }
  76429. bool RectangleList::Iterator::next() throw()
  76430. {
  76431. if (--index >= 0)
  76432. {
  76433. current = & (owner.rects.getReference (index));
  76434. return true;
  76435. }
  76436. return false;
  76437. }
  76438. void RectangleList::add (const Rectangle<int>& rect)
  76439. {
  76440. if (! rect.isEmpty())
  76441. {
  76442. if (rects.size() == 0)
  76443. {
  76444. rects.add (rect);
  76445. }
  76446. else
  76447. {
  76448. bool anyOverlaps = false;
  76449. int i;
  76450. for (i = rects.size(); --i >= 0;)
  76451. {
  76452. Rectangle<int>& ourRect = rects.getReference (i);
  76453. if (rect.intersects (ourRect))
  76454. {
  76455. if (rect.contains (ourRect))
  76456. rects.remove (i);
  76457. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76458. anyOverlaps = true;
  76459. }
  76460. }
  76461. if (anyOverlaps && rects.size() > 0)
  76462. {
  76463. RectangleList r (rect);
  76464. for (i = rects.size(); --i >= 0;)
  76465. {
  76466. const Rectangle<int>& ourRect = rects.getReference (i);
  76467. if (rect.intersects (ourRect))
  76468. {
  76469. r.subtract (ourRect);
  76470. if (r.rects.size() == 0)
  76471. return;
  76472. }
  76473. }
  76474. for (i = r.getNumRectangles(); --i >= 0;)
  76475. rects.add (r.rects.getReference (i));
  76476. }
  76477. else
  76478. {
  76479. rects.add (rect);
  76480. }
  76481. }
  76482. }
  76483. }
  76484. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76485. {
  76486. if (! rect.isEmpty())
  76487. rects.add (rect);
  76488. }
  76489. void RectangleList::add (const int x, const int y, const int w, const int h)
  76490. {
  76491. if (rects.size() == 0)
  76492. {
  76493. if (w > 0 && h > 0)
  76494. rects.add (Rectangle<int> (x, y, w, h));
  76495. }
  76496. else
  76497. {
  76498. add (Rectangle<int> (x, y, w, h));
  76499. }
  76500. }
  76501. void RectangleList::add (const RectangleList& other)
  76502. {
  76503. for (int i = 0; i < other.rects.size(); ++i)
  76504. add (other.rects.getReference (i));
  76505. }
  76506. void RectangleList::subtract (const Rectangle<int>& rect)
  76507. {
  76508. const int originalNumRects = rects.size();
  76509. if (originalNumRects > 0)
  76510. {
  76511. const int x1 = rect.x;
  76512. const int y1 = rect.y;
  76513. const int x2 = x1 + rect.w;
  76514. const int y2 = y1 + rect.h;
  76515. for (int i = getNumRectangles(); --i >= 0;)
  76516. {
  76517. Rectangle<int>& r = rects.getReference (i);
  76518. const int rx1 = r.x;
  76519. const int ry1 = r.y;
  76520. const int rx2 = rx1 + r.w;
  76521. const int ry2 = ry1 + r.h;
  76522. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76523. {
  76524. if (x1 > rx1 && x1 < rx2)
  76525. {
  76526. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76527. {
  76528. r.w = x1 - rx1;
  76529. }
  76530. else
  76531. {
  76532. r.x = x1;
  76533. r.w = rx2 - x1;
  76534. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76535. i += 2;
  76536. }
  76537. }
  76538. else if (x2 > rx1 && x2 < rx2)
  76539. {
  76540. r.x = x2;
  76541. r.w = rx2 - x2;
  76542. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76543. {
  76544. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76545. i += 2;
  76546. }
  76547. }
  76548. else if (y1 > ry1 && y1 < ry2)
  76549. {
  76550. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76551. {
  76552. r.h = y1 - ry1;
  76553. }
  76554. else
  76555. {
  76556. r.y = y1;
  76557. r.h = ry2 - y1;
  76558. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76559. i += 2;
  76560. }
  76561. }
  76562. else if (y2 > ry1 && y2 < ry2)
  76563. {
  76564. r.y = y2;
  76565. r.h = ry2 - y2;
  76566. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76567. {
  76568. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76569. i += 2;
  76570. }
  76571. }
  76572. else
  76573. {
  76574. rects.remove (i);
  76575. }
  76576. }
  76577. }
  76578. }
  76579. }
  76580. bool RectangleList::subtract (const RectangleList& otherList)
  76581. {
  76582. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76583. subtract (otherList.rects.getReference (i));
  76584. return rects.size() > 0;
  76585. }
  76586. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76587. {
  76588. bool notEmpty = false;
  76589. if (rect.isEmpty())
  76590. {
  76591. clear();
  76592. }
  76593. else
  76594. {
  76595. for (int i = rects.size(); --i >= 0;)
  76596. {
  76597. Rectangle<int>& r = rects.getReference (i);
  76598. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76599. rects.remove (i);
  76600. else
  76601. notEmpty = true;
  76602. }
  76603. }
  76604. return notEmpty;
  76605. }
  76606. bool RectangleList::clipTo (const RectangleList& other)
  76607. {
  76608. if (rects.size() == 0)
  76609. return false;
  76610. RectangleList result;
  76611. for (int j = 0; j < rects.size(); ++j)
  76612. {
  76613. const Rectangle<int>& rect = rects.getReference (j);
  76614. for (int i = other.rects.size(); --i >= 0;)
  76615. {
  76616. Rectangle<int> r (other.rects.getReference (i));
  76617. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76618. result.rects.add (r);
  76619. }
  76620. }
  76621. swapWith (result);
  76622. return ! isEmpty();
  76623. }
  76624. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76625. {
  76626. destRegion.clear();
  76627. if (! rect.isEmpty())
  76628. {
  76629. for (int i = rects.size(); --i >= 0;)
  76630. {
  76631. Rectangle<int> r (rects.getReference (i));
  76632. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76633. destRegion.rects.add (r);
  76634. }
  76635. }
  76636. return destRegion.rects.size() > 0;
  76637. }
  76638. void RectangleList::swapWith (RectangleList& otherList) throw()
  76639. {
  76640. rects.swapWithArray (otherList.rects);
  76641. }
  76642. void RectangleList::consolidate()
  76643. {
  76644. int i;
  76645. for (i = 0; i < getNumRectangles() - 1; ++i)
  76646. {
  76647. Rectangle<int>& r = rects.getReference (i);
  76648. const int rx1 = r.x;
  76649. const int ry1 = r.y;
  76650. const int rx2 = rx1 + r.w;
  76651. const int ry2 = ry1 + r.h;
  76652. for (int j = rects.size(); --j > i;)
  76653. {
  76654. Rectangle<int>& r2 = rects.getReference (j);
  76655. const int jrx1 = r2.x;
  76656. const int jry1 = r2.y;
  76657. const int jrx2 = jrx1 + r2.w;
  76658. const int jry2 = jry1 + r2.h;
  76659. // if the vertical edges of any blocks are touching and their horizontals don't
  76660. // line up, split them horizontally..
  76661. if (jrx1 == rx2 || jrx2 == rx1)
  76662. {
  76663. if (jry1 > ry1 && jry1 < ry2)
  76664. {
  76665. r.h = jry1 - ry1;
  76666. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76667. i = -1;
  76668. break;
  76669. }
  76670. if (jry2 > ry1 && jry2 < ry2)
  76671. {
  76672. r.h = jry2 - ry1;
  76673. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76674. i = -1;
  76675. break;
  76676. }
  76677. else if (ry1 > jry1 && ry1 < jry2)
  76678. {
  76679. r2.h = ry1 - jry1;
  76680. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76681. i = -1;
  76682. break;
  76683. }
  76684. else if (ry2 > jry1 && ry2 < jry2)
  76685. {
  76686. r2.h = ry2 - jry1;
  76687. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76688. i = -1;
  76689. break;
  76690. }
  76691. }
  76692. }
  76693. }
  76694. for (i = 0; i < rects.size() - 1; ++i)
  76695. {
  76696. Rectangle<int>& r = rects.getReference (i);
  76697. for (int j = rects.size(); --j > i;)
  76698. {
  76699. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76700. {
  76701. rects.remove (j);
  76702. i = -1;
  76703. break;
  76704. }
  76705. }
  76706. }
  76707. }
  76708. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76709. {
  76710. for (int i = getNumRectangles(); --i >= 0;)
  76711. if (rects.getReference (i).contains (x, y))
  76712. return true;
  76713. return false;
  76714. }
  76715. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76716. {
  76717. if (rects.size() > 1)
  76718. {
  76719. RectangleList r (rectangleToCheck);
  76720. for (int i = rects.size(); --i >= 0;)
  76721. {
  76722. r.subtract (rects.getReference (i));
  76723. if (r.rects.size() == 0)
  76724. return true;
  76725. }
  76726. }
  76727. else if (rects.size() > 0)
  76728. {
  76729. return rects.getReference (0).contains (rectangleToCheck);
  76730. }
  76731. return false;
  76732. }
  76733. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76734. {
  76735. for (int i = rects.size(); --i >= 0;)
  76736. if (rects.getReference (i).intersects (rectangleToCheck))
  76737. return true;
  76738. return false;
  76739. }
  76740. bool RectangleList::intersects (const RectangleList& other) const throw()
  76741. {
  76742. for (int i = rects.size(); --i >= 0;)
  76743. if (other.intersectsRectangle (rects.getReference (i)))
  76744. return true;
  76745. return false;
  76746. }
  76747. const Rectangle<int> RectangleList::getBounds() const throw()
  76748. {
  76749. if (rects.size() <= 1)
  76750. {
  76751. if (rects.size() == 0)
  76752. return Rectangle<int>();
  76753. else
  76754. return rects.getReference (0);
  76755. }
  76756. else
  76757. {
  76758. const Rectangle<int>& r = rects.getReference (0);
  76759. int minX = r.x;
  76760. int minY = r.y;
  76761. int maxX = minX + r.w;
  76762. int maxY = minY + r.h;
  76763. for (int i = rects.size(); --i > 0;)
  76764. {
  76765. const Rectangle<int>& r2 = rects.getReference (i);
  76766. minX = jmin (minX, r2.x);
  76767. minY = jmin (minY, r2.y);
  76768. maxX = jmax (maxX, r2.getRight());
  76769. maxY = jmax (maxY, r2.getBottom());
  76770. }
  76771. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76772. }
  76773. }
  76774. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76775. {
  76776. for (int i = rects.size(); --i >= 0;)
  76777. {
  76778. Rectangle<int>& r = rects.getReference (i);
  76779. r.x += dx;
  76780. r.y += dy;
  76781. }
  76782. }
  76783. const Path RectangleList::toPath() const
  76784. {
  76785. Path p;
  76786. for (int i = rects.size(); --i >= 0;)
  76787. {
  76788. const Rectangle<int>& r = rects.getReference (i);
  76789. p.addRectangle ((float) r.x,
  76790. (float) r.y,
  76791. (float) r.w,
  76792. (float) r.h);
  76793. }
  76794. return p;
  76795. }
  76796. END_JUCE_NAMESPACE
  76797. /*** End of inlined file: juce_RectangleList.cpp ***/
  76798. /*** Start of inlined file: juce_Image.cpp ***/
  76799. BEGIN_JUCE_NAMESPACE
  76800. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76801. : format (format_), width (width_), height (height_)
  76802. {
  76803. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76804. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76805. }
  76806. Image::SharedImage::~SharedImage()
  76807. {
  76808. }
  76809. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76810. {
  76811. return imageData + lineStride * y + pixelStride * x;
  76812. }
  76813. class SoftwareSharedImage : public Image::SharedImage
  76814. {
  76815. public:
  76816. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76817. : Image::SharedImage (format_, width_, height_)
  76818. {
  76819. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76820. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76821. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76822. imageData = imageDataAllocated;
  76823. }
  76824. Image::ImageType getType() const
  76825. {
  76826. return Image::SoftwareImage;
  76827. }
  76828. LowLevelGraphicsContext* createLowLevelContext()
  76829. {
  76830. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76831. }
  76832. Image::SharedImage* clone()
  76833. {
  76834. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76835. memcpy (s->imageData, imageData, lineStride * height);
  76836. return s;
  76837. }
  76838. private:
  76839. HeapBlock<uint8> imageDataAllocated;
  76840. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  76841. };
  76842. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76843. {
  76844. return new SoftwareSharedImage (format, width, height, clearImage);
  76845. }
  76846. class SubsectionSharedImage : public Image::SharedImage
  76847. {
  76848. public:
  76849. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76850. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76851. image (image_), area (area_)
  76852. {
  76853. pixelStride = image_->getPixelStride();
  76854. lineStride = image_->getLineStride();
  76855. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76856. }
  76857. Image::ImageType getType() const
  76858. {
  76859. return Image::SoftwareImage;
  76860. }
  76861. LowLevelGraphicsContext* createLowLevelContext()
  76862. {
  76863. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76864. g->clipToRectangle (area);
  76865. g->setOrigin (area.getX(), area.getY());
  76866. return g;
  76867. }
  76868. Image::SharedImage* clone()
  76869. {
  76870. return new SubsectionSharedImage (image->clone(), area);
  76871. }
  76872. private:
  76873. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76874. const Rectangle<int> area;
  76875. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  76876. };
  76877. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76878. {
  76879. if (area.contains (getBounds()))
  76880. return *this;
  76881. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76882. if (validArea.isEmpty())
  76883. return Image::null;
  76884. return Image (new SubsectionSharedImage (image, validArea));
  76885. }
  76886. Image::Image()
  76887. {
  76888. }
  76889. Image::Image (SharedImage* const instance)
  76890. : image (instance)
  76891. {
  76892. }
  76893. Image::Image (const PixelFormat format,
  76894. const int width, const int height,
  76895. const bool clearImage, const ImageType type)
  76896. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76897. : new SoftwareSharedImage (format, width, height, clearImage))
  76898. {
  76899. }
  76900. Image::Image (const Image& other)
  76901. : image (other.image)
  76902. {
  76903. }
  76904. Image& Image::operator= (const Image& other)
  76905. {
  76906. image = other.image;
  76907. return *this;
  76908. }
  76909. Image::~Image()
  76910. {
  76911. }
  76912. const Image Image::null;
  76913. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76914. {
  76915. return image == 0 ? 0 : image->createLowLevelContext();
  76916. }
  76917. void Image::duplicateIfShared()
  76918. {
  76919. if (image != 0 && image->getReferenceCount() > 1)
  76920. image = image->clone();
  76921. }
  76922. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76923. {
  76924. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76925. return *this;
  76926. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76927. Graphics g (newImage);
  76928. g.setImageResamplingQuality (quality);
  76929. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76930. return newImage;
  76931. }
  76932. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76933. {
  76934. if (image == 0 || newFormat == image->format)
  76935. return *this;
  76936. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76937. if (newFormat == SingleChannel)
  76938. {
  76939. if (! hasAlphaChannel())
  76940. {
  76941. newImage.clear (getBounds(), Colours::black);
  76942. }
  76943. else
  76944. {
  76945. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76946. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76947. for (int y = 0; y < image->height; ++y)
  76948. {
  76949. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76950. uint8* dst = destData.getLinePointer (y);
  76951. for (int x = image->width; --x >= 0;)
  76952. {
  76953. *dst++ = src->getAlpha();
  76954. ++src;
  76955. }
  76956. }
  76957. }
  76958. }
  76959. else
  76960. {
  76961. if (hasAlphaChannel())
  76962. newImage.clear (getBounds());
  76963. Graphics g (newImage);
  76964. g.drawImageAt (*this, 0, 0);
  76965. }
  76966. return newImage;
  76967. }
  76968. NamedValueSet* Image::getProperties() const
  76969. {
  76970. return image == 0 ? 0 : &(image->userData);
  76971. }
  76972. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76973. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76974. pixelFormat (image.getFormat()),
  76975. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76976. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76977. width (w),
  76978. height (h)
  76979. {
  76980. jassert (data != 0);
  76981. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76982. }
  76983. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76984. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76985. pixelFormat (image.getFormat()),
  76986. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76987. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76988. width (w),
  76989. height (h)
  76990. {
  76991. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76992. }
  76993. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76994. : data (image.image == 0 ? 0 : image.image->imageData),
  76995. pixelFormat (image.getFormat()),
  76996. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76997. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76998. width (image.getWidth()),
  76999. height (image.getHeight())
  77000. {
  77001. }
  77002. Image::BitmapData::~BitmapData()
  77003. {
  77004. }
  77005. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77006. {
  77007. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77008. const uint8* const pixel = getPixelPointer (x, y);
  77009. switch (pixelFormat)
  77010. {
  77011. case Image::ARGB:
  77012. {
  77013. PixelARGB p (*(const PixelARGB*) pixel);
  77014. p.unpremultiply();
  77015. return Colour (p.getARGB());
  77016. }
  77017. case Image::RGB:
  77018. return Colour (((const PixelRGB*) pixel)->getARGB());
  77019. case Image::SingleChannel:
  77020. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77021. default:
  77022. jassertfalse;
  77023. break;
  77024. }
  77025. return Colour();
  77026. }
  77027. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77028. {
  77029. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77030. uint8* const pixel = getPixelPointer (x, y);
  77031. const PixelARGB col (colour.getPixelARGB());
  77032. switch (pixelFormat)
  77033. {
  77034. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77035. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77036. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77037. default: jassertfalse; break;
  77038. }
  77039. }
  77040. void Image::setPixelData (int x, int y, int w, int h,
  77041. const uint8* const sourcePixelData, const int sourceLineStride)
  77042. {
  77043. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77044. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77045. {
  77046. const BitmapData dest (*this, x, y, w, h, true);
  77047. for (int i = 0; i < h; ++i)
  77048. {
  77049. memcpy (dest.getLinePointer(i),
  77050. sourcePixelData + sourceLineStride * i,
  77051. w * dest.pixelStride);
  77052. }
  77053. }
  77054. }
  77055. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77056. {
  77057. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77058. if (! clipped.isEmpty())
  77059. {
  77060. const PixelARGB col (colourToClearTo.getPixelARGB());
  77061. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77062. uint8* dest = destData.data;
  77063. int dh = clipped.getHeight();
  77064. while (--dh >= 0)
  77065. {
  77066. uint8* line = dest;
  77067. dest += destData.lineStride;
  77068. if (isARGB())
  77069. {
  77070. for (int x = clipped.getWidth(); --x >= 0;)
  77071. {
  77072. ((PixelARGB*) line)->set (col);
  77073. line += destData.pixelStride;
  77074. }
  77075. }
  77076. else if (isRGB())
  77077. {
  77078. for (int x = clipped.getWidth(); --x >= 0;)
  77079. {
  77080. ((PixelRGB*) line)->set (col);
  77081. line += destData.pixelStride;
  77082. }
  77083. }
  77084. else
  77085. {
  77086. for (int x = clipped.getWidth(); --x >= 0;)
  77087. {
  77088. *line = col.getAlpha();
  77089. line += destData.pixelStride;
  77090. }
  77091. }
  77092. }
  77093. }
  77094. }
  77095. const Colour Image::getPixelAt (const int x, const int y) const
  77096. {
  77097. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77098. {
  77099. const BitmapData srcData (*this, x, y, 1, 1);
  77100. return srcData.getPixelColour (0, 0);
  77101. }
  77102. return Colour();
  77103. }
  77104. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77105. {
  77106. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77107. {
  77108. const BitmapData destData (*this, x, y, 1, 1, true);
  77109. destData.setPixelColour (0, 0, colour);
  77110. }
  77111. }
  77112. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77113. {
  77114. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  77115. && hasAlphaChannel())
  77116. {
  77117. const BitmapData destData (*this, x, y, 1, 1, true);
  77118. if (isARGB())
  77119. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77120. else
  77121. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77122. }
  77123. }
  77124. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77125. {
  77126. if (hasAlphaChannel())
  77127. {
  77128. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77129. if (isARGB())
  77130. {
  77131. for (int y = 0; y < destData.height; ++y)
  77132. {
  77133. uint8* p = destData.getLinePointer (y);
  77134. for (int x = 0; x < destData.width; ++x)
  77135. {
  77136. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77137. p += destData.pixelStride;
  77138. }
  77139. }
  77140. }
  77141. else
  77142. {
  77143. for (int y = 0; y < destData.height; ++y)
  77144. {
  77145. uint8* p = destData.getLinePointer (y);
  77146. for (int x = 0; x < destData.width; ++x)
  77147. {
  77148. *p = (uint8) (*p * amountToMultiplyBy);
  77149. p += destData.pixelStride;
  77150. }
  77151. }
  77152. }
  77153. }
  77154. else
  77155. {
  77156. jassertfalse; // can't do this without an alpha-channel!
  77157. }
  77158. }
  77159. void Image::desaturate()
  77160. {
  77161. if (isARGB() || isRGB())
  77162. {
  77163. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77164. if (isARGB())
  77165. {
  77166. for (int y = 0; y < destData.height; ++y)
  77167. {
  77168. uint8* p = destData.getLinePointer (y);
  77169. for (int x = 0; x < destData.width; ++x)
  77170. {
  77171. ((PixelARGB*) p)->desaturate();
  77172. p += destData.pixelStride;
  77173. }
  77174. }
  77175. }
  77176. else
  77177. {
  77178. for (int y = 0; y < destData.height; ++y)
  77179. {
  77180. uint8* p = destData.getLinePointer (y);
  77181. for (int x = 0; x < destData.width; ++x)
  77182. {
  77183. ((PixelRGB*) p)->desaturate();
  77184. p += destData.pixelStride;
  77185. }
  77186. }
  77187. }
  77188. }
  77189. }
  77190. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77191. {
  77192. if (hasAlphaChannel())
  77193. {
  77194. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77195. SparseSet<int> pixelsOnRow;
  77196. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77197. for (int y = 0; y < srcData.height; ++y)
  77198. {
  77199. pixelsOnRow.clear();
  77200. const uint8* lineData = srcData.getLinePointer (y);
  77201. if (isARGB())
  77202. {
  77203. for (int x = 0; x < srcData.width; ++x)
  77204. {
  77205. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77206. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77207. lineData += srcData.pixelStride;
  77208. }
  77209. }
  77210. else
  77211. {
  77212. for (int x = 0; x < srcData.width; ++x)
  77213. {
  77214. if (*lineData >= threshold)
  77215. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77216. lineData += srcData.pixelStride;
  77217. }
  77218. }
  77219. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77220. {
  77221. const Range<int> range (pixelsOnRow.getRange (i));
  77222. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77223. }
  77224. result.consolidate();
  77225. }
  77226. }
  77227. else
  77228. {
  77229. result.add (0, 0, getWidth(), getHeight());
  77230. }
  77231. }
  77232. void Image::moveImageSection (int dx, int dy,
  77233. int sx, int sy,
  77234. int w, int h)
  77235. {
  77236. if (dx < 0)
  77237. {
  77238. w += dx;
  77239. sx -= dx;
  77240. dx = 0;
  77241. }
  77242. if (dy < 0)
  77243. {
  77244. h += dy;
  77245. sy -= dy;
  77246. dy = 0;
  77247. }
  77248. if (sx < 0)
  77249. {
  77250. w += sx;
  77251. dx -= sx;
  77252. sx = 0;
  77253. }
  77254. if (sy < 0)
  77255. {
  77256. h += sy;
  77257. dy -= sy;
  77258. sy = 0;
  77259. }
  77260. const int minX = jmin (dx, sx);
  77261. const int minY = jmin (dy, sy);
  77262. w = jmin (w, getWidth() - jmax (sx, dx));
  77263. h = jmin (h, getHeight() - jmax (sy, dy));
  77264. if (w > 0 && h > 0)
  77265. {
  77266. const int maxX = jmax (dx, sx) + w;
  77267. const int maxY = jmax (dy, sy) + h;
  77268. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77269. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77270. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77271. const int lineSize = destData.pixelStride * w;
  77272. if (dy > sy)
  77273. {
  77274. while (--h >= 0)
  77275. {
  77276. const int offset = h * destData.lineStride;
  77277. memmove (dst + offset, src + offset, lineSize);
  77278. }
  77279. }
  77280. else if (dst != src)
  77281. {
  77282. while (--h >= 0)
  77283. {
  77284. memmove (dst, src, lineSize);
  77285. dst += destData.lineStride;
  77286. src += destData.lineStride;
  77287. }
  77288. }
  77289. }
  77290. }
  77291. END_JUCE_NAMESPACE
  77292. /*** End of inlined file: juce_Image.cpp ***/
  77293. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77294. BEGIN_JUCE_NAMESPACE
  77295. class ImageCache::Pimpl : public Timer,
  77296. public DeletedAtShutdown
  77297. {
  77298. public:
  77299. Pimpl()
  77300. : cacheTimeout (5000)
  77301. {
  77302. }
  77303. ~Pimpl()
  77304. {
  77305. clearSingletonInstance();
  77306. }
  77307. const Image getFromHashCode (const int64 hashCode)
  77308. {
  77309. const ScopedLock sl (lock);
  77310. for (int i = images.size(); --i >= 0;)
  77311. {
  77312. Item* const item = images.getUnchecked(i);
  77313. if (item->hashCode == hashCode)
  77314. return item->image;
  77315. }
  77316. return Image::null;
  77317. }
  77318. void addImageToCache (const Image& image, const int64 hashCode)
  77319. {
  77320. if (image.isValid())
  77321. {
  77322. if (! isTimerRunning())
  77323. startTimer (2000);
  77324. Item* const item = new Item();
  77325. item->hashCode = hashCode;
  77326. item->image = image;
  77327. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77328. const ScopedLock sl (lock);
  77329. images.add (item);
  77330. }
  77331. }
  77332. void timerCallback()
  77333. {
  77334. const uint32 now = Time::getApproximateMillisecondCounter();
  77335. const ScopedLock sl (lock);
  77336. for (int i = images.size(); --i >= 0;)
  77337. {
  77338. Item* const item = images.getUnchecked(i);
  77339. if (item->image.getReferenceCount() <= 1)
  77340. {
  77341. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77342. images.remove (i);
  77343. }
  77344. else
  77345. {
  77346. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77347. }
  77348. }
  77349. if (images.size() == 0)
  77350. stopTimer();
  77351. }
  77352. struct Item
  77353. {
  77354. Image image;
  77355. int64 hashCode;
  77356. uint32 lastUseTime;
  77357. };
  77358. int cacheTimeout;
  77359. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77360. private:
  77361. OwnedArray<Item> images;
  77362. CriticalSection lock;
  77363. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77364. };
  77365. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77366. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77367. {
  77368. if (Pimpl::getInstanceWithoutCreating() != 0)
  77369. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77370. return Image::null;
  77371. }
  77372. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77373. {
  77374. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77375. }
  77376. const Image ImageCache::getFromFile (const File& file)
  77377. {
  77378. const int64 hashCode = file.hashCode64();
  77379. Image image (getFromHashCode (hashCode));
  77380. if (image.isNull())
  77381. {
  77382. image = ImageFileFormat::loadFrom (file);
  77383. addImageToCache (image, hashCode);
  77384. }
  77385. return image;
  77386. }
  77387. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77388. {
  77389. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77390. Image image (getFromHashCode (hashCode));
  77391. if (image.isNull())
  77392. {
  77393. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77394. addImageToCache (image, hashCode);
  77395. }
  77396. return image;
  77397. }
  77398. void ImageCache::setCacheTimeout (const int millisecs)
  77399. {
  77400. Pimpl::getInstance()->cacheTimeout = millisecs;
  77401. }
  77402. END_JUCE_NAMESPACE
  77403. /*** End of inlined file: juce_ImageCache.cpp ***/
  77404. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77405. BEGIN_JUCE_NAMESPACE
  77406. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77407. : values (size_ * size_),
  77408. size (size_)
  77409. {
  77410. clear();
  77411. }
  77412. ImageConvolutionKernel::~ImageConvolutionKernel()
  77413. {
  77414. }
  77415. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77416. {
  77417. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77418. return values [x + y * size];
  77419. jassertfalse;
  77420. return 0;
  77421. }
  77422. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77423. {
  77424. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77425. {
  77426. values [x + y * size] = value;
  77427. }
  77428. else
  77429. {
  77430. jassertfalse;
  77431. }
  77432. }
  77433. void ImageConvolutionKernel::clear()
  77434. {
  77435. for (int i = size * size; --i >= 0;)
  77436. values[i] = 0;
  77437. }
  77438. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77439. {
  77440. double currentTotal = 0.0;
  77441. for (int i = size * size; --i >= 0;)
  77442. currentTotal += values[i];
  77443. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77444. }
  77445. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77446. {
  77447. for (int i = size * size; --i >= 0;)
  77448. values[i] *= multiplier;
  77449. }
  77450. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77451. {
  77452. const double radiusFactor = -1.0 / (radius * radius * 2);
  77453. const int centre = size >> 1;
  77454. for (int y = size; --y >= 0;)
  77455. {
  77456. for (int x = size; --x >= 0;)
  77457. {
  77458. const int cx = x - centre;
  77459. const int cy = y - centre;
  77460. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77461. }
  77462. }
  77463. setOverallSum (1.0f);
  77464. }
  77465. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77466. const Image& sourceImage,
  77467. const Rectangle<int>& destinationArea) const
  77468. {
  77469. if (sourceImage == destImage)
  77470. {
  77471. destImage.duplicateIfShared();
  77472. }
  77473. else
  77474. {
  77475. if (sourceImage.getWidth() != destImage.getWidth()
  77476. || sourceImage.getHeight() != destImage.getHeight()
  77477. || sourceImage.getFormat() != destImage.getFormat())
  77478. {
  77479. jassertfalse;
  77480. return;
  77481. }
  77482. }
  77483. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77484. if (area.isEmpty())
  77485. return;
  77486. const int right = area.getRight();
  77487. const int bottom = area.getBottom();
  77488. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77489. uint8* line = destData.data;
  77490. const Image::BitmapData srcData (sourceImage, false);
  77491. if (destData.pixelStride == 4)
  77492. {
  77493. for (int y = area.getY(); y < bottom; ++y)
  77494. {
  77495. uint8* dest = line;
  77496. line += destData.lineStride;
  77497. for (int x = area.getX(); x < right; ++x)
  77498. {
  77499. float c1 = 0;
  77500. float c2 = 0;
  77501. float c3 = 0;
  77502. float c4 = 0;
  77503. for (int yy = 0; yy < size; ++yy)
  77504. {
  77505. const int sy = y + yy - (size >> 1);
  77506. if (sy >= srcData.height)
  77507. break;
  77508. if (sy >= 0)
  77509. {
  77510. int sx = x - (size >> 1);
  77511. const uint8* src = srcData.getPixelPointer (sx, sy);
  77512. for (int xx = 0; xx < size; ++xx)
  77513. {
  77514. if (sx >= srcData.width)
  77515. break;
  77516. if (sx >= 0)
  77517. {
  77518. const float kernelMult = values [xx + yy * size];
  77519. c1 += kernelMult * *src++;
  77520. c2 += kernelMult * *src++;
  77521. c3 += kernelMult * *src++;
  77522. c4 += kernelMult * *src++;
  77523. }
  77524. else
  77525. {
  77526. src += 4;
  77527. }
  77528. ++sx;
  77529. }
  77530. }
  77531. }
  77532. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77533. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77534. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77535. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77536. }
  77537. }
  77538. }
  77539. else if (destData.pixelStride == 3)
  77540. {
  77541. for (int y = area.getY(); y < bottom; ++y)
  77542. {
  77543. uint8* dest = line;
  77544. line += destData.lineStride;
  77545. for (int x = area.getX(); x < right; ++x)
  77546. {
  77547. float c1 = 0;
  77548. float c2 = 0;
  77549. float c3 = 0;
  77550. for (int yy = 0; yy < size; ++yy)
  77551. {
  77552. const int sy = y + yy - (size >> 1);
  77553. if (sy >= srcData.height)
  77554. break;
  77555. if (sy >= 0)
  77556. {
  77557. int sx = x - (size >> 1);
  77558. const uint8* src = srcData.getPixelPointer (sx, sy);
  77559. for (int xx = 0; xx < size; ++xx)
  77560. {
  77561. if (sx >= srcData.width)
  77562. break;
  77563. if (sx >= 0)
  77564. {
  77565. const float kernelMult = values [xx + yy * size];
  77566. c1 += kernelMult * *src++;
  77567. c2 += kernelMult * *src++;
  77568. c3 += kernelMult * *src++;
  77569. }
  77570. else
  77571. {
  77572. src += 3;
  77573. }
  77574. ++sx;
  77575. }
  77576. }
  77577. }
  77578. *dest++ = (uint8) roundToInt (c1);
  77579. *dest++ = (uint8) roundToInt (c2);
  77580. *dest++ = (uint8) roundToInt (c3);
  77581. }
  77582. }
  77583. }
  77584. }
  77585. END_JUCE_NAMESPACE
  77586. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77587. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77588. BEGIN_JUCE_NAMESPACE
  77589. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77590. {
  77591. static PNGImageFormat png;
  77592. static JPEGImageFormat jpg;
  77593. static GIFImageFormat gif;
  77594. ImageFileFormat* formats[4];
  77595. int numFormats = 0;
  77596. formats [numFormats++] = &png;
  77597. formats [numFormats++] = &jpg;
  77598. formats [numFormats++] = &gif;
  77599. const int64 streamPos = input.getPosition();
  77600. for (int i = 0; i < numFormats; ++i)
  77601. {
  77602. const bool found = formats[i]->canUnderstand (input);
  77603. input.setPosition (streamPos);
  77604. if (found)
  77605. return formats[i];
  77606. }
  77607. return 0;
  77608. }
  77609. const Image ImageFileFormat::loadFrom (InputStream& input)
  77610. {
  77611. ImageFileFormat* const format = findImageFormatForStream (input);
  77612. if (format != 0)
  77613. return format->decodeImage (input);
  77614. return Image::null;
  77615. }
  77616. const Image ImageFileFormat::loadFrom (const File& file)
  77617. {
  77618. InputStream* const in = file.createInputStream();
  77619. if (in != 0)
  77620. {
  77621. BufferedInputStream b (in, 8192, true);
  77622. return loadFrom (b);
  77623. }
  77624. return Image::null;
  77625. }
  77626. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77627. {
  77628. if (rawData != 0 && numBytes > 4)
  77629. {
  77630. MemoryInputStream stream (rawData, numBytes, false);
  77631. return loadFrom (stream);
  77632. }
  77633. return Image::null;
  77634. }
  77635. END_JUCE_NAMESPACE
  77636. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77637. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77638. BEGIN_JUCE_NAMESPACE
  77639. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77640. const Image juce_loadWithCoreImage (InputStream& input);
  77641. #else
  77642. class GIFLoader
  77643. {
  77644. public:
  77645. GIFLoader (InputStream& in)
  77646. : input (in),
  77647. dataBlockIsZero (false),
  77648. fresh (false),
  77649. finished (false)
  77650. {
  77651. currentBit = lastBit = lastByteIndex = 0;
  77652. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77653. firstcode = oldcode = 0;
  77654. clearCode = end_code = 0;
  77655. int imageWidth, imageHeight;
  77656. int transparent = -1;
  77657. if (! getSizeFromHeader (imageWidth, imageHeight))
  77658. return;
  77659. if ((imageWidth <= 0) || (imageHeight <= 0))
  77660. return;
  77661. unsigned char buf [16];
  77662. if (in.read (buf, 3) != 3)
  77663. return;
  77664. int numColours = 2 << (buf[0] & 7);
  77665. if ((buf[0] & 0x80) != 0)
  77666. readPalette (numColours);
  77667. for (;;)
  77668. {
  77669. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77670. break;
  77671. if (buf[0] == '!')
  77672. {
  77673. if (input.read (buf, 1) != 1)
  77674. break;
  77675. if (processExtension (buf[0], transparent) < 0)
  77676. break;
  77677. continue;
  77678. }
  77679. if (buf[0] != ',')
  77680. continue;
  77681. if (input.read (buf, 9) != 9)
  77682. break;
  77683. imageWidth = makeWord (buf[4], buf[5]);
  77684. imageHeight = makeWord (buf[6], buf[7]);
  77685. numColours = 2 << (buf[8] & 7);
  77686. if ((buf[8] & 0x80) != 0)
  77687. if (! readPalette (numColours))
  77688. break;
  77689. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77690. imageWidth, imageHeight, (transparent >= 0));
  77691. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77692. readImage ((buf[8] & 0x40) != 0, transparent);
  77693. break;
  77694. }
  77695. }
  77696. ~GIFLoader() {}
  77697. Image image;
  77698. private:
  77699. InputStream& input;
  77700. uint8 buffer [300];
  77701. uint8 palette [256][4];
  77702. bool dataBlockIsZero, fresh, finished;
  77703. int currentBit, lastBit, lastByteIndex;
  77704. int codeSize, setCodeSize;
  77705. int maxCode, maxCodeSize;
  77706. int firstcode, oldcode;
  77707. int clearCode, end_code;
  77708. enum { maxGifCode = 1 << 12 };
  77709. int table [2] [maxGifCode];
  77710. int stack [2 * maxGifCode];
  77711. int *sp;
  77712. bool getSizeFromHeader (int& w, int& h)
  77713. {
  77714. char b[8];
  77715. if (input.read (b, 6) == 6)
  77716. {
  77717. if ((strncmp ("GIF87a", b, 6) == 0)
  77718. || (strncmp ("GIF89a", b, 6) == 0))
  77719. {
  77720. if (input.read (b, 4) == 4)
  77721. {
  77722. w = makeWord (b[0], b[1]);
  77723. h = makeWord (b[2], b[3]);
  77724. return true;
  77725. }
  77726. }
  77727. }
  77728. return false;
  77729. }
  77730. bool readPalette (const int numCols)
  77731. {
  77732. unsigned char rgb[4];
  77733. for (int i = 0; i < numCols; ++i)
  77734. {
  77735. input.read (rgb, 3);
  77736. palette [i][0] = rgb[0];
  77737. palette [i][1] = rgb[1];
  77738. palette [i][2] = rgb[2];
  77739. palette [i][3] = 0xff;
  77740. }
  77741. return true;
  77742. }
  77743. int readDataBlock (unsigned char* dest)
  77744. {
  77745. unsigned char n;
  77746. if (input.read (&n, 1) == 1)
  77747. {
  77748. dataBlockIsZero = (n == 0);
  77749. if (dataBlockIsZero || (input.read (dest, n) == n))
  77750. return n;
  77751. }
  77752. return -1;
  77753. }
  77754. int processExtension (const int type, int& transparent)
  77755. {
  77756. unsigned char b [300];
  77757. int n = 0;
  77758. if (type == 0xf9)
  77759. {
  77760. n = readDataBlock (b);
  77761. if (n < 0)
  77762. return 1;
  77763. if ((b[0] & 0x1) != 0)
  77764. transparent = b[3];
  77765. }
  77766. do
  77767. {
  77768. n = readDataBlock (b);
  77769. }
  77770. while (n > 0);
  77771. return n;
  77772. }
  77773. int readLZWByte (const bool initialise, const int inputCodeSize)
  77774. {
  77775. int code, incode, i;
  77776. if (initialise)
  77777. {
  77778. setCodeSize = inputCodeSize;
  77779. codeSize = setCodeSize + 1;
  77780. clearCode = 1 << setCodeSize;
  77781. end_code = clearCode + 1;
  77782. maxCodeSize = 2 * clearCode;
  77783. maxCode = clearCode + 2;
  77784. getCode (0, true);
  77785. fresh = true;
  77786. for (i = 0; i < clearCode; ++i)
  77787. {
  77788. table[0][i] = 0;
  77789. table[1][i] = i;
  77790. }
  77791. for (; i < maxGifCode; ++i)
  77792. {
  77793. table[0][i] = 0;
  77794. table[1][i] = 0;
  77795. }
  77796. sp = stack;
  77797. return 0;
  77798. }
  77799. else if (fresh)
  77800. {
  77801. fresh = false;
  77802. do
  77803. {
  77804. firstcode = oldcode
  77805. = getCode (codeSize, false);
  77806. }
  77807. while (firstcode == clearCode);
  77808. return firstcode;
  77809. }
  77810. if (sp > stack)
  77811. return *--sp;
  77812. while ((code = getCode (codeSize, false)) >= 0)
  77813. {
  77814. if (code == clearCode)
  77815. {
  77816. for (i = 0; i < clearCode; ++i)
  77817. {
  77818. table[0][i] = 0;
  77819. table[1][i] = i;
  77820. }
  77821. for (; i < maxGifCode; ++i)
  77822. {
  77823. table[0][i] = 0;
  77824. table[1][i] = 0;
  77825. }
  77826. codeSize = setCodeSize + 1;
  77827. maxCodeSize = 2 * clearCode;
  77828. maxCode = clearCode + 2;
  77829. sp = stack;
  77830. firstcode = oldcode = getCode (codeSize, false);
  77831. return firstcode;
  77832. }
  77833. else if (code == end_code)
  77834. {
  77835. if (dataBlockIsZero)
  77836. return -2;
  77837. unsigned char buf [260];
  77838. int n;
  77839. while ((n = readDataBlock (buf)) > 0)
  77840. {}
  77841. if (n != 0)
  77842. return -2;
  77843. }
  77844. incode = code;
  77845. if (code >= maxCode)
  77846. {
  77847. *sp++ = firstcode;
  77848. code = oldcode;
  77849. }
  77850. while (code >= clearCode)
  77851. {
  77852. *sp++ = table[1][code];
  77853. if (code == table[0][code])
  77854. return -2;
  77855. code = table[0][code];
  77856. }
  77857. *sp++ = firstcode = table[1][code];
  77858. if ((code = maxCode) < maxGifCode)
  77859. {
  77860. table[0][code] = oldcode;
  77861. table[1][code] = firstcode;
  77862. ++maxCode;
  77863. if ((maxCode >= maxCodeSize)
  77864. && (maxCodeSize < maxGifCode))
  77865. {
  77866. maxCodeSize <<= 1;
  77867. ++codeSize;
  77868. }
  77869. }
  77870. oldcode = incode;
  77871. if (sp > stack)
  77872. return *--sp;
  77873. }
  77874. return code;
  77875. }
  77876. int getCode (const int codeSize_, const bool initialise)
  77877. {
  77878. if (initialise)
  77879. {
  77880. currentBit = 0;
  77881. lastBit = 0;
  77882. finished = false;
  77883. return 0;
  77884. }
  77885. if ((currentBit + codeSize_) >= lastBit)
  77886. {
  77887. if (finished)
  77888. return -1;
  77889. buffer[0] = buffer [lastByteIndex - 2];
  77890. buffer[1] = buffer [lastByteIndex - 1];
  77891. const int n = readDataBlock (&buffer[2]);
  77892. if (n == 0)
  77893. finished = true;
  77894. lastByteIndex = 2 + n;
  77895. currentBit = (currentBit - lastBit) + 16;
  77896. lastBit = (2 + n) * 8 ;
  77897. }
  77898. int result = 0;
  77899. int i = currentBit;
  77900. for (int j = 0; j < codeSize_; ++j)
  77901. {
  77902. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77903. ++i;
  77904. }
  77905. currentBit += codeSize_;
  77906. return result;
  77907. }
  77908. bool readImage (const int interlace, const int transparent)
  77909. {
  77910. unsigned char c;
  77911. if (input.read (&c, 1) != 1
  77912. || readLZWByte (true, c) < 0)
  77913. return false;
  77914. if (transparent >= 0)
  77915. {
  77916. palette [transparent][0] = 0;
  77917. palette [transparent][1] = 0;
  77918. palette [transparent][2] = 0;
  77919. palette [transparent][3] = 0;
  77920. }
  77921. int index;
  77922. int xpos = 0, ypos = 0, pass = 0;
  77923. const Image::BitmapData destData (image, true);
  77924. uint8* p = destData.data;
  77925. const bool hasAlpha = image.hasAlphaChannel();
  77926. while ((index = readLZWByte (false, c)) >= 0)
  77927. {
  77928. const uint8* const paletteEntry = palette [index];
  77929. if (hasAlpha)
  77930. {
  77931. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77932. paletteEntry[0],
  77933. paletteEntry[1],
  77934. paletteEntry[2]);
  77935. ((PixelARGB*) p)->premultiply();
  77936. }
  77937. else
  77938. {
  77939. ((PixelRGB*) p)->setARGB (0,
  77940. paletteEntry[0],
  77941. paletteEntry[1],
  77942. paletteEntry[2]);
  77943. }
  77944. p += destData.pixelStride;
  77945. ++xpos;
  77946. if (xpos == destData.width)
  77947. {
  77948. xpos = 0;
  77949. if (interlace)
  77950. {
  77951. switch (pass)
  77952. {
  77953. case 0:
  77954. case 1: ypos += 8; break;
  77955. case 2: ypos += 4; break;
  77956. case 3: ypos += 2; break;
  77957. }
  77958. while (ypos >= destData.height)
  77959. {
  77960. ++pass;
  77961. switch (pass)
  77962. {
  77963. case 1: ypos = 4; break;
  77964. case 2: ypos = 2; break;
  77965. case 3: ypos = 1; break;
  77966. default: return true;
  77967. }
  77968. }
  77969. }
  77970. else
  77971. {
  77972. ++ypos;
  77973. }
  77974. p = destData.getPixelPointer (xpos, ypos);
  77975. }
  77976. if (ypos >= destData.height)
  77977. break;
  77978. }
  77979. return true;
  77980. }
  77981. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77982. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  77983. };
  77984. #endif
  77985. GIFImageFormat::GIFImageFormat() {}
  77986. GIFImageFormat::~GIFImageFormat() {}
  77987. const String GIFImageFormat::getFormatName() { return "GIF"; }
  77988. bool GIFImageFormat::canUnderstand (InputStream& in)
  77989. {
  77990. char header [4];
  77991. return (in.read (header, sizeof (header)) == sizeof (header))
  77992. && header[0] == 'G'
  77993. && header[1] == 'I'
  77994. && header[2] == 'F';
  77995. }
  77996. const Image GIFImageFormat::decodeImage (InputStream& in)
  77997. {
  77998. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77999. return juce_loadWithCoreImage (in);
  78000. #else
  78001. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78002. return loader->image;
  78003. #endif
  78004. }
  78005. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78006. {
  78007. jassertfalse; // writing isn't implemented for GIFs!
  78008. return false;
  78009. }
  78010. END_JUCE_NAMESPACE
  78011. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78012. #endif
  78013. //==============================================================================
  78014. // some files include lots of library code, so leave them to the end to avoid cluttering
  78015. // up the build for the clean files.
  78016. #if JUCE_BUILD_CORE
  78017. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78018. namespace zlibNamespace
  78019. {
  78020. #if JUCE_INCLUDE_ZLIB_CODE
  78021. #undef OS_CODE
  78022. #undef fdopen
  78023. /*** Start of inlined file: zlib.h ***/
  78024. #ifndef ZLIB_H
  78025. #define ZLIB_H
  78026. /*** Start of inlined file: zconf.h ***/
  78027. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78028. #ifndef ZCONF_H
  78029. #define ZCONF_H
  78030. // *** Just a few hacks here to make it compile nicely with Juce..
  78031. #define Z_PREFIX 1
  78032. #undef __MACTYPES__
  78033. #ifdef _MSC_VER
  78034. #pragma warning (disable : 4131 4127 4244 4267)
  78035. #endif
  78036. /*
  78037. * If you *really* need a unique prefix for all types and library functions,
  78038. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78039. */
  78040. #ifdef Z_PREFIX
  78041. # define deflateInit_ z_deflateInit_
  78042. # define deflate z_deflate
  78043. # define deflateEnd z_deflateEnd
  78044. # define inflateInit_ z_inflateInit_
  78045. # define inflate z_inflate
  78046. # define inflateEnd z_inflateEnd
  78047. # define inflatePrime z_inflatePrime
  78048. # define inflateGetHeader z_inflateGetHeader
  78049. # define adler32_combine z_adler32_combine
  78050. # define crc32_combine z_crc32_combine
  78051. # define deflateInit2_ z_deflateInit2_
  78052. # define deflateSetDictionary z_deflateSetDictionary
  78053. # define deflateCopy z_deflateCopy
  78054. # define deflateReset z_deflateReset
  78055. # define deflateParams z_deflateParams
  78056. # define deflateBound z_deflateBound
  78057. # define deflatePrime z_deflatePrime
  78058. # define inflateInit2_ z_inflateInit2_
  78059. # define inflateSetDictionary z_inflateSetDictionary
  78060. # define inflateSync z_inflateSync
  78061. # define inflateSyncPoint z_inflateSyncPoint
  78062. # define inflateCopy z_inflateCopy
  78063. # define inflateReset z_inflateReset
  78064. # define inflateBack z_inflateBack
  78065. # define inflateBackEnd z_inflateBackEnd
  78066. # define compress z_compress
  78067. # define compress2 z_compress2
  78068. # define compressBound z_compressBound
  78069. # define uncompress z_uncompress
  78070. # define adler32 z_adler32
  78071. # define crc32 z_crc32
  78072. # define get_crc_table z_get_crc_table
  78073. # define zError z_zError
  78074. # define alloc_func z_alloc_func
  78075. # define free_func z_free_func
  78076. # define in_func z_in_func
  78077. # define out_func z_out_func
  78078. # define Byte z_Byte
  78079. # define uInt z_uInt
  78080. # define uLong z_uLong
  78081. # define Bytef z_Bytef
  78082. # define charf z_charf
  78083. # define intf z_intf
  78084. # define uIntf z_uIntf
  78085. # define uLongf z_uLongf
  78086. # define voidpf z_voidpf
  78087. # define voidp z_voidp
  78088. #endif
  78089. #if defined(__MSDOS__) && !defined(MSDOS)
  78090. # define MSDOS
  78091. #endif
  78092. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78093. # define OS2
  78094. #endif
  78095. #if defined(_WINDOWS) && !defined(WINDOWS)
  78096. # define WINDOWS
  78097. #endif
  78098. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78099. # ifndef WIN32
  78100. # define WIN32
  78101. # endif
  78102. #endif
  78103. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78104. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78105. # ifndef SYS16BIT
  78106. # define SYS16BIT
  78107. # endif
  78108. # endif
  78109. #endif
  78110. /*
  78111. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78112. * than 64k bytes at a time (needed on systems with 16-bit int).
  78113. */
  78114. #ifdef SYS16BIT
  78115. # define MAXSEG_64K
  78116. #endif
  78117. #ifdef MSDOS
  78118. # define UNALIGNED_OK
  78119. #endif
  78120. #ifdef __STDC_VERSION__
  78121. # ifndef STDC
  78122. # define STDC
  78123. # endif
  78124. # if __STDC_VERSION__ >= 199901L
  78125. # ifndef STDC99
  78126. # define STDC99
  78127. # endif
  78128. # endif
  78129. #endif
  78130. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78131. # define STDC
  78132. #endif
  78133. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78134. # define STDC
  78135. #endif
  78136. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78137. # define STDC
  78138. #endif
  78139. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78140. # define STDC
  78141. #endif
  78142. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78143. # define STDC
  78144. #endif
  78145. #ifndef STDC
  78146. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78147. # define const /* note: need a more gentle solution here */
  78148. # endif
  78149. #endif
  78150. /* Some Mac compilers merge all .h files incorrectly: */
  78151. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78152. # define NO_DUMMY_DECL
  78153. #endif
  78154. /* Maximum value for memLevel in deflateInit2 */
  78155. #ifndef MAX_MEM_LEVEL
  78156. # ifdef MAXSEG_64K
  78157. # define MAX_MEM_LEVEL 8
  78158. # else
  78159. # define MAX_MEM_LEVEL 9
  78160. # endif
  78161. #endif
  78162. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78163. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78164. * created by gzip. (Files created by minigzip can still be extracted by
  78165. * gzip.)
  78166. */
  78167. #ifndef MAX_WBITS
  78168. # define MAX_WBITS 15 /* 32K LZ77 window */
  78169. #endif
  78170. /* The memory requirements for deflate are (in bytes):
  78171. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78172. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78173. plus a few kilobytes for small objects. For example, if you want to reduce
  78174. the default memory requirements from 256K to 128K, compile with
  78175. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78176. Of course this will generally degrade compression (there's no free lunch).
  78177. The memory requirements for inflate are (in bytes) 1 << windowBits
  78178. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78179. for small objects.
  78180. */
  78181. /* Type declarations */
  78182. #ifndef OF /* function prototypes */
  78183. # ifdef STDC
  78184. # define OF(args) args
  78185. # else
  78186. # define OF(args) ()
  78187. # endif
  78188. #endif
  78189. /* The following definitions for FAR are needed only for MSDOS mixed
  78190. * model programming (small or medium model with some far allocations).
  78191. * This was tested only with MSC; for other MSDOS compilers you may have
  78192. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78193. * just define FAR to be empty.
  78194. */
  78195. #ifdef SYS16BIT
  78196. # if defined(M_I86SM) || defined(M_I86MM)
  78197. /* MSC small or medium model */
  78198. # define SMALL_MEDIUM
  78199. # ifdef _MSC_VER
  78200. # define FAR _far
  78201. # else
  78202. # define FAR far
  78203. # endif
  78204. # endif
  78205. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78206. /* Turbo C small or medium model */
  78207. # define SMALL_MEDIUM
  78208. # ifdef __BORLANDC__
  78209. # define FAR _far
  78210. # else
  78211. # define FAR far
  78212. # endif
  78213. # endif
  78214. #endif
  78215. #if defined(WINDOWS) || defined(WIN32)
  78216. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78217. * This is not mandatory, but it offers a little performance increase.
  78218. */
  78219. # ifdef ZLIB_DLL
  78220. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78221. # ifdef ZLIB_INTERNAL
  78222. # define ZEXTERN extern __declspec(dllexport)
  78223. # else
  78224. # define ZEXTERN extern __declspec(dllimport)
  78225. # endif
  78226. # endif
  78227. # endif /* ZLIB_DLL */
  78228. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78229. * define ZLIB_WINAPI.
  78230. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78231. */
  78232. # ifdef ZLIB_WINAPI
  78233. # ifdef FAR
  78234. # undef FAR
  78235. # endif
  78236. # include <windows.h>
  78237. /* No need for _export, use ZLIB.DEF instead. */
  78238. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78239. # define ZEXPORT WINAPI
  78240. # ifdef WIN32
  78241. # define ZEXPORTVA WINAPIV
  78242. # else
  78243. # define ZEXPORTVA FAR CDECL
  78244. # endif
  78245. # endif
  78246. #endif
  78247. #if defined (__BEOS__)
  78248. # ifdef ZLIB_DLL
  78249. # ifdef ZLIB_INTERNAL
  78250. # define ZEXPORT __declspec(dllexport)
  78251. # define ZEXPORTVA __declspec(dllexport)
  78252. # else
  78253. # define ZEXPORT __declspec(dllimport)
  78254. # define ZEXPORTVA __declspec(dllimport)
  78255. # endif
  78256. # endif
  78257. #endif
  78258. #ifndef ZEXTERN
  78259. # define ZEXTERN extern
  78260. #endif
  78261. #ifndef ZEXPORT
  78262. # define ZEXPORT
  78263. #endif
  78264. #ifndef ZEXPORTVA
  78265. # define ZEXPORTVA
  78266. #endif
  78267. #ifndef FAR
  78268. # define FAR
  78269. #endif
  78270. #if !defined(__MACTYPES__)
  78271. typedef unsigned char Byte; /* 8 bits */
  78272. #endif
  78273. typedef unsigned int uInt; /* 16 bits or more */
  78274. typedef unsigned long uLong; /* 32 bits or more */
  78275. #ifdef SMALL_MEDIUM
  78276. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78277. # define Bytef Byte FAR
  78278. #else
  78279. typedef Byte FAR Bytef;
  78280. #endif
  78281. typedef char FAR charf;
  78282. typedef int FAR intf;
  78283. typedef uInt FAR uIntf;
  78284. typedef uLong FAR uLongf;
  78285. #ifdef STDC
  78286. typedef void const *voidpc;
  78287. typedef void FAR *voidpf;
  78288. typedef void *voidp;
  78289. #else
  78290. typedef Byte const *voidpc;
  78291. typedef Byte FAR *voidpf;
  78292. typedef Byte *voidp;
  78293. #endif
  78294. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78295. # include <sys/types.h> /* for off_t */
  78296. # include <unistd.h> /* for SEEK_* and off_t */
  78297. # ifdef VMS
  78298. # include <unixio.h> /* for off_t */
  78299. # endif
  78300. # define z_off_t off_t
  78301. #endif
  78302. #ifndef SEEK_SET
  78303. # define SEEK_SET 0 /* Seek from beginning of file. */
  78304. # define SEEK_CUR 1 /* Seek from current position. */
  78305. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78306. #endif
  78307. #ifndef z_off_t
  78308. # define z_off_t long
  78309. #endif
  78310. #if defined(__OS400__)
  78311. # define NO_vsnprintf
  78312. #endif
  78313. #if defined(__MVS__)
  78314. # define NO_vsnprintf
  78315. # ifdef FAR
  78316. # undef FAR
  78317. # endif
  78318. #endif
  78319. /* MVS linker does not support external names larger than 8 bytes */
  78320. #if defined(__MVS__)
  78321. # pragma map(deflateInit_,"DEIN")
  78322. # pragma map(deflateInit2_,"DEIN2")
  78323. # pragma map(deflateEnd,"DEEND")
  78324. # pragma map(deflateBound,"DEBND")
  78325. # pragma map(inflateInit_,"ININ")
  78326. # pragma map(inflateInit2_,"ININ2")
  78327. # pragma map(inflateEnd,"INEND")
  78328. # pragma map(inflateSync,"INSY")
  78329. # pragma map(inflateSetDictionary,"INSEDI")
  78330. # pragma map(compressBound,"CMBND")
  78331. # pragma map(inflate_table,"INTABL")
  78332. # pragma map(inflate_fast,"INFA")
  78333. # pragma map(inflate_copyright,"INCOPY")
  78334. #endif
  78335. #endif /* ZCONF_H */
  78336. /*** End of inlined file: zconf.h ***/
  78337. #ifdef __cplusplus
  78338. //extern "C" {
  78339. #endif
  78340. #define ZLIB_VERSION "1.2.3"
  78341. #define ZLIB_VERNUM 0x1230
  78342. /*
  78343. The 'zlib' compression library provides in-memory compression and
  78344. decompression functions, including integrity checks of the uncompressed
  78345. data. This version of the library supports only one compression method
  78346. (deflation) but other algorithms will be added later and will have the same
  78347. stream interface.
  78348. Compression can be done in a single step if the buffers are large
  78349. enough (for example if an input file is mmap'ed), or can be done by
  78350. repeated calls of the compression function. In the latter case, the
  78351. application must provide more input and/or consume the output
  78352. (providing more output space) before each call.
  78353. The compressed data format used by default by the in-memory functions is
  78354. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78355. around a deflate stream, which is itself documented in RFC 1951.
  78356. The library also supports reading and writing files in gzip (.gz) format
  78357. with an interface similar to that of stdio using the functions that start
  78358. with "gz". The gzip format is different from the zlib format. gzip is a
  78359. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78360. This library can optionally read and write gzip streams in memory as well.
  78361. The zlib format was designed to be compact and fast for use in memory
  78362. and on communications channels. The gzip format was designed for single-
  78363. file compression on file systems, has a larger header than zlib to maintain
  78364. directory information, and uses a different, slower check method than zlib.
  78365. The library does not install any signal handler. The decoder checks
  78366. the consistency of the compressed data, so the library should never
  78367. crash even in case of corrupted input.
  78368. */
  78369. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78370. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78371. struct internal_state;
  78372. typedef struct z_stream_s {
  78373. Bytef *next_in; /* next input byte */
  78374. uInt avail_in; /* number of bytes available at next_in */
  78375. uLong total_in; /* total nb of input bytes read so far */
  78376. Bytef *next_out; /* next output byte should be put there */
  78377. uInt avail_out; /* remaining free space at next_out */
  78378. uLong total_out; /* total nb of bytes output so far */
  78379. char *msg; /* last error message, NULL if no error */
  78380. struct internal_state FAR *state; /* not visible by applications */
  78381. alloc_func zalloc; /* used to allocate the internal state */
  78382. free_func zfree; /* used to free the internal state */
  78383. voidpf opaque; /* private data object passed to zalloc and zfree */
  78384. int data_type; /* best guess about the data type: binary or text */
  78385. uLong adler; /* adler32 value of the uncompressed data */
  78386. uLong reserved; /* reserved for future use */
  78387. } z_stream;
  78388. typedef z_stream FAR *z_streamp;
  78389. /*
  78390. gzip header information passed to and from zlib routines. See RFC 1952
  78391. for more details on the meanings of these fields.
  78392. */
  78393. typedef struct gz_header_s {
  78394. int text; /* true if compressed data believed to be text */
  78395. uLong time; /* modification time */
  78396. int xflags; /* extra flags (not used when writing a gzip file) */
  78397. int os; /* operating system */
  78398. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78399. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78400. uInt extra_max; /* space at extra (only when reading header) */
  78401. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78402. uInt name_max; /* space at name (only when reading header) */
  78403. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78404. uInt comm_max; /* space at comment (only when reading header) */
  78405. int hcrc; /* true if there was or will be a header crc */
  78406. int done; /* true when done reading gzip header (not used
  78407. when writing a gzip file) */
  78408. } gz_header;
  78409. typedef gz_header FAR *gz_headerp;
  78410. /*
  78411. The application must update next_in and avail_in when avail_in has
  78412. dropped to zero. It must update next_out and avail_out when avail_out
  78413. has dropped to zero. The application must initialize zalloc, zfree and
  78414. opaque before calling the init function. All other fields are set by the
  78415. compression library and must not be updated by the application.
  78416. The opaque value provided by the application will be passed as the first
  78417. parameter for calls of zalloc and zfree. This can be useful for custom
  78418. memory management. The compression library attaches no meaning to the
  78419. opaque value.
  78420. zalloc must return Z_NULL if there is not enough memory for the object.
  78421. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78422. thread safe.
  78423. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78424. exactly 65536 bytes, but will not be required to allocate more than this
  78425. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78426. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78427. have their offset normalized to zero. The default allocation function
  78428. provided by this library ensures this (see zutil.c). To reduce memory
  78429. requirements and avoid any allocation of 64K objects, at the expense of
  78430. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78431. The fields total_in and total_out can be used for statistics or
  78432. progress reports. After compression, total_in holds the total size of
  78433. the uncompressed data and may be saved for use in the decompressor
  78434. (particularly if the decompressor wants to decompress everything in
  78435. a single step).
  78436. */
  78437. /* constants */
  78438. #define Z_NO_FLUSH 0
  78439. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78440. #define Z_SYNC_FLUSH 2
  78441. #define Z_FULL_FLUSH 3
  78442. #define Z_FINISH 4
  78443. #define Z_BLOCK 5
  78444. /* Allowed flush values; see deflate() and inflate() below for details */
  78445. #define Z_OK 0
  78446. #define Z_STREAM_END 1
  78447. #define Z_NEED_DICT 2
  78448. #define Z_ERRNO (-1)
  78449. #define Z_STREAM_ERROR (-2)
  78450. #define Z_DATA_ERROR (-3)
  78451. #define Z_MEM_ERROR (-4)
  78452. #define Z_BUF_ERROR (-5)
  78453. #define Z_VERSION_ERROR (-6)
  78454. /* Return codes for the compression/decompression functions. Negative
  78455. * values are errors, positive values are used for special but normal events.
  78456. */
  78457. #define Z_NO_COMPRESSION 0
  78458. #define Z_BEST_SPEED 1
  78459. #define Z_BEST_COMPRESSION 9
  78460. #define Z_DEFAULT_COMPRESSION (-1)
  78461. /* compression levels */
  78462. #define Z_FILTERED 1
  78463. #define Z_HUFFMAN_ONLY 2
  78464. #define Z_RLE 3
  78465. #define Z_FIXED 4
  78466. #define Z_DEFAULT_STRATEGY 0
  78467. /* compression strategy; see deflateInit2() below for details */
  78468. #define Z_BINARY 0
  78469. #define Z_TEXT 1
  78470. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78471. #define Z_UNKNOWN 2
  78472. /* Possible values of the data_type field (though see inflate()) */
  78473. #define Z_DEFLATED 8
  78474. /* The deflate compression method (the only one supported in this version) */
  78475. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78476. #define zlib_version zlibVersion()
  78477. /* for compatibility with versions < 1.0.2 */
  78478. /* basic functions */
  78479. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78480. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78481. If the first character differs, the library code actually used is
  78482. not compatible with the zlib.h header file used by the application.
  78483. This check is automatically made by deflateInit and inflateInit.
  78484. */
  78485. /*
  78486. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78487. Initializes the internal stream state for compression. The fields
  78488. zalloc, zfree and opaque must be initialized before by the caller.
  78489. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78490. use default allocation functions.
  78491. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78492. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78493. all (the input data is simply copied a block at a time).
  78494. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78495. compression (currently equivalent to level 6).
  78496. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78497. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78498. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78499. with the version assumed by the caller (ZLIB_VERSION).
  78500. msg is set to null if there is no error message. deflateInit does not
  78501. perform any compression: this will be done by deflate().
  78502. */
  78503. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78504. /*
  78505. deflate compresses as much data as possible, and stops when the input
  78506. buffer becomes empty or the output buffer becomes full. It may introduce some
  78507. output latency (reading input without producing any output) except when
  78508. forced to flush.
  78509. The detailed semantics are as follows. deflate performs one or both of the
  78510. following actions:
  78511. - Compress more input starting at next_in and update next_in and avail_in
  78512. accordingly. If not all input can be processed (because there is not
  78513. enough room in the output buffer), next_in and avail_in are updated and
  78514. processing will resume at this point for the next call of deflate().
  78515. - Provide more output starting at next_out and update next_out and avail_out
  78516. accordingly. This action is forced if the parameter flush is non zero.
  78517. Forcing flush frequently degrades the compression ratio, so this parameter
  78518. should be set only when necessary (in interactive applications).
  78519. Some output may be provided even if flush is not set.
  78520. Before the call of deflate(), the application should ensure that at least
  78521. one of the actions is possible, by providing more input and/or consuming
  78522. more output, and updating avail_in or avail_out accordingly; avail_out
  78523. should never be zero before the call. The application can consume the
  78524. compressed output when it wants, for example when the output buffer is full
  78525. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78526. and with zero avail_out, it must be called again after making room in the
  78527. output buffer because there might be more output pending.
  78528. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78529. decide how much data to accumualte before producing output, in order to
  78530. maximize compression.
  78531. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78532. flushed to the output buffer and the output is aligned on a byte boundary, so
  78533. that the decompressor can get all input data available so far. (In particular
  78534. avail_in is zero after the call if enough output space has been provided
  78535. before the call.) Flushing may degrade compression for some compression
  78536. algorithms and so it should be used only when necessary.
  78537. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78538. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78539. restart from this point if previous compressed data has been damaged or if
  78540. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78541. compression.
  78542. If deflate returns with avail_out == 0, this function must be called again
  78543. with the same value of the flush parameter and more output space (updated
  78544. avail_out), until the flush is complete (deflate returns with non-zero
  78545. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78546. avail_out is greater than six to avoid repeated flush markers due to
  78547. avail_out == 0 on return.
  78548. If the parameter flush is set to Z_FINISH, pending input is processed,
  78549. pending output is flushed and deflate returns with Z_STREAM_END if there
  78550. was enough output space; if deflate returns with Z_OK, this function must be
  78551. called again with Z_FINISH and more output space (updated avail_out) but no
  78552. more input data, until it returns with Z_STREAM_END or an error. After
  78553. deflate has returned Z_STREAM_END, the only possible operations on the
  78554. stream are deflateReset or deflateEnd.
  78555. Z_FINISH can be used immediately after deflateInit if all the compression
  78556. is to be done in a single step. In this case, avail_out must be at least
  78557. the value returned by deflateBound (see below). If deflate does not return
  78558. Z_STREAM_END, then it must be called again as described above.
  78559. deflate() sets strm->adler to the adler32 checksum of all input read
  78560. so far (that is, total_in bytes).
  78561. deflate() may update strm->data_type if it can make a good guess about
  78562. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78563. binary. This field is only for information purposes and does not affect
  78564. the compression algorithm in any manner.
  78565. deflate() returns Z_OK if some progress has been made (more input
  78566. processed or more output produced), Z_STREAM_END if all input has been
  78567. consumed and all output has been produced (only when flush is set to
  78568. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78569. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78570. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78571. fatal, and deflate() can be called again with more input and more output
  78572. space to continue compressing.
  78573. */
  78574. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78575. /*
  78576. All dynamically allocated data structures for this stream are freed.
  78577. This function discards any unprocessed input and does not flush any
  78578. pending output.
  78579. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78580. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78581. prematurely (some input or output was discarded). In the error case,
  78582. msg may be set but then points to a static string (which must not be
  78583. deallocated).
  78584. */
  78585. /*
  78586. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78587. Initializes the internal stream state for decompression. The fields
  78588. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78589. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78590. value depends on the compression method), inflateInit determines the
  78591. compression method from the zlib header and allocates all data structures
  78592. accordingly; otherwise the allocation will be deferred to the first call of
  78593. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78594. use default allocation functions.
  78595. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78596. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78597. version assumed by the caller. msg is set to null if there is no error
  78598. message. inflateInit does not perform any decompression apart from reading
  78599. the zlib header if present: this will be done by inflate(). (So next_in and
  78600. avail_in may be modified, but next_out and avail_out are unchanged.)
  78601. */
  78602. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78603. /*
  78604. inflate decompresses as much data as possible, and stops when the input
  78605. buffer becomes empty or the output buffer becomes full. It may introduce
  78606. some output latency (reading input without producing any output) except when
  78607. forced to flush.
  78608. The detailed semantics are as follows. inflate performs one or both of the
  78609. following actions:
  78610. - Decompress more input starting at next_in and update next_in and avail_in
  78611. accordingly. If not all input can be processed (because there is not
  78612. enough room in the output buffer), next_in is updated and processing
  78613. will resume at this point for the next call of inflate().
  78614. - Provide more output starting at next_out and update next_out and avail_out
  78615. accordingly. inflate() provides as much output as possible, until there
  78616. is no more input data or no more space in the output buffer (see below
  78617. about the flush parameter).
  78618. Before the call of inflate(), the application should ensure that at least
  78619. one of the actions is possible, by providing more input and/or consuming
  78620. more output, and updating the next_* and avail_* values accordingly.
  78621. The application can consume the uncompressed output when it wants, for
  78622. example when the output buffer is full (avail_out == 0), or after each
  78623. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78624. must be called again after making room in the output buffer because there
  78625. might be more output pending.
  78626. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78627. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78628. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78629. if and when it gets to the next deflate block boundary. When decoding the
  78630. zlib or gzip format, this will cause inflate() to return immediately after
  78631. the header and before the first block. When doing a raw inflate, inflate()
  78632. will go ahead and process the first block, and will return when it gets to
  78633. the end of that block, or when it runs out of data.
  78634. The Z_BLOCK option assists in appending to or combining deflate streams.
  78635. Also to assist in this, on return inflate() will set strm->data_type to the
  78636. number of unused bits in the last byte taken from strm->next_in, plus 64
  78637. if inflate() is currently decoding the last block in the deflate stream,
  78638. plus 128 if inflate() returned immediately after decoding an end-of-block
  78639. code or decoding the complete header up to just before the first byte of the
  78640. deflate stream. The end-of-block will not be indicated until all of the
  78641. uncompressed data from that block has been written to strm->next_out. The
  78642. number of unused bits may in general be greater than seven, except when
  78643. bit 7 of data_type is set, in which case the number of unused bits will be
  78644. less than eight.
  78645. inflate() should normally be called until it returns Z_STREAM_END or an
  78646. error. However if all decompression is to be performed in a single step
  78647. (a single call of inflate), the parameter flush should be set to
  78648. Z_FINISH. In this case all pending input is processed and all pending
  78649. output is flushed; avail_out must be large enough to hold all the
  78650. uncompressed data. (The size of the uncompressed data may have been saved
  78651. by the compressor for this purpose.) The next operation on this stream must
  78652. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78653. is never required, but can be used to inform inflate that a faster approach
  78654. may be used for the single inflate() call.
  78655. In this implementation, inflate() always flushes as much output as
  78656. possible to the output buffer, and always uses the faster approach on the
  78657. first call. So the only effect of the flush parameter in this implementation
  78658. is on the return value of inflate(), as noted below, or when it returns early
  78659. because Z_BLOCK is used.
  78660. If a preset dictionary is needed after this call (see inflateSetDictionary
  78661. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78662. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78663. strm->adler to the adler32 checksum of all output produced so far (that is,
  78664. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78665. below. At the end of the stream, inflate() checks that its computed adler32
  78666. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78667. only if the checksum is correct.
  78668. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78669. deflate data. The header type is detected automatically. Any information
  78670. contained in the gzip header is not retained, so applications that need that
  78671. information should instead use raw inflate, see inflateInit2() below, or
  78672. inflateBack() and perform their own processing of the gzip header and
  78673. trailer.
  78674. inflate() returns Z_OK if some progress has been made (more input processed
  78675. or more output produced), Z_STREAM_END if the end of the compressed data has
  78676. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78677. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78678. corrupted (input stream not conforming to the zlib format or incorrect check
  78679. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78680. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78681. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78682. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78683. inflate() can be called again with more input and more output space to
  78684. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78685. call inflateSync() to look for a good compression block if a partial recovery
  78686. of the data is desired.
  78687. */
  78688. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78689. /*
  78690. All dynamically allocated data structures for this stream are freed.
  78691. This function discards any unprocessed input and does not flush any
  78692. pending output.
  78693. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78694. was inconsistent. In the error case, msg may be set but then points to a
  78695. static string (which must not be deallocated).
  78696. */
  78697. /* Advanced functions */
  78698. /*
  78699. The following functions are needed only in some special applications.
  78700. */
  78701. /*
  78702. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78703. int level,
  78704. int method,
  78705. int windowBits,
  78706. int memLevel,
  78707. int strategy));
  78708. This is another version of deflateInit with more compression options. The
  78709. fields next_in, zalloc, zfree and opaque must be initialized before by
  78710. the caller.
  78711. The method parameter is the compression method. It must be Z_DEFLATED in
  78712. this version of the library.
  78713. The windowBits parameter is the base two logarithm of the window size
  78714. (the size of the history buffer). It should be in the range 8..15 for this
  78715. version of the library. Larger values of this parameter result in better
  78716. compression at the expense of memory usage. The default value is 15 if
  78717. deflateInit is used instead.
  78718. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78719. determines the window size. deflate() will then generate raw deflate data
  78720. with no zlib header or trailer, and will not compute an adler32 check value.
  78721. windowBits can also be greater than 15 for optional gzip encoding. Add
  78722. 16 to windowBits to write a simple gzip header and trailer around the
  78723. compressed data instead of a zlib wrapper. The gzip header will have no
  78724. file name, no extra data, no comment, no modification time (set to zero),
  78725. no header crc, and the operating system will be set to 255 (unknown). If a
  78726. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78727. The memLevel parameter specifies how much memory should be allocated
  78728. for the internal compression state. memLevel=1 uses minimum memory but
  78729. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78730. for optimal speed. The default value is 8. See zconf.h for total memory
  78731. usage as a function of windowBits and memLevel.
  78732. The strategy parameter is used to tune the compression algorithm. Use the
  78733. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78734. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78735. string match), or Z_RLE to limit match distances to one (run-length
  78736. encoding). Filtered data consists mostly of small values with a somewhat
  78737. random distribution. In this case, the compression algorithm is tuned to
  78738. compress them better. The effect of Z_FILTERED is to force more Huffman
  78739. coding and less string matching; it is somewhat intermediate between
  78740. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78741. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78742. parameter only affects the compression ratio but not the correctness of the
  78743. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78744. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78745. applications.
  78746. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78747. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78748. method). msg is set to null if there is no error message. deflateInit2 does
  78749. not perform any compression: this will be done by deflate().
  78750. */
  78751. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78752. const Bytef *dictionary,
  78753. uInt dictLength));
  78754. /*
  78755. Initializes the compression dictionary from the given byte sequence
  78756. without producing any compressed output. This function must be called
  78757. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78758. call of deflate. The compressor and decompressor must use exactly the same
  78759. dictionary (see inflateSetDictionary).
  78760. The dictionary should consist of strings (byte sequences) that are likely
  78761. to be encountered later in the data to be compressed, with the most commonly
  78762. used strings preferably put towards the end of the dictionary. Using a
  78763. dictionary is most useful when the data to be compressed is short and can be
  78764. predicted with good accuracy; the data can then be compressed better than
  78765. with the default empty dictionary.
  78766. Depending on the size of the compression data structures selected by
  78767. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78768. discarded, for example if the dictionary is larger than the window size in
  78769. deflate or deflate2. Thus the strings most likely to be useful should be
  78770. put at the end of the dictionary, not at the front. In addition, the
  78771. current implementation of deflate will use at most the window size minus
  78772. 262 bytes of the provided dictionary.
  78773. Upon return of this function, strm->adler is set to the adler32 value
  78774. of the dictionary; the decompressor may later use this value to determine
  78775. which dictionary has been used by the compressor. (The adler32 value
  78776. applies to the whole dictionary even if only a subset of the dictionary is
  78777. actually used by the compressor.) If a raw deflate was requested, then the
  78778. adler32 value is not computed and strm->adler is not set.
  78779. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78780. parameter is invalid (such as NULL dictionary) or the stream state is
  78781. inconsistent (for example if deflate has already been called for this stream
  78782. or if the compression method is bsort). deflateSetDictionary does not
  78783. perform any compression: this will be done by deflate().
  78784. */
  78785. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78786. z_streamp source));
  78787. /*
  78788. Sets the destination stream as a complete copy of the source stream.
  78789. This function can be useful when several compression strategies will be
  78790. tried, for example when there are several ways of pre-processing the input
  78791. data with a filter. The streams that will be discarded should then be freed
  78792. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78793. compression state which can be quite large, so this strategy is slow and
  78794. can consume lots of memory.
  78795. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78796. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78797. (such as zalloc being NULL). msg is left unchanged in both source and
  78798. destination.
  78799. */
  78800. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78801. /*
  78802. This function is equivalent to deflateEnd followed by deflateInit,
  78803. but does not free and reallocate all the internal compression state.
  78804. The stream will keep the same compression level and any other attributes
  78805. that may have been set by deflateInit2.
  78806. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78807. stream state was inconsistent (such as zalloc or state being NULL).
  78808. */
  78809. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78810. int level,
  78811. int strategy));
  78812. /*
  78813. Dynamically update the compression level and compression strategy. The
  78814. interpretation of level and strategy is as in deflateInit2. This can be
  78815. used to switch between compression and straight copy of the input data, or
  78816. to switch to a different kind of input data requiring a different
  78817. strategy. If the compression level is changed, the input available so far
  78818. is compressed with the old level (and may be flushed); the new level will
  78819. take effect only at the next call of deflate().
  78820. Before the call of deflateParams, the stream state must be set as for
  78821. a call of deflate(), since the currently available input may have to
  78822. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78823. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78824. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78825. if strm->avail_out was zero.
  78826. */
  78827. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78828. int good_length,
  78829. int max_lazy,
  78830. int nice_length,
  78831. int max_chain));
  78832. /*
  78833. Fine tune deflate's internal compression parameters. This should only be
  78834. used by someone who understands the algorithm used by zlib's deflate for
  78835. searching for the best matching string, and even then only by the most
  78836. fanatic optimizer trying to squeeze out the last compressed bit for their
  78837. specific input data. Read the deflate.c source code for the meaning of the
  78838. max_lazy, good_length, nice_length, and max_chain parameters.
  78839. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78840. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78841. */
  78842. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78843. uLong sourceLen));
  78844. /*
  78845. deflateBound() returns an upper bound on the compressed size after
  78846. deflation of sourceLen bytes. It must be called after deflateInit()
  78847. or deflateInit2(). This would be used to allocate an output buffer
  78848. for deflation in a single pass, and so would be called before deflate().
  78849. */
  78850. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78851. int bits,
  78852. int value));
  78853. /*
  78854. deflatePrime() inserts bits in the deflate output stream. The intent
  78855. is that this function is used to start off the deflate output with the
  78856. bits leftover from a previous deflate stream when appending to it. As such,
  78857. this function can only be used for raw deflate, and must be used before the
  78858. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78859. less than or equal to 16, and that many of the least significant bits of
  78860. value will be inserted in the output.
  78861. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78862. stream state was inconsistent.
  78863. */
  78864. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78865. gz_headerp head));
  78866. /*
  78867. deflateSetHeader() provides gzip header information for when a gzip
  78868. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78869. after deflateInit2() or deflateReset() and before the first call of
  78870. deflate(). The text, time, os, extra field, name, and comment information
  78871. in the provided gz_header structure are written to the gzip header (xflag is
  78872. ignored -- the extra flags are set according to the compression level). The
  78873. caller must assure that, if not Z_NULL, name and comment are terminated with
  78874. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78875. available there. If hcrc is true, a gzip header crc is included. Note that
  78876. the current versions of the command-line version of gzip (up through version
  78877. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78878. gzip file" and give up.
  78879. If deflateSetHeader is not used, the default gzip header has text false,
  78880. the time set to zero, and os set to 255, with no extra, name, or comment
  78881. fields. The gzip header is returned to the default state by deflateReset().
  78882. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78883. stream state was inconsistent.
  78884. */
  78885. /*
  78886. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78887. int windowBits));
  78888. This is another version of inflateInit with an extra parameter. The
  78889. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78890. before by the caller.
  78891. The windowBits parameter is the base two logarithm of the maximum window
  78892. size (the size of the history buffer). It should be in the range 8..15 for
  78893. this version of the library. The default value is 15 if inflateInit is used
  78894. instead. windowBits must be greater than or equal to the windowBits value
  78895. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78896. deflateInit2() was not used. If a compressed stream with a larger window
  78897. size is given as input, inflate() will return with the error code
  78898. Z_DATA_ERROR instead of trying to allocate a larger window.
  78899. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78900. determines the window size. inflate() will then process raw deflate data,
  78901. not looking for a zlib or gzip header, not generating a check value, and not
  78902. looking for any check values for comparison at the end of the stream. This
  78903. is for use with other formats that use the deflate compressed data format
  78904. such as zip. Those formats provide their own check values. If a custom
  78905. format is developed using the raw deflate format for compressed data, it is
  78906. recommended that a check value such as an adler32 or a crc32 be applied to
  78907. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78908. most applications, the zlib format should be used as is. Note that comments
  78909. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78910. windowBits can also be greater than 15 for optional gzip decoding. Add
  78911. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78912. detection, or add 16 to decode only the gzip format (the zlib format will
  78913. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78914. a crc32 instead of an adler32.
  78915. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78916. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78917. is set to null if there is no error message. inflateInit2 does not perform
  78918. any decompression apart from reading the zlib header if present: this will
  78919. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78920. and avail_out are unchanged.)
  78921. */
  78922. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78923. const Bytef *dictionary,
  78924. uInt dictLength));
  78925. /*
  78926. Initializes the decompression dictionary from the given uncompressed byte
  78927. sequence. This function must be called immediately after a call of inflate,
  78928. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78929. can be determined from the adler32 value returned by that call of inflate.
  78930. The compressor and decompressor must use exactly the same dictionary (see
  78931. deflateSetDictionary). For raw inflate, this function can be called
  78932. immediately after inflateInit2() or inflateReset() and before any call of
  78933. inflate() to set the dictionary. The application must insure that the
  78934. dictionary that was used for compression is provided.
  78935. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78936. parameter is invalid (such as NULL dictionary) or the stream state is
  78937. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78938. expected one (incorrect adler32 value). inflateSetDictionary does not
  78939. perform any decompression: this will be done by subsequent calls of
  78940. inflate().
  78941. */
  78942. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78943. /*
  78944. Skips invalid compressed data until a full flush point (see above the
  78945. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78946. available input is skipped. No output is provided.
  78947. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78948. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78949. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78950. case, the application may save the current current value of total_in which
  78951. indicates where valid compressed data was found. In the error case, the
  78952. application may repeatedly call inflateSync, providing more input each time,
  78953. until success or end of the input data.
  78954. */
  78955. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78956. z_streamp source));
  78957. /*
  78958. Sets the destination stream as a complete copy of the source stream.
  78959. This function can be useful when randomly accessing a large stream. The
  78960. first pass through the stream can periodically record the inflate state,
  78961. allowing restarting inflate at those points when randomly accessing the
  78962. stream.
  78963. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78964. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78965. (such as zalloc being NULL). msg is left unchanged in both source and
  78966. destination.
  78967. */
  78968. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78969. /*
  78970. This function is equivalent to inflateEnd followed by inflateInit,
  78971. but does not free and reallocate all the internal decompression state.
  78972. The stream will keep attributes that may have been set by inflateInit2.
  78973. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78974. stream state was inconsistent (such as zalloc or state being NULL).
  78975. */
  78976. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78977. int bits,
  78978. int value));
  78979. /*
  78980. This function inserts bits in the inflate input stream. The intent is
  78981. that this function is used to start inflating at a bit position in the
  78982. middle of a byte. The provided bits will be used before any bytes are used
  78983. from next_in. This function should only be used with raw inflate, and
  78984. should be used before the first inflate() call after inflateInit2() or
  78985. inflateReset(). bits must be less than or equal to 16, and that many of the
  78986. least significant bits of value will be inserted in the input.
  78987. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78988. stream state was inconsistent.
  78989. */
  78990. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78991. gz_headerp head));
  78992. /*
  78993. inflateGetHeader() requests that gzip header information be stored in the
  78994. provided gz_header structure. inflateGetHeader() may be called after
  78995. inflateInit2() or inflateReset(), and before the first call of inflate().
  78996. As inflate() processes the gzip stream, head->done is zero until the header
  78997. is completed, at which time head->done is set to one. If a zlib stream is
  78998. being decoded, then head->done is set to -1 to indicate that there will be
  78999. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79000. force inflate() to return immediately after header processing is complete
  79001. and before any actual data is decompressed.
  79002. The text, time, xflags, and os fields are filled in with the gzip header
  79003. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79004. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79005. contains the maximum number of bytes to write to extra. Once done is true,
  79006. extra_len contains the actual extra field length, and extra contains the
  79007. extra field, or that field truncated if extra_max is less than extra_len.
  79008. If name is not Z_NULL, then up to name_max characters are written there,
  79009. terminated with a zero unless the length is greater than name_max. If
  79010. comment is not Z_NULL, then up to comm_max characters are written there,
  79011. terminated with a zero unless the length is greater than comm_max. When
  79012. any of extra, name, or comment are not Z_NULL and the respective field is
  79013. not present in the header, then that field is set to Z_NULL to signal its
  79014. absence. This allows the use of deflateSetHeader() with the returned
  79015. structure to duplicate the header. However if those fields are set to
  79016. allocated memory, then the application will need to save those pointers
  79017. elsewhere so that they can be eventually freed.
  79018. If inflateGetHeader is not used, then the header information is simply
  79019. discarded. The header is always checked for validity, including the header
  79020. CRC if present. inflateReset() will reset the process to discard the header
  79021. information. The application would need to call inflateGetHeader() again to
  79022. retrieve the header from the next gzip stream.
  79023. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79024. stream state was inconsistent.
  79025. */
  79026. /*
  79027. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79028. unsigned char FAR *window));
  79029. Initialize the internal stream state for decompression using inflateBack()
  79030. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79031. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79032. derived memory allocation routines are used. windowBits is the base two
  79033. logarithm of the window size, in the range 8..15. window is a caller
  79034. supplied buffer of that size. Except for special applications where it is
  79035. assured that deflate was used with small window sizes, windowBits must be 15
  79036. and a 32K byte window must be supplied to be able to decompress general
  79037. deflate streams.
  79038. See inflateBack() for the usage of these routines.
  79039. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79040. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79041. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79042. match the version of the header file.
  79043. */
  79044. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79045. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79046. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79047. in_func in, void FAR *in_desc,
  79048. out_func out, void FAR *out_desc));
  79049. /*
  79050. inflateBack() does a raw inflate with a single call using a call-back
  79051. interface for input and output. This is more efficient than inflate() for
  79052. file i/o applications in that it avoids copying between the output and the
  79053. sliding window by simply making the window itself the output buffer. This
  79054. function trusts the application to not change the output buffer passed by
  79055. the output function, at least until inflateBack() returns.
  79056. inflateBackInit() must be called first to allocate the internal state
  79057. and to initialize the state with the user-provided window buffer.
  79058. inflateBack() may then be used multiple times to inflate a complete, raw
  79059. deflate stream with each call. inflateBackEnd() is then called to free
  79060. the allocated state.
  79061. A raw deflate stream is one with no zlib or gzip header or trailer.
  79062. This routine would normally be used in a utility that reads zip or gzip
  79063. files and writes out uncompressed files. The utility would decode the
  79064. header and process the trailer on its own, hence this routine expects
  79065. only the raw deflate stream to decompress. This is different from the
  79066. normal behavior of inflate(), which expects either a zlib or gzip header and
  79067. trailer around the deflate stream.
  79068. inflateBack() uses two subroutines supplied by the caller that are then
  79069. called by inflateBack() for input and output. inflateBack() calls those
  79070. routines until it reads a complete deflate stream and writes out all of the
  79071. uncompressed data, or until it encounters an error. The function's
  79072. parameters and return types are defined above in the in_func and out_func
  79073. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79074. number of bytes of provided input, and a pointer to that input in buf. If
  79075. there is no input available, in() must return zero--buf is ignored in that
  79076. case--and inflateBack() will return a buffer error. inflateBack() will call
  79077. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79078. should return zero on success, or non-zero on failure. If out() returns
  79079. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79080. are permitted to change the contents of the window provided to
  79081. inflateBackInit(), which is also the buffer that out() uses to write from.
  79082. The length written by out() will be at most the window size. Any non-zero
  79083. amount of input may be provided by in().
  79084. For convenience, inflateBack() can be provided input on the first call by
  79085. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79086. in() will be called. Therefore strm->next_in must be initialized before
  79087. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79088. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79089. must also be initialized, and then if strm->avail_in is not zero, input will
  79090. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79091. The in_desc and out_desc parameters of inflateBack() is passed as the
  79092. first parameter of in() and out() respectively when they are called. These
  79093. descriptors can be optionally used to pass any information that the caller-
  79094. supplied in() and out() functions need to do their job.
  79095. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79096. pass back any unused input that was provided by the last in() call. The
  79097. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79098. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79099. error in the deflate stream (in which case strm->msg is set to indicate the
  79100. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79101. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79102. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79103. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79104. out() returning non-zero. (in() will always be called before out(), so
  79105. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79106. that inflateBack() cannot return Z_OK.
  79107. */
  79108. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79109. /*
  79110. All memory allocated by inflateBackInit() is freed.
  79111. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79112. state was inconsistent.
  79113. */
  79114. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79115. /* Return flags indicating compile-time options.
  79116. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79117. 1.0: size of uInt
  79118. 3.2: size of uLong
  79119. 5.4: size of voidpf (pointer)
  79120. 7.6: size of z_off_t
  79121. Compiler, assembler, and debug options:
  79122. 8: DEBUG
  79123. 9: ASMV or ASMINF -- use ASM code
  79124. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79125. 11: 0 (reserved)
  79126. One-time table building (smaller code, but not thread-safe if true):
  79127. 12: BUILDFIXED -- build static block decoding tables when needed
  79128. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79129. 14,15: 0 (reserved)
  79130. Library content (indicates missing functionality):
  79131. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79132. deflate code when not needed)
  79133. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79134. and decode gzip streams (to avoid linking crc code)
  79135. 18-19: 0 (reserved)
  79136. Operation variations (changes in library functionality):
  79137. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79138. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79139. 22,23: 0 (reserved)
  79140. The sprintf variant used by gzprintf (zero is best):
  79141. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79142. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79143. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79144. Remainder:
  79145. 27-31: 0 (reserved)
  79146. */
  79147. /* utility functions */
  79148. /*
  79149. The following utility functions are implemented on top of the
  79150. basic stream-oriented functions. To simplify the interface, some
  79151. default options are assumed (compression level and memory usage,
  79152. standard memory allocation functions). The source code of these
  79153. utility functions can easily be modified if you need special options.
  79154. */
  79155. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79156. const Bytef *source, uLong sourceLen));
  79157. /*
  79158. Compresses the source buffer into the destination buffer. sourceLen is
  79159. the byte length of the source buffer. Upon entry, destLen is the total
  79160. size of the destination buffer, which must be at least the value returned
  79161. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79162. compressed buffer.
  79163. This function can be used to compress a whole file at once if the
  79164. input file is mmap'ed.
  79165. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79166. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79167. buffer.
  79168. */
  79169. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79170. const Bytef *source, uLong sourceLen,
  79171. int level));
  79172. /*
  79173. Compresses the source buffer into the destination buffer. The level
  79174. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79175. length of the source buffer. Upon entry, destLen is the total size of the
  79176. destination buffer, which must be at least the value returned by
  79177. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79178. compressed buffer.
  79179. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79180. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79181. Z_STREAM_ERROR if the level parameter is invalid.
  79182. */
  79183. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79184. /*
  79185. compressBound() returns an upper bound on the compressed size after
  79186. compress() or compress2() on sourceLen bytes. It would be used before
  79187. a compress() or compress2() call to allocate the destination buffer.
  79188. */
  79189. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79190. const Bytef *source, uLong sourceLen));
  79191. /*
  79192. Decompresses the source buffer into the destination buffer. sourceLen is
  79193. the byte length of the source buffer. Upon entry, destLen is the total
  79194. size of the destination buffer, which must be large enough to hold the
  79195. entire uncompressed data. (The size of the uncompressed data must have
  79196. been saved previously by the compressor and transmitted to the decompressor
  79197. by some mechanism outside the scope of this compression library.)
  79198. Upon exit, destLen is the actual size of the compressed buffer.
  79199. This function can be used to decompress a whole file at once if the
  79200. input file is mmap'ed.
  79201. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79202. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79203. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79204. */
  79205. typedef voidp gzFile;
  79206. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79207. /*
  79208. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79209. is as in fopen ("rb" or "wb") but can also include a compression level
  79210. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79211. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79212. as in "wb1R". (See the description of deflateInit2 for more information
  79213. about the strategy parameter.)
  79214. gzopen can be used to read a file which is not in gzip format; in this
  79215. case gzread will directly read from the file without decompression.
  79216. gzopen returns NULL if the file could not be opened or if there was
  79217. insufficient memory to allocate the (de)compression state; errno
  79218. can be checked to distinguish the two cases (if errno is zero, the
  79219. zlib error is Z_MEM_ERROR). */
  79220. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79221. /*
  79222. gzdopen() associates a gzFile with the file descriptor fd. File
  79223. descriptors are obtained from calls like open, dup, creat, pipe or
  79224. fileno (in the file has been previously opened with fopen).
  79225. The mode parameter is as in gzopen.
  79226. The next call of gzclose on the returned gzFile will also close the
  79227. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79228. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79229. gzdopen returns NULL if there was insufficient memory to allocate
  79230. the (de)compression state.
  79231. */
  79232. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79233. /*
  79234. Dynamically update the compression level or strategy. See the description
  79235. of deflateInit2 for the meaning of these parameters.
  79236. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79237. opened for writing.
  79238. */
  79239. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79240. /*
  79241. Reads the given number of uncompressed bytes from the compressed file.
  79242. If the input file was not in gzip format, gzread copies the given number
  79243. of bytes into the buffer.
  79244. gzread returns the number of uncompressed bytes actually read (0 for
  79245. end of file, -1 for error). */
  79246. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79247. voidpc buf, unsigned len));
  79248. /*
  79249. Writes the given number of uncompressed bytes into the compressed file.
  79250. gzwrite returns the number of uncompressed bytes actually written
  79251. (0 in case of error).
  79252. */
  79253. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79254. /*
  79255. Converts, formats, and writes the args to the compressed file under
  79256. control of the format string, as in fprintf. gzprintf returns the number of
  79257. uncompressed bytes actually written (0 in case of error). The number of
  79258. uncompressed bytes written is limited to 4095. The caller should assure that
  79259. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79260. return an error (0) with nothing written. In this case, there may also be a
  79261. buffer overflow with unpredictable consequences, which is possible only if
  79262. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79263. because the secure snprintf() or vsnprintf() functions were not available.
  79264. */
  79265. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79266. /*
  79267. Writes the given null-terminated string to the compressed file, excluding
  79268. the terminating null character.
  79269. gzputs returns the number of characters written, or -1 in case of error.
  79270. */
  79271. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79272. /*
  79273. Reads bytes from the compressed file until len-1 characters are read, or
  79274. a newline character is read and transferred to buf, or an end-of-file
  79275. condition is encountered. The string is then terminated with a null
  79276. character.
  79277. gzgets returns buf, or Z_NULL in case of error.
  79278. */
  79279. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79280. /*
  79281. Writes c, converted to an unsigned char, into the compressed file.
  79282. gzputc returns the value that was written, or -1 in case of error.
  79283. */
  79284. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79285. /*
  79286. Reads one byte from the compressed file. gzgetc returns this byte
  79287. or -1 in case of end of file or error.
  79288. */
  79289. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79290. /*
  79291. Push one character back onto the stream to be read again later.
  79292. Only one character of push-back is allowed. gzungetc() returns the
  79293. character pushed, or -1 on failure. gzungetc() will fail if a
  79294. character has been pushed but not read yet, or if c is -1. The pushed
  79295. character will be discarded if the stream is repositioned with gzseek()
  79296. or gzrewind().
  79297. */
  79298. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79299. /*
  79300. Flushes all pending output into the compressed file. The parameter
  79301. flush is as in the deflate() function. The return value is the zlib
  79302. error number (see function gzerror below). gzflush returns Z_OK if
  79303. the flush parameter is Z_FINISH and all output could be flushed.
  79304. gzflush should be called only when strictly necessary because it can
  79305. degrade compression.
  79306. */
  79307. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79308. z_off_t offset, int whence));
  79309. /*
  79310. Sets the starting position for the next gzread or gzwrite on the
  79311. given compressed file. The offset represents a number of bytes in the
  79312. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79313. the value SEEK_END is not supported.
  79314. If the file is opened for reading, this function is emulated but can be
  79315. extremely slow. If the file is opened for writing, only forward seeks are
  79316. supported; gzseek then compresses a sequence of zeroes up to the new
  79317. starting position.
  79318. gzseek returns the resulting offset location as measured in bytes from
  79319. the beginning of the uncompressed stream, or -1 in case of error, in
  79320. particular if the file is opened for writing and the new starting position
  79321. would be before the current position.
  79322. */
  79323. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79324. /*
  79325. Rewinds the given file. This function is supported only for reading.
  79326. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79327. */
  79328. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79329. /*
  79330. Returns the starting position for the next gzread or gzwrite on the
  79331. given compressed file. This position represents a number of bytes in the
  79332. uncompressed data stream.
  79333. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79334. */
  79335. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79336. /*
  79337. Returns 1 when EOF has previously been detected reading the given
  79338. input stream, otherwise zero.
  79339. */
  79340. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79341. /*
  79342. Returns 1 if file is being read directly without decompression, otherwise
  79343. zero.
  79344. */
  79345. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79346. /*
  79347. Flushes all pending output if necessary, closes the compressed file
  79348. and deallocates all the (de)compression state. The return value is the zlib
  79349. error number (see function gzerror below).
  79350. */
  79351. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79352. /*
  79353. Returns the error message for the last error which occurred on the
  79354. given compressed file. errnum is set to zlib error number. If an
  79355. error occurred in the file system and not in the compression library,
  79356. errnum is set to Z_ERRNO and the application may consult errno
  79357. to get the exact error code.
  79358. */
  79359. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79360. /*
  79361. Clears the error and end-of-file flags for file. This is analogous to the
  79362. clearerr() function in stdio. This is useful for continuing to read a gzip
  79363. file that is being written concurrently.
  79364. */
  79365. /* checksum functions */
  79366. /*
  79367. These functions are not related to compression but are exported
  79368. anyway because they might be useful in applications using the
  79369. compression library.
  79370. */
  79371. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79372. /*
  79373. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79374. return the updated checksum. If buf is NULL, this function returns
  79375. the required initial value for the checksum.
  79376. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79377. much faster. Usage example:
  79378. uLong adler = adler32(0L, Z_NULL, 0);
  79379. while (read_buffer(buffer, length) != EOF) {
  79380. adler = adler32(adler, buffer, length);
  79381. }
  79382. if (adler != original_adler) error();
  79383. */
  79384. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79385. z_off_t len2));
  79386. /*
  79387. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79388. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79389. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79390. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79391. */
  79392. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79393. /*
  79394. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79395. updated CRC-32. If buf is NULL, this function returns the required initial
  79396. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79397. performed within this function so it shouldn't be done by the application.
  79398. Usage example:
  79399. uLong crc = crc32(0L, Z_NULL, 0);
  79400. while (read_buffer(buffer, length) != EOF) {
  79401. crc = crc32(crc, buffer, length);
  79402. }
  79403. if (crc != original_crc) error();
  79404. */
  79405. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79406. /*
  79407. Combine two CRC-32 check values into one. For two sequences of bytes,
  79408. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79409. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79410. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79411. len2.
  79412. */
  79413. /* various hacks, don't look :) */
  79414. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79415. * and the compiler's view of z_stream:
  79416. */
  79417. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79418. const char *version, int stream_size));
  79419. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79420. const char *version, int stream_size));
  79421. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79422. int windowBits, int memLevel,
  79423. int strategy, const char *version,
  79424. int stream_size));
  79425. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79426. const char *version, int stream_size));
  79427. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79428. unsigned char FAR *window,
  79429. const char *version,
  79430. int stream_size));
  79431. #define deflateInit(strm, level) \
  79432. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79433. #define inflateInit(strm) \
  79434. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79435. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79436. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79437. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79438. #define inflateInit2(strm, windowBits) \
  79439. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79440. #define inflateBackInit(strm, windowBits, window) \
  79441. inflateBackInit_((strm), (windowBits), (window), \
  79442. ZLIB_VERSION, sizeof(z_stream))
  79443. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79444. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79445. #endif
  79446. ZEXTERN const char * ZEXPORT zError OF((int));
  79447. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79448. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79449. #ifdef __cplusplus
  79450. //}
  79451. #endif
  79452. #endif /* ZLIB_H */
  79453. /*** End of inlined file: zlib.h ***/
  79454. #undef OS_CODE
  79455. #else
  79456. #include <zlib.h>
  79457. #endif
  79458. }
  79459. BEGIN_JUCE_NAMESPACE
  79460. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79461. {
  79462. public:
  79463. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79464. : data (0),
  79465. dataSize (0),
  79466. compLevel (compressionLevel),
  79467. strategy (0),
  79468. setParams (true),
  79469. streamIsValid (false),
  79470. finished (false),
  79471. shouldFinish (false)
  79472. {
  79473. using namespace zlibNamespace;
  79474. zerostruct (stream);
  79475. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79476. windowBits != 0 ? windowBits : MAX_WBITS,
  79477. 8, strategy) == Z_OK);
  79478. }
  79479. ~GZIPCompressorHelper()
  79480. {
  79481. using namespace zlibNamespace;
  79482. if (streamIsValid)
  79483. deflateEnd (&stream);
  79484. }
  79485. bool needsInput() const throw()
  79486. {
  79487. return dataSize <= 0;
  79488. }
  79489. void setInput (const uint8* const newData, const int size) throw()
  79490. {
  79491. data = newData;
  79492. dataSize = size;
  79493. }
  79494. int doNextBlock (uint8* const dest, const int destSize) throw()
  79495. {
  79496. using namespace zlibNamespace;
  79497. if (streamIsValid)
  79498. {
  79499. stream.next_in = const_cast <uint8*> (data);
  79500. stream.next_out = dest;
  79501. stream.avail_in = dataSize;
  79502. stream.avail_out = destSize;
  79503. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79504. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79505. setParams = false;
  79506. switch (result)
  79507. {
  79508. case Z_STREAM_END:
  79509. finished = true;
  79510. // Deliberate fall-through..
  79511. case Z_OK:
  79512. data += dataSize - stream.avail_in;
  79513. dataSize = stream.avail_in;
  79514. return destSize - stream.avail_out;
  79515. default:
  79516. break;
  79517. }
  79518. }
  79519. return 0;
  79520. }
  79521. enum { gzipCompBufferSize = 32768 };
  79522. private:
  79523. zlibNamespace::z_stream stream;
  79524. const uint8* data;
  79525. int dataSize, compLevel, strategy;
  79526. bool setParams, streamIsValid;
  79527. public:
  79528. bool finished, shouldFinish;
  79529. };
  79530. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79531. int compressionLevel,
  79532. const bool deleteDestStream,
  79533. const int windowBits)
  79534. : destStream (destStream_),
  79535. streamToDelete (deleteDestStream ? destStream_ : 0),
  79536. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79537. {
  79538. if (compressionLevel < 1 || compressionLevel > 9)
  79539. compressionLevel = -1;
  79540. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79541. }
  79542. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79543. {
  79544. flush();
  79545. }
  79546. void GZIPCompressorOutputStream::flush()
  79547. {
  79548. if (! helper->finished)
  79549. {
  79550. helper->shouldFinish = true;
  79551. while (! helper->finished)
  79552. doNextBlock();
  79553. }
  79554. destStream->flush();
  79555. }
  79556. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79557. {
  79558. if (! helper->finished)
  79559. {
  79560. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79561. while (! helper->needsInput())
  79562. {
  79563. if (! doNextBlock())
  79564. return false;
  79565. }
  79566. }
  79567. return true;
  79568. }
  79569. bool GZIPCompressorOutputStream::doNextBlock()
  79570. {
  79571. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79572. return len <= 0 || destStream->write (buffer, len);
  79573. }
  79574. int64 GZIPCompressorOutputStream::getPosition()
  79575. {
  79576. return destStream->getPosition();
  79577. }
  79578. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79579. {
  79580. jassertfalse; // can't do it!
  79581. return false;
  79582. }
  79583. END_JUCE_NAMESPACE
  79584. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79585. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79586. #if JUCE_MSVC
  79587. #pragma warning (push)
  79588. #pragma warning (disable: 4309 4305)
  79589. #endif
  79590. namespace zlibNamespace
  79591. {
  79592. #if JUCE_INCLUDE_ZLIB_CODE
  79593. #undef OS_CODE
  79594. #undef fdopen
  79595. #define ZLIB_INTERNAL
  79596. #define NO_DUMMY_DECL
  79597. /*** Start of inlined file: adler32.c ***/
  79598. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79599. #define ZLIB_INTERNAL
  79600. #define BASE 65521UL /* largest prime smaller than 65536 */
  79601. #define NMAX 5552
  79602. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79603. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79604. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79605. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79606. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79607. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79608. /* use NO_DIVIDE if your processor does not do division in hardware */
  79609. #ifdef NO_DIVIDE
  79610. # define MOD(a) \
  79611. do { \
  79612. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79613. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79614. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79615. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79616. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79617. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79618. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79619. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79620. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79621. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79622. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79623. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79624. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79625. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79626. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79627. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79628. if (a >= BASE) a -= BASE; \
  79629. } while (0)
  79630. # define MOD4(a) \
  79631. do { \
  79632. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79633. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79634. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79635. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79636. if (a >= BASE) a -= BASE; \
  79637. } while (0)
  79638. #else
  79639. # define MOD(a) a %= BASE
  79640. # define MOD4(a) a %= BASE
  79641. #endif
  79642. /* ========================================================================= */
  79643. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79644. {
  79645. unsigned long sum2;
  79646. unsigned n;
  79647. /* split Adler-32 into component sums */
  79648. sum2 = (adler >> 16) & 0xffff;
  79649. adler &= 0xffff;
  79650. /* in case user likes doing a byte at a time, keep it fast */
  79651. if (len == 1) {
  79652. adler += buf[0];
  79653. if (adler >= BASE)
  79654. adler -= BASE;
  79655. sum2 += adler;
  79656. if (sum2 >= BASE)
  79657. sum2 -= BASE;
  79658. return adler | (sum2 << 16);
  79659. }
  79660. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79661. if (buf == Z_NULL)
  79662. return 1L;
  79663. /* in case short lengths are provided, keep it somewhat fast */
  79664. if (len < 16) {
  79665. while (len--) {
  79666. adler += *buf++;
  79667. sum2 += adler;
  79668. }
  79669. if (adler >= BASE)
  79670. adler -= BASE;
  79671. MOD4(sum2); /* only added so many BASE's */
  79672. return adler | (sum2 << 16);
  79673. }
  79674. /* do length NMAX blocks -- requires just one modulo operation */
  79675. while (len >= NMAX) {
  79676. len -= NMAX;
  79677. n = NMAX / 16; /* NMAX is divisible by 16 */
  79678. do {
  79679. DO16(buf); /* 16 sums unrolled */
  79680. buf += 16;
  79681. } while (--n);
  79682. MOD(adler);
  79683. MOD(sum2);
  79684. }
  79685. /* do remaining bytes (less than NMAX, still just one modulo) */
  79686. if (len) { /* avoid modulos if none remaining */
  79687. while (len >= 16) {
  79688. len -= 16;
  79689. DO16(buf);
  79690. buf += 16;
  79691. }
  79692. while (len--) {
  79693. adler += *buf++;
  79694. sum2 += adler;
  79695. }
  79696. MOD(adler);
  79697. MOD(sum2);
  79698. }
  79699. /* return recombined sums */
  79700. return adler | (sum2 << 16);
  79701. }
  79702. /* ========================================================================= */
  79703. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79704. {
  79705. unsigned long sum1;
  79706. unsigned long sum2;
  79707. unsigned rem;
  79708. /* the derivation of this formula is left as an exercise for the reader */
  79709. rem = (unsigned)(len2 % BASE);
  79710. sum1 = adler1 & 0xffff;
  79711. sum2 = rem * sum1;
  79712. MOD(sum2);
  79713. sum1 += (adler2 & 0xffff) + BASE - 1;
  79714. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79715. if (sum1 > BASE) sum1 -= BASE;
  79716. if (sum1 > BASE) sum1 -= BASE;
  79717. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79718. if (sum2 > BASE) sum2 -= BASE;
  79719. return sum1 | (sum2 << 16);
  79720. }
  79721. /*** End of inlined file: adler32.c ***/
  79722. /*** Start of inlined file: compress.c ***/
  79723. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79724. #define ZLIB_INTERNAL
  79725. /* ===========================================================================
  79726. Compresses the source buffer into the destination buffer. The level
  79727. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79728. length of the source buffer. Upon entry, destLen is the total size of the
  79729. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79730. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79731. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79732. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79733. Z_STREAM_ERROR if the level parameter is invalid.
  79734. */
  79735. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79736. uLong sourceLen, int level)
  79737. {
  79738. z_stream stream;
  79739. int err;
  79740. stream.next_in = (Bytef*)source;
  79741. stream.avail_in = (uInt)sourceLen;
  79742. #ifdef MAXSEG_64K
  79743. /* Check for source > 64K on 16-bit machine: */
  79744. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79745. #endif
  79746. stream.next_out = dest;
  79747. stream.avail_out = (uInt)*destLen;
  79748. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79749. stream.zalloc = (alloc_func)0;
  79750. stream.zfree = (free_func)0;
  79751. stream.opaque = (voidpf)0;
  79752. err = deflateInit(&stream, level);
  79753. if (err != Z_OK) return err;
  79754. err = deflate(&stream, Z_FINISH);
  79755. if (err != Z_STREAM_END) {
  79756. deflateEnd(&stream);
  79757. return err == Z_OK ? Z_BUF_ERROR : err;
  79758. }
  79759. *destLen = stream.total_out;
  79760. err = deflateEnd(&stream);
  79761. return err;
  79762. }
  79763. /* ===========================================================================
  79764. */
  79765. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79766. {
  79767. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79768. }
  79769. /* ===========================================================================
  79770. If the default memLevel or windowBits for deflateInit() is changed, then
  79771. this function needs to be updated.
  79772. */
  79773. uLong ZEXPORT compressBound (uLong sourceLen)
  79774. {
  79775. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79776. }
  79777. /*** End of inlined file: compress.c ***/
  79778. #undef DO1
  79779. #undef DO8
  79780. /*** Start of inlined file: crc32.c ***/
  79781. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79782. /*
  79783. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79784. protection on the static variables used to control the first-use generation
  79785. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79786. first call get_crc_table() to initialize the tables before allowing more than
  79787. one thread to use crc32().
  79788. */
  79789. #ifdef MAKECRCH
  79790. # include <stdio.h>
  79791. # ifndef DYNAMIC_CRC_TABLE
  79792. # define DYNAMIC_CRC_TABLE
  79793. # endif /* !DYNAMIC_CRC_TABLE */
  79794. #endif /* MAKECRCH */
  79795. /*** Start of inlined file: zutil.h ***/
  79796. /* WARNING: this file should *not* be used by applications. It is
  79797. part of the implementation of the compression library and is
  79798. subject to change. Applications should only use zlib.h.
  79799. */
  79800. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79801. #ifndef ZUTIL_H
  79802. #define ZUTIL_H
  79803. #define ZLIB_INTERNAL
  79804. #ifdef STDC
  79805. # ifndef _WIN32_WCE
  79806. # include <stddef.h>
  79807. # endif
  79808. # include <string.h>
  79809. # include <stdlib.h>
  79810. #endif
  79811. #ifdef NO_ERRNO_H
  79812. # ifdef _WIN32_WCE
  79813. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79814. * errno. We define it as a global variable to simplify porting.
  79815. * Its value is always 0 and should not be used. We rename it to
  79816. * avoid conflict with other libraries that use the same workaround.
  79817. */
  79818. # define errno z_errno
  79819. # endif
  79820. extern int errno;
  79821. #else
  79822. # ifndef _WIN32_WCE
  79823. # include <errno.h>
  79824. # endif
  79825. #endif
  79826. #ifndef local
  79827. # define local static
  79828. #endif
  79829. /* compile with -Dlocal if your debugger can't find static symbols */
  79830. typedef unsigned char uch;
  79831. typedef uch FAR uchf;
  79832. typedef unsigned short ush;
  79833. typedef ush FAR ushf;
  79834. typedef unsigned long ulg;
  79835. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79836. /* (size given to avoid silly warnings with Visual C++) */
  79837. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79838. #define ERR_RETURN(strm,err) \
  79839. return (strm->msg = (char*)ERR_MSG(err), (err))
  79840. /* To be used only when the state is known to be valid */
  79841. /* common constants */
  79842. #ifndef DEF_WBITS
  79843. # define DEF_WBITS MAX_WBITS
  79844. #endif
  79845. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79846. #if MAX_MEM_LEVEL >= 8
  79847. # define DEF_MEM_LEVEL 8
  79848. #else
  79849. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79850. #endif
  79851. /* default memLevel */
  79852. #define STORED_BLOCK 0
  79853. #define STATIC_TREES 1
  79854. #define DYN_TREES 2
  79855. /* The three kinds of block type */
  79856. #define MIN_MATCH 3
  79857. #define MAX_MATCH 258
  79858. /* The minimum and maximum match lengths */
  79859. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79860. /* target dependencies */
  79861. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79862. # define OS_CODE 0x00
  79863. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79864. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79865. /* Allow compilation with ANSI keywords only enabled */
  79866. void _Cdecl farfree( void *block );
  79867. void *_Cdecl farmalloc( unsigned long nbytes );
  79868. # else
  79869. # include <alloc.h>
  79870. # endif
  79871. # else /* MSC or DJGPP */
  79872. # include <malloc.h>
  79873. # endif
  79874. #endif
  79875. #ifdef AMIGA
  79876. # define OS_CODE 0x01
  79877. #endif
  79878. #if defined(VAXC) || defined(VMS)
  79879. # define OS_CODE 0x02
  79880. # define F_OPEN(name, mode) \
  79881. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79882. #endif
  79883. #if defined(ATARI) || defined(atarist)
  79884. # define OS_CODE 0x05
  79885. #endif
  79886. #ifdef OS2
  79887. # define OS_CODE 0x06
  79888. # ifdef M_I86
  79889. #include <malloc.h>
  79890. # endif
  79891. #endif
  79892. #if defined(MACOS) || TARGET_OS_MAC
  79893. # define OS_CODE 0x07
  79894. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79895. # include <unix.h> /* for fdopen */
  79896. # else
  79897. # ifndef fdopen
  79898. # define fdopen(fd,mode) NULL /* No fdopen() */
  79899. # endif
  79900. # endif
  79901. #endif
  79902. #ifdef TOPS20
  79903. # define OS_CODE 0x0a
  79904. #endif
  79905. #ifdef WIN32
  79906. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79907. # define OS_CODE 0x0b
  79908. # endif
  79909. #endif
  79910. #ifdef __50SERIES /* Prime/PRIMOS */
  79911. # define OS_CODE 0x0f
  79912. #endif
  79913. #if defined(_BEOS_) || defined(RISCOS)
  79914. # define fdopen(fd,mode) NULL /* No fdopen() */
  79915. #endif
  79916. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79917. # if defined(_WIN32_WCE)
  79918. # define fdopen(fd,mode) NULL /* No fdopen() */
  79919. # ifndef _PTRDIFF_T_DEFINED
  79920. typedef int ptrdiff_t;
  79921. # define _PTRDIFF_T_DEFINED
  79922. # endif
  79923. # else
  79924. # define fdopen(fd,type) _fdopen(fd,type)
  79925. # endif
  79926. #endif
  79927. /* common defaults */
  79928. #ifndef OS_CODE
  79929. # define OS_CODE 0x03 /* assume Unix */
  79930. #endif
  79931. #ifndef F_OPEN
  79932. # define F_OPEN(name, mode) fopen((name), (mode))
  79933. #endif
  79934. /* functions */
  79935. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79936. # ifndef HAVE_VSNPRINTF
  79937. # define HAVE_VSNPRINTF
  79938. # endif
  79939. #endif
  79940. #if defined(__CYGWIN__)
  79941. # ifndef HAVE_VSNPRINTF
  79942. # define HAVE_VSNPRINTF
  79943. # endif
  79944. #endif
  79945. #ifndef HAVE_VSNPRINTF
  79946. # ifdef MSDOS
  79947. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79948. but for now we just assume it doesn't. */
  79949. # define NO_vsnprintf
  79950. # endif
  79951. # ifdef __TURBOC__
  79952. # define NO_vsnprintf
  79953. # endif
  79954. # ifdef WIN32
  79955. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79956. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79957. # define vsnprintf _vsnprintf
  79958. # endif
  79959. # endif
  79960. # ifdef __SASC
  79961. # define NO_vsnprintf
  79962. # endif
  79963. #endif
  79964. #ifdef VMS
  79965. # define NO_vsnprintf
  79966. #endif
  79967. #if defined(pyr)
  79968. # define NO_MEMCPY
  79969. #endif
  79970. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79971. /* Use our own functions for small and medium model with MSC <= 5.0.
  79972. * You may have to use the same strategy for Borland C (untested).
  79973. * The __SC__ check is for Symantec.
  79974. */
  79975. # define NO_MEMCPY
  79976. #endif
  79977. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79978. # define HAVE_MEMCPY
  79979. #endif
  79980. #ifdef HAVE_MEMCPY
  79981. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79982. # define zmemcpy _fmemcpy
  79983. # define zmemcmp _fmemcmp
  79984. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79985. # else
  79986. # define zmemcpy memcpy
  79987. # define zmemcmp memcmp
  79988. # define zmemzero(dest, len) memset(dest, 0, len)
  79989. # endif
  79990. #else
  79991. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79992. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79993. extern void zmemzero OF((Bytef* dest, uInt len));
  79994. #endif
  79995. /* Diagnostic functions */
  79996. #ifdef DEBUG
  79997. # include <stdio.h>
  79998. extern int z_verbose;
  79999. extern void z_error OF((const char *m));
  80000. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80001. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80002. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80003. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80004. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80005. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80006. #else
  80007. # define Assert(cond,msg)
  80008. # define Trace(x)
  80009. # define Tracev(x)
  80010. # define Tracevv(x)
  80011. # define Tracec(c,x)
  80012. # define Tracecv(c,x)
  80013. #endif
  80014. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80015. void zcfree OF((voidpf opaque, voidpf ptr));
  80016. #define ZALLOC(strm, items, size) \
  80017. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80018. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80019. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80020. #endif /* ZUTIL_H */
  80021. /*** End of inlined file: zutil.h ***/
  80022. /* for STDC and FAR definitions */
  80023. #define local static
  80024. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80025. #ifndef NOBYFOUR
  80026. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80027. # include <limits.h>
  80028. # define BYFOUR
  80029. # if (UINT_MAX == 0xffffffffUL)
  80030. typedef unsigned int u4;
  80031. # else
  80032. # if (ULONG_MAX == 0xffffffffUL)
  80033. typedef unsigned long u4;
  80034. # else
  80035. # if (USHRT_MAX == 0xffffffffUL)
  80036. typedef unsigned short u4;
  80037. # else
  80038. # undef BYFOUR /* can't find a four-byte integer type! */
  80039. # endif
  80040. # endif
  80041. # endif
  80042. # endif /* STDC */
  80043. #endif /* !NOBYFOUR */
  80044. /* Definitions for doing the crc four data bytes at a time. */
  80045. #ifdef BYFOUR
  80046. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80047. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80048. local unsigned long crc32_little OF((unsigned long,
  80049. const unsigned char FAR *, unsigned));
  80050. local unsigned long crc32_big OF((unsigned long,
  80051. const unsigned char FAR *, unsigned));
  80052. # define TBLS 8
  80053. #else
  80054. # define TBLS 1
  80055. #endif /* BYFOUR */
  80056. /* Local functions for crc concatenation */
  80057. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80058. unsigned long vec));
  80059. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80060. #ifdef DYNAMIC_CRC_TABLE
  80061. local volatile int crc_table_empty = 1;
  80062. local unsigned long FAR crc_table[TBLS][256];
  80063. local void make_crc_table OF((void));
  80064. #ifdef MAKECRCH
  80065. local void write_table OF((FILE *, const unsigned long FAR *));
  80066. #endif /* MAKECRCH */
  80067. /*
  80068. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80069. 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.
  80070. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80071. with the lowest powers in the most significant bit. Then adding polynomials
  80072. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80073. one. If we call the above polynomial p, and represent a byte as the
  80074. polynomial q, also with the lowest power in the most significant bit (so the
  80075. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80076. where a mod b means the remainder after dividing a by b.
  80077. This calculation is done using the shift-register method of multiplying and
  80078. taking the remainder. The register is initialized to zero, and for each
  80079. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80080. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80081. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80082. out is a one). We start with the highest power (least significant bit) of
  80083. q and repeat for all eight bits of q.
  80084. The first table is simply the CRC of all possible eight bit values. This is
  80085. all the information needed to generate CRCs on data a byte at a time for all
  80086. combinations of CRC register values and incoming bytes. The remaining tables
  80087. allow for word-at-a-time CRC calculation for both big-endian and little-
  80088. endian machines, where a word is four bytes.
  80089. */
  80090. local void make_crc_table()
  80091. {
  80092. unsigned long c;
  80093. int n, k;
  80094. unsigned long poly; /* polynomial exclusive-or pattern */
  80095. /* terms of polynomial defining this crc (except x^32): */
  80096. static volatile int first = 1; /* flag to limit concurrent making */
  80097. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80098. /* See if another task is already doing this (not thread-safe, but better
  80099. than nothing -- significantly reduces duration of vulnerability in
  80100. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80101. if (first) {
  80102. first = 0;
  80103. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80104. poly = 0UL;
  80105. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80106. poly |= 1UL << (31 - p[n]);
  80107. /* generate a crc for every 8-bit value */
  80108. for (n = 0; n < 256; n++) {
  80109. c = (unsigned long)n;
  80110. for (k = 0; k < 8; k++)
  80111. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80112. crc_table[0][n] = c;
  80113. }
  80114. #ifdef BYFOUR
  80115. /* generate crc for each value followed by one, two, and three zeros,
  80116. and then the byte reversal of those as well as the first table */
  80117. for (n = 0; n < 256; n++) {
  80118. c = crc_table[0][n];
  80119. crc_table[4][n] = REV(c);
  80120. for (k = 1; k < 4; k++) {
  80121. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80122. crc_table[k][n] = c;
  80123. crc_table[k + 4][n] = REV(c);
  80124. }
  80125. }
  80126. #endif /* BYFOUR */
  80127. crc_table_empty = 0;
  80128. }
  80129. else { /* not first */
  80130. /* wait for the other guy to finish (not efficient, but rare) */
  80131. while (crc_table_empty)
  80132. ;
  80133. }
  80134. #ifdef MAKECRCH
  80135. /* write out CRC tables to crc32.h */
  80136. {
  80137. FILE *out;
  80138. out = fopen("crc32.h", "w");
  80139. if (out == NULL) return;
  80140. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80141. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80142. fprintf(out, "local const unsigned long FAR ");
  80143. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80144. write_table(out, crc_table[0]);
  80145. # ifdef BYFOUR
  80146. fprintf(out, "#ifdef BYFOUR\n");
  80147. for (k = 1; k < 8; k++) {
  80148. fprintf(out, " },\n {\n");
  80149. write_table(out, crc_table[k]);
  80150. }
  80151. fprintf(out, "#endif\n");
  80152. # endif /* BYFOUR */
  80153. fprintf(out, " }\n};\n");
  80154. fclose(out);
  80155. }
  80156. #endif /* MAKECRCH */
  80157. }
  80158. #ifdef MAKECRCH
  80159. local void write_table(out, table)
  80160. FILE *out;
  80161. const unsigned long FAR *table;
  80162. {
  80163. int n;
  80164. for (n = 0; n < 256; n++)
  80165. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80166. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80167. }
  80168. #endif /* MAKECRCH */
  80169. #else /* !DYNAMIC_CRC_TABLE */
  80170. /* ========================================================================
  80171. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80172. */
  80173. /*** Start of inlined file: crc32.h ***/
  80174. local const unsigned long FAR crc_table[TBLS][256] =
  80175. {
  80176. {
  80177. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80178. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80179. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80180. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80181. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80182. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80183. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80184. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80185. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80186. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80187. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80188. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80189. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80190. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80191. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80192. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80193. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80194. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80195. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80196. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80197. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80198. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80199. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80200. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80201. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80202. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80203. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80204. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80205. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80206. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80207. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80208. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80209. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80210. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80211. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80212. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80213. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80214. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80215. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80216. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80217. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80218. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80219. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80220. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80221. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80222. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80223. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80224. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80225. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80226. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80227. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80228. 0x2d02ef8dUL
  80229. #ifdef BYFOUR
  80230. },
  80231. {
  80232. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80233. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80234. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80235. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80236. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80237. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80238. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80239. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80240. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80241. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80242. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80243. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80244. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80245. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80246. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80247. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80248. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80249. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80250. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80251. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80252. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80253. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80254. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80255. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80256. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80257. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80258. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80259. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80260. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80261. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80262. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80263. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80264. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80265. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80266. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80267. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80268. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80269. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80270. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80271. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80272. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80273. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80274. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80275. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80276. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80277. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80278. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80279. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80280. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80281. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80282. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80283. 0x9324fd72UL
  80284. },
  80285. {
  80286. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80287. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80288. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80289. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80290. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80291. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80292. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80293. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80294. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80295. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80296. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80297. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80298. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80299. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80300. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80301. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80302. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80303. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80304. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80305. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80306. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80307. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80308. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80309. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80310. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80311. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80312. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80313. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80314. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80315. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80316. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80317. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80318. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80319. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80320. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80321. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80322. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80323. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80324. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80325. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80326. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80327. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80328. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80329. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80330. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80331. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80332. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80333. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80334. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80335. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80336. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80337. 0xbe9834edUL
  80338. },
  80339. {
  80340. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80341. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80342. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80343. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80344. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80345. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80346. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80347. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80348. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80349. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80350. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80351. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80352. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80353. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80354. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80355. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80356. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80357. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80358. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80359. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80360. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80361. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80362. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80363. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80364. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80365. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80366. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80367. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80368. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80369. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80370. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80371. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80372. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80373. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80374. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80375. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80376. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80377. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80378. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80379. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80380. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80381. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80382. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80383. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80384. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80385. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80386. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80387. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80388. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80389. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80390. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80391. 0xde0506f1UL
  80392. },
  80393. {
  80394. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80395. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80396. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80397. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80398. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80399. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80400. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80401. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80402. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80403. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80404. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80405. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80406. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80407. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80408. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80409. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80410. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80411. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80412. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80413. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80414. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80415. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80416. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80417. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80418. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80419. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80420. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80421. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80422. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80423. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80424. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80425. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80426. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80427. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80428. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80429. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80430. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80431. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80432. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80433. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80434. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80435. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80436. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80437. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80438. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80439. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80440. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80441. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80442. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80443. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80444. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80445. 0x8def022dUL
  80446. },
  80447. {
  80448. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80449. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80450. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80451. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80452. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80453. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80454. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80455. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80456. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80457. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80458. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80459. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80460. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80461. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80462. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80463. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80464. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80465. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80466. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80467. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80468. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80469. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80470. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80471. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80472. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80473. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80474. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80475. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80476. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80477. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80478. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80479. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80480. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80481. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80482. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80483. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80484. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80485. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80486. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80487. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80488. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80489. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80490. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80491. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80492. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80493. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80494. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80495. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80496. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80497. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80498. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80499. 0x72fd2493UL
  80500. },
  80501. {
  80502. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80503. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80504. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80505. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80506. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80507. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80508. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80509. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80510. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80511. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80512. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80513. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80514. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80515. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80516. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80517. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80518. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80519. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80520. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80521. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80522. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80523. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80524. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80525. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80526. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80527. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80528. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80529. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80530. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80531. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80532. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80533. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80534. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80535. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80536. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80537. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80538. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80539. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80540. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80541. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80542. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80543. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80544. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80545. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80546. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80547. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80548. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80549. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80550. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80551. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80552. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80553. 0xed3498beUL
  80554. },
  80555. {
  80556. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80557. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80558. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80559. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80560. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80561. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80562. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80563. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80564. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80565. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80566. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80567. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80568. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80569. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80570. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80571. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80572. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80573. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80574. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80575. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80576. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80577. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80578. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80579. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80580. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80581. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80582. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80583. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80584. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80585. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80586. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80587. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80588. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80589. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80590. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80591. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80592. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80593. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80594. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80595. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80596. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80597. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80598. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80599. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80600. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80601. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80602. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80603. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80604. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80605. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80606. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80607. 0xf10605deUL
  80608. #endif
  80609. }
  80610. };
  80611. /*** End of inlined file: crc32.h ***/
  80612. #endif /* DYNAMIC_CRC_TABLE */
  80613. /* =========================================================================
  80614. * This function can be used by asm versions of crc32()
  80615. */
  80616. const unsigned long FAR * ZEXPORT get_crc_table()
  80617. {
  80618. #ifdef DYNAMIC_CRC_TABLE
  80619. if (crc_table_empty)
  80620. make_crc_table();
  80621. #endif /* DYNAMIC_CRC_TABLE */
  80622. return (const unsigned long FAR *)crc_table;
  80623. }
  80624. /* ========================================================================= */
  80625. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80626. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80627. /* ========================================================================= */
  80628. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80629. {
  80630. if (buf == Z_NULL) return 0UL;
  80631. #ifdef DYNAMIC_CRC_TABLE
  80632. if (crc_table_empty)
  80633. make_crc_table();
  80634. #endif /* DYNAMIC_CRC_TABLE */
  80635. #ifdef BYFOUR
  80636. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80637. u4 endian;
  80638. endian = 1;
  80639. if (*((unsigned char *)(&endian)))
  80640. return crc32_little(crc, buf, len);
  80641. else
  80642. return crc32_big(crc, buf, len);
  80643. }
  80644. #endif /* BYFOUR */
  80645. crc = crc ^ 0xffffffffUL;
  80646. while (len >= 8) {
  80647. DO8;
  80648. len -= 8;
  80649. }
  80650. if (len) do {
  80651. DO1;
  80652. } while (--len);
  80653. return crc ^ 0xffffffffUL;
  80654. }
  80655. #ifdef BYFOUR
  80656. /* ========================================================================= */
  80657. #define DOLIT4 c ^= *buf4++; \
  80658. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80659. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80660. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80661. /* ========================================================================= */
  80662. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80663. {
  80664. register u4 c;
  80665. register const u4 FAR *buf4;
  80666. c = (u4)crc;
  80667. c = ~c;
  80668. while (len && ((ptrdiff_t)buf & 3)) {
  80669. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80670. len--;
  80671. }
  80672. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80673. while (len >= 32) {
  80674. DOLIT32;
  80675. len -= 32;
  80676. }
  80677. while (len >= 4) {
  80678. DOLIT4;
  80679. len -= 4;
  80680. }
  80681. buf = (const unsigned char FAR *)buf4;
  80682. if (len) do {
  80683. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80684. } while (--len);
  80685. c = ~c;
  80686. return (unsigned long)c;
  80687. }
  80688. /* ========================================================================= */
  80689. #define DOBIG4 c ^= *++buf4; \
  80690. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80691. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80692. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80693. /* ========================================================================= */
  80694. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80695. {
  80696. register u4 c;
  80697. register const u4 FAR *buf4;
  80698. c = REV((u4)crc);
  80699. c = ~c;
  80700. while (len && ((ptrdiff_t)buf & 3)) {
  80701. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80702. len--;
  80703. }
  80704. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80705. buf4--;
  80706. while (len >= 32) {
  80707. DOBIG32;
  80708. len -= 32;
  80709. }
  80710. while (len >= 4) {
  80711. DOBIG4;
  80712. len -= 4;
  80713. }
  80714. buf4++;
  80715. buf = (const unsigned char FAR *)buf4;
  80716. if (len) do {
  80717. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80718. } while (--len);
  80719. c = ~c;
  80720. return (unsigned long)(REV(c));
  80721. }
  80722. #endif /* BYFOUR */
  80723. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80724. /* ========================================================================= */
  80725. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80726. {
  80727. unsigned long sum;
  80728. sum = 0;
  80729. while (vec) {
  80730. if (vec & 1)
  80731. sum ^= *mat;
  80732. vec >>= 1;
  80733. mat++;
  80734. }
  80735. return sum;
  80736. }
  80737. /* ========================================================================= */
  80738. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80739. {
  80740. int n;
  80741. for (n = 0; n < GF2_DIM; n++)
  80742. square[n] = gf2_matrix_times(mat, mat[n]);
  80743. }
  80744. /* ========================================================================= */
  80745. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80746. {
  80747. int n;
  80748. unsigned long row;
  80749. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80750. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80751. /* degenerate case */
  80752. if (len2 == 0)
  80753. return crc1;
  80754. /* put operator for one zero bit in odd */
  80755. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80756. row = 1;
  80757. for (n = 1; n < GF2_DIM; n++) {
  80758. odd[n] = row;
  80759. row <<= 1;
  80760. }
  80761. /* put operator for two zero bits in even */
  80762. gf2_matrix_square(even, odd);
  80763. /* put operator for four zero bits in odd */
  80764. gf2_matrix_square(odd, even);
  80765. /* apply len2 zeros to crc1 (first square will put the operator for one
  80766. zero byte, eight zero bits, in even) */
  80767. do {
  80768. /* apply zeros operator for this bit of len2 */
  80769. gf2_matrix_square(even, odd);
  80770. if (len2 & 1)
  80771. crc1 = gf2_matrix_times(even, crc1);
  80772. len2 >>= 1;
  80773. /* if no more bits set, then done */
  80774. if (len2 == 0)
  80775. break;
  80776. /* another iteration of the loop with odd and even swapped */
  80777. gf2_matrix_square(odd, even);
  80778. if (len2 & 1)
  80779. crc1 = gf2_matrix_times(odd, crc1);
  80780. len2 >>= 1;
  80781. /* if no more bits set, then done */
  80782. } while (len2 != 0);
  80783. /* return combined crc */
  80784. crc1 ^= crc2;
  80785. return crc1;
  80786. }
  80787. /*** End of inlined file: crc32.c ***/
  80788. /*** Start of inlined file: deflate.c ***/
  80789. /*
  80790. * ALGORITHM
  80791. *
  80792. * The "deflation" process depends on being able to identify portions
  80793. * of the input text which are identical to earlier input (within a
  80794. * sliding window trailing behind the input currently being processed).
  80795. *
  80796. * The most straightforward technique turns out to be the fastest for
  80797. * most input files: try all possible matches and select the longest.
  80798. * The key feature of this algorithm is that insertions into the string
  80799. * dictionary are very simple and thus fast, and deletions are avoided
  80800. * completely. Insertions are performed at each input character, whereas
  80801. * string matches are performed only when the previous match ends. So it
  80802. * is preferable to spend more time in matches to allow very fast string
  80803. * insertions and avoid deletions. The matching algorithm for small
  80804. * strings is inspired from that of Rabin & Karp. A brute force approach
  80805. * is used to find longer strings when a small match has been found.
  80806. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80807. * (by Leonid Broukhis).
  80808. * A previous version of this file used a more sophisticated algorithm
  80809. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80810. * time, but has a larger average cost, uses more memory and is patented.
  80811. * However the F&G algorithm may be faster for some highly redundant
  80812. * files if the parameter max_chain_length (described below) is too large.
  80813. *
  80814. * ACKNOWLEDGEMENTS
  80815. *
  80816. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80817. * I found it in 'freeze' written by Leonid Broukhis.
  80818. * Thanks to many people for bug reports and testing.
  80819. *
  80820. * REFERENCES
  80821. *
  80822. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80823. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80824. *
  80825. * A description of the Rabin and Karp algorithm is given in the book
  80826. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80827. *
  80828. * Fiala,E.R., and Greene,D.H.
  80829. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80830. *
  80831. */
  80832. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80833. /*** Start of inlined file: deflate.h ***/
  80834. /* WARNING: this file should *not* be used by applications. It is
  80835. part of the implementation of the compression library and is
  80836. subject to change. Applications should only use zlib.h.
  80837. */
  80838. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80839. #ifndef DEFLATE_H
  80840. #define DEFLATE_H
  80841. /* define NO_GZIP when compiling if you want to disable gzip header and
  80842. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80843. the crc code when it is not needed. For shared libraries, gzip encoding
  80844. should be left enabled. */
  80845. #ifndef NO_GZIP
  80846. # define GZIP
  80847. #endif
  80848. #define NO_DUMMY_DECL
  80849. /* ===========================================================================
  80850. * Internal compression state.
  80851. */
  80852. #define LENGTH_CODES 29
  80853. /* number of length codes, not counting the special END_BLOCK code */
  80854. #define LITERALS 256
  80855. /* number of literal bytes 0..255 */
  80856. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80857. /* number of Literal or Length codes, including the END_BLOCK code */
  80858. #define D_CODES 30
  80859. /* number of distance codes */
  80860. #define BL_CODES 19
  80861. /* number of codes used to transfer the bit lengths */
  80862. #define HEAP_SIZE (2*L_CODES+1)
  80863. /* maximum heap size */
  80864. #define MAX_BITS 15
  80865. /* All codes must not exceed MAX_BITS bits */
  80866. #define INIT_STATE 42
  80867. #define EXTRA_STATE 69
  80868. #define NAME_STATE 73
  80869. #define COMMENT_STATE 91
  80870. #define HCRC_STATE 103
  80871. #define BUSY_STATE 113
  80872. #define FINISH_STATE 666
  80873. /* Stream status */
  80874. /* Data structure describing a single value and its code string. */
  80875. typedef struct ct_data_s {
  80876. union {
  80877. ush freq; /* frequency count */
  80878. ush code; /* bit string */
  80879. } fc;
  80880. union {
  80881. ush dad; /* father node in Huffman tree */
  80882. ush len; /* length of bit string */
  80883. } dl;
  80884. } FAR ct_data;
  80885. #define Freq fc.freq
  80886. #define Code fc.code
  80887. #define Dad dl.dad
  80888. #define Len dl.len
  80889. typedef struct static_tree_desc_s static_tree_desc;
  80890. typedef struct tree_desc_s {
  80891. ct_data *dyn_tree; /* the dynamic tree */
  80892. int max_code; /* largest code with non zero frequency */
  80893. static_tree_desc *stat_desc; /* the corresponding static tree */
  80894. } FAR tree_desc;
  80895. typedef ush Pos;
  80896. typedef Pos FAR Posf;
  80897. typedef unsigned IPos;
  80898. /* A Pos is an index in the character window. We use short instead of int to
  80899. * save space in the various tables. IPos is used only for parameter passing.
  80900. */
  80901. typedef struct internal_state {
  80902. z_streamp strm; /* pointer back to this zlib stream */
  80903. int status; /* as the name implies */
  80904. Bytef *pending_buf; /* output still pending */
  80905. ulg pending_buf_size; /* size of pending_buf */
  80906. Bytef *pending_out; /* next pending byte to output to the stream */
  80907. uInt pending; /* nb of bytes in the pending buffer */
  80908. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80909. gz_headerp gzhead; /* gzip header information to write */
  80910. uInt gzindex; /* where in extra, name, or comment */
  80911. Byte method; /* STORED (for zip only) or DEFLATED */
  80912. int last_flush; /* value of flush param for previous deflate call */
  80913. /* used by deflate.c: */
  80914. uInt w_size; /* LZ77 window size (32K by default) */
  80915. uInt w_bits; /* log2(w_size) (8..16) */
  80916. uInt w_mask; /* w_size - 1 */
  80917. Bytef *window;
  80918. /* Sliding window. Input bytes are read into the second half of the window,
  80919. * and move to the first half later to keep a dictionary of at least wSize
  80920. * bytes. With this organization, matches are limited to a distance of
  80921. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80922. * performed with a length multiple of the block size. Also, it limits
  80923. * the window size to 64K, which is quite useful on MSDOS.
  80924. * To do: use the user input buffer as sliding window.
  80925. */
  80926. ulg window_size;
  80927. /* Actual size of window: 2*wSize, except when the user input buffer
  80928. * is directly used as sliding window.
  80929. */
  80930. Posf *prev;
  80931. /* Link to older string with same hash index. To limit the size of this
  80932. * array to 64K, this link is maintained only for the last 32K strings.
  80933. * An index in this array is thus a window index modulo 32K.
  80934. */
  80935. Posf *head; /* Heads of the hash chains or NIL. */
  80936. uInt ins_h; /* hash index of string to be inserted */
  80937. uInt hash_size; /* number of elements in hash table */
  80938. uInt hash_bits; /* log2(hash_size) */
  80939. uInt hash_mask; /* hash_size-1 */
  80940. uInt hash_shift;
  80941. /* Number of bits by which ins_h must be shifted at each input
  80942. * step. It must be such that after MIN_MATCH steps, the oldest
  80943. * byte no longer takes part in the hash key, that is:
  80944. * hash_shift * MIN_MATCH >= hash_bits
  80945. */
  80946. long block_start;
  80947. /* Window position at the beginning of the current output block. Gets
  80948. * negative when the window is moved backwards.
  80949. */
  80950. uInt match_length; /* length of best match */
  80951. IPos prev_match; /* previous match */
  80952. int match_available; /* set if previous match exists */
  80953. uInt strstart; /* start of string to insert */
  80954. uInt match_start; /* start of matching string */
  80955. uInt lookahead; /* number of valid bytes ahead in window */
  80956. uInt prev_length;
  80957. /* Length of the best match at previous step. Matches not greater than this
  80958. * are discarded. This is used in the lazy match evaluation.
  80959. */
  80960. uInt max_chain_length;
  80961. /* To speed up deflation, hash chains are never searched beyond this
  80962. * length. A higher limit improves compression ratio but degrades the
  80963. * speed.
  80964. */
  80965. uInt max_lazy_match;
  80966. /* Attempt to find a better match only when the current match is strictly
  80967. * smaller than this value. This mechanism is used only for compression
  80968. * levels >= 4.
  80969. */
  80970. # define max_insert_length max_lazy_match
  80971. /* Insert new strings in the hash table only if the match length is not
  80972. * greater than this length. This saves time but degrades compression.
  80973. * max_insert_length is used only for compression levels <= 3.
  80974. */
  80975. int level; /* compression level (1..9) */
  80976. int strategy; /* favor or force Huffman coding*/
  80977. uInt good_match;
  80978. /* Use a faster search when the previous match is longer than this */
  80979. int nice_match; /* Stop searching when current match exceeds this */
  80980. /* used by trees.c: */
  80981. /* Didn't use ct_data typedef below to supress compiler warning */
  80982. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80983. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80984. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80985. struct tree_desc_s l_desc; /* desc. for literal tree */
  80986. struct tree_desc_s d_desc; /* desc. for distance tree */
  80987. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80988. ush bl_count[MAX_BITS+1];
  80989. /* number of codes at each bit length for an optimal tree */
  80990. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80991. int heap_len; /* number of elements in the heap */
  80992. int heap_max; /* element of largest frequency */
  80993. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80994. * The same heap array is used to build all trees.
  80995. */
  80996. uch depth[2*L_CODES+1];
  80997. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80998. */
  80999. uchf *l_buf; /* buffer for literals or lengths */
  81000. uInt lit_bufsize;
  81001. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81002. * limiting lit_bufsize to 64K:
  81003. * - frequencies can be kept in 16 bit counters
  81004. * - if compression is not successful for the first block, all input
  81005. * data is still in the window so we can still emit a stored block even
  81006. * when input comes from standard input. (This can also be done for
  81007. * all blocks if lit_bufsize is not greater than 32K.)
  81008. * - if compression is not successful for a file smaller than 64K, we can
  81009. * even emit a stored file instead of a stored block (saving 5 bytes).
  81010. * This is applicable only for zip (not gzip or zlib).
  81011. * - creating new Huffman trees less frequently may not provide fast
  81012. * adaptation to changes in the input data statistics. (Take for
  81013. * example a binary file with poorly compressible code followed by
  81014. * a highly compressible string table.) Smaller buffer sizes give
  81015. * fast adaptation but have of course the overhead of transmitting
  81016. * trees more frequently.
  81017. * - I can't count above 4
  81018. */
  81019. uInt last_lit; /* running index in l_buf */
  81020. ushf *d_buf;
  81021. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81022. * the same number of elements. To use different lengths, an extra flag
  81023. * array would be necessary.
  81024. */
  81025. ulg opt_len; /* bit length of current block with optimal trees */
  81026. ulg static_len; /* bit length of current block with static trees */
  81027. uInt matches; /* number of string matches in current block */
  81028. int last_eob_len; /* bit length of EOB code for last block */
  81029. #ifdef DEBUG
  81030. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81031. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81032. #endif
  81033. ush bi_buf;
  81034. /* Output buffer. bits are inserted starting at the bottom (least
  81035. * significant bits).
  81036. */
  81037. int bi_valid;
  81038. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81039. * are always zero.
  81040. */
  81041. } FAR deflate_state;
  81042. /* Output a byte on the stream.
  81043. * IN assertion: there is enough room in pending_buf.
  81044. */
  81045. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81046. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81047. /* Minimum amount of lookahead, except at the end of the input file.
  81048. * See deflate.c for comments about the MIN_MATCH+1.
  81049. */
  81050. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81051. /* In order to simplify the code, particularly on 16 bit machines, match
  81052. * distances are limited to MAX_DIST instead of WSIZE.
  81053. */
  81054. /* in trees.c */
  81055. void _tr_init OF((deflate_state *s));
  81056. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81057. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81058. int eof));
  81059. void _tr_align OF((deflate_state *s));
  81060. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81061. int eof));
  81062. #define d_code(dist) \
  81063. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81064. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81065. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81066. * used.
  81067. */
  81068. #ifndef DEBUG
  81069. /* Inline versions of _tr_tally for speed: */
  81070. #if defined(GEN_TREES_H) || !defined(STDC)
  81071. extern uch _length_code[];
  81072. extern uch _dist_code[];
  81073. #else
  81074. extern const uch _length_code[];
  81075. extern const uch _dist_code[];
  81076. #endif
  81077. # define _tr_tally_lit(s, c, flush) \
  81078. { uch cc = (c); \
  81079. s->d_buf[s->last_lit] = 0; \
  81080. s->l_buf[s->last_lit++] = cc; \
  81081. s->dyn_ltree[cc].Freq++; \
  81082. flush = (s->last_lit == s->lit_bufsize-1); \
  81083. }
  81084. # define _tr_tally_dist(s, distance, length, flush) \
  81085. { uch len = (length); \
  81086. ush dist = (distance); \
  81087. s->d_buf[s->last_lit] = dist; \
  81088. s->l_buf[s->last_lit++] = len; \
  81089. dist--; \
  81090. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81091. s->dyn_dtree[d_code(dist)].Freq++; \
  81092. flush = (s->last_lit == s->lit_bufsize-1); \
  81093. }
  81094. #else
  81095. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81096. # define _tr_tally_dist(s, distance, length, flush) \
  81097. flush = _tr_tally(s, distance, length)
  81098. #endif
  81099. #endif /* DEFLATE_H */
  81100. /*** End of inlined file: deflate.h ***/
  81101. const char deflate_copyright[] =
  81102. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81103. /*
  81104. If you use the zlib library in a product, an acknowledgment is welcome
  81105. in the documentation of your product. If for some reason you cannot
  81106. include such an acknowledgment, I would appreciate that you keep this
  81107. copyright string in the executable of your product.
  81108. */
  81109. /* ===========================================================================
  81110. * Function prototypes.
  81111. */
  81112. typedef enum {
  81113. need_more, /* block not completed, need more input or more output */
  81114. block_done, /* block flush performed */
  81115. finish_started, /* finish started, need only more output at next deflate */
  81116. finish_done /* finish done, accept no more input or output */
  81117. } block_state;
  81118. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81119. /* Compression function. Returns the block state after the call. */
  81120. local void fill_window OF((deflate_state *s));
  81121. local block_state deflate_stored OF((deflate_state *s, int flush));
  81122. local block_state deflate_fast OF((deflate_state *s, int flush));
  81123. #ifndef FASTEST
  81124. local block_state deflate_slow OF((deflate_state *s, int flush));
  81125. #endif
  81126. local void lm_init OF((deflate_state *s));
  81127. local void putShortMSB OF((deflate_state *s, uInt b));
  81128. local void flush_pending OF((z_streamp strm));
  81129. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81130. #ifndef FASTEST
  81131. #ifdef ASMV
  81132. void match_init OF((void)); /* asm code initialization */
  81133. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81134. #else
  81135. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81136. #endif
  81137. #endif
  81138. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81139. #ifdef DEBUG
  81140. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81141. int length));
  81142. #endif
  81143. /* ===========================================================================
  81144. * Local data
  81145. */
  81146. #define NIL 0
  81147. /* Tail of hash chains */
  81148. #ifndef TOO_FAR
  81149. # define TOO_FAR 4096
  81150. #endif
  81151. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81152. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81153. /* Minimum amount of lookahead, except at the end of the input file.
  81154. * See deflate.c for comments about the MIN_MATCH+1.
  81155. */
  81156. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81157. * the desired pack level (0..9). The values given below have been tuned to
  81158. * exclude worst case performance for pathological files. Better values may be
  81159. * found for specific files.
  81160. */
  81161. typedef struct config_s {
  81162. ush good_length; /* reduce lazy search above this match length */
  81163. ush max_lazy; /* do not perform lazy search above this match length */
  81164. ush nice_length; /* quit search above this match length */
  81165. ush max_chain;
  81166. compress_func func;
  81167. } config;
  81168. #ifdef FASTEST
  81169. local const config configuration_table[2] = {
  81170. /* good lazy nice chain */
  81171. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81172. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81173. #else
  81174. local const config configuration_table[10] = {
  81175. /* good lazy nice chain */
  81176. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81177. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81178. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81179. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81180. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81181. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81182. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81183. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81184. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81185. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81186. #endif
  81187. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81188. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81189. * meaning.
  81190. */
  81191. #define EQUAL 0
  81192. /* result of memcmp for equal strings */
  81193. #ifndef NO_DUMMY_DECL
  81194. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81195. #endif
  81196. /* ===========================================================================
  81197. * Update a hash value with the given input byte
  81198. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81199. * input characters, so that a running hash key can be computed from the
  81200. * previous key instead of complete recalculation each time.
  81201. */
  81202. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81203. /* ===========================================================================
  81204. * Insert string str in the dictionary and set match_head to the previous head
  81205. * of the hash chain (the most recent string with same hash key). Return
  81206. * the previous length of the hash chain.
  81207. * If this file is compiled with -DFASTEST, the compression level is forced
  81208. * to 1, and no hash chains are maintained.
  81209. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81210. * input characters and the first MIN_MATCH bytes of str are valid
  81211. * (except for the last MIN_MATCH-1 bytes of the input file).
  81212. */
  81213. #ifdef FASTEST
  81214. #define INSERT_STRING(s, str, match_head) \
  81215. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81216. match_head = s->head[s->ins_h], \
  81217. s->head[s->ins_h] = (Pos)(str))
  81218. #else
  81219. #define INSERT_STRING(s, str, match_head) \
  81220. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81221. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81222. s->head[s->ins_h] = (Pos)(str))
  81223. #endif
  81224. /* ===========================================================================
  81225. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81226. * prev[] will be initialized on the fly.
  81227. */
  81228. #define CLEAR_HASH(s) \
  81229. s->head[s->hash_size-1] = NIL; \
  81230. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81231. /* ========================================================================= */
  81232. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81233. {
  81234. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81235. Z_DEFAULT_STRATEGY, version, stream_size);
  81236. /* To do: ignore strm->next_in if we use it as window */
  81237. }
  81238. /* ========================================================================= */
  81239. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81240. {
  81241. deflate_state *s;
  81242. int wrap = 1;
  81243. static const char my_version[] = ZLIB_VERSION;
  81244. ushf *overlay;
  81245. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81246. * output size for (length,distance) codes is <= 24 bits.
  81247. */
  81248. if (version == Z_NULL || version[0] != my_version[0] ||
  81249. stream_size != sizeof(z_stream)) {
  81250. return Z_VERSION_ERROR;
  81251. }
  81252. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81253. strm->msg = Z_NULL;
  81254. if (strm->zalloc == (alloc_func)0) {
  81255. strm->zalloc = zcalloc;
  81256. strm->opaque = (voidpf)0;
  81257. }
  81258. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81259. #ifdef FASTEST
  81260. if (level != 0) level = 1;
  81261. #else
  81262. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81263. #endif
  81264. if (windowBits < 0) { /* suppress zlib wrapper */
  81265. wrap = 0;
  81266. windowBits = -windowBits;
  81267. }
  81268. #ifdef GZIP
  81269. else if (windowBits > 15) {
  81270. wrap = 2; /* write gzip wrapper instead */
  81271. windowBits -= 16;
  81272. }
  81273. #endif
  81274. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81275. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81276. strategy < 0 || strategy > Z_FIXED) {
  81277. return Z_STREAM_ERROR;
  81278. }
  81279. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81280. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81281. if (s == Z_NULL) return Z_MEM_ERROR;
  81282. strm->state = (struct internal_state FAR *)s;
  81283. s->strm = strm;
  81284. s->wrap = wrap;
  81285. s->gzhead = Z_NULL;
  81286. s->w_bits = windowBits;
  81287. s->w_size = 1 << s->w_bits;
  81288. s->w_mask = s->w_size - 1;
  81289. s->hash_bits = memLevel + 7;
  81290. s->hash_size = 1 << s->hash_bits;
  81291. s->hash_mask = s->hash_size - 1;
  81292. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81293. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81294. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81295. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81296. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81297. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81298. s->pending_buf = (uchf *) overlay;
  81299. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81300. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81301. s->pending_buf == Z_NULL) {
  81302. s->status = FINISH_STATE;
  81303. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81304. deflateEnd (strm);
  81305. return Z_MEM_ERROR;
  81306. }
  81307. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81308. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81309. s->level = level;
  81310. s->strategy = strategy;
  81311. s->method = (Byte)method;
  81312. return deflateReset(strm);
  81313. }
  81314. /* ========================================================================= */
  81315. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81316. {
  81317. deflate_state *s;
  81318. uInt length = dictLength;
  81319. uInt n;
  81320. IPos hash_head = 0;
  81321. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81322. strm->state->wrap == 2 ||
  81323. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81324. return Z_STREAM_ERROR;
  81325. s = strm->state;
  81326. if (s->wrap)
  81327. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81328. if (length < MIN_MATCH) return Z_OK;
  81329. if (length > MAX_DIST(s)) {
  81330. length = MAX_DIST(s);
  81331. dictionary += dictLength - length; /* use the tail of the dictionary */
  81332. }
  81333. zmemcpy(s->window, dictionary, length);
  81334. s->strstart = length;
  81335. s->block_start = (long)length;
  81336. /* Insert all strings in the hash table (except for the last two bytes).
  81337. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81338. * call of fill_window.
  81339. */
  81340. s->ins_h = s->window[0];
  81341. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81342. for (n = 0; n <= length - MIN_MATCH; n++) {
  81343. INSERT_STRING(s, n, hash_head);
  81344. }
  81345. if (hash_head) hash_head = 0; /* to make compiler happy */
  81346. return Z_OK;
  81347. }
  81348. /* ========================================================================= */
  81349. int ZEXPORT deflateReset (z_streamp strm)
  81350. {
  81351. deflate_state *s;
  81352. if (strm == Z_NULL || strm->state == Z_NULL ||
  81353. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81354. return Z_STREAM_ERROR;
  81355. }
  81356. strm->total_in = strm->total_out = 0;
  81357. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81358. strm->data_type = Z_UNKNOWN;
  81359. s = (deflate_state *)strm->state;
  81360. s->pending = 0;
  81361. s->pending_out = s->pending_buf;
  81362. if (s->wrap < 0) {
  81363. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81364. }
  81365. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81366. strm->adler =
  81367. #ifdef GZIP
  81368. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81369. #endif
  81370. adler32(0L, Z_NULL, 0);
  81371. s->last_flush = Z_NO_FLUSH;
  81372. _tr_init(s);
  81373. lm_init(s);
  81374. return Z_OK;
  81375. }
  81376. /* ========================================================================= */
  81377. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81378. {
  81379. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81380. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81381. strm->state->gzhead = head;
  81382. return Z_OK;
  81383. }
  81384. /* ========================================================================= */
  81385. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81386. {
  81387. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81388. strm->state->bi_valid = bits;
  81389. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81390. return Z_OK;
  81391. }
  81392. /* ========================================================================= */
  81393. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81394. {
  81395. deflate_state *s;
  81396. compress_func func;
  81397. int err = Z_OK;
  81398. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81399. s = strm->state;
  81400. #ifdef FASTEST
  81401. if (level != 0) level = 1;
  81402. #else
  81403. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81404. #endif
  81405. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81406. return Z_STREAM_ERROR;
  81407. }
  81408. func = configuration_table[s->level].func;
  81409. if (func != configuration_table[level].func && strm->total_in != 0) {
  81410. /* Flush the last buffer: */
  81411. err = deflate(strm, Z_PARTIAL_FLUSH);
  81412. }
  81413. if (s->level != level) {
  81414. s->level = level;
  81415. s->max_lazy_match = configuration_table[level].max_lazy;
  81416. s->good_match = configuration_table[level].good_length;
  81417. s->nice_match = configuration_table[level].nice_length;
  81418. s->max_chain_length = configuration_table[level].max_chain;
  81419. }
  81420. s->strategy = strategy;
  81421. return err;
  81422. }
  81423. /* ========================================================================= */
  81424. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81425. {
  81426. deflate_state *s;
  81427. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81428. s = strm->state;
  81429. s->good_match = good_length;
  81430. s->max_lazy_match = max_lazy;
  81431. s->nice_match = nice_length;
  81432. s->max_chain_length = max_chain;
  81433. return Z_OK;
  81434. }
  81435. /* =========================================================================
  81436. * For the default windowBits of 15 and memLevel of 8, this function returns
  81437. * a close to exact, as well as small, upper bound on the compressed size.
  81438. * They are coded as constants here for a reason--if the #define's are
  81439. * changed, then this function needs to be changed as well. The return
  81440. * value for 15 and 8 only works for those exact settings.
  81441. *
  81442. * For any setting other than those defaults for windowBits and memLevel,
  81443. * the value returned is a conservative worst case for the maximum expansion
  81444. * resulting from using fixed blocks instead of stored blocks, which deflate
  81445. * can emit on compressed data for some combinations of the parameters.
  81446. *
  81447. * This function could be more sophisticated to provide closer upper bounds
  81448. * for every combination of windowBits and memLevel, as well as wrap.
  81449. * But even the conservative upper bound of about 14% expansion does not
  81450. * seem onerous for output buffer allocation.
  81451. */
  81452. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81453. {
  81454. deflate_state *s;
  81455. uLong destLen;
  81456. /* conservative upper bound */
  81457. destLen = sourceLen +
  81458. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81459. /* if can't get parameters, return conservative bound */
  81460. if (strm == Z_NULL || strm->state == Z_NULL)
  81461. return destLen;
  81462. /* if not default parameters, return conservative bound */
  81463. s = strm->state;
  81464. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81465. return destLen;
  81466. /* default settings: return tight bound for that case */
  81467. return compressBound(sourceLen);
  81468. }
  81469. /* =========================================================================
  81470. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81471. * IN assertion: the stream state is correct and there is enough room in
  81472. * pending_buf.
  81473. */
  81474. local void putShortMSB (deflate_state *s, uInt b)
  81475. {
  81476. put_byte(s, (Byte)(b >> 8));
  81477. put_byte(s, (Byte)(b & 0xff));
  81478. }
  81479. /* =========================================================================
  81480. * Flush as much pending output as possible. All deflate() output goes
  81481. * through this function so some applications may wish to modify it
  81482. * to avoid allocating a large strm->next_out buffer and copying into it.
  81483. * (See also read_buf()).
  81484. */
  81485. local void flush_pending (z_streamp strm)
  81486. {
  81487. unsigned len = strm->state->pending;
  81488. if (len > strm->avail_out) len = strm->avail_out;
  81489. if (len == 0) return;
  81490. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81491. strm->next_out += len;
  81492. strm->state->pending_out += len;
  81493. strm->total_out += len;
  81494. strm->avail_out -= len;
  81495. strm->state->pending -= len;
  81496. if (strm->state->pending == 0) {
  81497. strm->state->pending_out = strm->state->pending_buf;
  81498. }
  81499. }
  81500. /* ========================================================================= */
  81501. int ZEXPORT deflate (z_streamp strm, int flush)
  81502. {
  81503. int old_flush; /* value of flush param for previous deflate call */
  81504. deflate_state *s;
  81505. if (strm == Z_NULL || strm->state == Z_NULL ||
  81506. flush > Z_FINISH || flush < 0) {
  81507. return Z_STREAM_ERROR;
  81508. }
  81509. s = strm->state;
  81510. if (strm->next_out == Z_NULL ||
  81511. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81512. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81513. ERR_RETURN(strm, Z_STREAM_ERROR);
  81514. }
  81515. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81516. s->strm = strm; /* just in case */
  81517. old_flush = s->last_flush;
  81518. s->last_flush = flush;
  81519. /* Write the header */
  81520. if (s->status == INIT_STATE) {
  81521. #ifdef GZIP
  81522. if (s->wrap == 2) {
  81523. strm->adler = crc32(0L, Z_NULL, 0);
  81524. put_byte(s, 31);
  81525. put_byte(s, 139);
  81526. put_byte(s, 8);
  81527. if (s->gzhead == NULL) {
  81528. put_byte(s, 0);
  81529. put_byte(s, 0);
  81530. put_byte(s, 0);
  81531. put_byte(s, 0);
  81532. put_byte(s, 0);
  81533. put_byte(s, s->level == 9 ? 2 :
  81534. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81535. 4 : 0));
  81536. put_byte(s, OS_CODE);
  81537. s->status = BUSY_STATE;
  81538. }
  81539. else {
  81540. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81541. (s->gzhead->hcrc ? 2 : 0) +
  81542. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81543. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81544. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81545. );
  81546. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81547. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81548. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81549. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81550. put_byte(s, s->level == 9 ? 2 :
  81551. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81552. 4 : 0));
  81553. put_byte(s, s->gzhead->os & 0xff);
  81554. if (s->gzhead->extra != NULL) {
  81555. put_byte(s, s->gzhead->extra_len & 0xff);
  81556. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81557. }
  81558. if (s->gzhead->hcrc)
  81559. strm->adler = crc32(strm->adler, s->pending_buf,
  81560. s->pending);
  81561. s->gzindex = 0;
  81562. s->status = EXTRA_STATE;
  81563. }
  81564. }
  81565. else
  81566. #endif
  81567. {
  81568. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81569. uInt level_flags;
  81570. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81571. level_flags = 0;
  81572. else if (s->level < 6)
  81573. level_flags = 1;
  81574. else if (s->level == 6)
  81575. level_flags = 2;
  81576. else
  81577. level_flags = 3;
  81578. header |= (level_flags << 6);
  81579. if (s->strstart != 0) header |= PRESET_DICT;
  81580. header += 31 - (header % 31);
  81581. s->status = BUSY_STATE;
  81582. putShortMSB(s, header);
  81583. /* Save the adler32 of the preset dictionary: */
  81584. if (s->strstart != 0) {
  81585. putShortMSB(s, (uInt)(strm->adler >> 16));
  81586. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81587. }
  81588. strm->adler = adler32(0L, Z_NULL, 0);
  81589. }
  81590. }
  81591. #ifdef GZIP
  81592. if (s->status == EXTRA_STATE) {
  81593. if (s->gzhead->extra != NULL) {
  81594. uInt beg = s->pending; /* start of bytes to update crc */
  81595. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81596. if (s->pending == s->pending_buf_size) {
  81597. if (s->gzhead->hcrc && s->pending > beg)
  81598. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81599. s->pending - beg);
  81600. flush_pending(strm);
  81601. beg = s->pending;
  81602. if (s->pending == s->pending_buf_size)
  81603. break;
  81604. }
  81605. put_byte(s, s->gzhead->extra[s->gzindex]);
  81606. s->gzindex++;
  81607. }
  81608. if (s->gzhead->hcrc && s->pending > beg)
  81609. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81610. s->pending - beg);
  81611. if (s->gzindex == s->gzhead->extra_len) {
  81612. s->gzindex = 0;
  81613. s->status = NAME_STATE;
  81614. }
  81615. }
  81616. else
  81617. s->status = NAME_STATE;
  81618. }
  81619. if (s->status == NAME_STATE) {
  81620. if (s->gzhead->name != NULL) {
  81621. uInt beg = s->pending; /* start of bytes to update crc */
  81622. int val;
  81623. do {
  81624. if (s->pending == s->pending_buf_size) {
  81625. if (s->gzhead->hcrc && s->pending > beg)
  81626. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81627. s->pending - beg);
  81628. flush_pending(strm);
  81629. beg = s->pending;
  81630. if (s->pending == s->pending_buf_size) {
  81631. val = 1;
  81632. break;
  81633. }
  81634. }
  81635. val = s->gzhead->name[s->gzindex++];
  81636. put_byte(s, val);
  81637. } while (val != 0);
  81638. if (s->gzhead->hcrc && s->pending > beg)
  81639. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81640. s->pending - beg);
  81641. if (val == 0) {
  81642. s->gzindex = 0;
  81643. s->status = COMMENT_STATE;
  81644. }
  81645. }
  81646. else
  81647. s->status = COMMENT_STATE;
  81648. }
  81649. if (s->status == COMMENT_STATE) {
  81650. if (s->gzhead->comment != NULL) {
  81651. uInt beg = s->pending; /* start of bytes to update crc */
  81652. int val;
  81653. do {
  81654. if (s->pending == s->pending_buf_size) {
  81655. if (s->gzhead->hcrc && s->pending > beg)
  81656. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81657. s->pending - beg);
  81658. flush_pending(strm);
  81659. beg = s->pending;
  81660. if (s->pending == s->pending_buf_size) {
  81661. val = 1;
  81662. break;
  81663. }
  81664. }
  81665. val = s->gzhead->comment[s->gzindex++];
  81666. put_byte(s, val);
  81667. } while (val != 0);
  81668. if (s->gzhead->hcrc && s->pending > beg)
  81669. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81670. s->pending - beg);
  81671. if (val == 0)
  81672. s->status = HCRC_STATE;
  81673. }
  81674. else
  81675. s->status = HCRC_STATE;
  81676. }
  81677. if (s->status == HCRC_STATE) {
  81678. if (s->gzhead->hcrc) {
  81679. if (s->pending + 2 > s->pending_buf_size)
  81680. flush_pending(strm);
  81681. if (s->pending + 2 <= s->pending_buf_size) {
  81682. put_byte(s, (Byte)(strm->adler & 0xff));
  81683. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81684. strm->adler = crc32(0L, Z_NULL, 0);
  81685. s->status = BUSY_STATE;
  81686. }
  81687. }
  81688. else
  81689. s->status = BUSY_STATE;
  81690. }
  81691. #endif
  81692. /* Flush as much pending output as possible */
  81693. if (s->pending != 0) {
  81694. flush_pending(strm);
  81695. if (strm->avail_out == 0) {
  81696. /* Since avail_out is 0, deflate will be called again with
  81697. * more output space, but possibly with both pending and
  81698. * avail_in equal to zero. There won't be anything to do,
  81699. * but this is not an error situation so make sure we
  81700. * return OK instead of BUF_ERROR at next call of deflate:
  81701. */
  81702. s->last_flush = -1;
  81703. return Z_OK;
  81704. }
  81705. /* Make sure there is something to do and avoid duplicate consecutive
  81706. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81707. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81708. */
  81709. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81710. flush != Z_FINISH) {
  81711. ERR_RETURN(strm, Z_BUF_ERROR);
  81712. }
  81713. /* User must not provide more input after the first FINISH: */
  81714. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81715. ERR_RETURN(strm, Z_BUF_ERROR);
  81716. }
  81717. /* Start a new block or continue the current one.
  81718. */
  81719. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81720. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81721. block_state bstate;
  81722. bstate = (*(configuration_table[s->level].func))(s, flush);
  81723. if (bstate == finish_started || bstate == finish_done) {
  81724. s->status = FINISH_STATE;
  81725. }
  81726. if (bstate == need_more || bstate == finish_started) {
  81727. if (strm->avail_out == 0) {
  81728. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81729. }
  81730. return Z_OK;
  81731. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81732. * of deflate should use the same flush parameter to make sure
  81733. * that the flush is complete. So we don't have to output an
  81734. * empty block here, this will be done at next call. This also
  81735. * ensures that for a very small output buffer, we emit at most
  81736. * one empty block.
  81737. */
  81738. }
  81739. if (bstate == block_done) {
  81740. if (flush == Z_PARTIAL_FLUSH) {
  81741. _tr_align(s);
  81742. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81743. _tr_stored_block(s, (char*)0, 0L, 0);
  81744. /* For a full flush, this empty block will be recognized
  81745. * as a special marker by inflate_sync().
  81746. */
  81747. if (flush == Z_FULL_FLUSH) {
  81748. CLEAR_HASH(s); /* forget history */
  81749. }
  81750. }
  81751. flush_pending(strm);
  81752. if (strm->avail_out == 0) {
  81753. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81754. return Z_OK;
  81755. }
  81756. }
  81757. }
  81758. Assert(strm->avail_out > 0, "bug2");
  81759. if (flush != Z_FINISH) return Z_OK;
  81760. if (s->wrap <= 0) return Z_STREAM_END;
  81761. /* Write the trailer */
  81762. #ifdef GZIP
  81763. if (s->wrap == 2) {
  81764. put_byte(s, (Byte)(strm->adler & 0xff));
  81765. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81766. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81767. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81768. put_byte(s, (Byte)(strm->total_in & 0xff));
  81769. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81770. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81771. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81772. }
  81773. else
  81774. #endif
  81775. {
  81776. putShortMSB(s, (uInt)(strm->adler >> 16));
  81777. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81778. }
  81779. flush_pending(strm);
  81780. /* If avail_out is zero, the application will call deflate again
  81781. * to flush the rest.
  81782. */
  81783. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81784. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81785. }
  81786. /* ========================================================================= */
  81787. int ZEXPORT deflateEnd (z_streamp strm)
  81788. {
  81789. int status;
  81790. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81791. status = strm->state->status;
  81792. if (status != INIT_STATE &&
  81793. status != EXTRA_STATE &&
  81794. status != NAME_STATE &&
  81795. status != COMMENT_STATE &&
  81796. status != HCRC_STATE &&
  81797. status != BUSY_STATE &&
  81798. status != FINISH_STATE) {
  81799. return Z_STREAM_ERROR;
  81800. }
  81801. /* Deallocate in reverse order of allocations: */
  81802. TRY_FREE(strm, strm->state->pending_buf);
  81803. TRY_FREE(strm, strm->state->head);
  81804. TRY_FREE(strm, strm->state->prev);
  81805. TRY_FREE(strm, strm->state->window);
  81806. ZFREE(strm, strm->state);
  81807. strm->state = Z_NULL;
  81808. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81809. }
  81810. /* =========================================================================
  81811. * Copy the source state to the destination state.
  81812. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81813. * doesn't have enough memory anyway to duplicate compression states).
  81814. */
  81815. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81816. {
  81817. #ifdef MAXSEG_64K
  81818. return Z_STREAM_ERROR;
  81819. #else
  81820. deflate_state *ds;
  81821. deflate_state *ss;
  81822. ushf *overlay;
  81823. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81824. return Z_STREAM_ERROR;
  81825. }
  81826. ss = source->state;
  81827. zmemcpy(dest, source, sizeof(z_stream));
  81828. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81829. if (ds == Z_NULL) return Z_MEM_ERROR;
  81830. dest->state = (struct internal_state FAR *) ds;
  81831. zmemcpy(ds, ss, sizeof(deflate_state));
  81832. ds->strm = dest;
  81833. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81834. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81835. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81836. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81837. ds->pending_buf = (uchf *) overlay;
  81838. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81839. ds->pending_buf == Z_NULL) {
  81840. deflateEnd (dest);
  81841. return Z_MEM_ERROR;
  81842. }
  81843. /* following zmemcpy do not work for 16-bit MSDOS */
  81844. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81845. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81846. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81847. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81848. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81849. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81850. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81851. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81852. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81853. ds->bl_desc.dyn_tree = ds->bl_tree;
  81854. return Z_OK;
  81855. #endif /* MAXSEG_64K */
  81856. }
  81857. /* ===========================================================================
  81858. * Read a new buffer from the current input stream, update the adler32
  81859. * and total number of bytes read. All deflate() input goes through
  81860. * this function so some applications may wish to modify it to avoid
  81861. * allocating a large strm->next_in buffer and copying from it.
  81862. * (See also flush_pending()).
  81863. */
  81864. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81865. {
  81866. unsigned len = strm->avail_in;
  81867. if (len > size) len = size;
  81868. if (len == 0) return 0;
  81869. strm->avail_in -= len;
  81870. if (strm->state->wrap == 1) {
  81871. strm->adler = adler32(strm->adler, strm->next_in, len);
  81872. }
  81873. #ifdef GZIP
  81874. else if (strm->state->wrap == 2) {
  81875. strm->adler = crc32(strm->adler, strm->next_in, len);
  81876. }
  81877. #endif
  81878. zmemcpy(buf, strm->next_in, len);
  81879. strm->next_in += len;
  81880. strm->total_in += len;
  81881. return (int)len;
  81882. }
  81883. /* ===========================================================================
  81884. * Initialize the "longest match" routines for a new zlib stream
  81885. */
  81886. local void lm_init (deflate_state *s)
  81887. {
  81888. s->window_size = (ulg)2L*s->w_size;
  81889. CLEAR_HASH(s);
  81890. /* Set the default configuration parameters:
  81891. */
  81892. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81893. s->good_match = configuration_table[s->level].good_length;
  81894. s->nice_match = configuration_table[s->level].nice_length;
  81895. s->max_chain_length = configuration_table[s->level].max_chain;
  81896. s->strstart = 0;
  81897. s->block_start = 0L;
  81898. s->lookahead = 0;
  81899. s->match_length = s->prev_length = MIN_MATCH-1;
  81900. s->match_available = 0;
  81901. s->ins_h = 0;
  81902. #ifndef FASTEST
  81903. #ifdef ASMV
  81904. match_init(); /* initialize the asm code */
  81905. #endif
  81906. #endif
  81907. }
  81908. #ifndef FASTEST
  81909. /* ===========================================================================
  81910. * Set match_start to the longest match starting at the given string and
  81911. * return its length. Matches shorter or equal to prev_length are discarded,
  81912. * in which case the result is equal to prev_length and match_start is
  81913. * garbage.
  81914. * IN assertions: cur_match is the head of the hash chain for the current
  81915. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81916. * OUT assertion: the match length is not greater than s->lookahead.
  81917. */
  81918. #ifndef ASMV
  81919. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81920. * match.S. The code will be functionally equivalent.
  81921. */
  81922. local uInt longest_match(deflate_state *s, IPos cur_match)
  81923. {
  81924. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81925. register Bytef *scan = s->window + s->strstart; /* current string */
  81926. register Bytef *match; /* matched string */
  81927. register int len; /* length of current match */
  81928. int best_len = s->prev_length; /* best match length so far */
  81929. int nice_match = s->nice_match; /* stop if match long enough */
  81930. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81931. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81932. /* Stop when cur_match becomes <= limit. To simplify the code,
  81933. * we prevent matches with the string of window index 0.
  81934. */
  81935. Posf *prev = s->prev;
  81936. uInt wmask = s->w_mask;
  81937. #ifdef UNALIGNED_OK
  81938. /* Compare two bytes at a time. Note: this is not always beneficial.
  81939. * Try with and without -DUNALIGNED_OK to check.
  81940. */
  81941. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81942. register ush scan_start = *(ushf*)scan;
  81943. register ush scan_end = *(ushf*)(scan+best_len-1);
  81944. #else
  81945. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81946. register Byte scan_end1 = scan[best_len-1];
  81947. register Byte scan_end = scan[best_len];
  81948. #endif
  81949. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81950. * It is easy to get rid of this optimization if necessary.
  81951. */
  81952. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81953. /* Do not waste too much time if we already have a good match: */
  81954. if (s->prev_length >= s->good_match) {
  81955. chain_length >>= 2;
  81956. }
  81957. /* Do not look for matches beyond the end of the input. This is necessary
  81958. * to make deflate deterministic.
  81959. */
  81960. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81961. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81962. do {
  81963. Assert(cur_match < s->strstart, "no future");
  81964. match = s->window + cur_match;
  81965. /* Skip to next match if the match length cannot increase
  81966. * or if the match length is less than 2. Note that the checks below
  81967. * for insufficient lookahead only occur occasionally for performance
  81968. * reasons. Therefore uninitialized memory will be accessed, and
  81969. * conditional jumps will be made that depend on those values.
  81970. * However the length of the match is limited to the lookahead, so
  81971. * the output of deflate is not affected by the uninitialized values.
  81972. */
  81973. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81974. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81975. * UNALIGNED_OK if your compiler uses a different size.
  81976. */
  81977. if (*(ushf*)(match+best_len-1) != scan_end ||
  81978. *(ushf*)match != scan_start) continue;
  81979. /* It is not necessary to compare scan[2] and match[2] since they are
  81980. * always equal when the other bytes match, given that the hash keys
  81981. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81982. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81983. * lookahead only every 4th comparison; the 128th check will be made
  81984. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81985. * necessary to put more guard bytes at the end of the window, or
  81986. * to check more often for insufficient lookahead.
  81987. */
  81988. Assert(scan[2] == match[2], "scan[2]?");
  81989. scan++, match++;
  81990. do {
  81991. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81992. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81993. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81994. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81995. scan < strend);
  81996. /* The funny "do {}" generates better code on most compilers */
  81997. /* Here, scan <= window+strstart+257 */
  81998. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81999. if (*scan == *match) scan++;
  82000. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82001. scan = strend - (MAX_MATCH-1);
  82002. #else /* UNALIGNED_OK */
  82003. if (match[best_len] != scan_end ||
  82004. match[best_len-1] != scan_end1 ||
  82005. *match != *scan ||
  82006. *++match != scan[1]) continue;
  82007. /* The check at best_len-1 can be removed because it will be made
  82008. * again later. (This heuristic is not always a win.)
  82009. * It is not necessary to compare scan[2] and match[2] since they
  82010. * are always equal when the other bytes match, given that
  82011. * the hash keys are equal and that HASH_BITS >= 8.
  82012. */
  82013. scan += 2, match++;
  82014. Assert(*scan == *match, "match[2]?");
  82015. /* We check for insufficient lookahead only every 8th comparison;
  82016. * the 256th check will be made at strstart+258.
  82017. */
  82018. do {
  82019. } while (*++scan == *++match && *++scan == *++match &&
  82020. *++scan == *++match && *++scan == *++match &&
  82021. *++scan == *++match && *++scan == *++match &&
  82022. *++scan == *++match && *++scan == *++match &&
  82023. scan < strend);
  82024. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82025. len = MAX_MATCH - (int)(strend - scan);
  82026. scan = strend - MAX_MATCH;
  82027. #endif /* UNALIGNED_OK */
  82028. if (len > best_len) {
  82029. s->match_start = cur_match;
  82030. best_len = len;
  82031. if (len >= nice_match) break;
  82032. #ifdef UNALIGNED_OK
  82033. scan_end = *(ushf*)(scan+best_len-1);
  82034. #else
  82035. scan_end1 = scan[best_len-1];
  82036. scan_end = scan[best_len];
  82037. #endif
  82038. }
  82039. } while ((cur_match = prev[cur_match & wmask]) > limit
  82040. && --chain_length != 0);
  82041. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82042. return s->lookahead;
  82043. }
  82044. #endif /* ASMV */
  82045. #endif /* FASTEST */
  82046. /* ---------------------------------------------------------------------------
  82047. * Optimized version for level == 1 or strategy == Z_RLE only
  82048. */
  82049. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82050. {
  82051. register Bytef *scan = s->window + s->strstart; /* current string */
  82052. register Bytef *match; /* matched string */
  82053. register int len; /* length of current match */
  82054. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82055. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82056. * It is easy to get rid of this optimization if necessary.
  82057. */
  82058. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82059. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82060. Assert(cur_match < s->strstart, "no future");
  82061. match = s->window + cur_match;
  82062. /* Return failure if the match length is less than 2:
  82063. */
  82064. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82065. /* The check at best_len-1 can be removed because it will be made
  82066. * again later. (This heuristic is not always a win.)
  82067. * It is not necessary to compare scan[2] and match[2] since they
  82068. * are always equal when the other bytes match, given that
  82069. * the hash keys are equal and that HASH_BITS >= 8.
  82070. */
  82071. scan += 2, match += 2;
  82072. Assert(*scan == *match, "match[2]?");
  82073. /* We check for insufficient lookahead only every 8th comparison;
  82074. * the 256th check will be made at strstart+258.
  82075. */
  82076. do {
  82077. } while (*++scan == *++match && *++scan == *++match &&
  82078. *++scan == *++match && *++scan == *++match &&
  82079. *++scan == *++match && *++scan == *++match &&
  82080. *++scan == *++match && *++scan == *++match &&
  82081. scan < strend);
  82082. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82083. len = MAX_MATCH - (int)(strend - scan);
  82084. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82085. s->match_start = cur_match;
  82086. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82087. }
  82088. #ifdef DEBUG
  82089. /* ===========================================================================
  82090. * Check that the match at match_start is indeed a match.
  82091. */
  82092. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82093. {
  82094. /* check that the match is indeed a match */
  82095. if (zmemcmp(s->window + match,
  82096. s->window + start, length) != EQUAL) {
  82097. fprintf(stderr, " start %u, match %u, length %d\n",
  82098. start, match, length);
  82099. do {
  82100. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82101. } while (--length != 0);
  82102. z_error("invalid match");
  82103. }
  82104. if (z_verbose > 1) {
  82105. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82106. do { putc(s->window[start++], stderr); } while (--length != 0);
  82107. }
  82108. }
  82109. #else
  82110. # define check_match(s, start, match, length)
  82111. #endif /* DEBUG */
  82112. /* ===========================================================================
  82113. * Fill the window when the lookahead becomes insufficient.
  82114. * Updates strstart and lookahead.
  82115. *
  82116. * IN assertion: lookahead < MIN_LOOKAHEAD
  82117. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82118. * At least one byte has been read, or avail_in == 0; reads are
  82119. * performed for at least two bytes (required for the zip translate_eol
  82120. * option -- not supported here).
  82121. */
  82122. local void fill_window (deflate_state *s)
  82123. {
  82124. register unsigned n, m;
  82125. register Posf *p;
  82126. unsigned more; /* Amount of free space at the end of the window. */
  82127. uInt wsize = s->w_size;
  82128. do {
  82129. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82130. /* Deal with !@#$% 64K limit: */
  82131. if (sizeof(int) <= 2) {
  82132. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82133. more = wsize;
  82134. } else if (more == (unsigned)(-1)) {
  82135. /* Very unlikely, but possible on 16 bit machine if
  82136. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82137. */
  82138. more--;
  82139. }
  82140. }
  82141. /* If the window is almost full and there is insufficient lookahead,
  82142. * move the upper half to the lower one to make room in the upper half.
  82143. */
  82144. if (s->strstart >= wsize+MAX_DIST(s)) {
  82145. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82146. s->match_start -= wsize;
  82147. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82148. s->block_start -= (long) wsize;
  82149. /* Slide the hash table (could be avoided with 32 bit values
  82150. at the expense of memory usage). We slide even when level == 0
  82151. to keep the hash table consistent if we switch back to level > 0
  82152. later. (Using level 0 permanently is not an optimal usage of
  82153. zlib, so we don't care about this pathological case.)
  82154. */
  82155. /* %%% avoid this when Z_RLE */
  82156. n = s->hash_size;
  82157. p = &s->head[n];
  82158. do {
  82159. m = *--p;
  82160. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82161. } while (--n);
  82162. n = wsize;
  82163. #ifndef FASTEST
  82164. p = &s->prev[n];
  82165. do {
  82166. m = *--p;
  82167. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82168. /* If n is not on any hash chain, prev[n] is garbage but
  82169. * its value will never be used.
  82170. */
  82171. } while (--n);
  82172. #endif
  82173. more += wsize;
  82174. }
  82175. if (s->strm->avail_in == 0) return;
  82176. /* If there was no sliding:
  82177. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82178. * more == window_size - lookahead - strstart
  82179. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82180. * => more >= window_size - 2*WSIZE + 2
  82181. * In the BIG_MEM or MMAP case (not yet supported),
  82182. * window_size == input_size + MIN_LOOKAHEAD &&
  82183. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82184. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82185. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82186. */
  82187. Assert(more >= 2, "more < 2");
  82188. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82189. s->lookahead += n;
  82190. /* Initialize the hash value now that we have some input: */
  82191. if (s->lookahead >= MIN_MATCH) {
  82192. s->ins_h = s->window[s->strstart];
  82193. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82194. #if MIN_MATCH != 3
  82195. Call UPDATE_HASH() MIN_MATCH-3 more times
  82196. #endif
  82197. }
  82198. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82199. * but this is not important since only literal bytes will be emitted.
  82200. */
  82201. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82202. }
  82203. /* ===========================================================================
  82204. * Flush the current block, with given end-of-file flag.
  82205. * IN assertion: strstart is set to the end of the current match.
  82206. */
  82207. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82208. _tr_flush_block(s, (s->block_start >= 0L ? \
  82209. (charf *)&s->window[(unsigned)s->block_start] : \
  82210. (charf *)Z_NULL), \
  82211. (ulg)((long)s->strstart - s->block_start), \
  82212. (eof)); \
  82213. s->block_start = s->strstart; \
  82214. flush_pending(s->strm); \
  82215. Tracev((stderr,"[FLUSH]")); \
  82216. }
  82217. /* Same but force premature exit if necessary. */
  82218. #define FLUSH_BLOCK(s, eof) { \
  82219. FLUSH_BLOCK_ONLY(s, eof); \
  82220. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82221. }
  82222. /* ===========================================================================
  82223. * Copy without compression as much as possible from the input stream, return
  82224. * the current block state.
  82225. * This function does not insert new strings in the dictionary since
  82226. * uncompressible data is probably not useful. This function is used
  82227. * only for the level=0 compression option.
  82228. * NOTE: this function should be optimized to avoid extra copying from
  82229. * window to pending_buf.
  82230. */
  82231. local block_state deflate_stored(deflate_state *s, int flush)
  82232. {
  82233. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82234. * to pending_buf_size, and each stored block has a 5 byte header:
  82235. */
  82236. ulg max_block_size = 0xffff;
  82237. ulg max_start;
  82238. if (max_block_size > s->pending_buf_size - 5) {
  82239. max_block_size = s->pending_buf_size - 5;
  82240. }
  82241. /* Copy as much as possible from input to output: */
  82242. for (;;) {
  82243. /* Fill the window as much as possible: */
  82244. if (s->lookahead <= 1) {
  82245. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82246. s->block_start >= (long)s->w_size, "slide too late");
  82247. fill_window(s);
  82248. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82249. if (s->lookahead == 0) break; /* flush the current block */
  82250. }
  82251. Assert(s->block_start >= 0L, "block gone");
  82252. s->strstart += s->lookahead;
  82253. s->lookahead = 0;
  82254. /* Emit a stored block if pending_buf will be full: */
  82255. max_start = s->block_start + max_block_size;
  82256. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82257. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82258. s->lookahead = (uInt)(s->strstart - max_start);
  82259. s->strstart = (uInt)max_start;
  82260. FLUSH_BLOCK(s, 0);
  82261. }
  82262. /* Flush if we may have to slide, otherwise block_start may become
  82263. * negative and the data will be gone:
  82264. */
  82265. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82266. FLUSH_BLOCK(s, 0);
  82267. }
  82268. }
  82269. FLUSH_BLOCK(s, flush == Z_FINISH);
  82270. return flush == Z_FINISH ? finish_done : block_done;
  82271. }
  82272. /* ===========================================================================
  82273. * Compress as much as possible from the input stream, return the current
  82274. * block state.
  82275. * This function does not perform lazy evaluation of matches and inserts
  82276. * new strings in the dictionary only for unmatched strings or for short
  82277. * matches. It is used only for the fast compression options.
  82278. */
  82279. local block_state deflate_fast(deflate_state *s, int flush)
  82280. {
  82281. IPos hash_head = NIL; /* head of the hash chain */
  82282. int bflush; /* set if current block must be flushed */
  82283. for (;;) {
  82284. /* Make sure that we always have enough lookahead, except
  82285. * at the end of the input file. We need MAX_MATCH bytes
  82286. * for the next match, plus MIN_MATCH bytes to insert the
  82287. * string following the next match.
  82288. */
  82289. if (s->lookahead < MIN_LOOKAHEAD) {
  82290. fill_window(s);
  82291. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82292. return need_more;
  82293. }
  82294. if (s->lookahead == 0) break; /* flush the current block */
  82295. }
  82296. /* Insert the string window[strstart .. strstart+2] in the
  82297. * dictionary, and set hash_head to the head of the hash chain:
  82298. */
  82299. if (s->lookahead >= MIN_MATCH) {
  82300. INSERT_STRING(s, s->strstart, hash_head);
  82301. }
  82302. /* Find the longest match, discarding those <= prev_length.
  82303. * At this point we have always match_length < MIN_MATCH
  82304. */
  82305. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82306. /* To simplify the code, we prevent matches with the string
  82307. * of window index 0 (in particular we have to avoid a match
  82308. * of the string with itself at the start of the input file).
  82309. */
  82310. #ifdef FASTEST
  82311. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82312. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82313. s->match_length = longest_match_fast (s, hash_head);
  82314. }
  82315. #else
  82316. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82317. s->match_length = longest_match (s, hash_head);
  82318. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82319. s->match_length = longest_match_fast (s, hash_head);
  82320. }
  82321. #endif
  82322. /* longest_match() or longest_match_fast() sets match_start */
  82323. }
  82324. if (s->match_length >= MIN_MATCH) {
  82325. check_match(s, s->strstart, s->match_start, s->match_length);
  82326. _tr_tally_dist(s, s->strstart - s->match_start,
  82327. s->match_length - MIN_MATCH, bflush);
  82328. s->lookahead -= s->match_length;
  82329. /* Insert new strings in the hash table only if the match length
  82330. * is not too large. This saves time but degrades compression.
  82331. */
  82332. #ifndef FASTEST
  82333. if (s->match_length <= s->max_insert_length &&
  82334. s->lookahead >= MIN_MATCH) {
  82335. s->match_length--; /* string at strstart already in table */
  82336. do {
  82337. s->strstart++;
  82338. INSERT_STRING(s, s->strstart, hash_head);
  82339. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82340. * always MIN_MATCH bytes ahead.
  82341. */
  82342. } while (--s->match_length != 0);
  82343. s->strstart++;
  82344. } else
  82345. #endif
  82346. {
  82347. s->strstart += s->match_length;
  82348. s->match_length = 0;
  82349. s->ins_h = s->window[s->strstart];
  82350. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82351. #if MIN_MATCH != 3
  82352. Call UPDATE_HASH() MIN_MATCH-3 more times
  82353. #endif
  82354. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82355. * matter since it will be recomputed at next deflate call.
  82356. */
  82357. }
  82358. } else {
  82359. /* No match, output a literal byte */
  82360. Tracevv((stderr,"%c", s->window[s->strstart]));
  82361. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82362. s->lookahead--;
  82363. s->strstart++;
  82364. }
  82365. if (bflush) FLUSH_BLOCK(s, 0);
  82366. }
  82367. FLUSH_BLOCK(s, flush == Z_FINISH);
  82368. return flush == Z_FINISH ? finish_done : block_done;
  82369. }
  82370. #ifndef FASTEST
  82371. /* ===========================================================================
  82372. * Same as above, but achieves better compression. We use a lazy
  82373. * evaluation for matches: a match is finally adopted only if there is
  82374. * no better match at the next window position.
  82375. */
  82376. local block_state deflate_slow(deflate_state *s, int flush)
  82377. {
  82378. IPos hash_head = NIL; /* head of hash chain */
  82379. int bflush; /* set if current block must be flushed */
  82380. /* Process the input block. */
  82381. for (;;) {
  82382. /* Make sure that we always have enough lookahead, except
  82383. * at the end of the input file. We need MAX_MATCH bytes
  82384. * for the next match, plus MIN_MATCH bytes to insert the
  82385. * string following the next match.
  82386. */
  82387. if (s->lookahead < MIN_LOOKAHEAD) {
  82388. fill_window(s);
  82389. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82390. return need_more;
  82391. }
  82392. if (s->lookahead == 0) break; /* flush the current block */
  82393. }
  82394. /* Insert the string window[strstart .. strstart+2] in the
  82395. * dictionary, and set hash_head to the head of the hash chain:
  82396. */
  82397. if (s->lookahead >= MIN_MATCH) {
  82398. INSERT_STRING(s, s->strstart, hash_head);
  82399. }
  82400. /* Find the longest match, discarding those <= prev_length.
  82401. */
  82402. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82403. s->match_length = MIN_MATCH-1;
  82404. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82405. s->strstart - hash_head <= MAX_DIST(s)) {
  82406. /* To simplify the code, we prevent matches with the string
  82407. * of window index 0 (in particular we have to avoid a match
  82408. * of the string with itself at the start of the input file).
  82409. */
  82410. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82411. s->match_length = longest_match (s, hash_head);
  82412. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82413. s->match_length = longest_match_fast (s, hash_head);
  82414. }
  82415. /* longest_match() or longest_match_fast() sets match_start */
  82416. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82417. #if TOO_FAR <= 32767
  82418. || (s->match_length == MIN_MATCH &&
  82419. s->strstart - s->match_start > TOO_FAR)
  82420. #endif
  82421. )) {
  82422. /* If prev_match is also MIN_MATCH, match_start is garbage
  82423. * but we will ignore the current match anyway.
  82424. */
  82425. s->match_length = MIN_MATCH-1;
  82426. }
  82427. }
  82428. /* If there was a match at the previous step and the current
  82429. * match is not better, output the previous match:
  82430. */
  82431. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82432. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82433. /* Do not insert strings in hash table beyond this. */
  82434. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82435. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82436. s->prev_length - MIN_MATCH, bflush);
  82437. /* Insert in hash table all strings up to the end of the match.
  82438. * strstart-1 and strstart are already inserted. If there is not
  82439. * enough lookahead, the last two strings are not inserted in
  82440. * the hash table.
  82441. */
  82442. s->lookahead -= s->prev_length-1;
  82443. s->prev_length -= 2;
  82444. do {
  82445. if (++s->strstart <= max_insert) {
  82446. INSERT_STRING(s, s->strstart, hash_head);
  82447. }
  82448. } while (--s->prev_length != 0);
  82449. s->match_available = 0;
  82450. s->match_length = MIN_MATCH-1;
  82451. s->strstart++;
  82452. if (bflush) FLUSH_BLOCK(s, 0);
  82453. } else if (s->match_available) {
  82454. /* If there was no match at the previous position, output a
  82455. * single literal. If there was a match but the current match
  82456. * is longer, truncate the previous match to a single literal.
  82457. */
  82458. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82459. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82460. if (bflush) {
  82461. FLUSH_BLOCK_ONLY(s, 0);
  82462. }
  82463. s->strstart++;
  82464. s->lookahead--;
  82465. if (s->strm->avail_out == 0) return need_more;
  82466. } else {
  82467. /* There is no previous match to compare with, wait for
  82468. * the next step to decide.
  82469. */
  82470. s->match_available = 1;
  82471. s->strstart++;
  82472. s->lookahead--;
  82473. }
  82474. }
  82475. Assert (flush != Z_NO_FLUSH, "no flush?");
  82476. if (s->match_available) {
  82477. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82478. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82479. s->match_available = 0;
  82480. }
  82481. FLUSH_BLOCK(s, flush == Z_FINISH);
  82482. return flush == Z_FINISH ? finish_done : block_done;
  82483. }
  82484. #endif /* FASTEST */
  82485. #if 0
  82486. /* ===========================================================================
  82487. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82488. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82489. * deflate switches away from Z_RLE.)
  82490. */
  82491. local block_state deflate_rle(s, flush)
  82492. deflate_state *s;
  82493. int flush;
  82494. {
  82495. int bflush; /* set if current block must be flushed */
  82496. uInt run; /* length of run */
  82497. uInt max; /* maximum length of run */
  82498. uInt prev; /* byte at distance one to match */
  82499. Bytef *scan; /* scan for end of run */
  82500. for (;;) {
  82501. /* Make sure that we always have enough lookahead, except
  82502. * at the end of the input file. We need MAX_MATCH bytes
  82503. * for the longest encodable run.
  82504. */
  82505. if (s->lookahead < MAX_MATCH) {
  82506. fill_window(s);
  82507. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82508. return need_more;
  82509. }
  82510. if (s->lookahead == 0) break; /* flush the current block */
  82511. }
  82512. /* See how many times the previous byte repeats */
  82513. run = 0;
  82514. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82515. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82516. scan = s->window + s->strstart - 1;
  82517. prev = *scan++;
  82518. do {
  82519. if (*scan++ != prev)
  82520. break;
  82521. } while (++run < max);
  82522. }
  82523. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82524. if (run >= MIN_MATCH) {
  82525. check_match(s, s->strstart, s->strstart - 1, run);
  82526. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82527. s->lookahead -= run;
  82528. s->strstart += run;
  82529. } else {
  82530. /* No match, output a literal byte */
  82531. Tracevv((stderr,"%c", s->window[s->strstart]));
  82532. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82533. s->lookahead--;
  82534. s->strstart++;
  82535. }
  82536. if (bflush) FLUSH_BLOCK(s, 0);
  82537. }
  82538. FLUSH_BLOCK(s, flush == Z_FINISH);
  82539. return flush == Z_FINISH ? finish_done : block_done;
  82540. }
  82541. #endif
  82542. /*** End of inlined file: deflate.c ***/
  82543. /*** Start of inlined file: inffast.c ***/
  82544. /*** Start of inlined file: inftrees.h ***/
  82545. /* WARNING: this file should *not* be used by applications. It is
  82546. part of the implementation of the compression library and is
  82547. subject to change. Applications should only use zlib.h.
  82548. */
  82549. #ifndef _INFTREES_H_
  82550. #define _INFTREES_H_
  82551. /* Structure for decoding tables. Each entry provides either the
  82552. information needed to do the operation requested by the code that
  82553. indexed that table entry, or it provides a pointer to another
  82554. table that indexes more bits of the code. op indicates whether
  82555. the entry is a pointer to another table, a literal, a length or
  82556. distance, an end-of-block, or an invalid code. For a table
  82557. pointer, the low four bits of op is the number of index bits of
  82558. that table. For a length or distance, the low four bits of op
  82559. is the number of extra bits to get after the code. bits is
  82560. the number of bits in this code or part of the code to drop off
  82561. of the bit buffer. val is the actual byte to output in the case
  82562. of a literal, the base length or distance, or the offset from
  82563. the current table to the next table. Each entry is four bytes. */
  82564. typedef struct {
  82565. unsigned char op; /* operation, extra bits, table bits */
  82566. unsigned char bits; /* bits in this part of the code */
  82567. unsigned short val; /* offset in table or code value */
  82568. } code;
  82569. /* op values as set by inflate_table():
  82570. 00000000 - literal
  82571. 0000tttt - table link, tttt != 0 is the number of table index bits
  82572. 0001eeee - length or distance, eeee is the number of extra bits
  82573. 01100000 - end of block
  82574. 01000000 - invalid code
  82575. */
  82576. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82577. exhaustive search was 1444 code structures (852 for length/literals
  82578. and 592 for distances, the latter actually the result of an
  82579. exhaustive search). The true maximum is not known, but the value
  82580. below is more than safe. */
  82581. #define ENOUGH 2048
  82582. #define MAXD 592
  82583. /* Type of code to build for inftable() */
  82584. typedef enum {
  82585. CODES,
  82586. LENS,
  82587. DISTS
  82588. } codetype;
  82589. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82590. unsigned codes, code FAR * FAR *table,
  82591. unsigned FAR *bits, unsigned short FAR *work));
  82592. #endif
  82593. /*** End of inlined file: inftrees.h ***/
  82594. /*** Start of inlined file: inflate.h ***/
  82595. /* WARNING: this file should *not* be used by applications. It is
  82596. part of the implementation of the compression library and is
  82597. subject to change. Applications should only use zlib.h.
  82598. */
  82599. #ifndef _INFLATE_H_
  82600. #define _INFLATE_H_
  82601. /* define NO_GZIP when compiling if you want to disable gzip header and
  82602. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82603. the crc code when it is not needed. For shared libraries, gzip decoding
  82604. should be left enabled. */
  82605. #ifndef NO_GZIP
  82606. # define GUNZIP
  82607. #endif
  82608. /* Possible inflate modes between inflate() calls */
  82609. typedef enum {
  82610. HEAD, /* i: waiting for magic header */
  82611. FLAGS, /* i: waiting for method and flags (gzip) */
  82612. TIME, /* i: waiting for modification time (gzip) */
  82613. OS, /* i: waiting for extra flags and operating system (gzip) */
  82614. EXLEN, /* i: waiting for extra length (gzip) */
  82615. EXTRA, /* i: waiting for extra bytes (gzip) */
  82616. NAME, /* i: waiting for end of file name (gzip) */
  82617. COMMENT, /* i: waiting for end of comment (gzip) */
  82618. HCRC, /* i: waiting for header crc (gzip) */
  82619. DICTID, /* i: waiting for dictionary check value */
  82620. DICT, /* waiting for inflateSetDictionary() call */
  82621. TYPE, /* i: waiting for type bits, including last-flag bit */
  82622. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82623. STORED, /* i: waiting for stored size (length and complement) */
  82624. COPY, /* i/o: waiting for input or output to copy stored block */
  82625. TABLE, /* i: waiting for dynamic block table lengths */
  82626. LENLENS, /* i: waiting for code length code lengths */
  82627. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82628. LEN, /* i: waiting for length/lit code */
  82629. LENEXT, /* i: waiting for length extra bits */
  82630. DIST, /* i: waiting for distance code */
  82631. DISTEXT, /* i: waiting for distance extra bits */
  82632. MATCH, /* o: waiting for output space to copy string */
  82633. LIT, /* o: waiting for output space to write literal */
  82634. CHECK, /* i: waiting for 32-bit check value */
  82635. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82636. DONE, /* finished check, done -- remain here until reset */
  82637. BAD, /* got a data error -- remain here until reset */
  82638. MEM, /* got an inflate() memory error -- remain here until reset */
  82639. SYNC /* looking for synchronization bytes to restart inflate() */
  82640. } inflate_mode;
  82641. /*
  82642. State transitions between above modes -
  82643. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82644. Process header:
  82645. HEAD -> (gzip) or (zlib)
  82646. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82647. NAME -> COMMENT -> HCRC -> TYPE
  82648. (zlib) -> DICTID or TYPE
  82649. DICTID -> DICT -> TYPE
  82650. Read deflate blocks:
  82651. TYPE -> STORED or TABLE or LEN or CHECK
  82652. STORED -> COPY -> TYPE
  82653. TABLE -> LENLENS -> CODELENS -> LEN
  82654. Read deflate codes:
  82655. LEN -> LENEXT or LIT or TYPE
  82656. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82657. LIT -> LEN
  82658. Process trailer:
  82659. CHECK -> LENGTH -> DONE
  82660. */
  82661. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82662. struct inflate_state {
  82663. inflate_mode mode; /* current inflate mode */
  82664. int last; /* true if processing last block */
  82665. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82666. int havedict; /* true if dictionary provided */
  82667. int flags; /* gzip header method and flags (0 if zlib) */
  82668. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82669. unsigned long check; /* protected copy of check value */
  82670. unsigned long total; /* protected copy of output count */
  82671. gz_headerp head; /* where to save gzip header information */
  82672. /* sliding window */
  82673. unsigned wbits; /* log base 2 of requested window size */
  82674. unsigned wsize; /* window size or zero if not using window */
  82675. unsigned whave; /* valid bytes in the window */
  82676. unsigned write; /* window write index */
  82677. unsigned char FAR *window; /* allocated sliding window, if needed */
  82678. /* bit accumulator */
  82679. unsigned long hold; /* input bit accumulator */
  82680. unsigned bits; /* number of bits in "in" */
  82681. /* for string and stored block copying */
  82682. unsigned length; /* literal or length of data to copy */
  82683. unsigned offset; /* distance back to copy string from */
  82684. /* for table and code decoding */
  82685. unsigned extra; /* extra bits needed */
  82686. /* fixed and dynamic code tables */
  82687. code const FAR *lencode; /* starting table for length/literal codes */
  82688. code const FAR *distcode; /* starting table for distance codes */
  82689. unsigned lenbits; /* index bits for lencode */
  82690. unsigned distbits; /* index bits for distcode */
  82691. /* dynamic table building */
  82692. unsigned ncode; /* number of code length code lengths */
  82693. unsigned nlen; /* number of length code lengths */
  82694. unsigned ndist; /* number of distance code lengths */
  82695. unsigned have; /* number of code lengths in lens[] */
  82696. code FAR *next; /* next available space in codes[] */
  82697. unsigned short lens[320]; /* temporary storage for code lengths */
  82698. unsigned short work[288]; /* work area for code table building */
  82699. code codes[ENOUGH]; /* space for code tables */
  82700. };
  82701. #endif
  82702. /*** End of inlined file: inflate.h ***/
  82703. /*** Start of inlined file: inffast.h ***/
  82704. /* WARNING: this file should *not* be used by applications. It is
  82705. part of the implementation of the compression library and is
  82706. subject to change. Applications should only use zlib.h.
  82707. */
  82708. void inflate_fast OF((z_streamp strm, unsigned start));
  82709. /*** End of inlined file: inffast.h ***/
  82710. #ifndef ASMINF
  82711. /* Allow machine dependent optimization for post-increment or pre-increment.
  82712. Based on testing to date,
  82713. Pre-increment preferred for:
  82714. - PowerPC G3 (Adler)
  82715. - MIPS R5000 (Randers-Pehrson)
  82716. Post-increment preferred for:
  82717. - none
  82718. No measurable difference:
  82719. - Pentium III (Anderson)
  82720. - M68060 (Nikl)
  82721. */
  82722. #ifdef POSTINC
  82723. # define OFF 0
  82724. # define PUP(a) *(a)++
  82725. #else
  82726. # define OFF 1
  82727. # define PUP(a) *++(a)
  82728. #endif
  82729. /*
  82730. Decode literal, length, and distance codes and write out the resulting
  82731. literal and match bytes until either not enough input or output is
  82732. available, an end-of-block is encountered, or a data error is encountered.
  82733. When large enough input and output buffers are supplied to inflate(), for
  82734. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82735. inflate execution time is spent in this routine.
  82736. Entry assumptions:
  82737. state->mode == LEN
  82738. strm->avail_in >= 6
  82739. strm->avail_out >= 258
  82740. start >= strm->avail_out
  82741. state->bits < 8
  82742. On return, state->mode is one of:
  82743. LEN -- ran out of enough output space or enough available input
  82744. TYPE -- reached end of block code, inflate() to interpret next block
  82745. BAD -- error in block data
  82746. Notes:
  82747. - The maximum input bits used by a length/distance pair is 15 bits for the
  82748. length code, 5 bits for the length extra, 15 bits for the distance code,
  82749. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82750. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82751. checking for available input while decoding.
  82752. - The maximum bytes that a single length/distance pair can output is 258
  82753. bytes, which is the maximum length that can be coded. inflate_fast()
  82754. requires strm->avail_out >= 258 for each loop to avoid checking for
  82755. output space.
  82756. */
  82757. void inflate_fast (z_streamp strm, unsigned start)
  82758. {
  82759. struct inflate_state FAR *state;
  82760. unsigned char FAR *in; /* local strm->next_in */
  82761. unsigned char FAR *last; /* while in < last, enough input available */
  82762. unsigned char FAR *out; /* local strm->next_out */
  82763. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82764. unsigned char FAR *end; /* while out < end, enough space available */
  82765. #ifdef INFLATE_STRICT
  82766. unsigned dmax; /* maximum distance from zlib header */
  82767. #endif
  82768. unsigned wsize; /* window size or zero if not using window */
  82769. unsigned whave; /* valid bytes in the window */
  82770. unsigned write; /* window write index */
  82771. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82772. unsigned long hold; /* local strm->hold */
  82773. unsigned bits; /* local strm->bits */
  82774. code const FAR *lcode; /* local strm->lencode */
  82775. code const FAR *dcode; /* local strm->distcode */
  82776. unsigned lmask; /* mask for first level of length codes */
  82777. unsigned dmask; /* mask for first level of distance codes */
  82778. code thisx; /* retrieved table entry */
  82779. unsigned op; /* code bits, operation, extra bits, or */
  82780. /* window position, window bytes to copy */
  82781. unsigned len; /* match length, unused bytes */
  82782. unsigned dist; /* match distance */
  82783. unsigned char FAR *from; /* where to copy match from */
  82784. /* copy state to local variables */
  82785. state = (struct inflate_state FAR *)strm->state;
  82786. in = strm->next_in - OFF;
  82787. last = in + (strm->avail_in - 5);
  82788. out = strm->next_out - OFF;
  82789. beg = out - (start - strm->avail_out);
  82790. end = out + (strm->avail_out - 257);
  82791. #ifdef INFLATE_STRICT
  82792. dmax = state->dmax;
  82793. #endif
  82794. wsize = state->wsize;
  82795. whave = state->whave;
  82796. write = state->write;
  82797. window = state->window;
  82798. hold = state->hold;
  82799. bits = state->bits;
  82800. lcode = state->lencode;
  82801. dcode = state->distcode;
  82802. lmask = (1U << state->lenbits) - 1;
  82803. dmask = (1U << state->distbits) - 1;
  82804. /* decode literals and length/distances until end-of-block or not enough
  82805. input data or output space */
  82806. do {
  82807. if (bits < 15) {
  82808. hold += (unsigned long)(PUP(in)) << bits;
  82809. bits += 8;
  82810. hold += (unsigned long)(PUP(in)) << bits;
  82811. bits += 8;
  82812. }
  82813. thisx = lcode[hold & lmask];
  82814. dolen:
  82815. op = (unsigned)(thisx.bits);
  82816. hold >>= op;
  82817. bits -= op;
  82818. op = (unsigned)(thisx.op);
  82819. if (op == 0) { /* literal */
  82820. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82821. "inflate: literal '%c'\n" :
  82822. "inflate: literal 0x%02x\n", thisx.val));
  82823. PUP(out) = (unsigned char)(thisx.val);
  82824. }
  82825. else if (op & 16) { /* length base */
  82826. len = (unsigned)(thisx.val);
  82827. op &= 15; /* number of extra bits */
  82828. if (op) {
  82829. if (bits < op) {
  82830. hold += (unsigned long)(PUP(in)) << bits;
  82831. bits += 8;
  82832. }
  82833. len += (unsigned)hold & ((1U << op) - 1);
  82834. hold >>= op;
  82835. bits -= op;
  82836. }
  82837. Tracevv((stderr, "inflate: length %u\n", len));
  82838. if (bits < 15) {
  82839. hold += (unsigned long)(PUP(in)) << bits;
  82840. bits += 8;
  82841. hold += (unsigned long)(PUP(in)) << bits;
  82842. bits += 8;
  82843. }
  82844. thisx = dcode[hold & dmask];
  82845. dodist:
  82846. op = (unsigned)(thisx.bits);
  82847. hold >>= op;
  82848. bits -= op;
  82849. op = (unsigned)(thisx.op);
  82850. if (op & 16) { /* distance base */
  82851. dist = (unsigned)(thisx.val);
  82852. op &= 15; /* number of extra bits */
  82853. if (bits < op) {
  82854. hold += (unsigned long)(PUP(in)) << bits;
  82855. bits += 8;
  82856. if (bits < op) {
  82857. hold += (unsigned long)(PUP(in)) << bits;
  82858. bits += 8;
  82859. }
  82860. }
  82861. dist += (unsigned)hold & ((1U << op) - 1);
  82862. #ifdef INFLATE_STRICT
  82863. if (dist > dmax) {
  82864. strm->msg = (char *)"invalid distance too far back";
  82865. state->mode = BAD;
  82866. break;
  82867. }
  82868. #endif
  82869. hold >>= op;
  82870. bits -= op;
  82871. Tracevv((stderr, "inflate: distance %u\n", dist));
  82872. op = (unsigned)(out - beg); /* max distance in output */
  82873. if (dist > op) { /* see if copy from window */
  82874. op = dist - op; /* distance back in window */
  82875. if (op > whave) {
  82876. strm->msg = (char *)"invalid distance too far back";
  82877. state->mode = BAD;
  82878. break;
  82879. }
  82880. from = window - OFF;
  82881. if (write == 0) { /* very common case */
  82882. from += wsize - op;
  82883. if (op < len) { /* some from window */
  82884. len -= op;
  82885. do {
  82886. PUP(out) = PUP(from);
  82887. } while (--op);
  82888. from = out - dist; /* rest from output */
  82889. }
  82890. }
  82891. else if (write < op) { /* wrap around window */
  82892. from += wsize + write - op;
  82893. op -= write;
  82894. if (op < len) { /* some from end of window */
  82895. len -= op;
  82896. do {
  82897. PUP(out) = PUP(from);
  82898. } while (--op);
  82899. from = window - OFF;
  82900. if (write < len) { /* some from start of window */
  82901. op = write;
  82902. len -= op;
  82903. do {
  82904. PUP(out) = PUP(from);
  82905. } while (--op);
  82906. from = out - dist; /* rest from output */
  82907. }
  82908. }
  82909. }
  82910. else { /* contiguous in window */
  82911. from += write - op;
  82912. if (op < len) { /* some from window */
  82913. len -= op;
  82914. do {
  82915. PUP(out) = PUP(from);
  82916. } while (--op);
  82917. from = out - dist; /* rest from output */
  82918. }
  82919. }
  82920. while (len > 2) {
  82921. PUP(out) = PUP(from);
  82922. PUP(out) = PUP(from);
  82923. PUP(out) = PUP(from);
  82924. len -= 3;
  82925. }
  82926. if (len) {
  82927. PUP(out) = PUP(from);
  82928. if (len > 1)
  82929. PUP(out) = PUP(from);
  82930. }
  82931. }
  82932. else {
  82933. from = out - dist; /* copy direct from output */
  82934. do { /* minimum length is three */
  82935. PUP(out) = PUP(from);
  82936. PUP(out) = PUP(from);
  82937. PUP(out) = PUP(from);
  82938. len -= 3;
  82939. } while (len > 2);
  82940. if (len) {
  82941. PUP(out) = PUP(from);
  82942. if (len > 1)
  82943. PUP(out) = PUP(from);
  82944. }
  82945. }
  82946. }
  82947. else if ((op & 64) == 0) { /* 2nd level distance code */
  82948. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82949. goto dodist;
  82950. }
  82951. else {
  82952. strm->msg = (char *)"invalid distance code";
  82953. state->mode = BAD;
  82954. break;
  82955. }
  82956. }
  82957. else if ((op & 64) == 0) { /* 2nd level length code */
  82958. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82959. goto dolen;
  82960. }
  82961. else if (op & 32) { /* end-of-block */
  82962. Tracevv((stderr, "inflate: end of block\n"));
  82963. state->mode = TYPE;
  82964. break;
  82965. }
  82966. else {
  82967. strm->msg = (char *)"invalid literal/length code";
  82968. state->mode = BAD;
  82969. break;
  82970. }
  82971. } while (in < last && out < end);
  82972. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82973. len = bits >> 3;
  82974. in -= len;
  82975. bits -= len << 3;
  82976. hold &= (1U << bits) - 1;
  82977. /* update state and return */
  82978. strm->next_in = in + OFF;
  82979. strm->next_out = out + OFF;
  82980. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82981. strm->avail_out = (unsigned)(out < end ?
  82982. 257 + (end - out) : 257 - (out - end));
  82983. state->hold = hold;
  82984. state->bits = bits;
  82985. return;
  82986. }
  82987. /*
  82988. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82989. - Using bit fields for code structure
  82990. - Different op definition to avoid & for extra bits (do & for table bits)
  82991. - Three separate decoding do-loops for direct, window, and write == 0
  82992. - Special case for distance > 1 copies to do overlapped load and store copy
  82993. - Explicit branch predictions (based on measured branch probabilities)
  82994. - Deferring match copy and interspersed it with decoding subsequent codes
  82995. - Swapping literal/length else
  82996. - Swapping window/direct else
  82997. - Larger unrolled copy loops (three is about right)
  82998. - Moving len -= 3 statement into middle of loop
  82999. */
  83000. #endif /* !ASMINF */
  83001. /*** End of inlined file: inffast.c ***/
  83002. #undef PULLBYTE
  83003. #undef LOAD
  83004. #undef RESTORE
  83005. #undef INITBITS
  83006. #undef NEEDBITS
  83007. #undef DROPBITS
  83008. #undef BYTEBITS
  83009. /*** Start of inlined file: inflate.c ***/
  83010. /*
  83011. * Change history:
  83012. *
  83013. * 1.2.beta0 24 Nov 2002
  83014. * - First version -- complete rewrite of inflate to simplify code, avoid
  83015. * creation of window when not needed, minimize use of window when it is
  83016. * needed, make inffast.c even faster, implement gzip decoding, and to
  83017. * improve code readability and style over the previous zlib inflate code
  83018. *
  83019. * 1.2.beta1 25 Nov 2002
  83020. * - Use pointers for available input and output checking in inffast.c
  83021. * - Remove input and output counters in inffast.c
  83022. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83023. * - Remove unnecessary second byte pull from length extra in inffast.c
  83024. * - Unroll direct copy to three copies per loop in inffast.c
  83025. *
  83026. * 1.2.beta2 4 Dec 2002
  83027. * - Change external routine names to reduce potential conflicts
  83028. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83029. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83030. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83031. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83032. *
  83033. * 1.2.beta3 22 Dec 2002
  83034. * - Add comments on state->bits assertion in inffast.c
  83035. * - Add comments on op field in inftrees.h
  83036. * - Fix bug in reuse of allocated window after inflateReset()
  83037. * - Remove bit fields--back to byte structure for speed
  83038. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83039. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83040. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83041. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83042. * - Use local copies of stream next and avail values, as well as local bit
  83043. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83044. *
  83045. * 1.2.beta4 1 Jan 2003
  83046. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83047. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83048. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83049. * - Rearrange window copies in inflate_fast() for speed and simplification
  83050. * - Unroll last copy for window match in inflate_fast()
  83051. * - Use local copies of window variables in inflate_fast() for speed
  83052. * - Pull out common write == 0 case for speed in inflate_fast()
  83053. * - Make op and len in inflate_fast() unsigned for consistency
  83054. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83055. * - Simplified bad distance check in inflate_fast()
  83056. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83057. * source file infback.c to provide a call-back interface to inflate for
  83058. * programs like gzip and unzip -- uses window as output buffer to avoid
  83059. * window copying
  83060. *
  83061. * 1.2.beta5 1 Jan 2003
  83062. * - Improved inflateBack() interface to allow the caller to provide initial
  83063. * input in strm.
  83064. * - Fixed stored blocks bug in inflateBack()
  83065. *
  83066. * 1.2.beta6 4 Jan 2003
  83067. * - Added comments in inffast.c on effectiveness of POSTINC
  83068. * - Typecasting all around to reduce compiler warnings
  83069. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83070. * make compilers happy
  83071. * - Changed type of window in inflateBackInit() to unsigned char *
  83072. *
  83073. * 1.2.beta7 27 Jan 2003
  83074. * - Changed many types to unsigned or unsigned short to avoid warnings
  83075. * - Added inflateCopy() function
  83076. *
  83077. * 1.2.0 9 Mar 2003
  83078. * - Changed inflateBack() interface to provide separate opaque descriptors
  83079. * for the in() and out() functions
  83080. * - Changed inflateBack() argument and in_func typedef to swap the length
  83081. * and buffer address return values for the input function
  83082. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83083. *
  83084. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83085. */
  83086. /*** Start of inlined file: inffast.h ***/
  83087. /* WARNING: this file should *not* be used by applications. It is
  83088. part of the implementation of the compression library and is
  83089. subject to change. Applications should only use zlib.h.
  83090. */
  83091. void inflate_fast OF((z_streamp strm, unsigned start));
  83092. /*** End of inlined file: inffast.h ***/
  83093. #ifdef MAKEFIXED
  83094. # ifndef BUILDFIXED
  83095. # define BUILDFIXED
  83096. # endif
  83097. #endif
  83098. /* function prototypes */
  83099. local void fixedtables OF((struct inflate_state FAR *state));
  83100. local int updatewindow OF((z_streamp strm, unsigned out));
  83101. #ifdef BUILDFIXED
  83102. void makefixed OF((void));
  83103. #endif
  83104. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83105. unsigned len));
  83106. int ZEXPORT inflateReset (z_streamp strm)
  83107. {
  83108. struct inflate_state FAR *state;
  83109. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83110. state = (struct inflate_state FAR *)strm->state;
  83111. strm->total_in = strm->total_out = state->total = 0;
  83112. strm->msg = Z_NULL;
  83113. strm->adler = 1; /* to support ill-conceived Java test suite */
  83114. state->mode = HEAD;
  83115. state->last = 0;
  83116. state->havedict = 0;
  83117. state->dmax = 32768U;
  83118. state->head = Z_NULL;
  83119. state->wsize = 0;
  83120. state->whave = 0;
  83121. state->write = 0;
  83122. state->hold = 0;
  83123. state->bits = 0;
  83124. state->lencode = state->distcode = state->next = state->codes;
  83125. Tracev((stderr, "inflate: reset\n"));
  83126. return Z_OK;
  83127. }
  83128. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83129. {
  83130. struct inflate_state FAR *state;
  83131. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83132. state = (struct inflate_state FAR *)strm->state;
  83133. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83134. value &= (1L << bits) - 1;
  83135. state->hold += value << state->bits;
  83136. state->bits += bits;
  83137. return Z_OK;
  83138. }
  83139. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83140. {
  83141. struct inflate_state FAR *state;
  83142. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83143. stream_size != (int)(sizeof(z_stream)))
  83144. return Z_VERSION_ERROR;
  83145. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83146. strm->msg = Z_NULL; /* in case we return an error */
  83147. if (strm->zalloc == (alloc_func)0) {
  83148. strm->zalloc = zcalloc;
  83149. strm->opaque = (voidpf)0;
  83150. }
  83151. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83152. state = (struct inflate_state FAR *)
  83153. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83154. if (state == Z_NULL) return Z_MEM_ERROR;
  83155. Tracev((stderr, "inflate: allocated\n"));
  83156. strm->state = (struct internal_state FAR *)state;
  83157. if (windowBits < 0) {
  83158. state->wrap = 0;
  83159. windowBits = -windowBits;
  83160. }
  83161. else {
  83162. state->wrap = (windowBits >> 4) + 1;
  83163. #ifdef GUNZIP
  83164. if (windowBits < 48) windowBits &= 15;
  83165. #endif
  83166. }
  83167. if (windowBits < 8 || windowBits > 15) {
  83168. ZFREE(strm, state);
  83169. strm->state = Z_NULL;
  83170. return Z_STREAM_ERROR;
  83171. }
  83172. state->wbits = (unsigned)windowBits;
  83173. state->window = Z_NULL;
  83174. return inflateReset(strm);
  83175. }
  83176. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83177. {
  83178. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83179. }
  83180. /*
  83181. Return state with length and distance decoding tables and index sizes set to
  83182. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83183. If BUILDFIXED is defined, then instead this routine builds the tables the
  83184. first time it's called, and returns those tables the first time and
  83185. thereafter. This reduces the size of the code by about 2K bytes, in
  83186. exchange for a little execution time. However, BUILDFIXED should not be
  83187. used for threaded applications, since the rewriting of the tables and virgin
  83188. may not be thread-safe.
  83189. */
  83190. local void fixedtables (struct inflate_state FAR *state)
  83191. {
  83192. #ifdef BUILDFIXED
  83193. static int virgin = 1;
  83194. static code *lenfix, *distfix;
  83195. static code fixed[544];
  83196. /* build fixed huffman tables if first call (may not be thread safe) */
  83197. if (virgin) {
  83198. unsigned sym, bits;
  83199. static code *next;
  83200. /* literal/length table */
  83201. sym = 0;
  83202. while (sym < 144) state->lens[sym++] = 8;
  83203. while (sym < 256) state->lens[sym++] = 9;
  83204. while (sym < 280) state->lens[sym++] = 7;
  83205. while (sym < 288) state->lens[sym++] = 8;
  83206. next = fixed;
  83207. lenfix = next;
  83208. bits = 9;
  83209. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83210. /* distance table */
  83211. sym = 0;
  83212. while (sym < 32) state->lens[sym++] = 5;
  83213. distfix = next;
  83214. bits = 5;
  83215. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83216. /* do this just once */
  83217. virgin = 0;
  83218. }
  83219. #else /* !BUILDFIXED */
  83220. /*** Start of inlined file: inffixed.h ***/
  83221. /* WARNING: this file should *not* be used by applications. It
  83222. is part of the implementation of the compression library and
  83223. is subject to change. Applications should only use zlib.h.
  83224. */
  83225. static const code lenfix[512] = {
  83226. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83227. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83228. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83229. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83230. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83231. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83232. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83233. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83234. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83235. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83236. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83237. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83238. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83239. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83240. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83241. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83242. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83243. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83244. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83245. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83246. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83247. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83248. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83249. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83250. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83251. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83252. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83253. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83254. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83255. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83256. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83257. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83258. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83259. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83260. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83261. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83262. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83263. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83264. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83265. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83266. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83267. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83268. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83269. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83270. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83271. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83272. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83273. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83274. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83275. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83276. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83277. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83278. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83279. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83280. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83281. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83282. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83283. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83284. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83285. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83286. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83287. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83288. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83289. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83290. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83291. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83292. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83293. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83294. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83295. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83296. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83297. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83298. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83299. {0,9,255}
  83300. };
  83301. static const code distfix[32] = {
  83302. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83303. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83304. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83305. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83306. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83307. {22,5,193},{64,5,0}
  83308. };
  83309. /*** End of inlined file: inffixed.h ***/
  83310. #endif /* BUILDFIXED */
  83311. state->lencode = lenfix;
  83312. state->lenbits = 9;
  83313. state->distcode = distfix;
  83314. state->distbits = 5;
  83315. }
  83316. #ifdef MAKEFIXED
  83317. #include <stdio.h>
  83318. /*
  83319. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83320. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83321. those tables to stdout, which would be piped to inffixed.h. A small program
  83322. can simply call makefixed to do this:
  83323. void makefixed(void);
  83324. int main(void)
  83325. {
  83326. makefixed();
  83327. return 0;
  83328. }
  83329. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83330. a.out > inffixed.h
  83331. */
  83332. void makefixed()
  83333. {
  83334. unsigned low, size;
  83335. struct inflate_state state;
  83336. fixedtables(&state);
  83337. puts(" /* inffixed.h -- table for decoding fixed codes");
  83338. puts(" * Generated automatically by makefixed().");
  83339. puts(" */");
  83340. puts("");
  83341. puts(" /* WARNING: this file should *not* be used by applications.");
  83342. puts(" It is part of the implementation of this library and is");
  83343. puts(" subject to change. Applications should only use zlib.h.");
  83344. puts(" */");
  83345. puts("");
  83346. size = 1U << 9;
  83347. printf(" static const code lenfix[%u] = {", size);
  83348. low = 0;
  83349. for (;;) {
  83350. if ((low % 7) == 0) printf("\n ");
  83351. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83352. state.lencode[low].val);
  83353. if (++low == size) break;
  83354. putchar(',');
  83355. }
  83356. puts("\n };");
  83357. size = 1U << 5;
  83358. printf("\n static const code distfix[%u] = {", size);
  83359. low = 0;
  83360. for (;;) {
  83361. if ((low % 6) == 0) printf("\n ");
  83362. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83363. state.distcode[low].val);
  83364. if (++low == size) break;
  83365. putchar(',');
  83366. }
  83367. puts("\n };");
  83368. }
  83369. #endif /* MAKEFIXED */
  83370. /*
  83371. Update the window with the last wsize (normally 32K) bytes written before
  83372. returning. If window does not exist yet, create it. This is only called
  83373. when a window is already in use, or when output has been written during this
  83374. inflate call, but the end of the deflate stream has not been reached yet.
  83375. It is also called to create a window for dictionary data when a dictionary
  83376. is loaded.
  83377. Providing output buffers larger than 32K to inflate() should provide a speed
  83378. advantage, since only the last 32K of output is copied to the sliding window
  83379. upon return from inflate(), and since all distances after the first 32K of
  83380. output will fall in the output data, making match copies simpler and faster.
  83381. The advantage may be dependent on the size of the processor's data caches.
  83382. */
  83383. local int updatewindow (z_streamp strm, unsigned out)
  83384. {
  83385. struct inflate_state FAR *state;
  83386. unsigned copy, dist;
  83387. state = (struct inflate_state FAR *)strm->state;
  83388. /* if it hasn't been done already, allocate space for the window */
  83389. if (state->window == Z_NULL) {
  83390. state->window = (unsigned char FAR *)
  83391. ZALLOC(strm, 1U << state->wbits,
  83392. sizeof(unsigned char));
  83393. if (state->window == Z_NULL) return 1;
  83394. }
  83395. /* if window not in use yet, initialize */
  83396. if (state->wsize == 0) {
  83397. state->wsize = 1U << state->wbits;
  83398. state->write = 0;
  83399. state->whave = 0;
  83400. }
  83401. /* copy state->wsize or less output bytes into the circular window */
  83402. copy = out - strm->avail_out;
  83403. if (copy >= state->wsize) {
  83404. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83405. state->write = 0;
  83406. state->whave = state->wsize;
  83407. }
  83408. else {
  83409. dist = state->wsize - state->write;
  83410. if (dist > copy) dist = copy;
  83411. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83412. copy -= dist;
  83413. if (copy) {
  83414. zmemcpy(state->window, strm->next_out - copy, copy);
  83415. state->write = copy;
  83416. state->whave = state->wsize;
  83417. }
  83418. else {
  83419. state->write += dist;
  83420. if (state->write == state->wsize) state->write = 0;
  83421. if (state->whave < state->wsize) state->whave += dist;
  83422. }
  83423. }
  83424. return 0;
  83425. }
  83426. /* Macros for inflate(): */
  83427. /* check function to use adler32() for zlib or crc32() for gzip */
  83428. #ifdef GUNZIP
  83429. # define UPDATE(check, buf, len) \
  83430. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83431. #else
  83432. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83433. #endif
  83434. /* check macros for header crc */
  83435. #ifdef GUNZIP
  83436. # define CRC2(check, word) \
  83437. do { \
  83438. hbuf[0] = (unsigned char)(word); \
  83439. hbuf[1] = (unsigned char)((word) >> 8); \
  83440. check = crc32(check, hbuf, 2); \
  83441. } while (0)
  83442. # define CRC4(check, word) \
  83443. do { \
  83444. hbuf[0] = (unsigned char)(word); \
  83445. hbuf[1] = (unsigned char)((word) >> 8); \
  83446. hbuf[2] = (unsigned char)((word) >> 16); \
  83447. hbuf[3] = (unsigned char)((word) >> 24); \
  83448. check = crc32(check, hbuf, 4); \
  83449. } while (0)
  83450. #endif
  83451. /* Load registers with state in inflate() for speed */
  83452. #define LOAD() \
  83453. do { \
  83454. put = strm->next_out; \
  83455. left = strm->avail_out; \
  83456. next = strm->next_in; \
  83457. have = strm->avail_in; \
  83458. hold = state->hold; \
  83459. bits = state->bits; \
  83460. } while (0)
  83461. /* Restore state from registers in inflate() */
  83462. #define RESTORE() \
  83463. do { \
  83464. strm->next_out = put; \
  83465. strm->avail_out = left; \
  83466. strm->next_in = next; \
  83467. strm->avail_in = have; \
  83468. state->hold = hold; \
  83469. state->bits = bits; \
  83470. } while (0)
  83471. /* Clear the input bit accumulator */
  83472. #define INITBITS() \
  83473. do { \
  83474. hold = 0; \
  83475. bits = 0; \
  83476. } while (0)
  83477. /* Get a byte of input into the bit accumulator, or return from inflate()
  83478. if there is no input available. */
  83479. #define PULLBYTE() \
  83480. do { \
  83481. if (have == 0) goto inf_leave; \
  83482. have--; \
  83483. hold += (unsigned long)(*next++) << bits; \
  83484. bits += 8; \
  83485. } while (0)
  83486. /* Assure that there are at least n bits in the bit accumulator. If there is
  83487. not enough available input to do that, then return from inflate(). */
  83488. #define NEEDBITS(n) \
  83489. do { \
  83490. while (bits < (unsigned)(n)) \
  83491. PULLBYTE(); \
  83492. } while (0)
  83493. /* Return the low n bits of the bit accumulator (n < 16) */
  83494. #define BITS(n) \
  83495. ((unsigned)hold & ((1U << (n)) - 1))
  83496. /* Remove n bits from the bit accumulator */
  83497. #define DROPBITS(n) \
  83498. do { \
  83499. hold >>= (n); \
  83500. bits -= (unsigned)(n); \
  83501. } while (0)
  83502. /* Remove zero to seven bits as needed to go to a byte boundary */
  83503. #define BYTEBITS() \
  83504. do { \
  83505. hold >>= bits & 7; \
  83506. bits -= bits & 7; \
  83507. } while (0)
  83508. /* Reverse the bytes in a 32-bit value */
  83509. #define REVERSE(q) \
  83510. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83511. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83512. /*
  83513. inflate() uses a state machine to process as much input data and generate as
  83514. much output data as possible before returning. The state machine is
  83515. structured roughly as follows:
  83516. for (;;) switch (state) {
  83517. ...
  83518. case STATEn:
  83519. if (not enough input data or output space to make progress)
  83520. return;
  83521. ... make progress ...
  83522. state = STATEm;
  83523. break;
  83524. ...
  83525. }
  83526. so when inflate() is called again, the same case is attempted again, and
  83527. if the appropriate resources are provided, the machine proceeds to the
  83528. next state. The NEEDBITS() macro is usually the way the state evaluates
  83529. whether it can proceed or should return. NEEDBITS() does the return if
  83530. the requested bits are not available. The typical use of the BITS macros
  83531. is:
  83532. NEEDBITS(n);
  83533. ... do something with BITS(n) ...
  83534. DROPBITS(n);
  83535. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83536. input left to load n bits into the accumulator, or it continues. BITS(n)
  83537. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83538. the low n bits off the accumulator. INITBITS() clears the accumulator
  83539. and sets the number of available bits to zero. BYTEBITS() discards just
  83540. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83541. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83542. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83543. if there is no input available. The decoding of variable length codes uses
  83544. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83545. code, and no more.
  83546. Some states loop until they get enough input, making sure that enough
  83547. state information is maintained to continue the loop where it left off
  83548. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83549. would all have to actually be part of the saved state in case NEEDBITS()
  83550. returns:
  83551. case STATEw:
  83552. while (want < need) {
  83553. NEEDBITS(n);
  83554. keep[want++] = BITS(n);
  83555. DROPBITS(n);
  83556. }
  83557. state = STATEx;
  83558. case STATEx:
  83559. As shown above, if the next state is also the next case, then the break
  83560. is omitted.
  83561. A state may also return if there is not enough output space available to
  83562. complete that state. Those states are copying stored data, writing a
  83563. literal byte, and copying a matching string.
  83564. When returning, a "goto inf_leave" is used to update the total counters,
  83565. update the check value, and determine whether any progress has been made
  83566. during that inflate() call in order to return the proper return code.
  83567. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83568. When there is a window, goto inf_leave will update the window with the last
  83569. output written. If a goto inf_leave occurs in the middle of decompression
  83570. and there is no window currently, goto inf_leave will create one and copy
  83571. output to the window for the next call of inflate().
  83572. In this implementation, the flush parameter of inflate() only affects the
  83573. return code (per zlib.h). inflate() always writes as much as possible to
  83574. strm->next_out, given the space available and the provided input--the effect
  83575. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83576. the allocation of and copying into a sliding window until necessary, which
  83577. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83578. stream available. So the only thing the flush parameter actually does is:
  83579. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83580. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83581. */
  83582. int ZEXPORT inflate (z_streamp strm, int flush)
  83583. {
  83584. struct inflate_state FAR *state;
  83585. unsigned char FAR *next; /* next input */
  83586. unsigned char FAR *put; /* next output */
  83587. unsigned have, left; /* available input and output */
  83588. unsigned long hold; /* bit buffer */
  83589. unsigned bits; /* bits in bit buffer */
  83590. unsigned in, out; /* save starting available input and output */
  83591. unsigned copy; /* number of stored or match bytes to copy */
  83592. unsigned char FAR *from; /* where to copy match bytes from */
  83593. code thisx; /* current decoding table entry */
  83594. code last; /* parent table entry */
  83595. unsigned len; /* length to copy for repeats, bits to drop */
  83596. int ret; /* return code */
  83597. #ifdef GUNZIP
  83598. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83599. #endif
  83600. static const unsigned short order[19] = /* permutation of code lengths */
  83601. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83602. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83603. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83604. return Z_STREAM_ERROR;
  83605. state = (struct inflate_state FAR *)strm->state;
  83606. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83607. LOAD();
  83608. in = have;
  83609. out = left;
  83610. ret = Z_OK;
  83611. for (;;)
  83612. switch (state->mode) {
  83613. case HEAD:
  83614. if (state->wrap == 0) {
  83615. state->mode = TYPEDO;
  83616. break;
  83617. }
  83618. NEEDBITS(16);
  83619. #ifdef GUNZIP
  83620. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83621. state->check = crc32(0L, Z_NULL, 0);
  83622. CRC2(state->check, hold);
  83623. INITBITS();
  83624. state->mode = FLAGS;
  83625. break;
  83626. }
  83627. state->flags = 0; /* expect zlib header */
  83628. if (state->head != Z_NULL)
  83629. state->head->done = -1;
  83630. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83631. #else
  83632. if (
  83633. #endif
  83634. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83635. strm->msg = (char *)"incorrect header check";
  83636. state->mode = BAD;
  83637. break;
  83638. }
  83639. if (BITS(4) != Z_DEFLATED) {
  83640. strm->msg = (char *)"unknown compression method";
  83641. state->mode = BAD;
  83642. break;
  83643. }
  83644. DROPBITS(4);
  83645. len = BITS(4) + 8;
  83646. if (len > state->wbits) {
  83647. strm->msg = (char *)"invalid window size";
  83648. state->mode = BAD;
  83649. break;
  83650. }
  83651. state->dmax = 1U << len;
  83652. Tracev((stderr, "inflate: zlib header ok\n"));
  83653. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83654. state->mode = hold & 0x200 ? DICTID : TYPE;
  83655. INITBITS();
  83656. break;
  83657. #ifdef GUNZIP
  83658. case FLAGS:
  83659. NEEDBITS(16);
  83660. state->flags = (int)(hold);
  83661. if ((state->flags & 0xff) != Z_DEFLATED) {
  83662. strm->msg = (char *)"unknown compression method";
  83663. state->mode = BAD;
  83664. break;
  83665. }
  83666. if (state->flags & 0xe000) {
  83667. strm->msg = (char *)"unknown header flags set";
  83668. state->mode = BAD;
  83669. break;
  83670. }
  83671. if (state->head != Z_NULL)
  83672. state->head->text = (int)((hold >> 8) & 1);
  83673. if (state->flags & 0x0200) CRC2(state->check, hold);
  83674. INITBITS();
  83675. state->mode = TIME;
  83676. case TIME:
  83677. NEEDBITS(32);
  83678. if (state->head != Z_NULL)
  83679. state->head->time = hold;
  83680. if (state->flags & 0x0200) CRC4(state->check, hold);
  83681. INITBITS();
  83682. state->mode = OS;
  83683. case OS:
  83684. NEEDBITS(16);
  83685. if (state->head != Z_NULL) {
  83686. state->head->xflags = (int)(hold & 0xff);
  83687. state->head->os = (int)(hold >> 8);
  83688. }
  83689. if (state->flags & 0x0200) CRC2(state->check, hold);
  83690. INITBITS();
  83691. state->mode = EXLEN;
  83692. case EXLEN:
  83693. if (state->flags & 0x0400) {
  83694. NEEDBITS(16);
  83695. state->length = (unsigned)(hold);
  83696. if (state->head != Z_NULL)
  83697. state->head->extra_len = (unsigned)hold;
  83698. if (state->flags & 0x0200) CRC2(state->check, hold);
  83699. INITBITS();
  83700. }
  83701. else if (state->head != Z_NULL)
  83702. state->head->extra = Z_NULL;
  83703. state->mode = EXTRA;
  83704. case EXTRA:
  83705. if (state->flags & 0x0400) {
  83706. copy = state->length;
  83707. if (copy > have) copy = have;
  83708. if (copy) {
  83709. if (state->head != Z_NULL &&
  83710. state->head->extra != Z_NULL) {
  83711. len = state->head->extra_len - state->length;
  83712. zmemcpy(state->head->extra + len, next,
  83713. len + copy > state->head->extra_max ?
  83714. state->head->extra_max - len : copy);
  83715. }
  83716. if (state->flags & 0x0200)
  83717. state->check = crc32(state->check, next, copy);
  83718. have -= copy;
  83719. next += copy;
  83720. state->length -= copy;
  83721. }
  83722. if (state->length) goto inf_leave;
  83723. }
  83724. state->length = 0;
  83725. state->mode = NAME;
  83726. case NAME:
  83727. if (state->flags & 0x0800) {
  83728. if (have == 0) goto inf_leave;
  83729. copy = 0;
  83730. do {
  83731. len = (unsigned)(next[copy++]);
  83732. if (state->head != Z_NULL &&
  83733. state->head->name != Z_NULL &&
  83734. state->length < state->head->name_max)
  83735. state->head->name[state->length++] = len;
  83736. } while (len && copy < have);
  83737. if (state->flags & 0x0200)
  83738. state->check = crc32(state->check, next, copy);
  83739. have -= copy;
  83740. next += copy;
  83741. if (len) goto inf_leave;
  83742. }
  83743. else if (state->head != Z_NULL)
  83744. state->head->name = Z_NULL;
  83745. state->length = 0;
  83746. state->mode = COMMENT;
  83747. case COMMENT:
  83748. if (state->flags & 0x1000) {
  83749. if (have == 0) goto inf_leave;
  83750. copy = 0;
  83751. do {
  83752. len = (unsigned)(next[copy++]);
  83753. if (state->head != Z_NULL &&
  83754. state->head->comment != Z_NULL &&
  83755. state->length < state->head->comm_max)
  83756. state->head->comment[state->length++] = len;
  83757. } while (len && copy < have);
  83758. if (state->flags & 0x0200)
  83759. state->check = crc32(state->check, next, copy);
  83760. have -= copy;
  83761. next += copy;
  83762. if (len) goto inf_leave;
  83763. }
  83764. else if (state->head != Z_NULL)
  83765. state->head->comment = Z_NULL;
  83766. state->mode = HCRC;
  83767. case HCRC:
  83768. if (state->flags & 0x0200) {
  83769. NEEDBITS(16);
  83770. if (hold != (state->check & 0xffff)) {
  83771. strm->msg = (char *)"header crc mismatch";
  83772. state->mode = BAD;
  83773. break;
  83774. }
  83775. INITBITS();
  83776. }
  83777. if (state->head != Z_NULL) {
  83778. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83779. state->head->done = 1;
  83780. }
  83781. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83782. state->mode = TYPE;
  83783. break;
  83784. #endif
  83785. case DICTID:
  83786. NEEDBITS(32);
  83787. strm->adler = state->check = REVERSE(hold);
  83788. INITBITS();
  83789. state->mode = DICT;
  83790. case DICT:
  83791. if (state->havedict == 0) {
  83792. RESTORE();
  83793. return Z_NEED_DICT;
  83794. }
  83795. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83796. state->mode = TYPE;
  83797. case TYPE:
  83798. if (flush == Z_BLOCK) goto inf_leave;
  83799. case TYPEDO:
  83800. if (state->last) {
  83801. BYTEBITS();
  83802. state->mode = CHECK;
  83803. break;
  83804. }
  83805. NEEDBITS(3);
  83806. state->last = BITS(1);
  83807. DROPBITS(1);
  83808. switch (BITS(2)) {
  83809. case 0: /* stored block */
  83810. Tracev((stderr, "inflate: stored block%s\n",
  83811. state->last ? " (last)" : ""));
  83812. state->mode = STORED;
  83813. break;
  83814. case 1: /* fixed block */
  83815. fixedtables(state);
  83816. Tracev((stderr, "inflate: fixed codes block%s\n",
  83817. state->last ? " (last)" : ""));
  83818. state->mode = LEN; /* decode codes */
  83819. break;
  83820. case 2: /* dynamic block */
  83821. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83822. state->last ? " (last)" : ""));
  83823. state->mode = TABLE;
  83824. break;
  83825. case 3:
  83826. strm->msg = (char *)"invalid block type";
  83827. state->mode = BAD;
  83828. }
  83829. DROPBITS(2);
  83830. break;
  83831. case STORED:
  83832. BYTEBITS(); /* go to byte boundary */
  83833. NEEDBITS(32);
  83834. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83835. strm->msg = (char *)"invalid stored block lengths";
  83836. state->mode = BAD;
  83837. break;
  83838. }
  83839. state->length = (unsigned)hold & 0xffff;
  83840. Tracev((stderr, "inflate: stored length %u\n",
  83841. state->length));
  83842. INITBITS();
  83843. state->mode = COPY;
  83844. case COPY:
  83845. copy = state->length;
  83846. if (copy) {
  83847. if (copy > have) copy = have;
  83848. if (copy > left) copy = left;
  83849. if (copy == 0) goto inf_leave;
  83850. zmemcpy(put, next, copy);
  83851. have -= copy;
  83852. next += copy;
  83853. left -= copy;
  83854. put += copy;
  83855. state->length -= copy;
  83856. break;
  83857. }
  83858. Tracev((stderr, "inflate: stored end\n"));
  83859. state->mode = TYPE;
  83860. break;
  83861. case TABLE:
  83862. NEEDBITS(14);
  83863. state->nlen = BITS(5) + 257;
  83864. DROPBITS(5);
  83865. state->ndist = BITS(5) + 1;
  83866. DROPBITS(5);
  83867. state->ncode = BITS(4) + 4;
  83868. DROPBITS(4);
  83869. #ifndef PKZIP_BUG_WORKAROUND
  83870. if (state->nlen > 286 || state->ndist > 30) {
  83871. strm->msg = (char *)"too many length or distance symbols";
  83872. state->mode = BAD;
  83873. break;
  83874. }
  83875. #endif
  83876. Tracev((stderr, "inflate: table sizes ok\n"));
  83877. state->have = 0;
  83878. state->mode = LENLENS;
  83879. case LENLENS:
  83880. while (state->have < state->ncode) {
  83881. NEEDBITS(3);
  83882. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83883. DROPBITS(3);
  83884. }
  83885. while (state->have < 19)
  83886. state->lens[order[state->have++]] = 0;
  83887. state->next = state->codes;
  83888. state->lencode = (code const FAR *)(state->next);
  83889. state->lenbits = 7;
  83890. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83891. &(state->lenbits), state->work);
  83892. if (ret) {
  83893. strm->msg = (char *)"invalid code lengths set";
  83894. state->mode = BAD;
  83895. break;
  83896. }
  83897. Tracev((stderr, "inflate: code lengths ok\n"));
  83898. state->have = 0;
  83899. state->mode = CODELENS;
  83900. case CODELENS:
  83901. while (state->have < state->nlen + state->ndist) {
  83902. for (;;) {
  83903. thisx = state->lencode[BITS(state->lenbits)];
  83904. if ((unsigned)(thisx.bits) <= bits) break;
  83905. PULLBYTE();
  83906. }
  83907. if (thisx.val < 16) {
  83908. NEEDBITS(thisx.bits);
  83909. DROPBITS(thisx.bits);
  83910. state->lens[state->have++] = thisx.val;
  83911. }
  83912. else {
  83913. if (thisx.val == 16) {
  83914. NEEDBITS(thisx.bits + 2);
  83915. DROPBITS(thisx.bits);
  83916. if (state->have == 0) {
  83917. strm->msg = (char *)"invalid bit length repeat";
  83918. state->mode = BAD;
  83919. break;
  83920. }
  83921. len = state->lens[state->have - 1];
  83922. copy = 3 + BITS(2);
  83923. DROPBITS(2);
  83924. }
  83925. else if (thisx.val == 17) {
  83926. NEEDBITS(thisx.bits + 3);
  83927. DROPBITS(thisx.bits);
  83928. len = 0;
  83929. copy = 3 + BITS(3);
  83930. DROPBITS(3);
  83931. }
  83932. else {
  83933. NEEDBITS(thisx.bits + 7);
  83934. DROPBITS(thisx.bits);
  83935. len = 0;
  83936. copy = 11 + BITS(7);
  83937. DROPBITS(7);
  83938. }
  83939. if (state->have + copy > state->nlen + state->ndist) {
  83940. strm->msg = (char *)"invalid bit length repeat";
  83941. state->mode = BAD;
  83942. break;
  83943. }
  83944. while (copy--)
  83945. state->lens[state->have++] = (unsigned short)len;
  83946. }
  83947. }
  83948. /* handle error breaks in while */
  83949. if (state->mode == BAD) break;
  83950. /* build code tables */
  83951. state->next = state->codes;
  83952. state->lencode = (code const FAR *)(state->next);
  83953. state->lenbits = 9;
  83954. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83955. &(state->lenbits), state->work);
  83956. if (ret) {
  83957. strm->msg = (char *)"invalid literal/lengths set";
  83958. state->mode = BAD;
  83959. break;
  83960. }
  83961. state->distcode = (code const FAR *)(state->next);
  83962. state->distbits = 6;
  83963. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83964. &(state->next), &(state->distbits), state->work);
  83965. if (ret) {
  83966. strm->msg = (char *)"invalid distances set";
  83967. state->mode = BAD;
  83968. break;
  83969. }
  83970. Tracev((stderr, "inflate: codes ok\n"));
  83971. state->mode = LEN;
  83972. case LEN:
  83973. if (have >= 6 && left >= 258) {
  83974. RESTORE();
  83975. inflate_fast(strm, out);
  83976. LOAD();
  83977. break;
  83978. }
  83979. for (;;) {
  83980. thisx = state->lencode[BITS(state->lenbits)];
  83981. if ((unsigned)(thisx.bits) <= bits) break;
  83982. PULLBYTE();
  83983. }
  83984. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83985. last = thisx;
  83986. for (;;) {
  83987. thisx = state->lencode[last.val +
  83988. (BITS(last.bits + last.op) >> last.bits)];
  83989. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83990. PULLBYTE();
  83991. }
  83992. DROPBITS(last.bits);
  83993. }
  83994. DROPBITS(thisx.bits);
  83995. state->length = (unsigned)thisx.val;
  83996. if ((int)(thisx.op) == 0) {
  83997. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83998. "inflate: literal '%c'\n" :
  83999. "inflate: literal 0x%02x\n", thisx.val));
  84000. state->mode = LIT;
  84001. break;
  84002. }
  84003. if (thisx.op & 32) {
  84004. Tracevv((stderr, "inflate: end of block\n"));
  84005. state->mode = TYPE;
  84006. break;
  84007. }
  84008. if (thisx.op & 64) {
  84009. strm->msg = (char *)"invalid literal/length code";
  84010. state->mode = BAD;
  84011. break;
  84012. }
  84013. state->extra = (unsigned)(thisx.op) & 15;
  84014. state->mode = LENEXT;
  84015. case LENEXT:
  84016. if (state->extra) {
  84017. NEEDBITS(state->extra);
  84018. state->length += BITS(state->extra);
  84019. DROPBITS(state->extra);
  84020. }
  84021. Tracevv((stderr, "inflate: length %u\n", state->length));
  84022. state->mode = DIST;
  84023. case DIST:
  84024. for (;;) {
  84025. thisx = state->distcode[BITS(state->distbits)];
  84026. if ((unsigned)(thisx.bits) <= bits) break;
  84027. PULLBYTE();
  84028. }
  84029. if ((thisx.op & 0xf0) == 0) {
  84030. last = thisx;
  84031. for (;;) {
  84032. thisx = state->distcode[last.val +
  84033. (BITS(last.bits + last.op) >> last.bits)];
  84034. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84035. PULLBYTE();
  84036. }
  84037. DROPBITS(last.bits);
  84038. }
  84039. DROPBITS(thisx.bits);
  84040. if (thisx.op & 64) {
  84041. strm->msg = (char *)"invalid distance code";
  84042. state->mode = BAD;
  84043. break;
  84044. }
  84045. state->offset = (unsigned)thisx.val;
  84046. state->extra = (unsigned)(thisx.op) & 15;
  84047. state->mode = DISTEXT;
  84048. case DISTEXT:
  84049. if (state->extra) {
  84050. NEEDBITS(state->extra);
  84051. state->offset += BITS(state->extra);
  84052. DROPBITS(state->extra);
  84053. }
  84054. #ifdef INFLATE_STRICT
  84055. if (state->offset > state->dmax) {
  84056. strm->msg = (char *)"invalid distance too far back";
  84057. state->mode = BAD;
  84058. break;
  84059. }
  84060. #endif
  84061. if (state->offset > state->whave + out - left) {
  84062. strm->msg = (char *)"invalid distance too far back";
  84063. state->mode = BAD;
  84064. break;
  84065. }
  84066. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84067. state->mode = MATCH;
  84068. case MATCH:
  84069. if (left == 0) goto inf_leave;
  84070. copy = out - left;
  84071. if (state->offset > copy) { /* copy from window */
  84072. copy = state->offset - copy;
  84073. if (copy > state->write) {
  84074. copy -= state->write;
  84075. from = state->window + (state->wsize - copy);
  84076. }
  84077. else
  84078. from = state->window + (state->write - copy);
  84079. if (copy > state->length) copy = state->length;
  84080. }
  84081. else { /* copy from output */
  84082. from = put - state->offset;
  84083. copy = state->length;
  84084. }
  84085. if (copy > left) copy = left;
  84086. left -= copy;
  84087. state->length -= copy;
  84088. do {
  84089. *put++ = *from++;
  84090. } while (--copy);
  84091. if (state->length == 0) state->mode = LEN;
  84092. break;
  84093. case LIT:
  84094. if (left == 0) goto inf_leave;
  84095. *put++ = (unsigned char)(state->length);
  84096. left--;
  84097. state->mode = LEN;
  84098. break;
  84099. case CHECK:
  84100. if (state->wrap) {
  84101. NEEDBITS(32);
  84102. out -= left;
  84103. strm->total_out += out;
  84104. state->total += out;
  84105. if (out)
  84106. strm->adler = state->check =
  84107. UPDATE(state->check, put - out, out);
  84108. out = left;
  84109. if ((
  84110. #ifdef GUNZIP
  84111. state->flags ? hold :
  84112. #endif
  84113. REVERSE(hold)) != state->check) {
  84114. strm->msg = (char *)"incorrect data check";
  84115. state->mode = BAD;
  84116. break;
  84117. }
  84118. INITBITS();
  84119. Tracev((stderr, "inflate: check matches trailer\n"));
  84120. }
  84121. #ifdef GUNZIP
  84122. state->mode = LENGTH;
  84123. case LENGTH:
  84124. if (state->wrap && state->flags) {
  84125. NEEDBITS(32);
  84126. if (hold != (state->total & 0xffffffffUL)) {
  84127. strm->msg = (char *)"incorrect length check";
  84128. state->mode = BAD;
  84129. break;
  84130. }
  84131. INITBITS();
  84132. Tracev((stderr, "inflate: length matches trailer\n"));
  84133. }
  84134. #endif
  84135. state->mode = DONE;
  84136. case DONE:
  84137. ret = Z_STREAM_END;
  84138. goto inf_leave;
  84139. case BAD:
  84140. ret = Z_DATA_ERROR;
  84141. goto inf_leave;
  84142. case MEM:
  84143. return Z_MEM_ERROR;
  84144. case SYNC:
  84145. default:
  84146. return Z_STREAM_ERROR;
  84147. }
  84148. /*
  84149. Return from inflate(), updating the total counts and the check value.
  84150. If there was no progress during the inflate() call, return a buffer
  84151. error. Call updatewindow() to create and/or update the window state.
  84152. Note: a memory error from inflate() is non-recoverable.
  84153. */
  84154. inf_leave:
  84155. RESTORE();
  84156. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84157. if (updatewindow(strm, out)) {
  84158. state->mode = MEM;
  84159. return Z_MEM_ERROR;
  84160. }
  84161. in -= strm->avail_in;
  84162. out -= strm->avail_out;
  84163. strm->total_in += in;
  84164. strm->total_out += out;
  84165. state->total += out;
  84166. if (state->wrap && out)
  84167. strm->adler = state->check =
  84168. UPDATE(state->check, strm->next_out - out, out);
  84169. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84170. (state->mode == TYPE ? 128 : 0);
  84171. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84172. ret = Z_BUF_ERROR;
  84173. return ret;
  84174. }
  84175. int ZEXPORT inflateEnd (z_streamp strm)
  84176. {
  84177. struct inflate_state FAR *state;
  84178. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84179. return Z_STREAM_ERROR;
  84180. state = (struct inflate_state FAR *)strm->state;
  84181. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84182. ZFREE(strm, strm->state);
  84183. strm->state = Z_NULL;
  84184. Tracev((stderr, "inflate: end\n"));
  84185. return Z_OK;
  84186. }
  84187. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84188. {
  84189. struct inflate_state FAR *state;
  84190. unsigned long id_;
  84191. /* check state */
  84192. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84193. state = (struct inflate_state FAR *)strm->state;
  84194. if (state->wrap != 0 && state->mode != DICT)
  84195. return Z_STREAM_ERROR;
  84196. /* check for correct dictionary id */
  84197. if (state->mode == DICT) {
  84198. id_ = adler32(0L, Z_NULL, 0);
  84199. id_ = adler32(id_, dictionary, dictLength);
  84200. if (id_ != state->check)
  84201. return Z_DATA_ERROR;
  84202. }
  84203. /* copy dictionary to window */
  84204. if (updatewindow(strm, strm->avail_out)) {
  84205. state->mode = MEM;
  84206. return Z_MEM_ERROR;
  84207. }
  84208. if (dictLength > state->wsize) {
  84209. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84210. state->wsize);
  84211. state->whave = state->wsize;
  84212. }
  84213. else {
  84214. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84215. dictLength);
  84216. state->whave = dictLength;
  84217. }
  84218. state->havedict = 1;
  84219. Tracev((stderr, "inflate: dictionary set\n"));
  84220. return Z_OK;
  84221. }
  84222. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84223. {
  84224. struct inflate_state FAR *state;
  84225. /* check state */
  84226. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84227. state = (struct inflate_state FAR *)strm->state;
  84228. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84229. /* save header structure */
  84230. state->head = head;
  84231. head->done = 0;
  84232. return Z_OK;
  84233. }
  84234. /*
  84235. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84236. or when out of input. When called, *have is the number of pattern bytes
  84237. found in order so far, in 0..3. On return *have is updated to the new
  84238. state. If on return *have equals four, then the pattern was found and the
  84239. return value is how many bytes were read including the last byte of the
  84240. pattern. If *have is less than four, then the pattern has not been found
  84241. yet and the return value is len. In the latter case, syncsearch() can be
  84242. called again with more data and the *have state. *have is initialized to
  84243. zero for the first call.
  84244. */
  84245. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84246. {
  84247. unsigned got;
  84248. unsigned next;
  84249. got = *have;
  84250. next = 0;
  84251. while (next < len && got < 4) {
  84252. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84253. got++;
  84254. else if (buf[next])
  84255. got = 0;
  84256. else
  84257. got = 4 - got;
  84258. next++;
  84259. }
  84260. *have = got;
  84261. return next;
  84262. }
  84263. int ZEXPORT inflateSync (z_streamp strm)
  84264. {
  84265. unsigned len; /* number of bytes to look at or looked at */
  84266. unsigned long in, out; /* temporary to save total_in and total_out */
  84267. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84268. struct inflate_state FAR *state;
  84269. /* check parameters */
  84270. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84271. state = (struct inflate_state FAR *)strm->state;
  84272. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84273. /* if first time, start search in bit buffer */
  84274. if (state->mode != SYNC) {
  84275. state->mode = SYNC;
  84276. state->hold <<= state->bits & 7;
  84277. state->bits -= state->bits & 7;
  84278. len = 0;
  84279. while (state->bits >= 8) {
  84280. buf[len++] = (unsigned char)(state->hold);
  84281. state->hold >>= 8;
  84282. state->bits -= 8;
  84283. }
  84284. state->have = 0;
  84285. syncsearch(&(state->have), buf, len);
  84286. }
  84287. /* search available input */
  84288. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84289. strm->avail_in -= len;
  84290. strm->next_in += len;
  84291. strm->total_in += len;
  84292. /* return no joy or set up to restart inflate() on a new block */
  84293. if (state->have != 4) return Z_DATA_ERROR;
  84294. in = strm->total_in; out = strm->total_out;
  84295. inflateReset(strm);
  84296. strm->total_in = in; strm->total_out = out;
  84297. state->mode = TYPE;
  84298. return Z_OK;
  84299. }
  84300. /*
  84301. Returns true if inflate is currently at the end of a block generated by
  84302. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84303. implementation to provide an additional safety check. PPP uses
  84304. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84305. block. When decompressing, PPP checks that at the end of input packet,
  84306. inflate is waiting for these length bytes.
  84307. */
  84308. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84309. {
  84310. struct inflate_state FAR *state;
  84311. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84312. state = (struct inflate_state FAR *)strm->state;
  84313. return state->mode == STORED && state->bits == 0;
  84314. }
  84315. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84316. {
  84317. struct inflate_state FAR *state;
  84318. struct inflate_state FAR *copy;
  84319. unsigned char FAR *window;
  84320. unsigned wsize;
  84321. /* check input */
  84322. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84323. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84324. return Z_STREAM_ERROR;
  84325. state = (struct inflate_state FAR *)source->state;
  84326. /* allocate space */
  84327. copy = (struct inflate_state FAR *)
  84328. ZALLOC(source, 1, sizeof(struct inflate_state));
  84329. if (copy == Z_NULL) return Z_MEM_ERROR;
  84330. window = Z_NULL;
  84331. if (state->window != Z_NULL) {
  84332. window = (unsigned char FAR *)
  84333. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84334. if (window == Z_NULL) {
  84335. ZFREE(source, copy);
  84336. return Z_MEM_ERROR;
  84337. }
  84338. }
  84339. /* copy state */
  84340. zmemcpy(dest, source, sizeof(z_stream));
  84341. zmemcpy(copy, state, sizeof(struct inflate_state));
  84342. if (state->lencode >= state->codes &&
  84343. state->lencode <= state->codes + ENOUGH - 1) {
  84344. copy->lencode = copy->codes + (state->lencode - state->codes);
  84345. copy->distcode = copy->codes + (state->distcode - state->codes);
  84346. }
  84347. copy->next = copy->codes + (state->next - state->codes);
  84348. if (window != Z_NULL) {
  84349. wsize = 1U << state->wbits;
  84350. zmemcpy(window, state->window, wsize);
  84351. }
  84352. copy->window = window;
  84353. dest->state = (struct internal_state FAR *)copy;
  84354. return Z_OK;
  84355. }
  84356. /*** End of inlined file: inflate.c ***/
  84357. /*** Start of inlined file: inftrees.c ***/
  84358. #define MAXBITS 15
  84359. const char inflate_copyright[] =
  84360. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84361. /*
  84362. If you use the zlib library in a product, an acknowledgment is welcome
  84363. in the documentation of your product. If for some reason you cannot
  84364. include such an acknowledgment, I would appreciate that you keep this
  84365. copyright string in the executable of your product.
  84366. */
  84367. /*
  84368. Build a set of tables to decode the provided canonical Huffman code.
  84369. The code lengths are lens[0..codes-1]. The result starts at *table,
  84370. whose indices are 0..2^bits-1. work is a writable array of at least
  84371. lens shorts, which is used as a work area. type is the type of code
  84372. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84373. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84374. on return points to the next available entry's address. bits is the
  84375. requested root table index bits, and on return it is the actual root
  84376. table index bits. It will differ if the request is greater than the
  84377. longest code or if it is less than the shortest code.
  84378. */
  84379. int inflate_table (codetype type,
  84380. unsigned short FAR *lens,
  84381. unsigned codes,
  84382. code FAR * FAR *table,
  84383. unsigned FAR *bits,
  84384. unsigned short FAR *work)
  84385. {
  84386. unsigned len; /* a code's length in bits */
  84387. unsigned sym; /* index of code symbols */
  84388. unsigned min, max; /* minimum and maximum code lengths */
  84389. unsigned root; /* number of index bits for root table */
  84390. unsigned curr; /* number of index bits for current table */
  84391. unsigned drop; /* code bits to drop for sub-table */
  84392. int left; /* number of prefix codes available */
  84393. unsigned used; /* code entries in table used */
  84394. unsigned huff; /* Huffman code */
  84395. unsigned incr; /* for incrementing code, index */
  84396. unsigned fill; /* index for replicating entries */
  84397. unsigned low; /* low bits for current root entry */
  84398. unsigned mask; /* mask for low root bits */
  84399. code thisx; /* table entry for duplication */
  84400. code FAR *next; /* next available space in table */
  84401. const unsigned short FAR *base; /* base value table to use */
  84402. const unsigned short FAR *extra; /* extra bits table to use */
  84403. int end; /* use base and extra for symbol > end */
  84404. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84405. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84406. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84407. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84408. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84409. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84410. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84411. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84412. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84413. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84414. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84415. 8193, 12289, 16385, 24577, 0, 0};
  84416. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84417. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84418. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84419. 28, 28, 29, 29, 64, 64};
  84420. /*
  84421. Process a set of code lengths to create a canonical Huffman code. The
  84422. code lengths are lens[0..codes-1]. Each length corresponds to the
  84423. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84424. symbols by length from short to long, and retaining the symbol order
  84425. for codes with equal lengths. Then the code starts with all zero bits
  84426. for the first code of the shortest length, and the codes are integer
  84427. increments for the same length, and zeros are appended as the length
  84428. increases. For the deflate format, these bits are stored backwards
  84429. from their more natural integer increment ordering, and so when the
  84430. decoding tables are built in the large loop below, the integer codes
  84431. are incremented backwards.
  84432. This routine assumes, but does not check, that all of the entries in
  84433. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84434. 1..MAXBITS is interpreted as that code length. zero means that that
  84435. symbol does not occur in this code.
  84436. The codes are sorted by computing a count of codes for each length,
  84437. creating from that a table of starting indices for each length in the
  84438. sorted table, and then entering the symbols in order in the sorted
  84439. table. The sorted table is work[], with that space being provided by
  84440. the caller.
  84441. The length counts are used for other purposes as well, i.e. finding
  84442. the minimum and maximum length codes, determining if there are any
  84443. codes at all, checking for a valid set of lengths, and looking ahead
  84444. at length counts to determine sub-table sizes when building the
  84445. decoding tables.
  84446. */
  84447. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84448. for (len = 0; len <= MAXBITS; len++)
  84449. count[len] = 0;
  84450. for (sym = 0; sym < codes; sym++)
  84451. count[lens[sym]]++;
  84452. /* bound code lengths, force root to be within code lengths */
  84453. root = *bits;
  84454. for (max = MAXBITS; max >= 1; max--)
  84455. if (count[max] != 0) break;
  84456. if (root > max) root = max;
  84457. if (max == 0) { /* no symbols to code at all */
  84458. thisx.op = (unsigned char)64; /* invalid code marker */
  84459. thisx.bits = (unsigned char)1;
  84460. thisx.val = (unsigned short)0;
  84461. *(*table)++ = thisx; /* make a table to force an error */
  84462. *(*table)++ = thisx;
  84463. *bits = 1;
  84464. return 0; /* no symbols, but wait for decoding to report error */
  84465. }
  84466. for (min = 1; min <= MAXBITS; min++)
  84467. if (count[min] != 0) break;
  84468. if (root < min) root = min;
  84469. /* check for an over-subscribed or incomplete set of lengths */
  84470. left = 1;
  84471. for (len = 1; len <= MAXBITS; len++) {
  84472. left <<= 1;
  84473. left -= count[len];
  84474. if (left < 0) return -1; /* over-subscribed */
  84475. }
  84476. if (left > 0 && (type == CODES || max != 1))
  84477. return -1; /* incomplete set */
  84478. /* generate offsets into symbol table for each length for sorting */
  84479. offs[1] = 0;
  84480. for (len = 1; len < MAXBITS; len++)
  84481. offs[len + 1] = offs[len] + count[len];
  84482. /* sort symbols by length, by symbol order within each length */
  84483. for (sym = 0; sym < codes; sym++)
  84484. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84485. /*
  84486. Create and fill in decoding tables. In this loop, the table being
  84487. filled is at next and has curr index bits. The code being used is huff
  84488. with length len. That code is converted to an index by dropping drop
  84489. bits off of the bottom. For codes where len is less than drop + curr,
  84490. those top drop + curr - len bits are incremented through all values to
  84491. fill the table with replicated entries.
  84492. root is the number of index bits for the root table. When len exceeds
  84493. root, sub-tables are created pointed to by the root entry with an index
  84494. of the low root bits of huff. This is saved in low to check for when a
  84495. new sub-table should be started. drop is zero when the root table is
  84496. being filled, and drop is root when sub-tables are being filled.
  84497. When a new sub-table is needed, it is necessary to look ahead in the
  84498. code lengths to determine what size sub-table is needed. The length
  84499. counts are used for this, and so count[] is decremented as codes are
  84500. entered in the tables.
  84501. used keeps track of how many table entries have been allocated from the
  84502. provided *table space. It is checked when a LENS table is being made
  84503. against the space in *table, ENOUGH, minus the maximum space needed by
  84504. the worst case distance code, MAXD. This should never happen, but the
  84505. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84506. This assumes that when type == LENS, bits == 9.
  84507. sym increments through all symbols, and the loop terminates when
  84508. all codes of length max, i.e. all codes, have been processed. This
  84509. routine permits incomplete codes, so another loop after this one fills
  84510. in the rest of the decoding tables with invalid code markers.
  84511. */
  84512. /* set up for code type */
  84513. switch (type) {
  84514. case CODES:
  84515. base = extra = work; /* dummy value--not used */
  84516. end = 19;
  84517. break;
  84518. case LENS:
  84519. base = lbase;
  84520. base -= 257;
  84521. extra = lext;
  84522. extra -= 257;
  84523. end = 256;
  84524. break;
  84525. default: /* DISTS */
  84526. base = dbase;
  84527. extra = dext;
  84528. end = -1;
  84529. }
  84530. /* initialize state for loop */
  84531. huff = 0; /* starting code */
  84532. sym = 0; /* starting code symbol */
  84533. len = min; /* starting code length */
  84534. next = *table; /* current table to fill in */
  84535. curr = root; /* current table index bits */
  84536. drop = 0; /* current bits to drop from code for index */
  84537. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84538. used = 1U << root; /* use root table entries */
  84539. mask = used - 1; /* mask for comparing low */
  84540. /* check available table space */
  84541. if (type == LENS && used >= ENOUGH - MAXD)
  84542. return 1;
  84543. /* process all codes and make table entries */
  84544. for (;;) {
  84545. /* create table entry */
  84546. thisx.bits = (unsigned char)(len - drop);
  84547. if ((int)(work[sym]) < end) {
  84548. thisx.op = (unsigned char)0;
  84549. thisx.val = work[sym];
  84550. }
  84551. else if ((int)(work[sym]) > end) {
  84552. thisx.op = (unsigned char)(extra[work[sym]]);
  84553. thisx.val = base[work[sym]];
  84554. }
  84555. else {
  84556. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84557. thisx.val = 0;
  84558. }
  84559. /* replicate for those indices with low len bits equal to huff */
  84560. incr = 1U << (len - drop);
  84561. fill = 1U << curr;
  84562. min = fill; /* save offset to next table */
  84563. do {
  84564. fill -= incr;
  84565. next[(huff >> drop) + fill] = thisx;
  84566. } while (fill != 0);
  84567. /* backwards increment the len-bit code huff */
  84568. incr = 1U << (len - 1);
  84569. while (huff & incr)
  84570. incr >>= 1;
  84571. if (incr != 0) {
  84572. huff &= incr - 1;
  84573. huff += incr;
  84574. }
  84575. else
  84576. huff = 0;
  84577. /* go to next symbol, update count, len */
  84578. sym++;
  84579. if (--(count[len]) == 0) {
  84580. if (len == max) break;
  84581. len = lens[work[sym]];
  84582. }
  84583. /* create new sub-table if needed */
  84584. if (len > root && (huff & mask) != low) {
  84585. /* if first time, transition to sub-tables */
  84586. if (drop == 0)
  84587. drop = root;
  84588. /* increment past last table */
  84589. next += min; /* here min is 1 << curr */
  84590. /* determine length of next table */
  84591. curr = len - drop;
  84592. left = (int)(1 << curr);
  84593. while (curr + drop < max) {
  84594. left -= count[curr + drop];
  84595. if (left <= 0) break;
  84596. curr++;
  84597. left <<= 1;
  84598. }
  84599. /* check for enough space */
  84600. used += 1U << curr;
  84601. if (type == LENS && used >= ENOUGH - MAXD)
  84602. return 1;
  84603. /* point entry in root table to sub-table */
  84604. low = huff & mask;
  84605. (*table)[low].op = (unsigned char)curr;
  84606. (*table)[low].bits = (unsigned char)root;
  84607. (*table)[low].val = (unsigned short)(next - *table);
  84608. }
  84609. }
  84610. /*
  84611. Fill in rest of table for incomplete codes. This loop is similar to the
  84612. loop above in incrementing huff for table indices. It is assumed that
  84613. len is equal to curr + drop, so there is no loop needed to increment
  84614. through high index bits. When the current sub-table is filled, the loop
  84615. drops back to the root table to fill in any remaining entries there.
  84616. */
  84617. thisx.op = (unsigned char)64; /* invalid code marker */
  84618. thisx.bits = (unsigned char)(len - drop);
  84619. thisx.val = (unsigned short)0;
  84620. while (huff != 0) {
  84621. /* when done with sub-table, drop back to root table */
  84622. if (drop != 0 && (huff & mask) != low) {
  84623. drop = 0;
  84624. len = root;
  84625. next = *table;
  84626. thisx.bits = (unsigned char)len;
  84627. }
  84628. /* put invalid code marker in table */
  84629. next[huff >> drop] = thisx;
  84630. /* backwards increment the len-bit code huff */
  84631. incr = 1U << (len - 1);
  84632. while (huff & incr)
  84633. incr >>= 1;
  84634. if (incr != 0) {
  84635. huff &= incr - 1;
  84636. huff += incr;
  84637. }
  84638. else
  84639. huff = 0;
  84640. }
  84641. /* set return parameters */
  84642. *table += used;
  84643. *bits = root;
  84644. return 0;
  84645. }
  84646. /*** End of inlined file: inftrees.c ***/
  84647. /*** Start of inlined file: trees.c ***/
  84648. /*
  84649. * ALGORITHM
  84650. *
  84651. * The "deflation" process uses several Huffman trees. The more
  84652. * common source values are represented by shorter bit sequences.
  84653. *
  84654. * Each code tree is stored in a compressed form which is itself
  84655. * a Huffman encoding of the lengths of all the code strings (in
  84656. * ascending order by source values). The actual code strings are
  84657. * reconstructed from the lengths in the inflate process, as described
  84658. * in the deflate specification.
  84659. *
  84660. * REFERENCES
  84661. *
  84662. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84663. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84664. *
  84665. * Storer, James A.
  84666. * Data Compression: Methods and Theory, pp. 49-50.
  84667. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84668. *
  84669. * Sedgewick, R.
  84670. * Algorithms, p290.
  84671. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84672. */
  84673. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84674. /* #define GEN_TREES_H */
  84675. #ifdef DEBUG
  84676. # include <ctype.h>
  84677. #endif
  84678. /* ===========================================================================
  84679. * Constants
  84680. */
  84681. #define MAX_BL_BITS 7
  84682. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84683. #define END_BLOCK 256
  84684. /* end of block literal code */
  84685. #define REP_3_6 16
  84686. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84687. #define REPZ_3_10 17
  84688. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84689. #define REPZ_11_138 18
  84690. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84691. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84692. = {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};
  84693. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84694. = {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};
  84695. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84696. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84697. local const uch bl_order[BL_CODES]
  84698. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84699. /* The lengths of the bit length codes are sent in order of decreasing
  84700. * probability, to avoid transmitting the lengths for unused bit length codes.
  84701. */
  84702. #define Buf_size (8 * 2*sizeof(char))
  84703. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84704. * more than 16 bits on some systems.)
  84705. */
  84706. /* ===========================================================================
  84707. * Local data. These are initialized only once.
  84708. */
  84709. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84710. #if defined(GEN_TREES_H) || !defined(STDC)
  84711. /* non ANSI compilers may not accept trees.h */
  84712. local ct_data static_ltree[L_CODES+2];
  84713. /* The static literal tree. Since the bit lengths are imposed, there is no
  84714. * need for the L_CODES extra codes used during heap construction. However
  84715. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84716. * below).
  84717. */
  84718. local ct_data static_dtree[D_CODES];
  84719. /* The static distance tree. (Actually a trivial tree since all codes use
  84720. * 5 bits.)
  84721. */
  84722. uch _dist_code[DIST_CODE_LEN];
  84723. /* Distance codes. The first 256 values correspond to the distances
  84724. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84725. * the 15 bit distances.
  84726. */
  84727. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84728. /* length code for each normalized match length (0 == MIN_MATCH) */
  84729. local int base_length[LENGTH_CODES];
  84730. /* First normalized length for each code (0 = MIN_MATCH) */
  84731. local int base_dist[D_CODES];
  84732. /* First normalized distance for each code (0 = distance of 1) */
  84733. #else
  84734. /*** Start of inlined file: trees.h ***/
  84735. local const ct_data static_ltree[L_CODES+2] = {
  84736. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84737. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84738. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84739. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84740. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84741. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84742. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84743. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84744. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84745. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84746. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84747. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84748. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84749. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84750. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84751. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84752. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84753. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84754. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84755. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84756. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84757. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84758. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84759. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84760. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84761. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84762. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84763. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84764. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84765. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84766. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84767. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84768. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84769. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84770. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84771. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84772. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84773. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84774. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84775. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84776. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84777. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84778. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84779. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84780. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84781. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84782. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84783. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84784. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84785. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84786. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84787. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84788. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84789. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84790. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84791. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84792. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84793. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84794. };
  84795. local const ct_data static_dtree[D_CODES] = {
  84796. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84797. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84798. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84799. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84800. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84801. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84802. };
  84803. const uch _dist_code[DIST_CODE_LEN] = {
  84804. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84805. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84806. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84807. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84808. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84809. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84810. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84811. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84812. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84813. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84814. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84815. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84816. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84817. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84818. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84819. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84820. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84821. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84822. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84823. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84824. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84825. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84826. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84827. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84828. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84829. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84830. };
  84831. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84832. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84833. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84834. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84835. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84836. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84837. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84838. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84839. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84840. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84841. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84842. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84843. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84844. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84845. };
  84846. local const int base_length[LENGTH_CODES] = {
  84847. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84848. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84849. };
  84850. local const int base_dist[D_CODES] = {
  84851. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84852. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84853. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84854. };
  84855. /*** End of inlined file: trees.h ***/
  84856. #endif /* GEN_TREES_H */
  84857. struct static_tree_desc_s {
  84858. const ct_data *static_tree; /* static tree or NULL */
  84859. const intf *extra_bits; /* extra bits for each code or NULL */
  84860. int extra_base; /* base index for extra_bits */
  84861. int elems; /* max number of elements in the tree */
  84862. int max_length; /* max bit length for the codes */
  84863. };
  84864. local static_tree_desc static_l_desc =
  84865. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84866. local static_tree_desc static_d_desc =
  84867. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84868. local static_tree_desc static_bl_desc =
  84869. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84870. /* ===========================================================================
  84871. * Local (static) routines in this file.
  84872. */
  84873. local void tr_static_init OF((void));
  84874. local void init_block OF((deflate_state *s));
  84875. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84876. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84877. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84878. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84879. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84880. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84881. local int build_bl_tree OF((deflate_state *s));
  84882. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84883. int blcodes));
  84884. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84885. ct_data *dtree));
  84886. local void set_data_type OF((deflate_state *s));
  84887. local unsigned bi_reverse OF((unsigned value, int length));
  84888. local void bi_windup OF((deflate_state *s));
  84889. local void bi_flush OF((deflate_state *s));
  84890. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84891. int header));
  84892. #ifdef GEN_TREES_H
  84893. local void gen_trees_header OF((void));
  84894. #endif
  84895. #ifndef DEBUG
  84896. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84897. /* Send a code of the given tree. c and tree must not have side effects */
  84898. #else /* DEBUG */
  84899. # define send_code(s, c, tree) \
  84900. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84901. send_bits(s, tree[c].Code, tree[c].Len); }
  84902. #endif
  84903. /* ===========================================================================
  84904. * Output a short LSB first on the stream.
  84905. * IN assertion: there is enough room in pendingBuf.
  84906. */
  84907. #define put_short(s, w) { \
  84908. put_byte(s, (uch)((w) & 0xff)); \
  84909. put_byte(s, (uch)((ush)(w) >> 8)); \
  84910. }
  84911. /* ===========================================================================
  84912. * Send a value on a given number of bits.
  84913. * IN assertion: length <= 16 and value fits in length bits.
  84914. */
  84915. #ifdef DEBUG
  84916. local void send_bits OF((deflate_state *s, int value, int length));
  84917. local void send_bits (deflate_state *s, int value, int length)
  84918. {
  84919. Tracevv((stderr," l %2d v %4x ", length, value));
  84920. Assert(length > 0 && length <= 15, "invalid length");
  84921. s->bits_sent += (ulg)length;
  84922. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84923. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84924. * unused bits in value.
  84925. */
  84926. if (s->bi_valid > (int)Buf_size - length) {
  84927. s->bi_buf |= (value << s->bi_valid);
  84928. put_short(s, s->bi_buf);
  84929. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84930. s->bi_valid += length - Buf_size;
  84931. } else {
  84932. s->bi_buf |= value << s->bi_valid;
  84933. s->bi_valid += length;
  84934. }
  84935. }
  84936. #else /* !DEBUG */
  84937. #define send_bits(s, value, length) \
  84938. { int len = length;\
  84939. if (s->bi_valid > (int)Buf_size - len) {\
  84940. int val = value;\
  84941. s->bi_buf |= (val << s->bi_valid);\
  84942. put_short(s, s->bi_buf);\
  84943. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84944. s->bi_valid += len - Buf_size;\
  84945. } else {\
  84946. s->bi_buf |= (value) << s->bi_valid;\
  84947. s->bi_valid += len;\
  84948. }\
  84949. }
  84950. #endif /* DEBUG */
  84951. /* the arguments must not have side effects */
  84952. /* ===========================================================================
  84953. * Initialize the various 'constant' tables.
  84954. */
  84955. local void tr_static_init()
  84956. {
  84957. #if defined(GEN_TREES_H) || !defined(STDC)
  84958. static int static_init_done = 0;
  84959. int n; /* iterates over tree elements */
  84960. int bits; /* bit counter */
  84961. int length; /* length value */
  84962. int code; /* code value */
  84963. int dist; /* distance index */
  84964. ush bl_count[MAX_BITS+1];
  84965. /* number of codes at each bit length for an optimal tree */
  84966. if (static_init_done) return;
  84967. /* For some embedded targets, global variables are not initialized: */
  84968. static_l_desc.static_tree = static_ltree;
  84969. static_l_desc.extra_bits = extra_lbits;
  84970. static_d_desc.static_tree = static_dtree;
  84971. static_d_desc.extra_bits = extra_dbits;
  84972. static_bl_desc.extra_bits = extra_blbits;
  84973. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84974. length = 0;
  84975. for (code = 0; code < LENGTH_CODES-1; code++) {
  84976. base_length[code] = length;
  84977. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84978. _length_code[length++] = (uch)code;
  84979. }
  84980. }
  84981. Assert (length == 256, "tr_static_init: length != 256");
  84982. /* Note that the length 255 (match length 258) can be represented
  84983. * in two different ways: code 284 + 5 bits or code 285, so we
  84984. * overwrite length_code[255] to use the best encoding:
  84985. */
  84986. _length_code[length-1] = (uch)code;
  84987. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84988. dist = 0;
  84989. for (code = 0 ; code < 16; code++) {
  84990. base_dist[code] = dist;
  84991. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84992. _dist_code[dist++] = (uch)code;
  84993. }
  84994. }
  84995. Assert (dist == 256, "tr_static_init: dist != 256");
  84996. dist >>= 7; /* from now on, all distances are divided by 128 */
  84997. for ( ; code < D_CODES; code++) {
  84998. base_dist[code] = dist << 7;
  84999. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85000. _dist_code[256 + dist++] = (uch)code;
  85001. }
  85002. }
  85003. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85004. /* Construct the codes of the static literal tree */
  85005. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85006. n = 0;
  85007. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85008. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85009. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85010. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85011. /* Codes 286 and 287 do not exist, but we must include them in the
  85012. * tree construction to get a canonical Huffman tree (longest code
  85013. * all ones)
  85014. */
  85015. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85016. /* The static distance tree is trivial: */
  85017. for (n = 0; n < D_CODES; n++) {
  85018. static_dtree[n].Len = 5;
  85019. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85020. }
  85021. static_init_done = 1;
  85022. # ifdef GEN_TREES_H
  85023. gen_trees_header();
  85024. # endif
  85025. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85026. }
  85027. /* ===========================================================================
  85028. * Genererate the file trees.h describing the static trees.
  85029. */
  85030. #ifdef GEN_TREES_H
  85031. # ifndef DEBUG
  85032. # include <stdio.h>
  85033. # endif
  85034. # define SEPARATOR(i, last, width) \
  85035. ((i) == (last)? "\n};\n\n" : \
  85036. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85037. void gen_trees_header()
  85038. {
  85039. FILE *header = fopen("trees.h", "w");
  85040. int i;
  85041. Assert (header != NULL, "Can't open trees.h");
  85042. fprintf(header,
  85043. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85044. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85045. for (i = 0; i < L_CODES+2; i++) {
  85046. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85047. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85048. }
  85049. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85050. for (i = 0; i < D_CODES; i++) {
  85051. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85052. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85053. }
  85054. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85055. for (i = 0; i < DIST_CODE_LEN; i++) {
  85056. fprintf(header, "%2u%s", _dist_code[i],
  85057. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85058. }
  85059. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85060. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85061. fprintf(header, "%2u%s", _length_code[i],
  85062. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85063. }
  85064. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85065. for (i = 0; i < LENGTH_CODES; i++) {
  85066. fprintf(header, "%1u%s", base_length[i],
  85067. SEPARATOR(i, LENGTH_CODES-1, 20));
  85068. }
  85069. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85070. for (i = 0; i < D_CODES; i++) {
  85071. fprintf(header, "%5u%s", base_dist[i],
  85072. SEPARATOR(i, D_CODES-1, 10));
  85073. }
  85074. fclose(header);
  85075. }
  85076. #endif /* GEN_TREES_H */
  85077. /* ===========================================================================
  85078. * Initialize the tree data structures for a new zlib stream.
  85079. */
  85080. void _tr_init(deflate_state *s)
  85081. {
  85082. tr_static_init();
  85083. s->l_desc.dyn_tree = s->dyn_ltree;
  85084. s->l_desc.stat_desc = &static_l_desc;
  85085. s->d_desc.dyn_tree = s->dyn_dtree;
  85086. s->d_desc.stat_desc = &static_d_desc;
  85087. s->bl_desc.dyn_tree = s->bl_tree;
  85088. s->bl_desc.stat_desc = &static_bl_desc;
  85089. s->bi_buf = 0;
  85090. s->bi_valid = 0;
  85091. s->last_eob_len = 8; /* enough lookahead for inflate */
  85092. #ifdef DEBUG
  85093. s->compressed_len = 0L;
  85094. s->bits_sent = 0L;
  85095. #endif
  85096. /* Initialize the first block of the first file: */
  85097. init_block(s);
  85098. }
  85099. /* ===========================================================================
  85100. * Initialize a new block.
  85101. */
  85102. local void init_block (deflate_state *s)
  85103. {
  85104. int n; /* iterates over tree elements */
  85105. /* Initialize the trees. */
  85106. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85107. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85108. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85109. s->dyn_ltree[END_BLOCK].Freq = 1;
  85110. s->opt_len = s->static_len = 0L;
  85111. s->last_lit = s->matches = 0;
  85112. }
  85113. #define SMALLEST 1
  85114. /* Index within the heap array of least frequent node in the Huffman tree */
  85115. /* ===========================================================================
  85116. * Remove the smallest element from the heap and recreate the heap with
  85117. * one less element. Updates heap and heap_len.
  85118. */
  85119. #define pqremove(s, tree, top) \
  85120. {\
  85121. top = s->heap[SMALLEST]; \
  85122. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85123. pqdownheap(s, tree, SMALLEST); \
  85124. }
  85125. /* ===========================================================================
  85126. * Compares to subtrees, using the tree depth as tie breaker when
  85127. * the subtrees have equal frequency. This minimizes the worst case length.
  85128. */
  85129. #define smaller(tree, n, m, depth) \
  85130. (tree[n].Freq < tree[m].Freq || \
  85131. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85132. /* ===========================================================================
  85133. * Restore the heap property by moving down the tree starting at node k,
  85134. * exchanging a node with the smallest of its two sons if necessary, stopping
  85135. * when the heap property is re-established (each father smaller than its
  85136. * two sons).
  85137. */
  85138. local void pqdownheap (deflate_state *s,
  85139. ct_data *tree, /* the tree to restore */
  85140. int k) /* node to move down */
  85141. {
  85142. int v = s->heap[k];
  85143. int j = k << 1; /* left son of k */
  85144. while (j <= s->heap_len) {
  85145. /* Set j to the smallest of the two sons: */
  85146. if (j < s->heap_len &&
  85147. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85148. j++;
  85149. }
  85150. /* Exit if v is smaller than both sons */
  85151. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85152. /* Exchange v with the smallest son */
  85153. s->heap[k] = s->heap[j]; k = j;
  85154. /* And continue down the tree, setting j to the left son of k */
  85155. j <<= 1;
  85156. }
  85157. s->heap[k] = v;
  85158. }
  85159. /* ===========================================================================
  85160. * Compute the optimal bit lengths for a tree and update the total bit length
  85161. * for the current block.
  85162. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85163. * above are the tree nodes sorted by increasing frequency.
  85164. * OUT assertions: the field len is set to the optimal bit length, the
  85165. * array bl_count contains the frequencies for each bit length.
  85166. * The length opt_len is updated; static_len is also updated if stree is
  85167. * not null.
  85168. */
  85169. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85170. {
  85171. ct_data *tree = desc->dyn_tree;
  85172. int max_code = desc->max_code;
  85173. const ct_data *stree = desc->stat_desc->static_tree;
  85174. const intf *extra = desc->stat_desc->extra_bits;
  85175. int base = desc->stat_desc->extra_base;
  85176. int max_length = desc->stat_desc->max_length;
  85177. int h; /* heap index */
  85178. int n, m; /* iterate over the tree elements */
  85179. int bits; /* bit length */
  85180. int xbits; /* extra bits */
  85181. ush f; /* frequency */
  85182. int overflow = 0; /* number of elements with bit length too large */
  85183. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85184. /* In a first pass, compute the optimal bit lengths (which may
  85185. * overflow in the case of the bit length tree).
  85186. */
  85187. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85188. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85189. n = s->heap[h];
  85190. bits = tree[tree[n].Dad].Len + 1;
  85191. if (bits > max_length) bits = max_length, overflow++;
  85192. tree[n].Len = (ush)bits;
  85193. /* We overwrite tree[n].Dad which is no longer needed */
  85194. if (n > max_code) continue; /* not a leaf node */
  85195. s->bl_count[bits]++;
  85196. xbits = 0;
  85197. if (n >= base) xbits = extra[n-base];
  85198. f = tree[n].Freq;
  85199. s->opt_len += (ulg)f * (bits + xbits);
  85200. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85201. }
  85202. if (overflow == 0) return;
  85203. Trace((stderr,"\nbit length overflow\n"));
  85204. /* This happens for example on obj2 and pic of the Calgary corpus */
  85205. /* Find the first bit length which could increase: */
  85206. do {
  85207. bits = max_length-1;
  85208. while (s->bl_count[bits] == 0) bits--;
  85209. s->bl_count[bits]--; /* move one leaf down the tree */
  85210. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85211. s->bl_count[max_length]--;
  85212. /* The brother of the overflow item also moves one step up,
  85213. * but this does not affect bl_count[max_length]
  85214. */
  85215. overflow -= 2;
  85216. } while (overflow > 0);
  85217. /* Now recompute all bit lengths, scanning in increasing frequency.
  85218. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85219. * lengths instead of fixing only the wrong ones. This idea is taken
  85220. * from 'ar' written by Haruhiko Okumura.)
  85221. */
  85222. for (bits = max_length; bits != 0; bits--) {
  85223. n = s->bl_count[bits];
  85224. while (n != 0) {
  85225. m = s->heap[--h];
  85226. if (m > max_code) continue;
  85227. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85228. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85229. s->opt_len += ((long)bits - (long)tree[m].Len)
  85230. *(long)tree[m].Freq;
  85231. tree[m].Len = (ush)bits;
  85232. }
  85233. n--;
  85234. }
  85235. }
  85236. }
  85237. /* ===========================================================================
  85238. * Generate the codes for a given tree and bit counts (which need not be
  85239. * optimal).
  85240. * IN assertion: the array bl_count contains the bit length statistics for
  85241. * the given tree and the field len is set for all tree elements.
  85242. * OUT assertion: the field code is set for all tree elements of non
  85243. * zero code length.
  85244. */
  85245. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85246. int max_code, /* largest code with non zero frequency */
  85247. ushf *bl_count) /* number of codes at each bit length */
  85248. {
  85249. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85250. ush code = 0; /* running code value */
  85251. int bits; /* bit index */
  85252. int n; /* code index */
  85253. /* The distribution counts are first used to generate the code values
  85254. * without bit reversal.
  85255. */
  85256. for (bits = 1; bits <= MAX_BITS; bits++) {
  85257. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85258. }
  85259. /* Check that the bit counts in bl_count are consistent. The last code
  85260. * must be all ones.
  85261. */
  85262. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85263. "inconsistent bit counts");
  85264. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85265. for (n = 0; n <= max_code; n++) {
  85266. int len = tree[n].Len;
  85267. if (len == 0) continue;
  85268. /* Now reverse the bits */
  85269. tree[n].Code = bi_reverse(next_code[len]++, len);
  85270. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85271. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85272. }
  85273. }
  85274. /* ===========================================================================
  85275. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85276. * Update the total bit length for the current block.
  85277. * IN assertion: the field freq is set for all tree elements.
  85278. * OUT assertions: the fields len and code are set to the optimal bit length
  85279. * and corresponding code. The length opt_len is updated; static_len is
  85280. * also updated if stree is not null. The field max_code is set.
  85281. */
  85282. local void build_tree (deflate_state *s,
  85283. tree_desc *desc) /* the tree descriptor */
  85284. {
  85285. ct_data *tree = desc->dyn_tree;
  85286. const ct_data *stree = desc->stat_desc->static_tree;
  85287. int elems = desc->stat_desc->elems;
  85288. int n, m; /* iterate over heap elements */
  85289. int max_code = -1; /* largest code with non zero frequency */
  85290. int node; /* new node being created */
  85291. /* Construct the initial heap, with least frequent element in
  85292. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85293. * heap[0] is not used.
  85294. */
  85295. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85296. for (n = 0; n < elems; n++) {
  85297. if (tree[n].Freq != 0) {
  85298. s->heap[++(s->heap_len)] = max_code = n;
  85299. s->depth[n] = 0;
  85300. } else {
  85301. tree[n].Len = 0;
  85302. }
  85303. }
  85304. /* The pkzip format requires that at least one distance code exists,
  85305. * and that at least one bit should be sent even if there is only one
  85306. * possible code. So to avoid special checks later on we force at least
  85307. * two codes of non zero frequency.
  85308. */
  85309. while (s->heap_len < 2) {
  85310. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85311. tree[node].Freq = 1;
  85312. s->depth[node] = 0;
  85313. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85314. /* node is 0 or 1 so it does not have extra bits */
  85315. }
  85316. desc->max_code = max_code;
  85317. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85318. * establish sub-heaps of increasing lengths:
  85319. */
  85320. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85321. /* Construct the Huffman tree by repeatedly combining the least two
  85322. * frequent nodes.
  85323. */
  85324. node = elems; /* next internal node of the tree */
  85325. do {
  85326. pqremove(s, tree, n); /* n = node of least frequency */
  85327. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85328. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85329. s->heap[--(s->heap_max)] = m;
  85330. /* Create a new node father of n and m */
  85331. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85332. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85333. s->depth[n] : s->depth[m]) + 1);
  85334. tree[n].Dad = tree[m].Dad = (ush)node;
  85335. #ifdef DUMP_BL_TREE
  85336. if (tree == s->bl_tree) {
  85337. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85338. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85339. }
  85340. #endif
  85341. /* and insert the new node in the heap */
  85342. s->heap[SMALLEST] = node++;
  85343. pqdownheap(s, tree, SMALLEST);
  85344. } while (s->heap_len >= 2);
  85345. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85346. /* At this point, the fields freq and dad are set. We can now
  85347. * generate the bit lengths.
  85348. */
  85349. gen_bitlen(s, (tree_desc *)desc);
  85350. /* The field len is now set, we can generate the bit codes */
  85351. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85352. }
  85353. /* ===========================================================================
  85354. * Scan a literal or distance tree to determine the frequencies of the codes
  85355. * in the bit length tree.
  85356. */
  85357. local void scan_tree (deflate_state *s,
  85358. ct_data *tree, /* the tree to be scanned */
  85359. int max_code) /* and its largest code of non zero frequency */
  85360. {
  85361. int n; /* iterates over all tree elements */
  85362. int prevlen = -1; /* last emitted length */
  85363. int curlen; /* length of current code */
  85364. int nextlen = tree[0].Len; /* length of next code */
  85365. int count = 0; /* repeat count of the current code */
  85366. int max_count = 7; /* max repeat count */
  85367. int min_count = 4; /* min repeat count */
  85368. if (nextlen == 0) max_count = 138, min_count = 3;
  85369. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85370. for (n = 0; n <= max_code; n++) {
  85371. curlen = nextlen; nextlen = tree[n+1].Len;
  85372. if (++count < max_count && curlen == nextlen) {
  85373. continue;
  85374. } else if (count < min_count) {
  85375. s->bl_tree[curlen].Freq += count;
  85376. } else if (curlen != 0) {
  85377. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85378. s->bl_tree[REP_3_6].Freq++;
  85379. } else if (count <= 10) {
  85380. s->bl_tree[REPZ_3_10].Freq++;
  85381. } else {
  85382. s->bl_tree[REPZ_11_138].Freq++;
  85383. }
  85384. count = 0; prevlen = curlen;
  85385. if (nextlen == 0) {
  85386. max_count = 138, min_count = 3;
  85387. } else if (curlen == nextlen) {
  85388. max_count = 6, min_count = 3;
  85389. } else {
  85390. max_count = 7, min_count = 4;
  85391. }
  85392. }
  85393. }
  85394. /* ===========================================================================
  85395. * Send a literal or distance tree in compressed form, using the codes in
  85396. * bl_tree.
  85397. */
  85398. local void send_tree (deflate_state *s,
  85399. ct_data *tree, /* the tree to be scanned */
  85400. int max_code) /* and its largest code of non zero frequency */
  85401. {
  85402. int n; /* iterates over all tree elements */
  85403. int prevlen = -1; /* last emitted length */
  85404. int curlen; /* length of current code */
  85405. int nextlen = tree[0].Len; /* length of next code */
  85406. int count = 0; /* repeat count of the current code */
  85407. int max_count = 7; /* max repeat count */
  85408. int min_count = 4; /* min repeat count */
  85409. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85410. if (nextlen == 0) max_count = 138, min_count = 3;
  85411. for (n = 0; n <= max_code; n++) {
  85412. curlen = nextlen; nextlen = tree[n+1].Len;
  85413. if (++count < max_count && curlen == nextlen) {
  85414. continue;
  85415. } else if (count < min_count) {
  85416. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85417. } else if (curlen != 0) {
  85418. if (curlen != prevlen) {
  85419. send_code(s, curlen, s->bl_tree); count--;
  85420. }
  85421. Assert(count >= 3 && count <= 6, " 3_6?");
  85422. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85423. } else if (count <= 10) {
  85424. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85425. } else {
  85426. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85427. }
  85428. count = 0; prevlen = curlen;
  85429. if (nextlen == 0) {
  85430. max_count = 138, min_count = 3;
  85431. } else if (curlen == nextlen) {
  85432. max_count = 6, min_count = 3;
  85433. } else {
  85434. max_count = 7, min_count = 4;
  85435. }
  85436. }
  85437. }
  85438. /* ===========================================================================
  85439. * Construct the Huffman tree for the bit lengths and return the index in
  85440. * bl_order of the last bit length code to send.
  85441. */
  85442. local int build_bl_tree (deflate_state *s)
  85443. {
  85444. int max_blindex; /* index of last bit length code of non zero freq */
  85445. /* Determine the bit length frequencies for literal and distance trees */
  85446. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85447. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85448. /* Build the bit length tree: */
  85449. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85450. /* opt_len now includes the length of the tree representations, except
  85451. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85452. */
  85453. /* Determine the number of bit length codes to send. The pkzip format
  85454. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85455. * 3 but the actual value used is 4.)
  85456. */
  85457. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85458. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85459. }
  85460. /* Update opt_len to include the bit length tree and counts */
  85461. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85462. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85463. s->opt_len, s->static_len));
  85464. return max_blindex;
  85465. }
  85466. /* ===========================================================================
  85467. * Send the header for a block using dynamic Huffman trees: the counts, the
  85468. * lengths of the bit length codes, the literal tree and the distance tree.
  85469. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85470. */
  85471. local void send_all_trees (deflate_state *s,
  85472. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85473. {
  85474. int rank; /* index in bl_order */
  85475. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85476. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85477. "too many codes");
  85478. Tracev((stderr, "\nbl counts: "));
  85479. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85480. send_bits(s, dcodes-1, 5);
  85481. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85482. for (rank = 0; rank < blcodes; rank++) {
  85483. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85484. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85485. }
  85486. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85487. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85488. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85489. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85490. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85491. }
  85492. /* ===========================================================================
  85493. * Send a stored block
  85494. */
  85495. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85496. {
  85497. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85498. #ifdef DEBUG
  85499. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85500. s->compressed_len += (stored_len + 4) << 3;
  85501. #endif
  85502. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85503. }
  85504. /* ===========================================================================
  85505. * Send one empty static block to give enough lookahead for inflate.
  85506. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85507. * The current inflate code requires 9 bits of lookahead. If the
  85508. * last two codes for the previous block (real code plus EOB) were coded
  85509. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85510. * the last real code. In this case we send two empty static blocks instead
  85511. * of one. (There are no problems if the previous block is stored or fixed.)
  85512. * To simplify the code, we assume the worst case of last real code encoded
  85513. * on one bit only.
  85514. */
  85515. void _tr_align (deflate_state *s)
  85516. {
  85517. send_bits(s, STATIC_TREES<<1, 3);
  85518. send_code(s, END_BLOCK, static_ltree);
  85519. #ifdef DEBUG
  85520. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85521. #endif
  85522. bi_flush(s);
  85523. /* Of the 10 bits for the empty block, we have already sent
  85524. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85525. * the EOB of the previous block) was thus at least one plus the length
  85526. * of the EOB plus what we have just sent of the empty static block.
  85527. */
  85528. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85529. send_bits(s, STATIC_TREES<<1, 3);
  85530. send_code(s, END_BLOCK, static_ltree);
  85531. #ifdef DEBUG
  85532. s->compressed_len += 10L;
  85533. #endif
  85534. bi_flush(s);
  85535. }
  85536. s->last_eob_len = 7;
  85537. }
  85538. /* ===========================================================================
  85539. * Determine the best encoding for the current block: dynamic trees, static
  85540. * trees or store, and output the encoded block to the zip file.
  85541. */
  85542. void _tr_flush_block (deflate_state *s,
  85543. charf *buf, /* input block, or NULL if too old */
  85544. ulg stored_len, /* length of input block */
  85545. int eof) /* true if this is the last block for a file */
  85546. {
  85547. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85548. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85549. /* Build the Huffman trees unless a stored block is forced */
  85550. if (s->level > 0) {
  85551. /* Check if the file is binary or text */
  85552. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85553. set_data_type(s);
  85554. /* Construct the literal and distance trees */
  85555. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85556. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85557. s->static_len));
  85558. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85559. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85560. s->static_len));
  85561. /* At this point, opt_len and static_len are the total bit lengths of
  85562. * the compressed block data, excluding the tree representations.
  85563. */
  85564. /* Build the bit length tree for the above two trees, and get the index
  85565. * in bl_order of the last bit length code to send.
  85566. */
  85567. max_blindex = build_bl_tree(s);
  85568. /* Determine the best encoding. Compute the block lengths in bytes. */
  85569. opt_lenb = (s->opt_len+3+7)>>3;
  85570. static_lenb = (s->static_len+3+7)>>3;
  85571. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85572. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85573. s->last_lit));
  85574. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85575. } else {
  85576. Assert(buf != (char*)0, "lost buf");
  85577. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85578. }
  85579. #ifdef FORCE_STORED
  85580. if (buf != (char*)0) { /* force stored block */
  85581. #else
  85582. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85583. /* 4: two words for the lengths */
  85584. #endif
  85585. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85586. * Otherwise we can't have processed more than WSIZE input bytes since
  85587. * the last block flush, because compression would have been
  85588. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85589. * transform a block into a stored block.
  85590. */
  85591. _tr_stored_block(s, buf, stored_len, eof);
  85592. #ifdef FORCE_STATIC
  85593. } else if (static_lenb >= 0) { /* force static trees */
  85594. #else
  85595. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85596. #endif
  85597. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85598. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85599. #ifdef DEBUG
  85600. s->compressed_len += 3 + s->static_len;
  85601. #endif
  85602. } else {
  85603. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85604. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85605. max_blindex+1);
  85606. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85607. #ifdef DEBUG
  85608. s->compressed_len += 3 + s->opt_len;
  85609. #endif
  85610. }
  85611. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85612. /* The above check is made mod 2^32, for files larger than 512 MB
  85613. * and uLong implemented on 32 bits.
  85614. */
  85615. init_block(s);
  85616. if (eof) {
  85617. bi_windup(s);
  85618. #ifdef DEBUG
  85619. s->compressed_len += 7; /* align on byte boundary */
  85620. #endif
  85621. }
  85622. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85623. s->compressed_len-7*eof));
  85624. }
  85625. /* ===========================================================================
  85626. * Save the match info and tally the frequency counts. Return true if
  85627. * the current block must be flushed.
  85628. */
  85629. int _tr_tally (deflate_state *s,
  85630. unsigned dist, /* distance of matched string */
  85631. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85632. {
  85633. s->d_buf[s->last_lit] = (ush)dist;
  85634. s->l_buf[s->last_lit++] = (uch)lc;
  85635. if (dist == 0) {
  85636. /* lc is the unmatched char */
  85637. s->dyn_ltree[lc].Freq++;
  85638. } else {
  85639. s->matches++;
  85640. /* Here, lc is the match length - MIN_MATCH */
  85641. dist--; /* dist = match distance - 1 */
  85642. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85643. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85644. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85645. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85646. s->dyn_dtree[d_code(dist)].Freq++;
  85647. }
  85648. #ifdef TRUNCATE_BLOCK
  85649. /* Try to guess if it is profitable to stop the current block here */
  85650. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85651. /* Compute an upper bound for the compressed length */
  85652. ulg out_length = (ulg)s->last_lit*8L;
  85653. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85654. int dcode;
  85655. for (dcode = 0; dcode < D_CODES; dcode++) {
  85656. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85657. (5L+extra_dbits[dcode]);
  85658. }
  85659. out_length >>= 3;
  85660. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85661. s->last_lit, in_length, out_length,
  85662. 100L - out_length*100L/in_length));
  85663. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85664. }
  85665. #endif
  85666. return (s->last_lit == s->lit_bufsize-1);
  85667. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85668. * on 16 bit machines and because stored blocks are restricted to
  85669. * 64K-1 bytes.
  85670. */
  85671. }
  85672. /* ===========================================================================
  85673. * Send the block data compressed using the given Huffman trees
  85674. */
  85675. local void compress_block (deflate_state *s,
  85676. ct_data *ltree, /* literal tree */
  85677. ct_data *dtree) /* distance tree */
  85678. {
  85679. unsigned dist; /* distance of matched string */
  85680. int lc; /* match length or unmatched char (if dist == 0) */
  85681. unsigned lx = 0; /* running index in l_buf */
  85682. unsigned code; /* the code to send */
  85683. int extra; /* number of extra bits to send */
  85684. if (s->last_lit != 0) do {
  85685. dist = s->d_buf[lx];
  85686. lc = s->l_buf[lx++];
  85687. if (dist == 0) {
  85688. send_code(s, lc, ltree); /* send a literal byte */
  85689. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85690. } else {
  85691. /* Here, lc is the match length - MIN_MATCH */
  85692. code = _length_code[lc];
  85693. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85694. extra = extra_lbits[code];
  85695. if (extra != 0) {
  85696. lc -= base_length[code];
  85697. send_bits(s, lc, extra); /* send the extra length bits */
  85698. }
  85699. dist--; /* dist is now the match distance - 1 */
  85700. code = d_code(dist);
  85701. Assert (code < D_CODES, "bad d_code");
  85702. send_code(s, code, dtree); /* send the distance code */
  85703. extra = extra_dbits[code];
  85704. if (extra != 0) {
  85705. dist -= base_dist[code];
  85706. send_bits(s, dist, extra); /* send the extra distance bits */
  85707. }
  85708. } /* literal or match pair ? */
  85709. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85710. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85711. "pendingBuf overflow");
  85712. } while (lx < s->last_lit);
  85713. send_code(s, END_BLOCK, ltree);
  85714. s->last_eob_len = ltree[END_BLOCK].Len;
  85715. }
  85716. /* ===========================================================================
  85717. * Set the data type to BINARY or TEXT, using a crude approximation:
  85718. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85719. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85720. * IN assertion: the fields Freq of dyn_ltree are set.
  85721. */
  85722. local void set_data_type (deflate_state *s)
  85723. {
  85724. int n;
  85725. for (n = 0; n < 9; n++)
  85726. if (s->dyn_ltree[n].Freq != 0)
  85727. break;
  85728. if (n == 9)
  85729. for (n = 14; n < 32; n++)
  85730. if (s->dyn_ltree[n].Freq != 0)
  85731. break;
  85732. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85733. }
  85734. /* ===========================================================================
  85735. * Reverse the first len bits of a code, using straightforward code (a faster
  85736. * method would use a table)
  85737. * IN assertion: 1 <= len <= 15
  85738. */
  85739. local unsigned bi_reverse (unsigned code, int len)
  85740. {
  85741. register unsigned res = 0;
  85742. do {
  85743. res |= code & 1;
  85744. code >>= 1, res <<= 1;
  85745. } while (--len > 0);
  85746. return res >> 1;
  85747. }
  85748. /* ===========================================================================
  85749. * Flush the bit buffer, keeping at most 7 bits in it.
  85750. */
  85751. local void bi_flush (deflate_state *s)
  85752. {
  85753. if (s->bi_valid == 16) {
  85754. put_short(s, s->bi_buf);
  85755. s->bi_buf = 0;
  85756. s->bi_valid = 0;
  85757. } else if (s->bi_valid >= 8) {
  85758. put_byte(s, (Byte)s->bi_buf);
  85759. s->bi_buf >>= 8;
  85760. s->bi_valid -= 8;
  85761. }
  85762. }
  85763. /* ===========================================================================
  85764. * Flush the bit buffer and align the output on a byte boundary
  85765. */
  85766. local void bi_windup (deflate_state *s)
  85767. {
  85768. if (s->bi_valid > 8) {
  85769. put_short(s, s->bi_buf);
  85770. } else if (s->bi_valid > 0) {
  85771. put_byte(s, (Byte)s->bi_buf);
  85772. }
  85773. s->bi_buf = 0;
  85774. s->bi_valid = 0;
  85775. #ifdef DEBUG
  85776. s->bits_sent = (s->bits_sent+7) & ~7;
  85777. #endif
  85778. }
  85779. /* ===========================================================================
  85780. * Copy a stored block, storing first the length and its
  85781. * one's complement if requested.
  85782. */
  85783. local void copy_block(deflate_state *s,
  85784. charf *buf, /* the input data */
  85785. unsigned len, /* its length */
  85786. int header) /* true if block header must be written */
  85787. {
  85788. bi_windup(s); /* align on byte boundary */
  85789. s->last_eob_len = 8; /* enough lookahead for inflate */
  85790. if (header) {
  85791. put_short(s, (ush)len);
  85792. put_short(s, (ush)~len);
  85793. #ifdef DEBUG
  85794. s->bits_sent += 2*16;
  85795. #endif
  85796. }
  85797. #ifdef DEBUG
  85798. s->bits_sent += (ulg)len<<3;
  85799. #endif
  85800. while (len--) {
  85801. put_byte(s, *buf++);
  85802. }
  85803. }
  85804. /*** End of inlined file: trees.c ***/
  85805. /*** Start of inlined file: zutil.c ***/
  85806. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85807. #ifndef NO_DUMMY_DECL
  85808. struct internal_state {int dummy;}; /* for buggy compilers */
  85809. #endif
  85810. const char * const z_errmsg[10] = {
  85811. "need dictionary", /* Z_NEED_DICT 2 */
  85812. "stream end", /* Z_STREAM_END 1 */
  85813. "", /* Z_OK 0 */
  85814. "file error", /* Z_ERRNO (-1) */
  85815. "stream error", /* Z_STREAM_ERROR (-2) */
  85816. "data error", /* Z_DATA_ERROR (-3) */
  85817. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85818. "buffer error", /* Z_BUF_ERROR (-5) */
  85819. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85820. ""};
  85821. /*const char * ZEXPORT zlibVersion()
  85822. {
  85823. return ZLIB_VERSION;
  85824. }
  85825. uLong ZEXPORT zlibCompileFlags()
  85826. {
  85827. uLong flags;
  85828. flags = 0;
  85829. switch (sizeof(uInt)) {
  85830. case 2: break;
  85831. case 4: flags += 1; break;
  85832. case 8: flags += 2; break;
  85833. default: flags += 3;
  85834. }
  85835. switch (sizeof(uLong)) {
  85836. case 2: break;
  85837. case 4: flags += 1 << 2; break;
  85838. case 8: flags += 2 << 2; break;
  85839. default: flags += 3 << 2;
  85840. }
  85841. switch (sizeof(voidpf)) {
  85842. case 2: break;
  85843. case 4: flags += 1 << 4; break;
  85844. case 8: flags += 2 << 4; break;
  85845. default: flags += 3 << 4;
  85846. }
  85847. switch (sizeof(z_off_t)) {
  85848. case 2: break;
  85849. case 4: flags += 1 << 6; break;
  85850. case 8: flags += 2 << 6; break;
  85851. default: flags += 3 << 6;
  85852. }
  85853. #ifdef DEBUG
  85854. flags += 1 << 8;
  85855. #endif
  85856. #if defined(ASMV) || defined(ASMINF)
  85857. flags += 1 << 9;
  85858. #endif
  85859. #ifdef ZLIB_WINAPI
  85860. flags += 1 << 10;
  85861. #endif
  85862. #ifdef BUILDFIXED
  85863. flags += 1 << 12;
  85864. #endif
  85865. #ifdef DYNAMIC_CRC_TABLE
  85866. flags += 1 << 13;
  85867. #endif
  85868. #ifdef NO_GZCOMPRESS
  85869. flags += 1L << 16;
  85870. #endif
  85871. #ifdef NO_GZIP
  85872. flags += 1L << 17;
  85873. #endif
  85874. #ifdef PKZIP_BUG_WORKAROUND
  85875. flags += 1L << 20;
  85876. #endif
  85877. #ifdef FASTEST
  85878. flags += 1L << 21;
  85879. #endif
  85880. #ifdef STDC
  85881. # ifdef NO_vsnprintf
  85882. flags += 1L << 25;
  85883. # ifdef HAS_vsprintf_void
  85884. flags += 1L << 26;
  85885. # endif
  85886. # else
  85887. # ifdef HAS_vsnprintf_void
  85888. flags += 1L << 26;
  85889. # endif
  85890. # endif
  85891. #else
  85892. flags += 1L << 24;
  85893. # ifdef NO_snprintf
  85894. flags += 1L << 25;
  85895. # ifdef HAS_sprintf_void
  85896. flags += 1L << 26;
  85897. # endif
  85898. # else
  85899. # ifdef HAS_snprintf_void
  85900. flags += 1L << 26;
  85901. # endif
  85902. # endif
  85903. #endif
  85904. return flags;
  85905. }*/
  85906. #ifdef DEBUG
  85907. # ifndef verbose
  85908. # define verbose 0
  85909. # endif
  85910. int z_verbose = verbose;
  85911. void z_error (const char *m)
  85912. {
  85913. fprintf(stderr, "%s\n", m);
  85914. exit(1);
  85915. }
  85916. #endif
  85917. /* exported to allow conversion of error code to string for compress() and
  85918. * uncompress()
  85919. */
  85920. const char * ZEXPORT zError(int err)
  85921. {
  85922. return ERR_MSG(err);
  85923. }
  85924. #if defined(_WIN32_WCE)
  85925. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85926. * errno. We define it as a global variable to simplify porting.
  85927. * Its value is always 0 and should not be used.
  85928. */
  85929. int errno = 0;
  85930. #endif
  85931. #ifndef HAVE_MEMCPY
  85932. void zmemcpy(dest, source, len)
  85933. Bytef* dest;
  85934. const Bytef* source;
  85935. uInt len;
  85936. {
  85937. if (len == 0) return;
  85938. do {
  85939. *dest++ = *source++; /* ??? to be unrolled */
  85940. } while (--len != 0);
  85941. }
  85942. int zmemcmp(s1, s2, len)
  85943. const Bytef* s1;
  85944. const Bytef* s2;
  85945. uInt len;
  85946. {
  85947. uInt j;
  85948. for (j = 0; j < len; j++) {
  85949. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85950. }
  85951. return 0;
  85952. }
  85953. void zmemzero(dest, len)
  85954. Bytef* dest;
  85955. uInt len;
  85956. {
  85957. if (len == 0) return;
  85958. do {
  85959. *dest++ = 0; /* ??? to be unrolled */
  85960. } while (--len != 0);
  85961. }
  85962. #endif
  85963. #ifdef SYS16BIT
  85964. #ifdef __TURBOC__
  85965. /* Turbo C in 16-bit mode */
  85966. # define MY_ZCALLOC
  85967. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85968. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85969. * must fix the pointer. Warning: the pointer must be put back to its
  85970. * original form in order to free it, use zcfree().
  85971. */
  85972. #define MAX_PTR 10
  85973. /* 10*64K = 640K */
  85974. local int next_ptr = 0;
  85975. typedef struct ptr_table_s {
  85976. voidpf org_ptr;
  85977. voidpf new_ptr;
  85978. } ptr_table;
  85979. local ptr_table table[MAX_PTR];
  85980. /* This table is used to remember the original form of pointers
  85981. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85982. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85983. * protected from concurrent access. This hack doesn't work anyway on
  85984. * a protected system like OS/2. Use Microsoft C instead.
  85985. */
  85986. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85987. {
  85988. voidpf buf = opaque; /* just to make some compilers happy */
  85989. ulg bsize = (ulg)items*size;
  85990. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85991. * will return a usable pointer which doesn't have to be normalized.
  85992. */
  85993. if (bsize < 65520L) {
  85994. buf = farmalloc(bsize);
  85995. if (*(ush*)&buf != 0) return buf;
  85996. } else {
  85997. buf = farmalloc(bsize + 16L);
  85998. }
  85999. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86000. table[next_ptr].org_ptr = buf;
  86001. /* Normalize the pointer to seg:0 */
  86002. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86003. *(ush*)&buf = 0;
  86004. table[next_ptr++].new_ptr = buf;
  86005. return buf;
  86006. }
  86007. void zcfree (voidpf opaque, voidpf ptr)
  86008. {
  86009. int n;
  86010. if (*(ush*)&ptr != 0) { /* object < 64K */
  86011. farfree(ptr);
  86012. return;
  86013. }
  86014. /* Find the original pointer */
  86015. for (n = 0; n < next_ptr; n++) {
  86016. if (ptr != table[n].new_ptr) continue;
  86017. farfree(table[n].org_ptr);
  86018. while (++n < next_ptr) {
  86019. table[n-1] = table[n];
  86020. }
  86021. next_ptr--;
  86022. return;
  86023. }
  86024. ptr = opaque; /* just to make some compilers happy */
  86025. Assert(0, "zcfree: ptr not found");
  86026. }
  86027. #endif /* __TURBOC__ */
  86028. #ifdef M_I86
  86029. /* Microsoft C in 16-bit mode */
  86030. # define MY_ZCALLOC
  86031. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86032. # define _halloc halloc
  86033. # define _hfree hfree
  86034. #endif
  86035. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86036. {
  86037. if (opaque) opaque = 0; /* to make compiler happy */
  86038. return _halloc((long)items, size);
  86039. }
  86040. void zcfree (voidpf opaque, voidpf ptr)
  86041. {
  86042. if (opaque) opaque = 0; /* to make compiler happy */
  86043. _hfree(ptr);
  86044. }
  86045. #endif /* M_I86 */
  86046. #endif /* SYS16BIT */
  86047. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86048. #ifndef STDC
  86049. extern voidp malloc OF((uInt size));
  86050. extern voidp calloc OF((uInt items, uInt size));
  86051. extern void free OF((voidpf ptr));
  86052. #endif
  86053. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86054. {
  86055. if (opaque) items += size - size; /* make compiler happy */
  86056. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86057. (voidpf)calloc(items, size);
  86058. }
  86059. void zcfree (voidpf opaque, voidpf ptr)
  86060. {
  86061. free(ptr);
  86062. if (opaque) return; /* make compiler happy */
  86063. }
  86064. #endif /* MY_ZCALLOC */
  86065. /*** End of inlined file: zutil.c ***/
  86066. #undef Byte
  86067. #else
  86068. #include <zlib.h>
  86069. #endif
  86070. }
  86071. #if JUCE_MSVC
  86072. #pragma warning (pop)
  86073. #endif
  86074. BEGIN_JUCE_NAMESPACE
  86075. // internal helper object that holds the zlib structures so they don't have to be
  86076. // included publicly.
  86077. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86078. {
  86079. public:
  86080. GZIPDecompressHelper (const bool noWrap)
  86081. : finished (true),
  86082. needsDictionary (false),
  86083. error (true),
  86084. streamIsValid (false),
  86085. data (0),
  86086. dataSize (0)
  86087. {
  86088. using namespace zlibNamespace;
  86089. zerostruct (stream);
  86090. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86091. finished = error = ! streamIsValid;
  86092. }
  86093. ~GZIPDecompressHelper()
  86094. {
  86095. using namespace zlibNamespace;
  86096. if (streamIsValid)
  86097. inflateEnd (&stream);
  86098. }
  86099. bool needsInput() const throw() { return dataSize <= 0; }
  86100. void setInput (uint8* const data_, const int size) throw()
  86101. {
  86102. data = data_;
  86103. dataSize = size;
  86104. }
  86105. int doNextBlock (uint8* const dest, const int destSize)
  86106. {
  86107. using namespace zlibNamespace;
  86108. if (streamIsValid && data != 0 && ! finished)
  86109. {
  86110. stream.next_in = data;
  86111. stream.next_out = dest;
  86112. stream.avail_in = dataSize;
  86113. stream.avail_out = destSize;
  86114. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86115. {
  86116. case Z_STREAM_END:
  86117. finished = true;
  86118. // deliberate fall-through
  86119. case Z_OK:
  86120. data += dataSize - stream.avail_in;
  86121. dataSize = stream.avail_in;
  86122. return destSize - stream.avail_out;
  86123. case Z_NEED_DICT:
  86124. needsDictionary = true;
  86125. data += dataSize - stream.avail_in;
  86126. dataSize = stream.avail_in;
  86127. break;
  86128. case Z_DATA_ERROR:
  86129. case Z_MEM_ERROR:
  86130. error = true;
  86131. default:
  86132. break;
  86133. }
  86134. }
  86135. return 0;
  86136. }
  86137. bool finished, needsDictionary, error, streamIsValid;
  86138. enum { gzipDecompBufferSize = 32768 };
  86139. private:
  86140. zlibNamespace::z_stream stream;
  86141. uint8* data;
  86142. int dataSize;
  86143. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  86144. };
  86145. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86146. const bool deleteSourceWhenDestroyed,
  86147. const bool noWrap_,
  86148. const int64 uncompressedStreamLength_)
  86149. : sourceStream (sourceStream_),
  86150. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86151. uncompressedStreamLength (uncompressedStreamLength_),
  86152. noWrap (noWrap_),
  86153. isEof (false),
  86154. activeBufferSize (0),
  86155. originalSourcePos (sourceStream_->getPosition()),
  86156. currentPos (0),
  86157. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86158. helper (new GZIPDecompressHelper (noWrap_))
  86159. {
  86160. }
  86161. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86162. : sourceStream (&sourceStream_),
  86163. uncompressedStreamLength (-1),
  86164. noWrap (false),
  86165. isEof (false),
  86166. activeBufferSize (0),
  86167. originalSourcePos (sourceStream_.getPosition()),
  86168. currentPos (0),
  86169. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86170. helper (new GZIPDecompressHelper (false))
  86171. {
  86172. }
  86173. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86174. {
  86175. }
  86176. int64 GZIPDecompressorInputStream::getTotalLength()
  86177. {
  86178. return uncompressedStreamLength;
  86179. }
  86180. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86181. {
  86182. if ((howMany > 0) && ! isEof)
  86183. {
  86184. jassert (destBuffer != 0);
  86185. if (destBuffer != 0)
  86186. {
  86187. int numRead = 0;
  86188. uint8* d = static_cast <uint8*> (destBuffer);
  86189. while (! helper->error)
  86190. {
  86191. const int n = helper->doNextBlock (d, howMany);
  86192. currentPos += n;
  86193. if (n == 0)
  86194. {
  86195. if (helper->finished || helper->needsDictionary)
  86196. {
  86197. isEof = true;
  86198. return numRead;
  86199. }
  86200. if (helper->needsInput())
  86201. {
  86202. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86203. if (activeBufferSize > 0)
  86204. {
  86205. helper->setInput (buffer, activeBufferSize);
  86206. }
  86207. else
  86208. {
  86209. isEof = true;
  86210. return numRead;
  86211. }
  86212. }
  86213. }
  86214. else
  86215. {
  86216. numRead += n;
  86217. howMany -= n;
  86218. d += n;
  86219. if (howMany <= 0)
  86220. return numRead;
  86221. }
  86222. }
  86223. }
  86224. }
  86225. return 0;
  86226. }
  86227. bool GZIPDecompressorInputStream::isExhausted()
  86228. {
  86229. return helper->error || isEof;
  86230. }
  86231. int64 GZIPDecompressorInputStream::getPosition()
  86232. {
  86233. return currentPos;
  86234. }
  86235. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86236. {
  86237. if (newPos < currentPos)
  86238. {
  86239. // to go backwards, reset the stream and start again..
  86240. isEof = false;
  86241. activeBufferSize = 0;
  86242. currentPos = 0;
  86243. helper = new GZIPDecompressHelper (noWrap);
  86244. sourceStream->setPosition (originalSourcePos);
  86245. }
  86246. skipNextBytes (newPos - currentPos);
  86247. return true;
  86248. }
  86249. END_JUCE_NAMESPACE
  86250. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86251. #endif
  86252. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86253. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86254. #if JUCE_USE_FLAC
  86255. #if JUCE_WINDOWS
  86256. #include <windows.h>
  86257. #endif
  86258. namespace FlacNamespace
  86259. {
  86260. #if JUCE_INCLUDE_FLAC_CODE
  86261. #if JUCE_MSVC
  86262. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86263. #endif
  86264. #define FLAC__NO_DLL 1
  86265. #if ! defined (SIZE_MAX)
  86266. #define SIZE_MAX 0xffffffff
  86267. #endif
  86268. #define __STDC_LIMIT_MACROS 1
  86269. /*** Start of inlined file: all.h ***/
  86270. #ifndef FLAC__ALL_H
  86271. #define FLAC__ALL_H
  86272. /*** Start of inlined file: export.h ***/
  86273. #ifndef FLAC__EXPORT_H
  86274. #define FLAC__EXPORT_H
  86275. /** \file include/FLAC/export.h
  86276. *
  86277. * \brief
  86278. * This module contains #defines and symbols for exporting function
  86279. * calls, and providing version information and compiled-in features.
  86280. *
  86281. * See the \link flac_export export \endlink module.
  86282. */
  86283. /** \defgroup flac_export FLAC/export.h: export symbols
  86284. * \ingroup flac
  86285. *
  86286. * \brief
  86287. * This module contains #defines and symbols for exporting function
  86288. * calls, and providing version information and compiled-in features.
  86289. *
  86290. * If you are compiling with MSVC and will link to the static library
  86291. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86292. * make sure the symbols are exported properly.
  86293. *
  86294. * \{
  86295. */
  86296. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86297. #define FLAC_API
  86298. #else
  86299. #ifdef FLAC_API_EXPORTS
  86300. #define FLAC_API _declspec(dllexport)
  86301. #else
  86302. #define FLAC_API _declspec(dllimport)
  86303. #endif
  86304. #endif
  86305. /** These #defines will mirror the libtool-based library version number, see
  86306. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86307. */
  86308. #define FLAC_API_VERSION_CURRENT 10
  86309. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86310. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86311. #ifdef __cplusplus
  86312. extern "C" {
  86313. #endif
  86314. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86315. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86316. #ifdef __cplusplus
  86317. }
  86318. #endif
  86319. /* \} */
  86320. #endif
  86321. /*** End of inlined file: export.h ***/
  86322. /*** Start of inlined file: assert.h ***/
  86323. #ifndef FLAC__ASSERT_H
  86324. #define FLAC__ASSERT_H
  86325. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86326. #ifdef DEBUG
  86327. #include <assert.h>
  86328. #define FLAC__ASSERT(x) assert(x)
  86329. #define FLAC__ASSERT_DECLARATION(x) x
  86330. #else
  86331. #define FLAC__ASSERT(x)
  86332. #define FLAC__ASSERT_DECLARATION(x)
  86333. #endif
  86334. #endif
  86335. /*** End of inlined file: assert.h ***/
  86336. /*** Start of inlined file: callback.h ***/
  86337. #ifndef FLAC__CALLBACK_H
  86338. #define FLAC__CALLBACK_H
  86339. /*** Start of inlined file: ordinals.h ***/
  86340. #ifndef FLAC__ORDINALS_H
  86341. #define FLAC__ORDINALS_H
  86342. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86343. #include <inttypes.h>
  86344. #endif
  86345. typedef signed char FLAC__int8;
  86346. typedef unsigned char FLAC__uint8;
  86347. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86348. typedef __int16 FLAC__int16;
  86349. typedef __int32 FLAC__int32;
  86350. typedef __int64 FLAC__int64;
  86351. typedef unsigned __int16 FLAC__uint16;
  86352. typedef unsigned __int32 FLAC__uint32;
  86353. typedef unsigned __int64 FLAC__uint64;
  86354. #elif defined(__EMX__)
  86355. typedef short FLAC__int16;
  86356. typedef long FLAC__int32;
  86357. typedef long long FLAC__int64;
  86358. typedef unsigned short FLAC__uint16;
  86359. typedef unsigned long FLAC__uint32;
  86360. typedef unsigned long long FLAC__uint64;
  86361. #else
  86362. typedef int16_t FLAC__int16;
  86363. typedef int32_t FLAC__int32;
  86364. typedef int64_t FLAC__int64;
  86365. typedef uint16_t FLAC__uint16;
  86366. typedef uint32_t FLAC__uint32;
  86367. typedef uint64_t FLAC__uint64;
  86368. #endif
  86369. typedef int FLAC__bool;
  86370. typedef FLAC__uint8 FLAC__byte;
  86371. #ifdef true
  86372. #undef true
  86373. #endif
  86374. #ifdef false
  86375. #undef false
  86376. #endif
  86377. #ifndef __cplusplus
  86378. #define true 1
  86379. #define false 0
  86380. #endif
  86381. #endif
  86382. /*** End of inlined file: ordinals.h ***/
  86383. #include <stdlib.h> /* for size_t */
  86384. /** \file include/FLAC/callback.h
  86385. *
  86386. * \brief
  86387. * This module defines the structures for describing I/O callbacks
  86388. * to the other FLAC interfaces.
  86389. *
  86390. * See the detailed documentation for callbacks in the
  86391. * \link flac_callbacks callbacks \endlink module.
  86392. */
  86393. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86394. * \ingroup flac
  86395. *
  86396. * \brief
  86397. * This module defines the structures for describing I/O callbacks
  86398. * to the other FLAC interfaces.
  86399. *
  86400. * The purpose of the I/O callback functions is to create a common way
  86401. * for the metadata interfaces to handle I/O.
  86402. *
  86403. * Originally the metadata interfaces required filenames as the way of
  86404. * specifying FLAC files to operate on. This is problematic in some
  86405. * environments so there is an additional option to specify a set of
  86406. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86407. *
  86408. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86409. * opaque structure for a data source.
  86410. *
  86411. * The callback function prototypes are similar (but not identical) to the
  86412. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86413. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86414. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86415. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86416. * is required. \warning You generally CANNOT directly use fseek or ftell
  86417. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86418. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86419. * large files. You will have to find an equivalent function (e.g. ftello),
  86420. * or write a wrapper. The same is true for feof() since this is usually
  86421. * implemented as a macro, not as a function whose address can be taken.
  86422. *
  86423. * \{
  86424. */
  86425. #ifdef __cplusplus
  86426. extern "C" {
  86427. #endif
  86428. /** This is the opaque handle type used by the callbacks. Typically
  86429. * this is a \c FILE* or address of a file descriptor.
  86430. */
  86431. typedef void* FLAC__IOHandle;
  86432. /** Signature for the read callback.
  86433. * The signature and semantics match POSIX fread() implementations
  86434. * and can generally be used interchangeably.
  86435. *
  86436. * \param ptr The address of the read buffer.
  86437. * \param size The size of the records to be read.
  86438. * \param nmemb The number of records to be read.
  86439. * \param handle The handle to the data source.
  86440. * \retval size_t
  86441. * The number of records read.
  86442. */
  86443. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86444. /** Signature for the write callback.
  86445. * The signature and semantics match POSIX fwrite() implementations
  86446. * and can generally be used interchangeably.
  86447. *
  86448. * \param ptr The address of the write buffer.
  86449. * \param size The size of the records to be written.
  86450. * \param nmemb The number of records to be written.
  86451. * \param handle The handle to the data source.
  86452. * \retval size_t
  86453. * The number of records written.
  86454. */
  86455. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86456. /** Signature for the seek callback.
  86457. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86458. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86459. * and 32-bits wide.
  86460. *
  86461. * \param handle The handle to the data source.
  86462. * \param offset The new position, relative to \a whence
  86463. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86464. * \retval int
  86465. * \c 0 on success, \c -1 on error.
  86466. */
  86467. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86468. /** Signature for the tell callback.
  86469. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86470. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86471. * and 32-bits wide.
  86472. *
  86473. * \param handle The handle to the data source.
  86474. * \retval FLAC__int64
  86475. * The current position on success, \c -1 on error.
  86476. */
  86477. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86478. /** Signature for the EOF callback.
  86479. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86480. * on many systems, feof() is a macro, so in this case a wrapper function
  86481. * must be provided instead.
  86482. *
  86483. * \param handle The handle to the data source.
  86484. * \retval int
  86485. * \c 0 if not at end of file, nonzero if at end of file.
  86486. */
  86487. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86488. /** Signature for the close callback.
  86489. * The signature and semantics match POSIX fclose() implementations
  86490. * and can generally be used interchangeably.
  86491. *
  86492. * \param handle The handle to the data source.
  86493. * \retval int
  86494. * \c 0 on success, \c EOF on error.
  86495. */
  86496. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86497. /** A structure for holding a set of callbacks.
  86498. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86499. * describe which of the callbacks are required. The ones that are not
  86500. * required may be set to NULL.
  86501. *
  86502. * If the seek requirement for an interface is optional, you can signify that
  86503. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86504. */
  86505. typedef struct {
  86506. FLAC__IOCallback_Read read;
  86507. FLAC__IOCallback_Write write;
  86508. FLAC__IOCallback_Seek seek;
  86509. FLAC__IOCallback_Tell tell;
  86510. FLAC__IOCallback_Eof eof;
  86511. FLAC__IOCallback_Close close;
  86512. } FLAC__IOCallbacks;
  86513. /* \} */
  86514. #ifdef __cplusplus
  86515. }
  86516. #endif
  86517. #endif
  86518. /*** End of inlined file: callback.h ***/
  86519. /*** Start of inlined file: format.h ***/
  86520. #ifndef FLAC__FORMAT_H
  86521. #define FLAC__FORMAT_H
  86522. #ifdef __cplusplus
  86523. extern "C" {
  86524. #endif
  86525. /** \file include/FLAC/format.h
  86526. *
  86527. * \brief
  86528. * This module contains structure definitions for the representation
  86529. * of FLAC format components in memory. These are the basic
  86530. * structures used by the rest of the interfaces.
  86531. *
  86532. * See the detailed documentation in the
  86533. * \link flac_format format \endlink module.
  86534. */
  86535. /** \defgroup flac_format FLAC/format.h: format components
  86536. * \ingroup flac
  86537. *
  86538. * \brief
  86539. * This module contains structure definitions for the representation
  86540. * of FLAC format components in memory. These are the basic
  86541. * structures used by the rest of the interfaces.
  86542. *
  86543. * First, you should be familiar with the
  86544. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86545. * follow directly from the specification. As a user of libFLAC, the
  86546. * interesting parts really are the structures that describe the frame
  86547. * header and metadata blocks.
  86548. *
  86549. * The format structures here are very primitive, designed to store
  86550. * information in an efficient way. Reading information from the
  86551. * structures is easy but creating or modifying them directly is
  86552. * more complex. For the most part, as a user of a library, editing
  86553. * is not necessary; however, for metadata blocks it is, so there are
  86554. * convenience functions provided in the \link flac_metadata metadata
  86555. * module \endlink to simplify the manipulation of metadata blocks.
  86556. *
  86557. * \note
  86558. * It's not the best convention, but symbols ending in _LEN are in bits
  86559. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86560. * global variables because they are usually used when declaring byte
  86561. * arrays and some compilers require compile-time knowledge of array
  86562. * sizes when declared on the stack.
  86563. *
  86564. * \{
  86565. */
  86566. /*
  86567. Most of the values described in this file are defined by the FLAC
  86568. format specification. There is nothing to tune here.
  86569. */
  86570. /** The largest legal metadata type code. */
  86571. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86572. /** The minimum block size, in samples, permitted by the format. */
  86573. #define FLAC__MIN_BLOCK_SIZE (16u)
  86574. /** The maximum block size, in samples, permitted by the format. */
  86575. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86576. /** The maximum block size, in samples, permitted by the FLAC subset for
  86577. * sample rates up to 48kHz. */
  86578. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86579. /** The maximum number of channels permitted by the format. */
  86580. #define FLAC__MAX_CHANNELS (8u)
  86581. /** The minimum sample resolution permitted by the format. */
  86582. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86583. /** The maximum sample resolution permitted by the format. */
  86584. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86585. /** The maximum sample resolution permitted by libFLAC.
  86586. *
  86587. * \warning
  86588. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86589. * the reference encoder/decoder is currently limited to 24 bits because
  86590. * of prevalent 32-bit math, so make sure and use this value when
  86591. * appropriate.
  86592. */
  86593. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86594. /** The maximum sample rate permitted by the format. The value is
  86595. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86596. * as to why.
  86597. */
  86598. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86599. /** The maximum LPC order permitted by the format. */
  86600. #define FLAC__MAX_LPC_ORDER (32u)
  86601. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86602. * up to 48kHz. */
  86603. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86604. /** The minimum quantized linear predictor coefficient precision
  86605. * permitted by the format.
  86606. */
  86607. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86608. /** The maximum quantized linear predictor coefficient precision
  86609. * permitted by the format.
  86610. */
  86611. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86612. /** The maximum order of the fixed predictors permitted by the format. */
  86613. #define FLAC__MAX_FIXED_ORDER (4u)
  86614. /** The maximum Rice partition order permitted by the format. */
  86615. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86616. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86617. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86618. /** The version string of the release, stamped onto the libraries and binaries.
  86619. *
  86620. * \note
  86621. * This does not correspond to the shared library version number, which
  86622. * is used to determine binary compatibility.
  86623. */
  86624. extern FLAC_API const char *FLAC__VERSION_STRING;
  86625. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86626. * This is a NUL-terminated ASCII string; when inserted into the
  86627. * VORBIS_COMMENT the trailing null is stripped.
  86628. */
  86629. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86630. /** The byte string representation of the beginning of a FLAC stream. */
  86631. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86632. /** The 32-bit integer big-endian representation of the beginning of
  86633. * a FLAC stream.
  86634. */
  86635. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86636. /** The length of the FLAC signature in bits. */
  86637. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86638. /** The length of the FLAC signature in bytes. */
  86639. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86640. /*****************************************************************************
  86641. *
  86642. * Subframe structures
  86643. *
  86644. *****************************************************************************/
  86645. /*****************************************************************************/
  86646. /** An enumeration of the available entropy coding methods. */
  86647. typedef enum {
  86648. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86649. /**< Residual is coded by partitioning into contexts, each with it's own
  86650. * 4-bit Rice parameter. */
  86651. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86652. /**< Residual is coded by partitioning into contexts, each with it's own
  86653. * 5-bit Rice parameter. */
  86654. } FLAC__EntropyCodingMethodType;
  86655. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86656. *
  86657. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86658. * give the string equivalent. The contents should not be modified.
  86659. */
  86660. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86661. /** Contents of a Rice partitioned residual
  86662. */
  86663. typedef struct {
  86664. unsigned *parameters;
  86665. /**< The Rice parameters for each context. */
  86666. unsigned *raw_bits;
  86667. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86668. * partitions and zero for unescaped partitions.
  86669. */
  86670. unsigned capacity_by_order;
  86671. /**< The capacity of the \a parameters and \a raw_bits arrays
  86672. * specified as an order, i.e. the number of array elements
  86673. * allocated is 2 ^ \a capacity_by_order.
  86674. */
  86675. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86676. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86677. */
  86678. typedef struct {
  86679. unsigned order;
  86680. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86681. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86682. /**< The context's Rice parameters and/or raw bits. */
  86683. } FLAC__EntropyCodingMethod_PartitionedRice;
  86684. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86685. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86686. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86687. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86688. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86689. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86690. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86691. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86692. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86693. */
  86694. typedef struct {
  86695. FLAC__EntropyCodingMethodType type;
  86696. union {
  86697. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86698. } data;
  86699. } FLAC__EntropyCodingMethod;
  86700. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86701. /*****************************************************************************/
  86702. /** An enumeration of the available subframe types. */
  86703. typedef enum {
  86704. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86705. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86706. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86707. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86708. } FLAC__SubframeType;
  86709. /** Maps a FLAC__SubframeType to a C string.
  86710. *
  86711. * Using a FLAC__SubframeType as the index to this array will
  86712. * give the string equivalent. The contents should not be modified.
  86713. */
  86714. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86715. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86716. */
  86717. typedef struct {
  86718. FLAC__int32 value; /**< The constant signal value. */
  86719. } FLAC__Subframe_Constant;
  86720. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86721. */
  86722. typedef struct {
  86723. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86724. } FLAC__Subframe_Verbatim;
  86725. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86726. */
  86727. typedef struct {
  86728. FLAC__EntropyCodingMethod entropy_coding_method;
  86729. /**< The residual coding method. */
  86730. unsigned order;
  86731. /**< The polynomial order. */
  86732. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86733. /**< Warmup samples to prime the predictor, length == order. */
  86734. const FLAC__int32 *residual;
  86735. /**< The residual signal, length == (blocksize minus order) samples. */
  86736. } FLAC__Subframe_Fixed;
  86737. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86738. */
  86739. typedef struct {
  86740. FLAC__EntropyCodingMethod entropy_coding_method;
  86741. /**< The residual coding method. */
  86742. unsigned order;
  86743. /**< The FIR order. */
  86744. unsigned qlp_coeff_precision;
  86745. /**< Quantized FIR filter coefficient precision in bits. */
  86746. int quantization_level;
  86747. /**< The qlp coeff shift needed. */
  86748. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86749. /**< FIR filter coefficients. */
  86750. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86751. /**< Warmup samples to prime the predictor, length == order. */
  86752. const FLAC__int32 *residual;
  86753. /**< The residual signal, length == (blocksize minus order) samples. */
  86754. } FLAC__Subframe_LPC;
  86755. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86756. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86757. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86758. */
  86759. typedef struct {
  86760. FLAC__SubframeType type;
  86761. union {
  86762. FLAC__Subframe_Constant constant;
  86763. FLAC__Subframe_Fixed fixed;
  86764. FLAC__Subframe_LPC lpc;
  86765. FLAC__Subframe_Verbatim verbatim;
  86766. } data;
  86767. unsigned wasted_bits;
  86768. } FLAC__Subframe;
  86769. /** == 1 (bit)
  86770. *
  86771. * This used to be a zero-padding bit (hence the name
  86772. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86773. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86774. * to mean something else.
  86775. */
  86776. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86777. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86778. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86779. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86780. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86781. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86782. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86783. /*****************************************************************************/
  86784. /*****************************************************************************
  86785. *
  86786. * Frame structures
  86787. *
  86788. *****************************************************************************/
  86789. /** An enumeration of the available channel assignments. */
  86790. typedef enum {
  86791. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86792. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86793. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86794. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86795. } FLAC__ChannelAssignment;
  86796. /** Maps a FLAC__ChannelAssignment to a C string.
  86797. *
  86798. * Using a FLAC__ChannelAssignment as the index to this array will
  86799. * give the string equivalent. The contents should not be modified.
  86800. */
  86801. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86802. /** An enumeration of the possible frame numbering methods. */
  86803. typedef enum {
  86804. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86805. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86806. } FLAC__FrameNumberType;
  86807. /** Maps a FLAC__FrameNumberType to a C string.
  86808. *
  86809. * Using a FLAC__FrameNumberType as the index to this array will
  86810. * give the string equivalent. The contents should not be modified.
  86811. */
  86812. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86813. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86814. */
  86815. typedef struct {
  86816. unsigned blocksize;
  86817. /**< The number of samples per subframe. */
  86818. unsigned sample_rate;
  86819. /**< The sample rate in Hz. */
  86820. unsigned channels;
  86821. /**< The number of channels (== number of subframes). */
  86822. FLAC__ChannelAssignment channel_assignment;
  86823. /**< The channel assignment for the frame. */
  86824. unsigned bits_per_sample;
  86825. /**< The sample resolution. */
  86826. FLAC__FrameNumberType number_type;
  86827. /**< The numbering scheme used for the frame. As a convenience, the
  86828. * decoder will always convert a frame number to a sample number because
  86829. * the rules are complex. */
  86830. union {
  86831. FLAC__uint32 frame_number;
  86832. FLAC__uint64 sample_number;
  86833. } number;
  86834. /**< The frame number or sample number of first sample in frame;
  86835. * use the \a number_type value to determine which to use. */
  86836. FLAC__uint8 crc;
  86837. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86838. * of the raw frame header bytes, meaning everything before the CRC byte
  86839. * including the sync code.
  86840. */
  86841. } FLAC__FrameHeader;
  86842. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86843. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86844. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86845. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86846. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86847. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86848. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86849. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86850. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86851. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86852. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86853. */
  86854. typedef struct {
  86855. FLAC__uint16 crc;
  86856. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86857. * 0) of the bytes before the crc, back to and including the frame header
  86858. * sync code.
  86859. */
  86860. } FLAC__FrameFooter;
  86861. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86862. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86863. */
  86864. typedef struct {
  86865. FLAC__FrameHeader header;
  86866. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86867. FLAC__FrameFooter footer;
  86868. } FLAC__Frame;
  86869. /*****************************************************************************/
  86870. /*****************************************************************************
  86871. *
  86872. * Meta-data structures
  86873. *
  86874. *****************************************************************************/
  86875. /** An enumeration of the available metadata block types. */
  86876. typedef enum {
  86877. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86878. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86879. FLAC__METADATA_TYPE_PADDING = 1,
  86880. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86881. FLAC__METADATA_TYPE_APPLICATION = 2,
  86882. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86883. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86884. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86885. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86886. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86887. FLAC__METADATA_TYPE_CUESHEET = 5,
  86888. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86889. FLAC__METADATA_TYPE_PICTURE = 6,
  86890. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86891. FLAC__METADATA_TYPE_UNDEFINED = 7
  86892. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86893. } FLAC__MetadataType;
  86894. /** Maps a FLAC__MetadataType to a C string.
  86895. *
  86896. * Using a FLAC__MetadataType as the index to this array will
  86897. * give the string equivalent. The contents should not be modified.
  86898. */
  86899. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86900. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86901. */
  86902. typedef struct {
  86903. unsigned min_blocksize, max_blocksize;
  86904. unsigned min_framesize, max_framesize;
  86905. unsigned sample_rate;
  86906. unsigned channels;
  86907. unsigned bits_per_sample;
  86908. FLAC__uint64 total_samples;
  86909. FLAC__byte md5sum[16];
  86910. } FLAC__StreamMetadata_StreamInfo;
  86911. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86912. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86913. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86914. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86915. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86916. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86917. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86918. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86919. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86920. /** The total stream length of the STREAMINFO block in bytes. */
  86921. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86922. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86923. */
  86924. typedef struct {
  86925. int dummy;
  86926. /**< Conceptually this is an empty struct since we don't store the
  86927. * padding bytes. Empty structs are not allowed by some C compilers,
  86928. * hence the dummy.
  86929. */
  86930. } FLAC__StreamMetadata_Padding;
  86931. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86932. */
  86933. typedef struct {
  86934. FLAC__byte id[4];
  86935. FLAC__byte *data;
  86936. } FLAC__StreamMetadata_Application;
  86937. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86938. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86939. */
  86940. typedef struct {
  86941. FLAC__uint64 sample_number;
  86942. /**< The sample number of the target frame. */
  86943. FLAC__uint64 stream_offset;
  86944. /**< The offset, in bytes, of the target frame with respect to
  86945. * beginning of the first frame. */
  86946. unsigned frame_samples;
  86947. /**< The number of samples in the target frame. */
  86948. } FLAC__StreamMetadata_SeekPoint;
  86949. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86950. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86951. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86952. /** The total stream length of a seek point in bytes. */
  86953. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86954. /** The value used in the \a sample_number field of
  86955. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86956. * point (== 0xffffffffffffffff).
  86957. */
  86958. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86959. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86960. *
  86961. * \note From the format specification:
  86962. * - The seek points must be sorted by ascending sample number.
  86963. * - Each seek point's sample number must be the first sample of the
  86964. * target frame.
  86965. * - Each seek point's sample number must be unique within the table.
  86966. * - Existence of a SEEKTABLE block implies a correct setting of
  86967. * total_samples in the stream_info block.
  86968. * - Behavior is undefined when more than one SEEKTABLE block is
  86969. * present in a stream.
  86970. */
  86971. typedef struct {
  86972. unsigned num_points;
  86973. FLAC__StreamMetadata_SeekPoint *points;
  86974. } FLAC__StreamMetadata_SeekTable;
  86975. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86976. *
  86977. * For convenience, the APIs maintain a trailing NUL character at the end of
  86978. * \a entry which is not counted toward \a length, i.e.
  86979. * \code strlen(entry) == length \endcode
  86980. */
  86981. typedef struct {
  86982. FLAC__uint32 length;
  86983. FLAC__byte *entry;
  86984. } FLAC__StreamMetadata_VorbisComment_Entry;
  86985. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86986. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86987. */
  86988. typedef struct {
  86989. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86990. FLAC__uint32 num_comments;
  86991. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86992. } FLAC__StreamMetadata_VorbisComment;
  86993. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86994. /** FLAC CUESHEET track index structure. (See the
  86995. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86996. * the full description of each field.)
  86997. */
  86998. typedef struct {
  86999. FLAC__uint64 offset;
  87000. /**< Offset in samples, relative to the track offset, of the index
  87001. * point.
  87002. */
  87003. FLAC__byte number;
  87004. /**< The index point number. */
  87005. } FLAC__StreamMetadata_CueSheet_Index;
  87006. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87007. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87008. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87009. /** FLAC CUESHEET track structure. (See the
  87010. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87011. * the full description of each field.)
  87012. */
  87013. typedef struct {
  87014. FLAC__uint64 offset;
  87015. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87016. FLAC__byte number;
  87017. /**< The track number. */
  87018. char isrc[13];
  87019. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87020. unsigned type:1;
  87021. /**< The track type: 0 for audio, 1 for non-audio. */
  87022. unsigned pre_emphasis:1;
  87023. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87024. FLAC__byte num_indices;
  87025. /**< The number of track index points. */
  87026. FLAC__StreamMetadata_CueSheet_Index *indices;
  87027. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87028. } FLAC__StreamMetadata_CueSheet_Track;
  87029. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87030. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87031. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87032. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87033. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87034. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87035. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87036. /** FLAC CUESHEET structure. (See the
  87037. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87038. * for the full description of each field.)
  87039. */
  87040. typedef struct {
  87041. char media_catalog_number[129];
  87042. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87043. * general, the media catalog number may be 0 to 128 bytes long; any
  87044. * unused characters should be right-padded with NUL characters.
  87045. */
  87046. FLAC__uint64 lead_in;
  87047. /**< The number of lead-in samples. */
  87048. FLAC__bool is_cd;
  87049. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87050. unsigned num_tracks;
  87051. /**< The number of tracks. */
  87052. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87053. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87054. } FLAC__StreamMetadata_CueSheet;
  87055. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87056. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87057. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87058. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87059. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87060. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87061. typedef enum {
  87062. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87063. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87064. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87065. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87066. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87067. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87068. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87069. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87070. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87071. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87072. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87073. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87074. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87075. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87076. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87077. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87078. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87079. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87080. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87081. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87082. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87083. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87084. } FLAC__StreamMetadata_Picture_Type;
  87085. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87086. *
  87087. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87088. * will give the string equivalent. The contents should not be
  87089. * modified.
  87090. */
  87091. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87092. /** FLAC PICTURE structure. (See the
  87093. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87094. * for the full description of each field.)
  87095. */
  87096. typedef struct {
  87097. FLAC__StreamMetadata_Picture_Type type;
  87098. /**< The kind of picture stored. */
  87099. char *mime_type;
  87100. /**< Picture data's MIME type, in ASCII printable characters
  87101. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87102. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87103. * MIME type of '-->' is also allowed, in which case the picture
  87104. * data should be a complete URL. In file storage, the MIME type is
  87105. * stored as a 32-bit length followed by the ASCII string with no NUL
  87106. * terminator, but is converted to a plain C string in this structure
  87107. * for convenience.
  87108. */
  87109. FLAC__byte *description;
  87110. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87111. * the description is stored as a 32-bit length followed by the UTF-8
  87112. * string with no NUL terminator, but is converted to a plain C string
  87113. * in this structure for convenience.
  87114. */
  87115. FLAC__uint32 width;
  87116. /**< Picture's width in pixels. */
  87117. FLAC__uint32 height;
  87118. /**< Picture's height in pixels. */
  87119. FLAC__uint32 depth;
  87120. /**< Picture's color depth in bits-per-pixel. */
  87121. FLAC__uint32 colors;
  87122. /**< For indexed palettes (like GIF), picture's number of colors (the
  87123. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87124. */
  87125. FLAC__uint32 data_length;
  87126. /**< Length of binary picture data in bytes. */
  87127. FLAC__byte *data;
  87128. /**< Binary picture data. */
  87129. } FLAC__StreamMetadata_Picture;
  87130. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87131. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87132. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87133. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87134. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87135. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87136. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87137. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87138. /** Structure that is used when a metadata block of unknown type is loaded.
  87139. * The contents are opaque. The structure is used only internally to
  87140. * correctly handle unknown metadata.
  87141. */
  87142. typedef struct {
  87143. FLAC__byte *data;
  87144. } FLAC__StreamMetadata_Unknown;
  87145. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87146. */
  87147. typedef struct {
  87148. FLAC__MetadataType type;
  87149. /**< The type of the metadata block; used determine which member of the
  87150. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87151. * then \a data.unknown must be used. */
  87152. FLAC__bool is_last;
  87153. /**< \c true if this metadata block is the last, else \a false */
  87154. unsigned length;
  87155. /**< Length, in bytes, of the block data as it appears in the stream. */
  87156. union {
  87157. FLAC__StreamMetadata_StreamInfo stream_info;
  87158. FLAC__StreamMetadata_Padding padding;
  87159. FLAC__StreamMetadata_Application application;
  87160. FLAC__StreamMetadata_SeekTable seek_table;
  87161. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87162. FLAC__StreamMetadata_CueSheet cue_sheet;
  87163. FLAC__StreamMetadata_Picture picture;
  87164. FLAC__StreamMetadata_Unknown unknown;
  87165. } data;
  87166. /**< Polymorphic block data; use the \a type value to determine which
  87167. * to use. */
  87168. } FLAC__StreamMetadata;
  87169. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87170. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87171. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87172. /** The total stream length of a metadata block header in bytes. */
  87173. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87174. /*****************************************************************************/
  87175. /*****************************************************************************
  87176. *
  87177. * Utility functions
  87178. *
  87179. *****************************************************************************/
  87180. /** Tests that a sample rate is valid for FLAC.
  87181. *
  87182. * \param sample_rate The sample rate to test for compliance.
  87183. * \retval FLAC__bool
  87184. * \c true if the given sample rate conforms to the specification, else
  87185. * \c false.
  87186. */
  87187. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87188. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87189. * for valid sample rates are slightly more complex since the rate has to
  87190. * be expressible completely in the frame header.
  87191. *
  87192. * \param sample_rate The sample rate to test for compliance.
  87193. * \retval FLAC__bool
  87194. * \c true if the given sample rate conforms to the specification for the
  87195. * subset, else \c false.
  87196. */
  87197. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87198. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87199. * comment specification.
  87200. *
  87201. * Vorbis comment names must be composed only of characters from
  87202. * [0x20-0x3C,0x3E-0x7D].
  87203. *
  87204. * \param name A NUL-terminated string to be checked.
  87205. * \assert
  87206. * \code name != NULL \endcode
  87207. * \retval FLAC__bool
  87208. * \c false if entry name is illegal, else \c true.
  87209. */
  87210. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87211. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87212. * comment specification.
  87213. *
  87214. * Vorbis comment values must be valid UTF-8 sequences.
  87215. *
  87216. * \param value A string to be checked.
  87217. * \param length A the length of \a value in bytes. May be
  87218. * \c (unsigned)(-1) to indicate that \a value is a plain
  87219. * UTF-8 NUL-terminated string.
  87220. * \assert
  87221. * \code value != NULL \endcode
  87222. * \retval FLAC__bool
  87223. * \c false if entry name is illegal, else \c true.
  87224. */
  87225. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87226. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87227. * comment specification.
  87228. *
  87229. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87230. * 'value' must be legal according to
  87231. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87232. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87233. *
  87234. * \param entry An entry to be checked.
  87235. * \param length The length of \a entry in bytes.
  87236. * \assert
  87237. * \code value != NULL \endcode
  87238. * \retval FLAC__bool
  87239. * \c false if entry name is illegal, else \c true.
  87240. */
  87241. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87242. /** Check a seek table to see if it conforms to the FLAC specification.
  87243. * See the format specification for limits on the contents of the
  87244. * seek table.
  87245. *
  87246. * \param seek_table A pointer to a seek table to be checked.
  87247. * \assert
  87248. * \code seek_table != NULL \endcode
  87249. * \retval FLAC__bool
  87250. * \c false if seek table is illegal, else \c true.
  87251. */
  87252. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87253. /** Sort a seek table's seek points according to the format specification.
  87254. * This includes a "unique-ification" step to remove duplicates, i.e.
  87255. * seek points with identical \a sample_number values. Duplicate seek
  87256. * points are converted into placeholder points and sorted to the end of
  87257. * the table.
  87258. *
  87259. * \param seek_table A pointer to a seek table to be sorted.
  87260. * \assert
  87261. * \code seek_table != NULL \endcode
  87262. * \retval unsigned
  87263. * The number of duplicate seek points converted into placeholders.
  87264. */
  87265. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87266. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87267. * See the format specification for limits on the contents of the
  87268. * cue sheet.
  87269. *
  87270. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87271. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87272. * stringent requirements for a CD-DA (audio) disc.
  87273. * \param violation Address of a pointer to a string. If there is a
  87274. * violation, a pointer to a string explanation of the
  87275. * violation will be returned here. \a violation may be
  87276. * \c NULL if you don't need the returned string. Do not
  87277. * free the returned string; it will always point to static
  87278. * data.
  87279. * \assert
  87280. * \code cue_sheet != NULL \endcode
  87281. * \retval FLAC__bool
  87282. * \c false if cue sheet is illegal, else \c true.
  87283. */
  87284. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87285. /** Check picture data to see if it conforms to the FLAC specification.
  87286. * See the format specification for limits on the contents of the
  87287. * PICTURE block.
  87288. *
  87289. * \param picture A pointer to existing picture data to be checked.
  87290. * \param violation Address of a pointer to a string. If there is a
  87291. * violation, a pointer to a string explanation of the
  87292. * violation will be returned here. \a violation may be
  87293. * \c NULL if you don't need the returned string. Do not
  87294. * free the returned string; it will always point to static
  87295. * data.
  87296. * \assert
  87297. * \code picture != NULL \endcode
  87298. * \retval FLAC__bool
  87299. * \c false if picture data is illegal, else \c true.
  87300. */
  87301. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87302. /* \} */
  87303. #ifdef __cplusplus
  87304. }
  87305. #endif
  87306. #endif
  87307. /*** End of inlined file: format.h ***/
  87308. /*** Start of inlined file: metadata.h ***/
  87309. #ifndef FLAC__METADATA_H
  87310. #define FLAC__METADATA_H
  87311. #include <sys/types.h> /* for off_t */
  87312. /* --------------------------------------------------------------------
  87313. (For an example of how all these routines are used, see the source
  87314. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87315. metaflac in src/metaflac/)
  87316. ------------------------------------------------------------------*/
  87317. /** \file include/FLAC/metadata.h
  87318. *
  87319. * \brief
  87320. * This module provides functions for creating and manipulating FLAC
  87321. * metadata blocks in memory, and three progressively more powerful
  87322. * interfaces for traversing and editing metadata in FLAC files.
  87323. *
  87324. * See the detailed documentation for each interface in the
  87325. * \link flac_metadata metadata \endlink module.
  87326. */
  87327. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87328. * \ingroup flac
  87329. *
  87330. * \brief
  87331. * This module provides functions for creating and manipulating FLAC
  87332. * metadata blocks in memory, and three progressively more powerful
  87333. * interfaces for traversing and editing metadata in native FLAC files.
  87334. * Note that currently only the Chain interface (level 2) supports Ogg
  87335. * FLAC files, and it is read-only i.e. no writing back changed
  87336. * metadata to file.
  87337. *
  87338. * There are three metadata interfaces of increasing complexity:
  87339. *
  87340. * Level 0:
  87341. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87342. * PICTURE blocks.
  87343. *
  87344. * Level 1:
  87345. * Read-write access to all metadata blocks. This level is write-
  87346. * efficient in most cases (more on this below), and uses less memory
  87347. * than level 2.
  87348. *
  87349. * Level 2:
  87350. * Read-write access to all metadata blocks. This level is write-
  87351. * efficient in all cases, but uses more memory since all metadata for
  87352. * the whole file is read into memory and manipulated before writing
  87353. * out again.
  87354. *
  87355. * What do we mean by efficient? Since FLAC metadata appears at the
  87356. * beginning of the file, when writing metadata back to a FLAC file
  87357. * it is possible to grow or shrink the metadata such that the entire
  87358. * file must be rewritten. However, if the size remains the same during
  87359. * changes or PADDING blocks are utilized, only the metadata needs to be
  87360. * overwritten, which is much faster.
  87361. *
  87362. * Efficient means the whole file is rewritten at most one time, and only
  87363. * when necessary. Level 1 is not efficient only in the case that you
  87364. * cause more than one metadata block to grow or shrink beyond what can
  87365. * be accomodated by padding. In this case you should probably use level
  87366. * 2, which allows you to edit all the metadata for a file in memory and
  87367. * write it out all at once.
  87368. *
  87369. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87370. * front of the file.
  87371. *
  87372. * All levels access files via their filenames. In addition, level 2
  87373. * has additional alternative read and write functions that take an I/O
  87374. * handle and callbacks, for situations where access by filename is not
  87375. * possible.
  87376. *
  87377. * In addition to the three interfaces, this module defines functions for
  87378. * creating and manipulating various metadata objects in memory. As we see
  87379. * from the Format module, FLAC metadata blocks in memory are very primitive
  87380. * structures for storing information in an efficient way. Reading
  87381. * information from the structures is easy but creating or modifying them
  87382. * directly is more complex. The metadata object routines here facilitate
  87383. * this by taking care of the consistency and memory management drudgery.
  87384. *
  87385. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87386. * metadata however, you will not probably not need these.
  87387. *
  87388. * From a dependency standpoint, none of the encoders or decoders require
  87389. * the metadata module. This is so that embedded users can strip out the
  87390. * metadata module from libFLAC to reduce the size and complexity.
  87391. */
  87392. #ifdef __cplusplus
  87393. extern "C" {
  87394. #endif
  87395. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87396. * \ingroup flac_metadata
  87397. *
  87398. * \brief
  87399. * The level 0 interface consists of individual routines to read the
  87400. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87401. * only a filename.
  87402. *
  87403. * They try to skip any ID3v2 tag at the head of the file.
  87404. *
  87405. * \{
  87406. */
  87407. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87408. * will try to skip any ID3v2 tag at the head of the file.
  87409. *
  87410. * \param filename The path to the FLAC file to read.
  87411. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87412. * FLAC__StreamMetadata is a simple structure with no
  87413. * memory allocation involved, you pass the address of
  87414. * an existing structure. It need not be initialized.
  87415. * \assert
  87416. * \code filename != NULL \endcode
  87417. * \code streaminfo != NULL \endcode
  87418. * \retval FLAC__bool
  87419. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87420. * \c false if there was a memory allocation error, a file decoder error,
  87421. * or the file contained no STREAMINFO block. (A memory allocation error
  87422. * is possible because this function must set up a file decoder.)
  87423. */
  87424. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87425. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87426. * function will try to skip any ID3v2 tag at the head of the file.
  87427. *
  87428. * \param filename The path to the FLAC file to read.
  87429. * \param tags The address where the returned pointer will be
  87430. * stored. The \a tags object must be deleted by
  87431. * the caller using FLAC__metadata_object_delete().
  87432. * \assert
  87433. * \code filename != NULL \endcode
  87434. * \code tags != NULL \endcode
  87435. * \retval FLAC__bool
  87436. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87437. * and \a *tags will be set to the address of the metadata structure.
  87438. * Returns \c false if there was a memory allocation error, a file
  87439. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87440. * \a *tags will be set to \c NULL.
  87441. */
  87442. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87443. /** Read the CUESHEET metadata block of the given FLAC file. This
  87444. * function will try to skip any ID3v2 tag at the head of the file.
  87445. *
  87446. * \param filename The path to the FLAC file to read.
  87447. * \param cuesheet The address where the returned pointer will be
  87448. * stored. The \a cuesheet object must be deleted by
  87449. * the caller using FLAC__metadata_object_delete().
  87450. * \assert
  87451. * \code filename != NULL \endcode
  87452. * \code cuesheet != NULL \endcode
  87453. * \retval FLAC__bool
  87454. * \c true if a valid CUESHEET block was read from \a filename,
  87455. * and \a *cuesheet will be set to the address of the metadata
  87456. * structure. Returns \c false if there was a memory allocation
  87457. * error, a file decoder error, or the file contained no CUESHEET
  87458. * block, and \a *cuesheet will be set to \c NULL.
  87459. */
  87460. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87461. /** Read a PICTURE metadata block of the given FLAC file. This
  87462. * function will try to skip any ID3v2 tag at the head of the file.
  87463. * Since there can be more than one PICTURE block in a file, this
  87464. * function takes a number of parameters that act as constraints to
  87465. * the search. The PICTURE block with the largest area matching all
  87466. * the constraints will be returned, or \a *picture will be set to
  87467. * \c NULL if there was no such block.
  87468. *
  87469. * \param filename The path to the FLAC file to read.
  87470. * \param picture The address where the returned pointer will be
  87471. * stored. The \a picture object must be deleted by
  87472. * the caller using FLAC__metadata_object_delete().
  87473. * \param type The desired picture type. Use \c -1 to mean
  87474. * "any type".
  87475. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87476. * string will be matched exactly. Use \c NULL to
  87477. * mean "any MIME type".
  87478. * \param description The desired description. The string will be
  87479. * matched exactly. Use \c NULL to mean "any
  87480. * description".
  87481. * \param max_width The maximum width in pixels desired. Use
  87482. * \c (unsigned)(-1) to mean "any width".
  87483. * \param max_height The maximum height in pixels desired. Use
  87484. * \c (unsigned)(-1) to mean "any height".
  87485. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87486. * Use \c (unsigned)(-1) to mean "any depth".
  87487. * \param max_colors The maximum number of colors desired. Use
  87488. * \c (unsigned)(-1) to mean "any number of colors".
  87489. * \assert
  87490. * \code filename != NULL \endcode
  87491. * \code picture != NULL \endcode
  87492. * \retval FLAC__bool
  87493. * \c true if a valid PICTURE block was read from \a filename,
  87494. * and \a *picture will be set to the address of the metadata
  87495. * structure. Returns \c false if there was a memory allocation
  87496. * error, a file decoder error, or the file contained no PICTURE
  87497. * block, and \a *picture will be set to \c NULL.
  87498. */
  87499. 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);
  87500. /* \} */
  87501. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87502. * \ingroup flac_metadata
  87503. *
  87504. * \brief
  87505. * The level 1 interface provides read-write access to FLAC file metadata and
  87506. * operates directly on the FLAC file.
  87507. *
  87508. * The general usage of this interface is:
  87509. *
  87510. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87511. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87512. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87513. * see if the file is writable, or only read access is allowed.
  87514. * - Use FLAC__metadata_simple_iterator_next() and
  87515. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87516. * This is does not read the actual blocks themselves.
  87517. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87518. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87519. * forward from the front of the file.
  87520. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87521. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87522. * the current iterator position. The returned object is yours to modify
  87523. * and free.
  87524. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87525. * back. You must have write permission to the original file. Make sure to
  87526. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87527. * below.
  87528. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87529. * Use the object creation functions from
  87530. * \link flac_metadata_object here \endlink to generate new objects.
  87531. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87532. * currently referred to by the iterator, or replace it with padding.
  87533. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87534. * finished.
  87535. *
  87536. * \note
  87537. * The FLAC file remains open the whole time between
  87538. * FLAC__metadata_simple_iterator_init() and
  87539. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87540. * the file during this time.
  87541. *
  87542. * \note
  87543. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87544. * FLAC__StreamMetadata objects. These are managed automatically.
  87545. *
  87546. * \note
  87547. * If any of the modification functions
  87548. * (FLAC__metadata_simple_iterator_set_block(),
  87549. * FLAC__metadata_simple_iterator_delete_block(),
  87550. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87551. * you should delete the iterator as it may no longer be valid.
  87552. *
  87553. * \{
  87554. */
  87555. struct FLAC__Metadata_SimpleIterator;
  87556. /** The opaque structure definition for the level 1 iterator type.
  87557. * See the
  87558. * \link flac_metadata_level1 metadata level 1 module \endlink
  87559. * for a detailed description.
  87560. */
  87561. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87562. /** Status type for FLAC__Metadata_SimpleIterator.
  87563. *
  87564. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87565. */
  87566. typedef enum {
  87567. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87568. /**< The iterator is in the normal OK state */
  87569. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87570. /**< The data passed into a function violated the function's usage criteria */
  87571. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87572. /**< The iterator could not open the target file */
  87573. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87574. /**< The iterator could not find the FLAC signature at the start of the file */
  87575. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87576. /**< The iterator tried to write to a file that was not writable */
  87577. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87578. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87579. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87580. /**< The iterator encountered an error while reading the FLAC file */
  87581. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87582. /**< The iterator encountered an error while seeking in the FLAC file */
  87583. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87584. /**< The iterator encountered an error while writing the FLAC file */
  87585. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87586. /**< The iterator encountered an error renaming the FLAC file */
  87587. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87588. /**< The iterator encountered an error removing the temporary file */
  87589. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87590. /**< Memory allocation failed */
  87591. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87592. /**< The caller violated an assertion or an unexpected error occurred */
  87593. } FLAC__Metadata_SimpleIteratorStatus;
  87594. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87595. *
  87596. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87597. * will give the string equivalent. The contents should not be modified.
  87598. */
  87599. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87600. /** Create a new iterator instance.
  87601. *
  87602. * \retval FLAC__Metadata_SimpleIterator*
  87603. * \c NULL if there was an error allocating memory, else the new instance.
  87604. */
  87605. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87606. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87607. *
  87608. * \param iterator A pointer to an existing iterator.
  87609. * \assert
  87610. * \code iterator != NULL \endcode
  87611. */
  87612. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87613. /** Get the current status of the iterator. Call this after a function
  87614. * returns \c false to get the reason for the error. Also resets the status
  87615. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87616. *
  87617. * \param iterator A pointer to an existing iterator.
  87618. * \assert
  87619. * \code iterator != NULL \endcode
  87620. * \retval FLAC__Metadata_SimpleIteratorStatus
  87621. * The current status of the iterator.
  87622. */
  87623. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87624. /** Initialize the iterator to point to the first metadata block in the
  87625. * given FLAC file.
  87626. *
  87627. * \param iterator A pointer to an existing iterator.
  87628. * \param filename The path to the FLAC file.
  87629. * \param read_only If \c true, the FLAC file will be opened
  87630. * in read-only mode; if \c false, the FLAC
  87631. * file will be opened for edit even if no
  87632. * edits are performed.
  87633. * \param preserve_file_stats If \c true, the owner and modification
  87634. * time will be preserved even if the FLAC
  87635. * file is written to.
  87636. * \assert
  87637. * \code iterator != NULL \endcode
  87638. * \code filename != NULL \endcode
  87639. * \retval FLAC__bool
  87640. * \c false if a memory allocation error occurs, the file can't be
  87641. * opened, or another error occurs, else \c true.
  87642. */
  87643. 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);
  87644. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87645. * FLAC__metadata_simple_iterator_set_block() and
  87646. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87647. *
  87648. * \param iterator A pointer to an existing iterator.
  87649. * \assert
  87650. * \code iterator != NULL \endcode
  87651. * \retval FLAC__bool
  87652. * See above.
  87653. */
  87654. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87655. /** Moves the iterator forward one metadata block, returning \c false if
  87656. * already at the end.
  87657. *
  87658. * \param iterator A pointer to an existing initialized iterator.
  87659. * \assert
  87660. * \code iterator != NULL \endcode
  87661. * \a iterator has been successfully initialized with
  87662. * FLAC__metadata_simple_iterator_init()
  87663. * \retval FLAC__bool
  87664. * \c false if already at the last metadata block of the chain, else
  87665. * \c true.
  87666. */
  87667. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87668. /** Moves the iterator backward one metadata block, returning \c false if
  87669. * already at the beginning.
  87670. *
  87671. * \param iterator A pointer to an existing initialized iterator.
  87672. * \assert
  87673. * \code iterator != NULL \endcode
  87674. * \a iterator has been successfully initialized with
  87675. * FLAC__metadata_simple_iterator_init()
  87676. * \retval FLAC__bool
  87677. * \c false if already at the first metadata block of the chain, else
  87678. * \c true.
  87679. */
  87680. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87681. /** Returns a flag telling if the current metadata block is the last.
  87682. *
  87683. * \param iterator A pointer to an existing initialized iterator.
  87684. * \assert
  87685. * \code iterator != NULL \endcode
  87686. * \a iterator has been successfully initialized with
  87687. * FLAC__metadata_simple_iterator_init()
  87688. * \retval FLAC__bool
  87689. * \c true if the current metadata block is the last in the file,
  87690. * else \c false.
  87691. */
  87692. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87693. /** Get the offset of the metadata block at the current position. This
  87694. * avoids reading the actual block data which can save time for large
  87695. * blocks.
  87696. *
  87697. * \param iterator A pointer to an existing initialized iterator.
  87698. * \assert
  87699. * \code iterator != NULL \endcode
  87700. * \a iterator has been successfully initialized with
  87701. * FLAC__metadata_simple_iterator_init()
  87702. * \retval off_t
  87703. * The offset of the metadata block at the current iterator position.
  87704. * This is the byte offset relative to the beginning of the file of
  87705. * the current metadata block's header.
  87706. */
  87707. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87708. /** Get the type of the metadata block at the current position. This
  87709. * avoids reading the actual block data which can save time for large
  87710. * blocks.
  87711. *
  87712. * \param iterator A pointer to an existing initialized iterator.
  87713. * \assert
  87714. * \code iterator != NULL \endcode
  87715. * \a iterator has been successfully initialized with
  87716. * FLAC__metadata_simple_iterator_init()
  87717. * \retval FLAC__MetadataType
  87718. * The type of the metadata block at the current iterator position.
  87719. */
  87720. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87721. /** Get the length of the metadata block at the current position. This
  87722. * avoids reading the actual block data which can save time for large
  87723. * blocks.
  87724. *
  87725. * \param iterator A pointer to an existing initialized iterator.
  87726. * \assert
  87727. * \code iterator != NULL \endcode
  87728. * \a iterator has been successfully initialized with
  87729. * FLAC__metadata_simple_iterator_init()
  87730. * \retval unsigned
  87731. * The length of the metadata block at the current iterator position.
  87732. * The is same length as that in the
  87733. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87734. * i.e. the length of the metadata body that follows the header.
  87735. */
  87736. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87737. /** Get the application ID of the \c APPLICATION block at the current
  87738. * position. This avoids reading the actual block data which can save
  87739. * time for large blocks.
  87740. *
  87741. * \param iterator A pointer to an existing initialized iterator.
  87742. * \param id A pointer to a buffer of at least \c 4 bytes where
  87743. * the ID will be stored.
  87744. * \assert
  87745. * \code iterator != NULL \endcode
  87746. * \code id != NULL \endcode
  87747. * \a iterator has been successfully initialized with
  87748. * FLAC__metadata_simple_iterator_init()
  87749. * \retval FLAC__bool
  87750. * \c true if the ID was successfully read, else \c false, in which
  87751. * case you should check FLAC__metadata_simple_iterator_status() to
  87752. * find out why. If the status is
  87753. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87754. * current metadata block is not an \c APPLICATION block. Otherwise
  87755. * if the status is
  87756. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87757. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87758. * occurred and the iterator can no longer be used.
  87759. */
  87760. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87761. /** Get the metadata block at the current position. You can modify the
  87762. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87763. * write it back to the FLAC file.
  87764. *
  87765. * You must call FLAC__metadata_object_delete() on the returned object
  87766. * when you are finished with it.
  87767. *
  87768. * \param iterator A pointer to an existing initialized iterator.
  87769. * \assert
  87770. * \code iterator != NULL \endcode
  87771. * \a iterator has been successfully initialized with
  87772. * FLAC__metadata_simple_iterator_init()
  87773. * \retval FLAC__StreamMetadata*
  87774. * The current metadata block, or \c NULL if there was a memory
  87775. * allocation error.
  87776. */
  87777. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87778. /** Write a block back to the FLAC file. This function tries to be
  87779. * as efficient as possible; how the block is actually written is
  87780. * shown by the following:
  87781. *
  87782. * Existing block is a STREAMINFO block and the new block is a
  87783. * STREAMINFO block: the new block is written in place. Make sure
  87784. * you know what you're doing when changing the values of a
  87785. * STREAMINFO block.
  87786. *
  87787. * Existing block is a STREAMINFO block and the new block is a
  87788. * not a STREAMINFO block: this is an error since the first block
  87789. * must be a STREAMINFO block. Returns \c false without altering the
  87790. * file.
  87791. *
  87792. * Existing block is not a STREAMINFO block and the new block is a
  87793. * STREAMINFO block: this is an error since there may be only one
  87794. * STREAMINFO block. Returns \c false without altering the file.
  87795. *
  87796. * Existing block and new block are the same length: the existing
  87797. * block will be replaced by the new block, written in place.
  87798. *
  87799. * Existing block is longer than new block: if use_padding is \c true,
  87800. * the existing block will be overwritten in place with the new
  87801. * block followed by a PADDING block, if possible, to make the total
  87802. * size the same as the existing block. Remember that a padding
  87803. * block requires at least four bytes so if the difference in size
  87804. * between the new block and existing block is less than that, the
  87805. * entire file will have to be rewritten, using the new block's
  87806. * exact size. If use_padding is \c false, the entire file will be
  87807. * rewritten, replacing the existing block by the new block.
  87808. *
  87809. * Existing block is shorter than new block: if use_padding is \c true,
  87810. * the function will try and expand the new block into the following
  87811. * PADDING block, if it exists and doing so won't shrink the PADDING
  87812. * block to less than 4 bytes. If there is no following PADDING
  87813. * block, or it will shrink to less than 4 bytes, or use_padding is
  87814. * \c false, the entire file is rewritten, replacing the existing block
  87815. * with the new block. Note that in this case any following PADDING
  87816. * block is preserved as is.
  87817. *
  87818. * After writing the block, the iterator will remain in the same
  87819. * place, i.e. pointing to the new block.
  87820. *
  87821. * \param iterator A pointer to an existing initialized iterator.
  87822. * \param block The block to set.
  87823. * \param use_padding See above.
  87824. * \assert
  87825. * \code iterator != NULL \endcode
  87826. * \a iterator has been successfully initialized with
  87827. * FLAC__metadata_simple_iterator_init()
  87828. * \code block != NULL \endcode
  87829. * \retval FLAC__bool
  87830. * \c true if successful, else \c false.
  87831. */
  87832. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87833. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87834. * except that instead of writing over an existing block, it appends
  87835. * a block after the existing block. \a use_padding is again used to
  87836. * tell the function to try an expand into following padding in an
  87837. * attempt to avoid rewriting the entire file.
  87838. *
  87839. * This function will fail and return \c false if given a STREAMINFO
  87840. * block.
  87841. *
  87842. * After writing the block, the iterator will be pointing to the
  87843. * new block.
  87844. *
  87845. * \param iterator A pointer to an existing initialized iterator.
  87846. * \param block The block to set.
  87847. * \param use_padding See above.
  87848. * \assert
  87849. * \code iterator != NULL \endcode
  87850. * \a iterator has been successfully initialized with
  87851. * FLAC__metadata_simple_iterator_init()
  87852. * \code block != NULL \endcode
  87853. * \retval FLAC__bool
  87854. * \c true if successful, else \c false.
  87855. */
  87856. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87857. /** Deletes the block at the current position. This will cause the
  87858. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87859. * in which case the block will be replaced by an equal-sized PADDING
  87860. * block. The iterator will be left pointing to the block before the
  87861. * one just deleted.
  87862. *
  87863. * You may not delete the STREAMINFO block.
  87864. *
  87865. * \param iterator A pointer to an existing initialized iterator.
  87866. * \param use_padding See above.
  87867. * \assert
  87868. * \code iterator != NULL \endcode
  87869. * \a iterator has been successfully initialized with
  87870. * FLAC__metadata_simple_iterator_init()
  87871. * \retval FLAC__bool
  87872. * \c true if successful, else \c false.
  87873. */
  87874. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87875. /* \} */
  87876. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87877. * \ingroup flac_metadata
  87878. *
  87879. * \brief
  87880. * The level 2 interface provides read-write access to FLAC file metadata;
  87881. * all metadata is read into memory, operated on in memory, and then written
  87882. * to file, which is more efficient than level 1 when editing multiple blocks.
  87883. *
  87884. * Currently Ogg FLAC is supported for read only, via
  87885. * FLAC__metadata_chain_read_ogg() but a subsequent
  87886. * FLAC__metadata_chain_write() will fail.
  87887. *
  87888. * The general usage of this interface is:
  87889. *
  87890. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87891. * linked list of FLAC metadata blocks.
  87892. * - Read all metadata into the the chain from a FLAC file using
  87893. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87894. * check the status.
  87895. * - Optionally, consolidate the padding using
  87896. * FLAC__metadata_chain_merge_padding() or
  87897. * FLAC__metadata_chain_sort_padding().
  87898. * - Create a new iterator using FLAC__metadata_iterator_new()
  87899. * - Initialize the iterator to point to the first element in the chain
  87900. * using FLAC__metadata_iterator_init()
  87901. * - Traverse the chain using FLAC__metadata_iterator_next and
  87902. * FLAC__metadata_iterator_prev().
  87903. * - Get a block for reading or modification using
  87904. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87905. * inside the chain is returned, so the block is yours to modify.
  87906. * Changes will be reflected in the FLAC file when you write the
  87907. * chain. You can also add and delete blocks (see functions below).
  87908. * - When done, write out the chain using FLAC__metadata_chain_write().
  87909. * Make sure to read the whole comment to the function below.
  87910. * - Delete the chain using FLAC__metadata_chain_delete().
  87911. *
  87912. * \note
  87913. * Even though the FLAC file is not open while the chain is being
  87914. * manipulated, you must not alter the file externally during
  87915. * this time. The chain assumes the FLAC file will not change
  87916. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87917. * and FLAC__metadata_chain_write().
  87918. *
  87919. * \note
  87920. * Do not modify the is_last, length, or type fields of returned
  87921. * FLAC__StreamMetadata objects. These are managed automatically.
  87922. *
  87923. * \note
  87924. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87925. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87926. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87927. * become owned by the chain and they will be deleted when the chain is
  87928. * deleted.
  87929. *
  87930. * \{
  87931. */
  87932. struct FLAC__Metadata_Chain;
  87933. /** The opaque structure definition for the level 2 chain type.
  87934. */
  87935. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87936. struct FLAC__Metadata_Iterator;
  87937. /** The opaque structure definition for the level 2 iterator type.
  87938. */
  87939. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87940. typedef enum {
  87941. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87942. /**< The chain is in the normal OK state */
  87943. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87944. /**< The data passed into a function violated the function's usage criteria */
  87945. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87946. /**< The chain could not open the target file */
  87947. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87948. /**< The chain could not find the FLAC signature at the start of the file */
  87949. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87950. /**< The chain tried to write to a file that was not writable */
  87951. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87952. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87953. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87954. /**< The chain encountered an error while reading the FLAC file */
  87955. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87956. /**< The chain encountered an error while seeking in the FLAC file */
  87957. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87958. /**< The chain encountered an error while writing the FLAC file */
  87959. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87960. /**< The chain encountered an error renaming the FLAC file */
  87961. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87962. /**< The chain encountered an error removing the temporary file */
  87963. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87964. /**< Memory allocation failed */
  87965. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87966. /**< The caller violated an assertion or an unexpected error occurred */
  87967. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87968. /**< One or more of the required callbacks was NULL */
  87969. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87970. /**< FLAC__metadata_chain_write() was called on a chain read by
  87971. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87972. * or
  87973. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87974. * was called on a chain read by
  87975. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87976. * Matching read/write methods must always be used. */
  87977. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87978. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87979. * chain write requires a tempfile; use
  87980. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87981. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87982. * called when the chain write does not require a tempfile; use
  87983. * FLAC__metadata_chain_write_with_callbacks() instead.
  87984. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87985. * before writing via callbacks. */
  87986. } FLAC__Metadata_ChainStatus;
  87987. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87988. *
  87989. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87990. * will give the string equivalent. The contents should not be modified.
  87991. */
  87992. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87993. /*********** FLAC__Metadata_Chain ***********/
  87994. /** Create a new chain instance.
  87995. *
  87996. * \retval FLAC__Metadata_Chain*
  87997. * \c NULL if there was an error allocating memory, else the new instance.
  87998. */
  87999. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88000. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88001. *
  88002. * \param chain A pointer to an existing chain.
  88003. * \assert
  88004. * \code chain != NULL \endcode
  88005. */
  88006. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88007. /** Get the current status of the chain. Call this after a function
  88008. * returns \c false to get the reason for the error. Also resets the
  88009. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88010. *
  88011. * \param chain A pointer to an existing chain.
  88012. * \assert
  88013. * \code chain != NULL \endcode
  88014. * \retval FLAC__Metadata_ChainStatus
  88015. * The current status of the chain.
  88016. */
  88017. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88018. /** Read all metadata from a FLAC file into the chain.
  88019. *
  88020. * \param chain A pointer to an existing chain.
  88021. * \param filename The path to the FLAC file to read.
  88022. * \assert
  88023. * \code chain != NULL \endcode
  88024. * \code filename != NULL \endcode
  88025. * \retval FLAC__bool
  88026. * \c true if a valid list of metadata blocks was read from
  88027. * \a filename, else \c false. On failure, check the status with
  88028. * FLAC__metadata_chain_status().
  88029. */
  88030. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88031. /** Read all metadata from an Ogg FLAC file into the chain.
  88032. *
  88033. * \note Ogg FLAC metadata data writing is not supported yet and
  88034. * FLAC__metadata_chain_write() will fail.
  88035. *
  88036. * \param chain A pointer to an existing chain.
  88037. * \param filename The path to the Ogg FLAC file to read.
  88038. * \assert
  88039. * \code chain != NULL \endcode
  88040. * \code filename != NULL \endcode
  88041. * \retval FLAC__bool
  88042. * \c true if a valid list of metadata blocks was read from
  88043. * \a filename, else \c false. On failure, check the status with
  88044. * FLAC__metadata_chain_status().
  88045. */
  88046. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88047. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88048. *
  88049. * The \a handle need only be open for reading, but must be seekable.
  88050. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88051. * for Windows).
  88052. *
  88053. * \param chain A pointer to an existing chain.
  88054. * \param handle The I/O handle of the FLAC stream to read. The
  88055. * handle will NOT be closed after the metadata is read;
  88056. * that is the duty of the caller.
  88057. * \param callbacks
  88058. * A set of callbacks to use for I/O. The mandatory
  88059. * callbacks are \a read, \a seek, and \a tell.
  88060. * \assert
  88061. * \code chain != NULL \endcode
  88062. * \retval FLAC__bool
  88063. * \c true if a valid list of metadata blocks was read from
  88064. * \a handle, else \c false. On failure, check the status with
  88065. * FLAC__metadata_chain_status().
  88066. */
  88067. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88068. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88069. *
  88070. * The \a handle need only be open for reading, but must be seekable.
  88071. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88072. * for Windows).
  88073. *
  88074. * \note Ogg FLAC metadata data writing is not supported yet and
  88075. * FLAC__metadata_chain_write() will fail.
  88076. *
  88077. * \param chain A pointer to an existing chain.
  88078. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88079. * handle will NOT be closed after the metadata is read;
  88080. * that is the duty of the caller.
  88081. * \param callbacks
  88082. * A set of callbacks to use for I/O. The mandatory
  88083. * callbacks are \a read, \a seek, and \a tell.
  88084. * \assert
  88085. * \code chain != NULL \endcode
  88086. * \retval FLAC__bool
  88087. * \c true if a valid list of metadata blocks was read from
  88088. * \a handle, else \c false. On failure, check the status with
  88089. * FLAC__metadata_chain_status().
  88090. */
  88091. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88092. /** Checks if writing the given chain would require the use of a
  88093. * temporary file, or if it could be written in place.
  88094. *
  88095. * Under certain conditions, padding can be utilized so that writing
  88096. * edited metadata back to the FLAC file does not require rewriting the
  88097. * entire file. If rewriting is required, then a temporary workfile is
  88098. * required. When writing metadata using callbacks, you must check
  88099. * this function to know whether to call
  88100. * FLAC__metadata_chain_write_with_callbacks() or
  88101. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88102. * writing with FLAC__metadata_chain_write(), the temporary file is
  88103. * handled internally.
  88104. *
  88105. * \param chain A pointer to an existing chain.
  88106. * \param use_padding
  88107. * Whether or not padding will be allowed to be used
  88108. * during the write. The value of \a use_padding given
  88109. * here must match the value later passed to
  88110. * FLAC__metadata_chain_write_with_callbacks() or
  88111. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88112. * \assert
  88113. * \code chain != NULL \endcode
  88114. * \retval FLAC__bool
  88115. * \c true if writing the current chain would require a tempfile, or
  88116. * \c false if metadata can be written in place.
  88117. */
  88118. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88119. /** Write all metadata out to the FLAC file. This function tries to be as
  88120. * efficient as possible; how the metadata is actually written is shown by
  88121. * the following:
  88122. *
  88123. * If the current chain is the same size as the existing metadata, the new
  88124. * data is written in place.
  88125. *
  88126. * If the current chain is longer than the existing metadata, and
  88127. * \a use_padding is \c true, and the last block is a PADDING block of
  88128. * sufficient length, the function will truncate the final padding block
  88129. * so that the overall size of the metadata is the same as the existing
  88130. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88131. * the above conditions are met, the entire FLAC file must be rewritten.
  88132. * If you want to use padding this way it is a good idea to call
  88133. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88134. * amount of padding to work with, unless you need to preserve ordering
  88135. * of the PADDING blocks for some reason.
  88136. *
  88137. * If the current chain is shorter than the existing metadata, and
  88138. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88139. * is extended to make the overall size the same as the existing data. If
  88140. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88141. * PADDING block is added to the end of the new data to make it the same
  88142. * size as the existing data (if possible, see the note to
  88143. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88144. * and the new data is written in place. If none of the above apply or
  88145. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88146. *
  88147. * If \a preserve_file_stats is \c true, the owner and modification time will
  88148. * be preserved even if the FLAC file is written.
  88149. *
  88150. * For this write function to be used, the chain must have been read with
  88151. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88152. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88153. *
  88154. * \param chain A pointer to an existing chain.
  88155. * \param use_padding See above.
  88156. * \param preserve_file_stats See above.
  88157. * \assert
  88158. * \code chain != NULL \endcode
  88159. * \retval FLAC__bool
  88160. * \c true if the write succeeded, else \c false. On failure,
  88161. * check the status with FLAC__metadata_chain_status().
  88162. */
  88163. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88164. /** Write all metadata out to a FLAC stream via callbacks.
  88165. *
  88166. * (See FLAC__metadata_chain_write() for the details on how padding is
  88167. * used to write metadata in place if possible.)
  88168. *
  88169. * The \a handle must be open for updating and be seekable. The
  88170. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88171. * for Windows).
  88172. *
  88173. * For this write function to be used, the chain must have been read with
  88174. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88175. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88176. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88177. * \c false.
  88178. *
  88179. * \param chain A pointer to an existing chain.
  88180. * \param use_padding See FLAC__metadata_chain_write()
  88181. * \param handle The I/O handle of the FLAC stream to write. The
  88182. * handle will NOT be closed after the metadata is
  88183. * written; that is the duty of the caller.
  88184. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88185. * callbacks are \a write and \a seek.
  88186. * \assert
  88187. * \code chain != NULL \endcode
  88188. * \retval FLAC__bool
  88189. * \c true if the write succeeded, else \c false. On failure,
  88190. * check the status with FLAC__metadata_chain_status().
  88191. */
  88192. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88193. /** Write all metadata out to a FLAC stream via callbacks.
  88194. *
  88195. * (See FLAC__metadata_chain_write() for the details on how padding is
  88196. * used to write metadata in place if possible.)
  88197. *
  88198. * This version of the write-with-callbacks function must be used when
  88199. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88200. * this function, you must supply an I/O handle corresponding to the
  88201. * FLAC file to edit, and a temporary handle to which the new FLAC
  88202. * file will be written. It is the caller's job to move this temporary
  88203. * FLAC file on top of the original FLAC file to complete the metadata
  88204. * edit.
  88205. *
  88206. * The \a handle must be open for reading and be seekable. The
  88207. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88208. * for Windows).
  88209. *
  88210. * The \a temp_handle must be open for writing. The
  88211. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88212. * for Windows). It should be an empty stream, or at least positioned
  88213. * at the start-of-file (in which case it is the caller's duty to
  88214. * truncate it on return).
  88215. *
  88216. * For this write function to be used, the chain must have been read with
  88217. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88218. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88219. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88220. * \c true.
  88221. *
  88222. * \param chain A pointer to an existing chain.
  88223. * \param use_padding See FLAC__metadata_chain_write()
  88224. * \param handle The I/O handle of the original FLAC stream to read.
  88225. * The handle will NOT be closed after the metadata is
  88226. * written; that is the duty of the caller.
  88227. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88228. * The mandatory callbacks are \a read, \a seek, and
  88229. * \a eof.
  88230. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88231. * handle will NOT be closed after the metadata is
  88232. * written; that is the duty of the caller.
  88233. * \param temp_callbacks
  88234. * A set of callbacks to use for I/O on temp_handle.
  88235. * The only mandatory callback is \a write.
  88236. * \assert
  88237. * \code chain != NULL \endcode
  88238. * \retval FLAC__bool
  88239. * \c true if the write succeeded, else \c false. On failure,
  88240. * check the status with FLAC__metadata_chain_status().
  88241. */
  88242. 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);
  88243. /** Merge adjacent PADDING blocks into a single block.
  88244. *
  88245. * \note This function does not write to the FLAC file, it only
  88246. * modifies the chain.
  88247. *
  88248. * \warning Any iterator on the current chain will become invalid after this
  88249. * call. You should delete the iterator and get a new one.
  88250. *
  88251. * \param chain A pointer to an existing chain.
  88252. * \assert
  88253. * \code chain != NULL \endcode
  88254. */
  88255. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88256. /** This function will move all PADDING blocks to the end on the metadata,
  88257. * then merge them into a single block.
  88258. *
  88259. * \note This function does not write to the FLAC file, it only
  88260. * modifies the chain.
  88261. *
  88262. * \warning Any iterator on the current chain will become invalid after this
  88263. * call. You should delete the iterator and get a new one.
  88264. *
  88265. * \param chain A pointer to an existing chain.
  88266. * \assert
  88267. * \code chain != NULL \endcode
  88268. */
  88269. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88270. /*********** FLAC__Metadata_Iterator ***********/
  88271. /** Create a new iterator instance.
  88272. *
  88273. * \retval FLAC__Metadata_Iterator*
  88274. * \c NULL if there was an error allocating memory, else the new instance.
  88275. */
  88276. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88277. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88278. *
  88279. * \param iterator A pointer to an existing iterator.
  88280. * \assert
  88281. * \code iterator != NULL \endcode
  88282. */
  88283. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88284. /** Initialize the iterator to point to the first metadata block in the
  88285. * given chain.
  88286. *
  88287. * \param iterator A pointer to an existing iterator.
  88288. * \param chain A pointer to an existing and initialized (read) chain.
  88289. * \assert
  88290. * \code iterator != NULL \endcode
  88291. * \code chain != NULL \endcode
  88292. */
  88293. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88294. /** Moves the iterator forward one metadata block, returning \c false if
  88295. * already at the end.
  88296. *
  88297. * \param iterator A pointer to an existing initialized iterator.
  88298. * \assert
  88299. * \code iterator != NULL \endcode
  88300. * \a iterator has been successfully initialized with
  88301. * FLAC__metadata_iterator_init()
  88302. * \retval FLAC__bool
  88303. * \c false if already at the last metadata block of the chain, else
  88304. * \c true.
  88305. */
  88306. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88307. /** Moves the iterator backward one metadata block, returning \c false if
  88308. * already at the beginning.
  88309. *
  88310. * \param iterator A pointer to an existing initialized iterator.
  88311. * \assert
  88312. * \code iterator != NULL \endcode
  88313. * \a iterator has been successfully initialized with
  88314. * FLAC__metadata_iterator_init()
  88315. * \retval FLAC__bool
  88316. * \c false if already at the first metadata block of the chain, else
  88317. * \c true.
  88318. */
  88319. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88320. /** Get the type of the metadata block at the current position.
  88321. *
  88322. * \param iterator A pointer to an existing initialized iterator.
  88323. * \assert
  88324. * \code iterator != NULL \endcode
  88325. * \a iterator has been successfully initialized with
  88326. * FLAC__metadata_iterator_init()
  88327. * \retval FLAC__MetadataType
  88328. * The type of the metadata block at the current iterator position.
  88329. */
  88330. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88331. /** Get the metadata block at the current position. You can modify
  88332. * the block in place but must write the chain before the changes
  88333. * are reflected to the FLAC file. You do not need to call
  88334. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88335. * the pointer returned by FLAC__metadata_iterator_get_block()
  88336. * points directly into the chain.
  88337. *
  88338. * \warning
  88339. * Do not call FLAC__metadata_object_delete() on the returned object;
  88340. * to delete a block use FLAC__metadata_iterator_delete_block().
  88341. *
  88342. * \param iterator A pointer to an existing initialized iterator.
  88343. * \assert
  88344. * \code iterator != NULL \endcode
  88345. * \a iterator has been successfully initialized with
  88346. * FLAC__metadata_iterator_init()
  88347. * \retval FLAC__StreamMetadata*
  88348. * The current metadata block.
  88349. */
  88350. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88351. /** Set the metadata block at the current position, replacing the existing
  88352. * block. The new block passed in becomes owned by the chain and it will be
  88353. * deleted when the chain is deleted.
  88354. *
  88355. * \param iterator A pointer to an existing initialized iterator.
  88356. * \param block A pointer to a metadata block.
  88357. * \assert
  88358. * \code iterator != NULL \endcode
  88359. * \a iterator has been successfully initialized with
  88360. * FLAC__metadata_iterator_init()
  88361. * \code block != NULL \endcode
  88362. * \retval FLAC__bool
  88363. * \c false if the conditions in the above description are not met, or
  88364. * a memory allocation error occurs, otherwise \c true.
  88365. */
  88366. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88367. /** Removes the current block from the chain. If \a replace_with_padding is
  88368. * \c true, the block will instead be replaced with a padding block of equal
  88369. * size. You can not delete the STREAMINFO block. The iterator will be
  88370. * left pointing to the block before the one just "deleted", even if
  88371. * \a replace_with_padding is \c true.
  88372. *
  88373. * \param iterator A pointer to an existing initialized iterator.
  88374. * \param replace_with_padding See above.
  88375. * \assert
  88376. * \code iterator != NULL \endcode
  88377. * \a iterator has been successfully initialized with
  88378. * FLAC__metadata_iterator_init()
  88379. * \retval FLAC__bool
  88380. * \c false if the conditions in the above description are not met,
  88381. * otherwise \c true.
  88382. */
  88383. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88384. /** Insert a new block before the current block. You cannot insert a block
  88385. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88386. * as there can be only one, the one that already exists at the head when you
  88387. * read in a chain. The chain takes ownership of the new block and it will be
  88388. * deleted when the chain is deleted. The iterator will be left pointing to
  88389. * the new block.
  88390. *
  88391. * \param iterator A pointer to an existing initialized iterator.
  88392. * \param block A pointer to a metadata block to insert.
  88393. * \assert
  88394. * \code iterator != NULL \endcode
  88395. * \a iterator has been successfully initialized with
  88396. * FLAC__metadata_iterator_init()
  88397. * \retval FLAC__bool
  88398. * \c false if the conditions in the above description are not met, or
  88399. * a memory allocation error occurs, otherwise \c true.
  88400. */
  88401. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88402. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88403. * block as there can be only one, the one that already exists at the head when
  88404. * you read in a chain. The chain takes ownership of the new block and it will
  88405. * be deleted when the chain is deleted. The iterator will be left pointing to
  88406. * the new block.
  88407. *
  88408. * \param iterator A pointer to an existing initialized iterator.
  88409. * \param block A pointer to a metadata block to insert.
  88410. * \assert
  88411. * \code iterator != NULL \endcode
  88412. * \a iterator has been successfully initialized with
  88413. * FLAC__metadata_iterator_init()
  88414. * \retval FLAC__bool
  88415. * \c false if the conditions in the above description are not met, or
  88416. * a memory allocation error occurs, otherwise \c true.
  88417. */
  88418. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88419. /* \} */
  88420. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88421. * \ingroup flac_metadata
  88422. *
  88423. * \brief
  88424. * This module contains methods for manipulating FLAC metadata objects.
  88425. *
  88426. * Since many are variable length we have to be careful about the memory
  88427. * management. We decree that all pointers to data in the object are
  88428. * owned by the object and memory-managed by the object.
  88429. *
  88430. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88431. * functions to create all instances. When using the
  88432. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88433. * \a copy to \c true to have the function make it's own copy of the data, or
  88434. * to \c false to give the object ownership of your data. In the latter case
  88435. * your pointer must be freeable by free() and will be free()d when the object
  88436. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88437. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88438. * the length argument is 0 and the \a copy argument is \c false.
  88439. *
  88440. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88441. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88442. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88443. * case of a memory allocation error.
  88444. *
  88445. * We don't have the convenience of C++ here, so note that the library relies
  88446. * on you to keep the types straight. In other words, if you pass, for
  88447. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88448. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88449. * failure.
  88450. *
  88451. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88452. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88453. * toward the length or stored in the stream, but it can make working with plain
  88454. * comments (those that don't contain embedded-NULs in the value) easier.
  88455. * Entries passed into these functions have trailing NULs added if missing, and
  88456. * returned entries are guaranteed to have a trailing NUL.
  88457. *
  88458. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88459. * comment entry/name/value will first validate that it complies with the Vorbis
  88460. * comment specification and return false if it does not.
  88461. *
  88462. * There is no need to recalculate the length field on metadata blocks you
  88463. * have modified. They will be calculated automatically before they are
  88464. * written back to a file.
  88465. *
  88466. * \{
  88467. */
  88468. /** Create a new metadata object instance of the given type.
  88469. *
  88470. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88471. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88472. * the vendor string set (but zero comments).
  88473. *
  88474. * Do not pass in a value greater than or equal to
  88475. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88476. * doing.
  88477. *
  88478. * \param type Type of object to create
  88479. * \retval FLAC__StreamMetadata*
  88480. * \c NULL if there was an error allocating memory or the type code is
  88481. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88482. */
  88483. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88484. /** Create a copy of an existing metadata object.
  88485. *
  88486. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88487. * object is also copied. The caller takes ownership of the new block and
  88488. * is responsible for freeing it with FLAC__metadata_object_delete().
  88489. *
  88490. * \param object Pointer to object to copy.
  88491. * \assert
  88492. * \code object != NULL \endcode
  88493. * \retval FLAC__StreamMetadata*
  88494. * \c NULL if there was an error allocating memory, else the new instance.
  88495. */
  88496. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88497. /** Free a metadata object. Deletes the object pointed to by \a object.
  88498. *
  88499. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88500. * object is also deleted.
  88501. *
  88502. * \param object A pointer to an existing object.
  88503. * \assert
  88504. * \code object != NULL \endcode
  88505. */
  88506. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88507. /** Compares two metadata objects.
  88508. *
  88509. * The compare is "deep", i.e. dynamically allocated data within the
  88510. * object is also compared.
  88511. *
  88512. * \param block1 A pointer to an existing object.
  88513. * \param block2 A pointer to an existing object.
  88514. * \assert
  88515. * \code block1 != NULL \endcode
  88516. * \code block2 != NULL \endcode
  88517. * \retval FLAC__bool
  88518. * \c true if objects are identical, else \c false.
  88519. */
  88520. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88521. /** Sets the application data of an APPLICATION block.
  88522. *
  88523. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88524. * takes ownership of the pointer. The existing data will be freed if this
  88525. * function is successful, otherwise the original data will remain if \a copy
  88526. * is \c true and malloc() fails.
  88527. *
  88528. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88529. *
  88530. * \param object A pointer to an existing APPLICATION object.
  88531. * \param data A pointer to the data to set.
  88532. * \param length The length of \a data in bytes.
  88533. * \param copy See above.
  88534. * \assert
  88535. * \code object != NULL \endcode
  88536. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88537. * \code (data != NULL && length > 0) ||
  88538. * (data == NULL && length == 0 && copy == false) \endcode
  88539. * \retval FLAC__bool
  88540. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88541. */
  88542. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88543. /** Resize the seekpoint array.
  88544. *
  88545. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88546. * points will be added to the end.
  88547. *
  88548. * \param object A pointer to an existing SEEKTABLE object.
  88549. * \param new_num_points The desired length of the array; may be \c 0.
  88550. * \assert
  88551. * \code object != NULL \endcode
  88552. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88553. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88554. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88555. * \retval FLAC__bool
  88556. * \c false if memory allocation error, else \c true.
  88557. */
  88558. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88559. /** Set a seekpoint in a seektable.
  88560. *
  88561. * \param object A pointer to an existing SEEKTABLE object.
  88562. * \param point_num Index into seekpoint array to set.
  88563. * \param point The point to set.
  88564. * \assert
  88565. * \code object != NULL \endcode
  88566. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88567. * \code object->data.seek_table.num_points > point_num \endcode
  88568. */
  88569. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88570. /** Insert a seekpoint into a seektable.
  88571. *
  88572. * \param object A pointer to an existing SEEKTABLE object.
  88573. * \param point_num Index into seekpoint array to set.
  88574. * \param point The point to set.
  88575. * \assert
  88576. * \code object != NULL \endcode
  88577. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88578. * \code object->data.seek_table.num_points >= point_num \endcode
  88579. * \retval FLAC__bool
  88580. * \c false if memory allocation error, else \c true.
  88581. */
  88582. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88583. /** Delete a seekpoint from a seektable.
  88584. *
  88585. * \param object A pointer to an existing SEEKTABLE object.
  88586. * \param point_num Index into seekpoint array to set.
  88587. * \assert
  88588. * \code object != NULL \endcode
  88589. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88590. * \code object->data.seek_table.num_points > point_num \endcode
  88591. * \retval FLAC__bool
  88592. * \c false if memory allocation error, else \c true.
  88593. */
  88594. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88595. /** Check a seektable to see if it conforms to the FLAC specification.
  88596. * See the format specification for limits on the contents of the
  88597. * seektable.
  88598. *
  88599. * \param object A pointer to an existing SEEKTABLE object.
  88600. * \assert
  88601. * \code object != NULL \endcode
  88602. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88603. * \retval FLAC__bool
  88604. * \c false if seek table is illegal, else \c true.
  88605. */
  88606. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88607. /** Append a number of placeholder points to the end of a seek table.
  88608. *
  88609. * \note
  88610. * As with the other ..._seektable_template_... functions, you should
  88611. * call FLAC__metadata_object_seektable_template_sort() when finished
  88612. * to make the seek table legal.
  88613. *
  88614. * \param object A pointer to an existing SEEKTABLE object.
  88615. * \param num The number of placeholder points to append.
  88616. * \assert
  88617. * \code object != NULL \endcode
  88618. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88619. * \retval FLAC__bool
  88620. * \c false if memory allocation fails, else \c true.
  88621. */
  88622. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88623. /** Append a specific seek point template to the end of a seek table.
  88624. *
  88625. * \note
  88626. * As with the other ..._seektable_template_... functions, you should
  88627. * call FLAC__metadata_object_seektable_template_sort() when finished
  88628. * to make the seek table legal.
  88629. *
  88630. * \param object A pointer to an existing SEEKTABLE object.
  88631. * \param sample_number The sample number of the seek point template.
  88632. * \assert
  88633. * \code object != NULL \endcode
  88634. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88635. * \retval FLAC__bool
  88636. * \c false if memory allocation fails, else \c true.
  88637. */
  88638. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88639. /** Append specific seek point templates to the end of a seek table.
  88640. *
  88641. * \note
  88642. * As with the other ..._seektable_template_... functions, you should
  88643. * call FLAC__metadata_object_seektable_template_sort() when finished
  88644. * to make the seek table legal.
  88645. *
  88646. * \param object A pointer to an existing SEEKTABLE object.
  88647. * \param sample_numbers An array of sample numbers for the seek points.
  88648. * \param num The number of seek point templates to append.
  88649. * \assert
  88650. * \code object != NULL \endcode
  88651. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88652. * \retval FLAC__bool
  88653. * \c false if memory allocation fails, else \c true.
  88654. */
  88655. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88656. /** Append a set of evenly-spaced seek point templates to the end of a
  88657. * seek table.
  88658. *
  88659. * \note
  88660. * As with the other ..._seektable_template_... functions, you should
  88661. * call FLAC__metadata_object_seektable_template_sort() when finished
  88662. * to make the seek table legal.
  88663. *
  88664. * \param object A pointer to an existing SEEKTABLE object.
  88665. * \param num The number of placeholder points to append.
  88666. * \param total_samples The total number of samples to be encoded;
  88667. * the seekpoints will be spaced approximately
  88668. * \a total_samples / \a num samples apart.
  88669. * \assert
  88670. * \code object != NULL \endcode
  88671. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88672. * \code total_samples > 0 \endcode
  88673. * \retval FLAC__bool
  88674. * \c false if memory allocation fails, else \c true.
  88675. */
  88676. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88677. /** Append a set of evenly-spaced seek point templates to the end of a
  88678. * seek table.
  88679. *
  88680. * \note
  88681. * As with the other ..._seektable_template_... functions, you should
  88682. * call FLAC__metadata_object_seektable_template_sort() when finished
  88683. * to make the seek table legal.
  88684. *
  88685. * \param object A pointer to an existing SEEKTABLE object.
  88686. * \param samples The number of samples apart to space the placeholder
  88687. * points. The first point will be at sample \c 0, the
  88688. * second at sample \a samples, then 2*\a samples, and
  88689. * so on. As long as \a samples and \a total_samples
  88690. * are greater than \c 0, there will always be at least
  88691. * one seekpoint at sample \c 0.
  88692. * \param total_samples The total number of samples to be encoded;
  88693. * the seekpoints will be spaced
  88694. * \a samples samples apart.
  88695. * \assert
  88696. * \code object != NULL \endcode
  88697. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88698. * \code samples > 0 \endcode
  88699. * \code total_samples > 0 \endcode
  88700. * \retval FLAC__bool
  88701. * \c false if memory allocation fails, else \c true.
  88702. */
  88703. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88704. /** Sort a seek table's seek points according to the format specification,
  88705. * removing duplicates.
  88706. *
  88707. * \param object A pointer to a seek table to be sorted.
  88708. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88709. * If \c true, duplicates are deleted and the seek table is
  88710. * shrunk appropriately; the number of placeholder points
  88711. * present in the seek table will be the same after the call
  88712. * as before.
  88713. * \assert
  88714. * \code object != NULL \endcode
  88715. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88716. * \retval FLAC__bool
  88717. * \c false if realloc() fails, else \c true.
  88718. */
  88719. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88720. /** Sets the vendor string in a VORBIS_COMMENT block.
  88721. *
  88722. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88723. * one already.
  88724. *
  88725. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88726. * takes ownership of the \c entry.entry pointer.
  88727. *
  88728. * \note If this function returns \c false, the caller still owns the
  88729. * pointer.
  88730. *
  88731. * \param object A pointer to an existing VORBIS_COMMENT object.
  88732. * \param entry The entry to set the vendor string to.
  88733. * \param copy See above.
  88734. * \assert
  88735. * \code object != NULL \endcode
  88736. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88737. * \code (entry.entry != NULL && entry.length > 0) ||
  88738. * (entry.entry == NULL && entry.length == 0) \endcode
  88739. * \retval FLAC__bool
  88740. * \c false if memory allocation fails or \a entry does not comply with the
  88741. * Vorbis comment specification, else \c true.
  88742. */
  88743. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88744. /** Resize the comment array.
  88745. *
  88746. * If the size shrinks, elements will truncated; if it grows, new empty
  88747. * fields will be added to the end.
  88748. *
  88749. * \param object A pointer to an existing VORBIS_COMMENT object.
  88750. * \param new_num_comments The desired length of the array; may be \c 0.
  88751. * \assert
  88752. * \code object != NULL \endcode
  88753. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88754. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88755. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88756. * \retval FLAC__bool
  88757. * \c false if memory allocation fails, else \c true.
  88758. */
  88759. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88760. /** Sets a comment in a VORBIS_COMMENT block.
  88761. *
  88762. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88763. * one already.
  88764. *
  88765. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88766. * takes ownership of the \c entry.entry pointer.
  88767. *
  88768. * \note If this function returns \c false, the caller still owns the
  88769. * pointer.
  88770. *
  88771. * \param object A pointer to an existing VORBIS_COMMENT object.
  88772. * \param comment_num Index into comment array to set.
  88773. * \param entry The entry to set the comment to.
  88774. * \param copy See above.
  88775. * \assert
  88776. * \code object != NULL \endcode
  88777. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88778. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88779. * \code (entry.entry != NULL && entry.length > 0) ||
  88780. * (entry.entry == NULL && entry.length == 0) \endcode
  88781. * \retval FLAC__bool
  88782. * \c false if memory allocation fails or \a entry does not comply with the
  88783. * Vorbis comment specification, else \c true.
  88784. */
  88785. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88786. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88787. *
  88788. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88789. * one already.
  88790. *
  88791. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88792. * takes ownership of the \c entry.entry pointer.
  88793. *
  88794. * \note If this function returns \c false, the caller still owns the
  88795. * pointer.
  88796. *
  88797. * \param object A pointer to an existing VORBIS_COMMENT object.
  88798. * \param comment_num The index at which to insert the comment. The comments
  88799. * at and after \a comment_num move right one position.
  88800. * To append a comment to the end, set \a comment_num to
  88801. * \c object->data.vorbis_comment.num_comments .
  88802. * \param entry The comment to insert.
  88803. * \param copy See above.
  88804. * \assert
  88805. * \code object != NULL \endcode
  88806. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88807. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88808. * \code (entry.entry != NULL && entry.length > 0) ||
  88809. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88810. * \retval FLAC__bool
  88811. * \c false if memory allocation fails or \a entry does not comply with the
  88812. * Vorbis comment specification, else \c true.
  88813. */
  88814. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88815. /** Appends a comment to a VORBIS_COMMENT block.
  88816. *
  88817. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88818. * one already.
  88819. *
  88820. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88821. * takes ownership of the \c entry.entry pointer.
  88822. *
  88823. * \note If this function returns \c false, the caller still owns the
  88824. * pointer.
  88825. *
  88826. * \param object A pointer to an existing VORBIS_COMMENT object.
  88827. * \param entry The comment to insert.
  88828. * \param copy See above.
  88829. * \assert
  88830. * \code object != NULL \endcode
  88831. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88832. * \code (entry.entry != NULL && entry.length > 0) ||
  88833. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88834. * \retval FLAC__bool
  88835. * \c false if memory allocation fails or \a entry does not comply with the
  88836. * Vorbis comment specification, else \c true.
  88837. */
  88838. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88839. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88840. *
  88841. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88842. * one already.
  88843. *
  88844. * Depending on the the value of \a all, either all or just the first comment
  88845. * whose field name(s) match the given entry's name will be replaced by the
  88846. * given entry. If no comments match, \a entry will simply be appended.
  88847. *
  88848. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88849. * takes ownership of the \c entry.entry pointer.
  88850. *
  88851. * \note If this function returns \c false, the caller still owns the
  88852. * pointer.
  88853. *
  88854. * \param object A pointer to an existing VORBIS_COMMENT object.
  88855. * \param entry The comment to insert.
  88856. * \param all If \c true, all comments whose field name matches
  88857. * \a entry's field name will be removed, and \a entry will
  88858. * be inserted at the position of the first matching
  88859. * comment. If \c false, only the first comment whose
  88860. * field name matches \a entry's field name will be
  88861. * replaced with \a entry.
  88862. * \param copy See above.
  88863. * \assert
  88864. * \code object != NULL \endcode
  88865. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88866. * \code (entry.entry != NULL && entry.length > 0) ||
  88867. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88868. * \retval FLAC__bool
  88869. * \c false if memory allocation fails or \a entry does not comply with the
  88870. * Vorbis comment specification, else \c true.
  88871. */
  88872. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88873. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88874. *
  88875. * \param object A pointer to an existing VORBIS_COMMENT object.
  88876. * \param comment_num The index of the comment to delete.
  88877. * \assert
  88878. * \code object != NULL \endcode
  88879. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88880. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88881. * \retval FLAC__bool
  88882. * \c false if realloc() fails, else \c true.
  88883. */
  88884. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88885. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88886. *
  88887. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88888. * memory and shall be owned by the caller. For convenience the entry will
  88889. * have a terminating NUL.
  88890. *
  88891. * \param entry A pointer to a Vorbis comment entry. The entry's
  88892. * \c entry pointer should not point to allocated
  88893. * memory as it will be overwritten.
  88894. * \param field_name The field name in ASCII, \c NUL terminated.
  88895. * \param field_value The field value in UTF-8, \c NUL terminated.
  88896. * \assert
  88897. * \code entry != NULL \endcode
  88898. * \code field_name != NULL \endcode
  88899. * \code field_value != NULL \endcode
  88900. * \retval FLAC__bool
  88901. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88902. * not comply with the Vorbis comment specification, else \c true.
  88903. */
  88904. 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);
  88905. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88906. *
  88907. * The returned pointers to name and value will be allocated by malloc()
  88908. * and shall be owned by the caller.
  88909. *
  88910. * \param entry An existing Vorbis comment entry.
  88911. * \param field_name The address of where the returned pointer to the
  88912. * field name will be stored.
  88913. * \param field_value The address of where the returned pointer to the
  88914. * field value will be stored.
  88915. * \assert
  88916. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88917. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88918. * \code field_name != NULL \endcode
  88919. * \code field_value != NULL \endcode
  88920. * \retval FLAC__bool
  88921. * \c false if memory allocation fails or \a entry does not comply with the
  88922. * Vorbis comment specification, else \c true.
  88923. */
  88924. 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);
  88925. /** Check if the given Vorbis comment entry's field name matches the given
  88926. * field name.
  88927. *
  88928. * \param entry An existing Vorbis comment entry.
  88929. * \param field_name The field name to check.
  88930. * \param field_name_length The length of \a field_name, not including the
  88931. * terminating \c NUL.
  88932. * \assert
  88933. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88934. * \retval FLAC__bool
  88935. * \c true if the field names match, else \c false
  88936. */
  88937. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88938. /** Find a Vorbis comment with the given field name.
  88939. *
  88940. * The search begins at entry number \a offset; use an offset of 0 to
  88941. * search from the beginning of the comment array.
  88942. *
  88943. * \param object A pointer to an existing VORBIS_COMMENT object.
  88944. * \param offset The offset into the comment array from where to start
  88945. * the search.
  88946. * \param field_name The field name of the comment to find.
  88947. * \assert
  88948. * \code object != NULL \endcode
  88949. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88950. * \code field_name != NULL \endcode
  88951. * \retval int
  88952. * The offset in the comment array of the first comment whose field
  88953. * name matches \a field_name, or \c -1 if no match was found.
  88954. */
  88955. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88956. /** Remove first Vorbis comment matching the given field name.
  88957. *
  88958. * \param object A pointer to an existing VORBIS_COMMENT object.
  88959. * \param field_name The field name of comment to delete.
  88960. * \assert
  88961. * \code object != NULL \endcode
  88962. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88963. * \retval int
  88964. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88965. * \c 1 for one matching entry deleted.
  88966. */
  88967. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88968. /** Remove all Vorbis comments matching the given field name.
  88969. *
  88970. * \param object A pointer to an existing VORBIS_COMMENT object.
  88971. * \param field_name The field name of comments to delete.
  88972. * \assert
  88973. * \code object != NULL \endcode
  88974. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88975. * \retval int
  88976. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88977. * else the number of matching entries deleted.
  88978. */
  88979. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88980. /** Create a new CUESHEET track instance.
  88981. *
  88982. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88983. *
  88984. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88985. * \c NULL if there was an error allocating memory, else the new instance.
  88986. */
  88987. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88988. /** Create a copy of an existing CUESHEET track object.
  88989. *
  88990. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88991. * object is also copied. The caller takes ownership of the new object and
  88992. * is responsible for freeing it with
  88993. * FLAC__metadata_object_cuesheet_track_delete().
  88994. *
  88995. * \param object Pointer to object to copy.
  88996. * \assert
  88997. * \code object != NULL \endcode
  88998. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88999. * \c NULL if there was an error allocating memory, else the new instance.
  89000. */
  89001. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89002. /** Delete a CUESHEET track object
  89003. *
  89004. * \param object A pointer to an existing CUESHEET track object.
  89005. * \assert
  89006. * \code object != NULL \endcode
  89007. */
  89008. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89009. /** Resize a track's index point array.
  89010. *
  89011. * If the size shrinks, elements will truncated; if it grows, new blank
  89012. * indices will be added to the end.
  89013. *
  89014. * \param object A pointer to an existing CUESHEET object.
  89015. * \param track_num The index of the track to modify. NOTE: this is not
  89016. * necessarily the same as the track's \a number field.
  89017. * \param new_num_indices The desired length of the array; may be \c 0.
  89018. * \assert
  89019. * \code object != NULL \endcode
  89020. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89021. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89022. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89023. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89024. * \retval FLAC__bool
  89025. * \c false if memory allocation error, else \c true.
  89026. */
  89027. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89028. /** Insert an index point in a CUESHEET track at the given index.
  89029. *
  89030. * \param object A pointer to an existing CUESHEET object.
  89031. * \param track_num The index of the track to modify. NOTE: this is not
  89032. * necessarily the same as the track's \a number field.
  89033. * \param index_num The index into the track's index array at which to
  89034. * insert the index point. NOTE: this is not necessarily
  89035. * the same as the index point's \a number field. The
  89036. * indices at and after \a index_num move right one
  89037. * position. To append an index point to the end, set
  89038. * \a index_num to
  89039. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89040. * \param index The index point to insert.
  89041. * \assert
  89042. * \code object != NULL \endcode
  89043. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89044. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89045. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89046. * \retval FLAC__bool
  89047. * \c false if realloc() fails, else \c true.
  89048. */
  89049. 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);
  89050. /** Insert a blank index point in a CUESHEET track at the given index.
  89051. *
  89052. * A blank index point is one in which all field values are zero.
  89053. *
  89054. * \param object A pointer to an existing CUESHEET object.
  89055. * \param track_num The index of the track to modify. NOTE: this is not
  89056. * necessarily the same as the track's \a number field.
  89057. * \param index_num The index into the track's index array at which to
  89058. * insert the index point. NOTE: this is not necessarily
  89059. * the same as the index point's \a number field. The
  89060. * indices at and after \a index_num move right one
  89061. * position. To append an index point to the end, set
  89062. * \a index_num to
  89063. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89064. * \assert
  89065. * \code object != NULL \endcode
  89066. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89067. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89068. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89069. * \retval FLAC__bool
  89070. * \c false if realloc() fails, else \c true.
  89071. */
  89072. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89073. /** Delete an index point in a CUESHEET track at the given index.
  89074. *
  89075. * \param object A pointer to an existing CUESHEET object.
  89076. * \param track_num The index into the track array of the track to
  89077. * modify. NOTE: this is not necessarily the same
  89078. * as the track's \a number field.
  89079. * \param index_num The index into the track's index array of the index
  89080. * to delete. NOTE: this is not necessarily the same
  89081. * as the index's \a number field.
  89082. * \assert
  89083. * \code object != NULL \endcode
  89084. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89085. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89086. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89087. * \retval FLAC__bool
  89088. * \c false if realloc() fails, else \c true.
  89089. */
  89090. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89091. /** Resize the track array.
  89092. *
  89093. * If the size shrinks, elements will truncated; if it grows, new blank
  89094. * tracks will be added to the end.
  89095. *
  89096. * \param object A pointer to an existing CUESHEET object.
  89097. * \param new_num_tracks The desired length of the array; may be \c 0.
  89098. * \assert
  89099. * \code object != NULL \endcode
  89100. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89101. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89102. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89103. * \retval FLAC__bool
  89104. * \c false if memory allocation error, else \c true.
  89105. */
  89106. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89107. /** Sets a track in a CUESHEET block.
  89108. *
  89109. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89110. * takes ownership of the \a track pointer.
  89111. *
  89112. * \param object A pointer to an existing CUESHEET object.
  89113. * \param track_num Index into track array to set. NOTE: this is not
  89114. * necessarily the same as the track's \a number field.
  89115. * \param track The track to set the track to. You may safely pass in
  89116. * a const pointer if \a copy is \c true.
  89117. * \param copy See above.
  89118. * \assert
  89119. * \code object != NULL \endcode
  89120. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89121. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89122. * \code (track->indices != NULL && track->num_indices > 0) ||
  89123. * (track->indices == NULL && track->num_indices == 0)
  89124. * \retval FLAC__bool
  89125. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89126. */
  89127. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89128. /** Insert a track in a CUESHEET block at the given index.
  89129. *
  89130. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89131. * takes ownership of the \a track pointer.
  89132. *
  89133. * \param object A pointer to an existing CUESHEET object.
  89134. * \param track_num The index at which to insert the track. NOTE: this
  89135. * is not necessarily the same as the track's \a number
  89136. * field. The tracks at and after \a track_num move right
  89137. * one position. To append a track to the end, set
  89138. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89139. * \param track The track to insert. You may safely pass in a const
  89140. * pointer if \a copy is \c true.
  89141. * \param copy See above.
  89142. * \assert
  89143. * \code object != NULL \endcode
  89144. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89145. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89146. * \retval FLAC__bool
  89147. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89148. */
  89149. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89150. /** Insert a blank track in a CUESHEET block at the given index.
  89151. *
  89152. * A blank track is one in which all field values are zero.
  89153. *
  89154. * \param object A pointer to an existing CUESHEET object.
  89155. * \param track_num The index at which to insert the track. NOTE: this
  89156. * is not necessarily the same as the track's \a number
  89157. * field. The tracks at and after \a track_num move right
  89158. * one position. To append a track to the end, set
  89159. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89160. * \assert
  89161. * \code object != NULL \endcode
  89162. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89163. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89164. * \retval FLAC__bool
  89165. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89166. */
  89167. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89168. /** Delete a track in a CUESHEET block at the given index.
  89169. *
  89170. * \param object A pointer to an existing CUESHEET object.
  89171. * \param track_num The index into the track array of the track to
  89172. * delete. NOTE: this is not necessarily the same
  89173. * as the track's \a number field.
  89174. * \assert
  89175. * \code object != NULL \endcode
  89176. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89177. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89178. * \retval FLAC__bool
  89179. * \c false if realloc() fails, else \c true.
  89180. */
  89181. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89182. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89183. * See the format specification for limits on the contents of the
  89184. * cue sheet.
  89185. *
  89186. * \param object A pointer to an existing CUESHEET object.
  89187. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89188. * stringent requirements for a CD-DA (audio) disc.
  89189. * \param violation Address of a pointer to a string. If there is a
  89190. * violation, a pointer to a string explanation of the
  89191. * violation will be returned here. \a violation may be
  89192. * \c NULL if you don't need the returned string. Do not
  89193. * free the returned string; it will always point to static
  89194. * data.
  89195. * \assert
  89196. * \code object != NULL \endcode
  89197. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89198. * \retval FLAC__bool
  89199. * \c false if cue sheet is illegal, else \c true.
  89200. */
  89201. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89202. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89203. * assumes the cue sheet corresponds to a CD; the result is undefined
  89204. * if the cuesheet's is_cd bit is not set.
  89205. *
  89206. * \param object A pointer to an existing CUESHEET object.
  89207. * \assert
  89208. * \code object != NULL \endcode
  89209. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89210. * \retval FLAC__uint32
  89211. * The unsigned integer representation of the CDDB/freedb ID
  89212. */
  89213. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89214. /** Sets the MIME type of a PICTURE block.
  89215. *
  89216. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89217. * takes ownership of the pointer. The existing string will be freed if this
  89218. * function is successful, otherwise the original string will remain if \a copy
  89219. * is \c true and malloc() fails.
  89220. *
  89221. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89222. *
  89223. * \param object A pointer to an existing PICTURE object.
  89224. * \param mime_type A pointer to the MIME type string. The string must be
  89225. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89226. * is done.
  89227. * \param copy See above.
  89228. * \assert
  89229. * \code object != NULL \endcode
  89230. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89231. * \code (mime_type != NULL) \endcode
  89232. * \retval FLAC__bool
  89233. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89234. */
  89235. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89236. /** Sets the description of a PICTURE block.
  89237. *
  89238. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89239. * takes ownership of the pointer. The existing string will be freed if this
  89240. * function is successful, otherwise the original string will remain if \a copy
  89241. * is \c true and malloc() fails.
  89242. *
  89243. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89244. *
  89245. * \param object A pointer to an existing PICTURE object.
  89246. * \param description A pointer to the description string. The string must be
  89247. * valid UTF-8, NUL-terminated. No validation is done.
  89248. * \param copy See above.
  89249. * \assert
  89250. * \code object != NULL \endcode
  89251. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89252. * \code (description != NULL) \endcode
  89253. * \retval FLAC__bool
  89254. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89255. */
  89256. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89257. /** Sets the picture data of a PICTURE block.
  89258. *
  89259. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89260. * takes ownership of the pointer. Also sets the \a data_length field of the
  89261. * metadata object to what is passed in as the \a length parameter. The
  89262. * existing data will be freed if this function is successful, otherwise the
  89263. * original data and data_length will remain if \a copy is \c true and
  89264. * malloc() fails.
  89265. *
  89266. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89267. *
  89268. * \param object A pointer to an existing PICTURE object.
  89269. * \param data A pointer to the data to set.
  89270. * \param length The length of \a data in bytes.
  89271. * \param copy See above.
  89272. * \assert
  89273. * \code object != NULL \endcode
  89274. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89275. * \code (data != NULL && length > 0) ||
  89276. * (data == NULL && length == 0 && copy == false) \endcode
  89277. * \retval FLAC__bool
  89278. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89279. */
  89280. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89281. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89282. * See the format specification for limits on the contents of the
  89283. * PICTURE block.
  89284. *
  89285. * \param object A pointer to existing PICTURE block to be checked.
  89286. * \param violation Address of a pointer to a string. If there is a
  89287. * violation, a pointer to a string explanation of the
  89288. * violation will be returned here. \a violation may be
  89289. * \c NULL if you don't need the returned string. Do not
  89290. * free the returned string; it will always point to static
  89291. * data.
  89292. * \assert
  89293. * \code object != NULL \endcode
  89294. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89295. * \retval FLAC__bool
  89296. * \c false if PICTURE block is illegal, else \c true.
  89297. */
  89298. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89299. /* \} */
  89300. #ifdef __cplusplus
  89301. }
  89302. #endif
  89303. #endif
  89304. /*** End of inlined file: metadata.h ***/
  89305. /*** Start of inlined file: stream_decoder.h ***/
  89306. #ifndef FLAC__STREAM_DECODER_H
  89307. #define FLAC__STREAM_DECODER_H
  89308. #include <stdio.h> /* for FILE */
  89309. #ifdef __cplusplus
  89310. extern "C" {
  89311. #endif
  89312. /** \file include/FLAC/stream_decoder.h
  89313. *
  89314. * \brief
  89315. * This module contains the functions which implement the stream
  89316. * decoder.
  89317. *
  89318. * See the detailed documentation in the
  89319. * \link flac_stream_decoder stream decoder \endlink module.
  89320. */
  89321. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89322. * \ingroup flac
  89323. *
  89324. * \brief
  89325. * This module describes the decoder layers provided by libFLAC.
  89326. *
  89327. * The stream decoder can be used to decode complete streams either from
  89328. * the client via callbacks, or directly from a file, depending on how
  89329. * it is initialized. When decoding via callbacks, the client provides
  89330. * callbacks for reading FLAC data and writing decoded samples, and
  89331. * handling metadata and errors. If the client also supplies seek-related
  89332. * callback, the decoder function for sample-accurate seeking within the
  89333. * FLAC input is also available. When decoding from a file, the client
  89334. * needs only supply a filename or open \c FILE* and write/metadata/error
  89335. * callbacks; the rest of the callbacks are supplied internally. For more
  89336. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89337. */
  89338. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89339. * \ingroup flac_decoder
  89340. *
  89341. * \brief
  89342. * This module contains the functions which implement the stream
  89343. * decoder.
  89344. *
  89345. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89346. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89347. *
  89348. * The basic usage of this decoder is as follows:
  89349. * - The program creates an instance of a decoder using
  89350. * FLAC__stream_decoder_new().
  89351. * - The program overrides the default settings using
  89352. * FLAC__stream_decoder_set_*() functions.
  89353. * - The program initializes the instance to validate the settings and
  89354. * prepare for decoding using
  89355. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89356. * or FLAC__stream_decoder_init_file() for native FLAC,
  89357. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89358. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89359. * - The program calls the FLAC__stream_decoder_process_*() functions
  89360. * to decode data, which subsequently calls the callbacks.
  89361. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89362. * which flushes the input and output and resets the decoder to the
  89363. * uninitialized state.
  89364. * - The instance may be used again or deleted with
  89365. * FLAC__stream_decoder_delete().
  89366. *
  89367. * In more detail, the program will create a new instance by calling
  89368. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89369. * functions to override the default decoder options, and call
  89370. * one of the FLAC__stream_decoder_init_*() functions.
  89371. *
  89372. * There are three initialization functions for native FLAC, one for
  89373. * setting up the decoder to decode FLAC data from the client via
  89374. * callbacks, and two for decoding directly from a FLAC file.
  89375. *
  89376. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89377. * You must also supply several callbacks for handling I/O. Some (like
  89378. * seeking) are optional, depending on the capabilities of the input.
  89379. *
  89380. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89381. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89382. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89383. * the other callbacks internally.
  89384. *
  89385. * There are three similarly-named init functions for decoding from Ogg
  89386. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89387. * library has been built with Ogg support.
  89388. *
  89389. * Once the decoder is initialized, your program will call one of several
  89390. * functions to start the decoding process:
  89391. *
  89392. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89393. * most one metadata block or audio frame and return, calling either the
  89394. * metadata callback or write callback, respectively, once. If the decoder
  89395. * loses sync it will return with only the error callback being called.
  89396. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89397. * to process the stream from the current location and stop upon reaching
  89398. * the first audio frame. The client will get one metadata, write, or error
  89399. * callback per metadata block, audio frame, or sync error, respectively.
  89400. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89401. * to process the stream from the current location until the read callback
  89402. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89403. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89404. * write, or error callback per metadata block, audio frame, or sync error,
  89405. * respectively.
  89406. *
  89407. * When the decoder has finished decoding (normally or through an abort),
  89408. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89409. * ensures the decoder is in the correct state and frees memory. Then the
  89410. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89411. * again to decode another stream.
  89412. *
  89413. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89414. * At any point after the stream decoder has been initialized, the client can
  89415. * call this function to seek to an exact sample within the stream.
  89416. * Subsequently, the first time the write callback is called it will be
  89417. * passed a (possibly partial) block starting at that sample.
  89418. *
  89419. * If the client cannot seek via the callback interface provided, but still
  89420. * has another way of seeking, it can flush the decoder using
  89421. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89422. * through the read callback.
  89423. *
  89424. * The stream decoder also provides MD5 signature checking. If this is
  89425. * turned on before initialization, FLAC__stream_decoder_finish() will
  89426. * report when the decoded MD5 signature does not match the one stored
  89427. * in the STREAMINFO block. MD5 checking is automatically turned off
  89428. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89429. * in the STREAMINFO block or when a seek is attempted.
  89430. *
  89431. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89432. * attention. By default, the decoder only calls the metadata_callback for
  89433. * the STREAMINFO block. These functions allow you to tell the decoder
  89434. * explicitly which blocks to parse and return via the metadata_callback
  89435. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89436. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89437. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89438. * which blocks to return. Remember that metadata blocks can potentially
  89439. * be big (for example, cover art) so filtering out the ones you don't
  89440. * use can reduce the memory requirements of the decoder. Also note the
  89441. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89442. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89443. * filtering APPLICATION blocks based on the application ID.
  89444. *
  89445. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89446. * they still can legally be filtered from the metadata_callback.
  89447. *
  89448. * \note
  89449. * The "set" functions may only be called when the decoder is in the
  89450. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89451. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89452. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89453. * return \c true, otherwise \c false.
  89454. *
  89455. * \note
  89456. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89457. * defaults, including the callbacks.
  89458. *
  89459. * \{
  89460. */
  89461. /** State values for a FLAC__StreamDecoder
  89462. *
  89463. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89464. */
  89465. typedef enum {
  89466. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89467. /**< The decoder is ready to search for metadata. */
  89468. FLAC__STREAM_DECODER_READ_METADATA,
  89469. /**< The decoder is ready to or is in the process of reading metadata. */
  89470. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89471. /**< The decoder is ready to or is in the process of searching for the
  89472. * frame sync code.
  89473. */
  89474. FLAC__STREAM_DECODER_READ_FRAME,
  89475. /**< The decoder is ready to or is in the process of reading a frame. */
  89476. FLAC__STREAM_DECODER_END_OF_STREAM,
  89477. /**< The decoder has reached the end of the stream. */
  89478. FLAC__STREAM_DECODER_OGG_ERROR,
  89479. /**< An error occurred in the underlying Ogg layer. */
  89480. FLAC__STREAM_DECODER_SEEK_ERROR,
  89481. /**< An error occurred while seeking. The decoder must be flushed
  89482. * with FLAC__stream_decoder_flush() or reset with
  89483. * FLAC__stream_decoder_reset() before decoding can continue.
  89484. */
  89485. FLAC__STREAM_DECODER_ABORTED,
  89486. /**< The decoder was aborted by the read callback. */
  89487. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89488. /**< An error occurred allocating memory. The decoder is in an invalid
  89489. * state and can no longer be used.
  89490. */
  89491. FLAC__STREAM_DECODER_UNINITIALIZED
  89492. /**< The decoder is in the uninitialized state; one of the
  89493. * FLAC__stream_decoder_init_*() functions must be called before samples
  89494. * can be processed.
  89495. */
  89496. } FLAC__StreamDecoderState;
  89497. /** Maps a FLAC__StreamDecoderState to a C string.
  89498. *
  89499. * Using a FLAC__StreamDecoderState as the index to this array
  89500. * will give the string equivalent. The contents should not be modified.
  89501. */
  89502. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89503. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89504. */
  89505. typedef enum {
  89506. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89507. /**< Initialization was successful. */
  89508. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89509. /**< The library was not compiled with support for the given container
  89510. * format.
  89511. */
  89512. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89513. /**< A required callback was not supplied. */
  89514. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89515. /**< An error occurred allocating memory. */
  89516. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89517. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89518. * FLAC__stream_decoder_init_ogg_file(). */
  89519. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89520. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89521. * already initialized, usually because
  89522. * FLAC__stream_decoder_finish() was not called.
  89523. */
  89524. } FLAC__StreamDecoderInitStatus;
  89525. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89526. *
  89527. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89528. * will give the string equivalent. The contents should not be modified.
  89529. */
  89530. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89531. /** Return values for the FLAC__StreamDecoder read callback.
  89532. */
  89533. typedef enum {
  89534. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89535. /**< The read was OK and decoding can continue. */
  89536. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89537. /**< The read was attempted while at the end of the stream. Note that
  89538. * the client must only return this value when the read callback was
  89539. * called when already at the end of the stream. Otherwise, if the read
  89540. * itself moves to the end of the stream, the client should still return
  89541. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89542. * the next read callback it should return
  89543. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89544. * of \c 0.
  89545. */
  89546. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89547. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89548. } FLAC__StreamDecoderReadStatus;
  89549. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89550. *
  89551. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89552. * will give the string equivalent. The contents should not be modified.
  89553. */
  89554. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89555. /** Return values for the FLAC__StreamDecoder seek callback.
  89556. */
  89557. typedef enum {
  89558. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89559. /**< The seek was OK and decoding can continue. */
  89560. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89561. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89562. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89563. /**< Client does not support seeking. */
  89564. } FLAC__StreamDecoderSeekStatus;
  89565. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89566. *
  89567. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89568. * will give the string equivalent. The contents should not be modified.
  89569. */
  89570. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89571. /** Return values for the FLAC__StreamDecoder tell callback.
  89572. */
  89573. typedef enum {
  89574. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89575. /**< The tell was OK and decoding can continue. */
  89576. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89577. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89578. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89579. /**< Client does not support telling the position. */
  89580. } FLAC__StreamDecoderTellStatus;
  89581. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89582. *
  89583. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89584. * will give the string equivalent. The contents should not be modified.
  89585. */
  89586. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89587. /** Return values for the FLAC__StreamDecoder length callback.
  89588. */
  89589. typedef enum {
  89590. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89591. /**< The length call was OK and decoding can continue. */
  89592. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89593. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89594. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89595. /**< Client does not support reporting the length. */
  89596. } FLAC__StreamDecoderLengthStatus;
  89597. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89598. *
  89599. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89600. * will give the string equivalent. The contents should not be modified.
  89601. */
  89602. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89603. /** Return values for the FLAC__StreamDecoder write callback.
  89604. */
  89605. typedef enum {
  89606. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89607. /**< The write was OK and decoding can continue. */
  89608. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89609. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89610. } FLAC__StreamDecoderWriteStatus;
  89611. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89612. *
  89613. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89614. * will give the string equivalent. The contents should not be modified.
  89615. */
  89616. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89617. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89618. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89619. * all. The rest could be caused by bad sync (false synchronization on
  89620. * data that is not the start of a frame) or corrupted data. The error
  89621. * itself is the decoder's best guess at what happened assuming a correct
  89622. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89623. * could be caused by a correct sync on the start of a frame, but some
  89624. * data in the frame header was corrupted. Or it could be the result of
  89625. * syncing on a point the stream that looked like the starting of a frame
  89626. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89627. * could be because the decoder encountered a valid frame made by a future
  89628. * version of the encoder which it cannot parse, or because of a false
  89629. * sync making it appear as though an encountered frame was generated by
  89630. * a future encoder.
  89631. */
  89632. typedef enum {
  89633. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89634. /**< An error in the stream caused the decoder to lose synchronization. */
  89635. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89636. /**< The decoder encountered a corrupted frame header. */
  89637. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89638. /**< The frame's data did not match the CRC in the footer. */
  89639. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89640. /**< The decoder encountered reserved fields in use in the stream. */
  89641. } FLAC__StreamDecoderErrorStatus;
  89642. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89643. *
  89644. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89645. * will give the string equivalent. The contents should not be modified.
  89646. */
  89647. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89648. /***********************************************************************
  89649. *
  89650. * class FLAC__StreamDecoder
  89651. *
  89652. ***********************************************************************/
  89653. struct FLAC__StreamDecoderProtected;
  89654. struct FLAC__StreamDecoderPrivate;
  89655. /** The opaque structure definition for the stream decoder type.
  89656. * See the \link flac_stream_decoder stream decoder module \endlink
  89657. * for a detailed description.
  89658. */
  89659. typedef struct {
  89660. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89661. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89662. } FLAC__StreamDecoder;
  89663. /** Signature for the read callback.
  89664. *
  89665. * A function pointer matching this signature must be passed to
  89666. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89667. * called when the decoder needs more input data. The address of the
  89668. * buffer to be filled is supplied, along with the number of bytes the
  89669. * buffer can hold. The callback may choose to supply less data and
  89670. * modify the byte count but must be careful not to overflow the buffer.
  89671. * The callback then returns a status code chosen from
  89672. * FLAC__StreamDecoderReadStatus.
  89673. *
  89674. * Here is an example of a read callback for stdio streams:
  89675. * \code
  89676. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89677. * {
  89678. * FILE *file = ((MyClientData*)client_data)->file;
  89679. * if(*bytes > 0) {
  89680. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89681. * if(ferror(file))
  89682. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89683. * else if(*bytes == 0)
  89684. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89685. * else
  89686. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89687. * }
  89688. * else
  89689. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89690. * }
  89691. * \endcode
  89692. *
  89693. * \note In general, FLAC__StreamDecoder functions which change the
  89694. * state should not be called on the \a decoder while in the callback.
  89695. *
  89696. * \param decoder The decoder instance calling the callback.
  89697. * \param buffer A pointer to a location for the callee to store
  89698. * data to be decoded.
  89699. * \param bytes A pointer to the size of the buffer. On entry
  89700. * to the callback, it contains the maximum number
  89701. * of bytes that may be stored in \a buffer. The
  89702. * callee must set it to the actual number of bytes
  89703. * stored (0 in case of error or end-of-stream) before
  89704. * returning.
  89705. * \param client_data The callee's client data set through
  89706. * FLAC__stream_decoder_init_*().
  89707. * \retval FLAC__StreamDecoderReadStatus
  89708. * The callee's return status. Note that the callback should return
  89709. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89710. * zero bytes were read and there is no more data to be read.
  89711. */
  89712. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89713. /** Signature for the seek callback.
  89714. *
  89715. * A function pointer matching this signature may be passed to
  89716. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89717. * called when the decoder needs to seek the input stream. The decoder
  89718. * will pass the absolute byte offset to seek to, 0 meaning the
  89719. * beginning of the stream.
  89720. *
  89721. * Here is an example of a seek callback for stdio streams:
  89722. * \code
  89723. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89724. * {
  89725. * FILE *file = ((MyClientData*)client_data)->file;
  89726. * if(file == stdin)
  89727. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89728. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89729. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89730. * else
  89731. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89732. * }
  89733. * \endcode
  89734. *
  89735. * \note In general, FLAC__StreamDecoder functions which change the
  89736. * state should not be called on the \a decoder while in the callback.
  89737. *
  89738. * \param decoder The decoder instance calling the callback.
  89739. * \param absolute_byte_offset The offset from the beginning of the stream
  89740. * to seek to.
  89741. * \param client_data The callee's client data set through
  89742. * FLAC__stream_decoder_init_*().
  89743. * \retval FLAC__StreamDecoderSeekStatus
  89744. * The callee's return status.
  89745. */
  89746. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89747. /** Signature for the tell callback.
  89748. *
  89749. * A function pointer matching this signature may be passed to
  89750. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89751. * called when the decoder wants to know the current position of the
  89752. * stream. The callback should return the byte offset from the
  89753. * beginning of the stream.
  89754. *
  89755. * Here is an example of a tell callback for stdio streams:
  89756. * \code
  89757. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89758. * {
  89759. * FILE *file = ((MyClientData*)client_data)->file;
  89760. * off_t pos;
  89761. * if(file == stdin)
  89762. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89763. * else if((pos = ftello(file)) < 0)
  89764. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89765. * else {
  89766. * *absolute_byte_offset = (FLAC__uint64)pos;
  89767. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89768. * }
  89769. * }
  89770. * \endcode
  89771. *
  89772. * \note In general, FLAC__StreamDecoder functions which change the
  89773. * state should not be called on the \a decoder while in the callback.
  89774. *
  89775. * \param decoder The decoder instance calling the callback.
  89776. * \param absolute_byte_offset A pointer to storage for the current offset
  89777. * from the beginning of the stream.
  89778. * \param client_data The callee's client data set through
  89779. * FLAC__stream_decoder_init_*().
  89780. * \retval FLAC__StreamDecoderTellStatus
  89781. * The callee's return status.
  89782. */
  89783. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89784. /** Signature for the length callback.
  89785. *
  89786. * A function pointer matching this signature may be passed to
  89787. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89788. * called when the decoder wants to know the total length of the stream
  89789. * in bytes.
  89790. *
  89791. * Here is an example of a length callback for stdio streams:
  89792. * \code
  89793. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89794. * {
  89795. * FILE *file = ((MyClientData*)client_data)->file;
  89796. * struct stat filestats;
  89797. *
  89798. * if(file == stdin)
  89799. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89800. * else if(fstat(fileno(file), &filestats) != 0)
  89801. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89802. * else {
  89803. * *stream_length = (FLAC__uint64)filestats.st_size;
  89804. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89805. * }
  89806. * }
  89807. * \endcode
  89808. *
  89809. * \note In general, FLAC__StreamDecoder functions which change the
  89810. * state should not be called on the \a decoder while in the callback.
  89811. *
  89812. * \param decoder The decoder instance calling the callback.
  89813. * \param stream_length A pointer to storage for the length of the stream
  89814. * in bytes.
  89815. * \param client_data The callee's client data set through
  89816. * FLAC__stream_decoder_init_*().
  89817. * \retval FLAC__StreamDecoderLengthStatus
  89818. * The callee's return status.
  89819. */
  89820. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89821. /** Signature for the EOF callback.
  89822. *
  89823. * A function pointer matching this signature may be passed to
  89824. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89825. * called when the decoder needs to know if the end of the stream has
  89826. * been reached.
  89827. *
  89828. * Here is an example of a EOF callback for stdio streams:
  89829. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89830. * \code
  89831. * {
  89832. * FILE *file = ((MyClientData*)client_data)->file;
  89833. * return feof(file)? true : false;
  89834. * }
  89835. * \endcode
  89836. *
  89837. * \note In general, FLAC__StreamDecoder functions which change the
  89838. * state should not be called on the \a decoder while in the callback.
  89839. *
  89840. * \param decoder The decoder instance calling the callback.
  89841. * \param client_data The callee's client data set through
  89842. * FLAC__stream_decoder_init_*().
  89843. * \retval FLAC__bool
  89844. * \c true if the currently at the end of the stream, else \c false.
  89845. */
  89846. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89847. /** Signature for the write callback.
  89848. *
  89849. * A function pointer matching this signature must be passed to one of
  89850. * the FLAC__stream_decoder_init_*() functions.
  89851. * The supplied function will be called when the decoder has decoded a
  89852. * single audio frame. The decoder will pass the frame metadata as well
  89853. * as an array of pointers (one for each channel) pointing to the
  89854. * decoded audio.
  89855. *
  89856. * \note In general, FLAC__StreamDecoder functions which change the
  89857. * state should not be called on the \a decoder while in the callback.
  89858. *
  89859. * \param decoder The decoder instance calling the callback.
  89860. * \param frame The description of the decoded frame. See
  89861. * FLAC__Frame.
  89862. * \param buffer An array of pointers to decoded channels of data.
  89863. * Each pointer will point to an array of signed
  89864. * samples of length \a frame->header.blocksize.
  89865. * Channels will be ordered according to the FLAC
  89866. * specification; see the documentation for the
  89867. * <A HREF="../format.html#frame_header">frame header</A>.
  89868. * \param client_data The callee's client data set through
  89869. * FLAC__stream_decoder_init_*().
  89870. * \retval FLAC__StreamDecoderWriteStatus
  89871. * The callee's return status.
  89872. */
  89873. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89874. /** Signature for the metadata callback.
  89875. *
  89876. * A function pointer matching this signature must be passed to one of
  89877. * the FLAC__stream_decoder_init_*() functions.
  89878. * The supplied function will be called when the decoder has decoded a
  89879. * metadata block. In a valid FLAC file there will always be one
  89880. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89881. * These will be supplied by the decoder in the same order as they
  89882. * appear in the stream and always before the first audio frame (i.e.
  89883. * write callback). The metadata block that is passed in must not be
  89884. * modified, and it doesn't live beyond the callback, so you should make
  89885. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89886. * elsewhere. Since metadata blocks can potentially be large, by
  89887. * default the decoder only calls the metadata callback for the
  89888. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89889. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89890. *
  89891. * \note In general, FLAC__StreamDecoder functions which change the
  89892. * state should not be called on the \a decoder while in the callback.
  89893. *
  89894. * \param decoder The decoder instance calling the callback.
  89895. * \param metadata The decoded metadata block.
  89896. * \param client_data The callee's client data set through
  89897. * FLAC__stream_decoder_init_*().
  89898. */
  89899. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89900. /** Signature for the error callback.
  89901. *
  89902. * A function pointer matching this signature must be passed to one of
  89903. * the FLAC__stream_decoder_init_*() functions.
  89904. * The supplied function will be called whenever an error occurs during
  89905. * decoding.
  89906. *
  89907. * \note In general, FLAC__StreamDecoder functions which change the
  89908. * state should not be called on the \a decoder while in the callback.
  89909. *
  89910. * \param decoder The decoder instance calling the callback.
  89911. * \param status The error encountered by the decoder.
  89912. * \param client_data The callee's client data set through
  89913. * FLAC__stream_decoder_init_*().
  89914. */
  89915. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89916. /***********************************************************************
  89917. *
  89918. * Class constructor/destructor
  89919. *
  89920. ***********************************************************************/
  89921. /** Create a new stream decoder instance. The instance is created with
  89922. * default settings; see the individual FLAC__stream_decoder_set_*()
  89923. * functions for each setting's default.
  89924. *
  89925. * \retval FLAC__StreamDecoder*
  89926. * \c NULL if there was an error allocating memory, else the new instance.
  89927. */
  89928. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89929. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89930. *
  89931. * \param decoder A pointer to an existing decoder.
  89932. * \assert
  89933. * \code decoder != NULL \endcode
  89934. */
  89935. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89936. /***********************************************************************
  89937. *
  89938. * Public class method prototypes
  89939. *
  89940. ***********************************************************************/
  89941. /** Set the serial number for the FLAC stream within the Ogg container.
  89942. * The default behavior is to use the serial number of the first Ogg
  89943. * page. Setting a serial number here will explicitly specify which
  89944. * stream is to be decoded.
  89945. *
  89946. * \note
  89947. * This does not need to be set for native FLAC decoding.
  89948. *
  89949. * \default \c use serial number of first page
  89950. * \param decoder A decoder instance to set.
  89951. * \param serial_number See above.
  89952. * \assert
  89953. * \code decoder != NULL \endcode
  89954. * \retval FLAC__bool
  89955. * \c false if the decoder is already initialized, else \c true.
  89956. */
  89957. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89958. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89959. * compute the MD5 signature of the unencoded audio data while decoding
  89960. * and compare it to the signature from the STREAMINFO block, if it
  89961. * exists, during FLAC__stream_decoder_finish().
  89962. *
  89963. * MD5 signature checking will be turned off (until the next
  89964. * FLAC__stream_decoder_reset()) if there is no signature in the
  89965. * STREAMINFO block or when a seek is attempted.
  89966. *
  89967. * Clients that do not use the MD5 check should leave this off to speed
  89968. * up decoding.
  89969. *
  89970. * \default \c false
  89971. * \param decoder A decoder instance to set.
  89972. * \param value Flag value (see above).
  89973. * \assert
  89974. * \code decoder != NULL \endcode
  89975. * \retval FLAC__bool
  89976. * \c false if the decoder is already initialized, else \c true.
  89977. */
  89978. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89979. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89980. *
  89981. * \default By default, only the \c STREAMINFO block is returned via the
  89982. * metadata callback.
  89983. * \param decoder A decoder instance to set.
  89984. * \param type See above.
  89985. * \assert
  89986. * \code decoder != NULL \endcode
  89987. * \a type is valid
  89988. * \retval FLAC__bool
  89989. * \c false if the decoder is already initialized, else \c true.
  89990. */
  89991. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89992. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89993. * given \a id.
  89994. *
  89995. * \default By default, only the \c STREAMINFO block is returned via the
  89996. * metadata callback.
  89997. * \param decoder A decoder instance to set.
  89998. * \param id See above.
  89999. * \assert
  90000. * \code decoder != NULL \endcode
  90001. * \code id != NULL \endcode
  90002. * \retval FLAC__bool
  90003. * \c false if the decoder is already initialized, else \c true.
  90004. */
  90005. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90006. /** Direct the decoder to pass on all metadata blocks of any type.
  90007. *
  90008. * \default By default, only the \c STREAMINFO block is returned via the
  90009. * metadata callback.
  90010. * \param decoder A decoder instance to set.
  90011. * \assert
  90012. * \code decoder != NULL \endcode
  90013. * \retval FLAC__bool
  90014. * \c false if the decoder is already initialized, else \c true.
  90015. */
  90016. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90017. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90018. *
  90019. * \default By default, only the \c STREAMINFO block is returned via the
  90020. * metadata callback.
  90021. * \param decoder A decoder instance to set.
  90022. * \param type See above.
  90023. * \assert
  90024. * \code decoder != NULL \endcode
  90025. * \a type is valid
  90026. * \retval FLAC__bool
  90027. * \c false if the decoder is already initialized, else \c true.
  90028. */
  90029. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90030. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90031. * the given \a id.
  90032. *
  90033. * \default By default, only the \c STREAMINFO block is returned via the
  90034. * metadata callback.
  90035. * \param decoder A decoder instance to set.
  90036. * \param id See above.
  90037. * \assert
  90038. * \code decoder != NULL \endcode
  90039. * \code id != NULL \endcode
  90040. * \retval FLAC__bool
  90041. * \c false if the decoder is already initialized, else \c true.
  90042. */
  90043. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90044. /** Direct the decoder to filter out all metadata blocks of any type.
  90045. *
  90046. * \default By default, only the \c STREAMINFO block is returned via the
  90047. * metadata callback.
  90048. * \param decoder A decoder instance to set.
  90049. * \assert
  90050. * \code decoder != NULL \endcode
  90051. * \retval FLAC__bool
  90052. * \c false if the decoder is already initialized, else \c true.
  90053. */
  90054. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90055. /** Get the current decoder state.
  90056. *
  90057. * \param decoder A decoder instance to query.
  90058. * \assert
  90059. * \code decoder != NULL \endcode
  90060. * \retval FLAC__StreamDecoderState
  90061. * The current decoder state.
  90062. */
  90063. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90064. /** Get the current decoder state as a C string.
  90065. *
  90066. * \param decoder A decoder instance to query.
  90067. * \assert
  90068. * \code decoder != NULL \endcode
  90069. * \retval const char *
  90070. * The decoder state as a C string. Do not modify the contents.
  90071. */
  90072. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90073. /** Get the "MD5 signature checking" flag.
  90074. * This is the value of the setting, not whether or not the decoder is
  90075. * currently checking the MD5 (remember, it can be turned off automatically
  90076. * by a seek). When the decoder is reset the flag will be restored to the
  90077. * value returned by this function.
  90078. *
  90079. * \param decoder A decoder instance to query.
  90080. * \assert
  90081. * \code decoder != NULL \endcode
  90082. * \retval FLAC__bool
  90083. * See above.
  90084. */
  90085. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90086. /** Get the total number of samples in the stream being decoded.
  90087. * Will only be valid after decoding has started and will contain the
  90088. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90089. *
  90090. * \param decoder A decoder instance to query.
  90091. * \assert
  90092. * \code decoder != NULL \endcode
  90093. * \retval unsigned
  90094. * See above.
  90095. */
  90096. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90097. /** Get the current number of channels in the stream being decoded.
  90098. * Will only be valid after decoding has started and will contain the
  90099. * value from the most recently decoded frame header.
  90100. *
  90101. * \param decoder A decoder instance to query.
  90102. * \assert
  90103. * \code decoder != NULL \endcode
  90104. * \retval unsigned
  90105. * See above.
  90106. */
  90107. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90108. /** Get the current channel assignment in the stream being decoded.
  90109. * Will only be valid after decoding has started and will contain the
  90110. * value from the most recently decoded frame header.
  90111. *
  90112. * \param decoder A decoder instance to query.
  90113. * \assert
  90114. * \code decoder != NULL \endcode
  90115. * \retval FLAC__ChannelAssignment
  90116. * See above.
  90117. */
  90118. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90119. /** Get the current sample resolution in the stream being decoded.
  90120. * Will only be valid after decoding has started and will contain the
  90121. * value from the most recently decoded frame header.
  90122. *
  90123. * \param decoder A decoder instance to query.
  90124. * \assert
  90125. * \code decoder != NULL \endcode
  90126. * \retval unsigned
  90127. * See above.
  90128. */
  90129. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90130. /** Get the current sample rate in Hz of the stream being decoded.
  90131. * Will only be valid after decoding has started and will contain the
  90132. * value from the most recently decoded frame header.
  90133. *
  90134. * \param decoder A decoder instance to query.
  90135. * \assert
  90136. * \code decoder != NULL \endcode
  90137. * \retval unsigned
  90138. * See above.
  90139. */
  90140. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90141. /** Get the current blocksize of the stream being decoded.
  90142. * Will only be valid after decoding has started and will contain the
  90143. * value from the most recently decoded frame header.
  90144. *
  90145. * \param decoder A decoder instance to query.
  90146. * \assert
  90147. * \code decoder != NULL \endcode
  90148. * \retval unsigned
  90149. * See above.
  90150. */
  90151. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90152. /** Returns the decoder's current read position within the stream.
  90153. * The position is the byte offset from the start of the stream.
  90154. * Bytes before this position have been fully decoded. Note that
  90155. * there may still be undecoded bytes in the decoder's read FIFO.
  90156. * The returned position is correct even after a seek.
  90157. *
  90158. * \warning This function currently only works for native FLAC,
  90159. * not Ogg FLAC streams.
  90160. *
  90161. * \param decoder A decoder instance to query.
  90162. * \param position Address at which to return the desired position.
  90163. * \assert
  90164. * \code decoder != NULL \endcode
  90165. * \code position != NULL \endcode
  90166. * \retval FLAC__bool
  90167. * \c true if successful, \c false if the stream is not native FLAC,
  90168. * or there was an error from the 'tell' callback or it returned
  90169. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90170. */
  90171. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90172. /** Initialize the decoder instance to decode native FLAC streams.
  90173. *
  90174. * This flavor of initialization sets up the decoder to decode from a
  90175. * native FLAC stream. I/O is performed via callbacks to the client.
  90176. * For decoding from a plain file via filename or open FILE*,
  90177. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90178. * provide a simpler interface.
  90179. *
  90180. * This function should be called after FLAC__stream_decoder_new() and
  90181. * FLAC__stream_decoder_set_*() but before any of the
  90182. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90183. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90184. * if initialization succeeded.
  90185. *
  90186. * \param decoder An uninitialized decoder instance.
  90187. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90188. * pointer must not be \c NULL.
  90189. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90190. * pointer may be \c NULL if seeking is not
  90191. * supported. If \a seek_callback is not \c NULL then a
  90192. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90193. * Alternatively, a dummy seek callback that just
  90194. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90195. * may also be supplied, all though this is slightly
  90196. * less efficient for the decoder.
  90197. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90198. * pointer may be \c NULL if not supported by the client. If
  90199. * \a seek_callback is not \c NULL then a
  90200. * \a tell_callback must also be supplied.
  90201. * Alternatively, a dummy tell callback that just
  90202. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90203. * may also be supplied, all though this is slightly
  90204. * less efficient for the decoder.
  90205. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90206. * pointer may be \c NULL if not supported by the client. If
  90207. * \a seek_callback is not \c NULL then a
  90208. * \a length_callback must also be supplied.
  90209. * Alternatively, a dummy length callback that just
  90210. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90211. * may also be supplied, all though this is slightly
  90212. * less efficient for the decoder.
  90213. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90214. * pointer may be \c NULL if not supported by the client. If
  90215. * \a seek_callback is not \c NULL then a
  90216. * \a eof_callback must also be supplied.
  90217. * Alternatively, a dummy length callback that just
  90218. * returns \c false
  90219. * may also be supplied, all though this is slightly
  90220. * less efficient for the decoder.
  90221. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90222. * pointer must not be \c NULL.
  90223. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90224. * pointer may be \c NULL if the callback is not
  90225. * desired.
  90226. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90227. * pointer must not be \c NULL.
  90228. * \param client_data This value will be supplied to callbacks in their
  90229. * \a client_data argument.
  90230. * \assert
  90231. * \code decoder != NULL \endcode
  90232. * \retval FLAC__StreamDecoderInitStatus
  90233. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90234. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90235. */
  90236. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90237. FLAC__StreamDecoder *decoder,
  90238. FLAC__StreamDecoderReadCallback read_callback,
  90239. FLAC__StreamDecoderSeekCallback seek_callback,
  90240. FLAC__StreamDecoderTellCallback tell_callback,
  90241. FLAC__StreamDecoderLengthCallback length_callback,
  90242. FLAC__StreamDecoderEofCallback eof_callback,
  90243. FLAC__StreamDecoderWriteCallback write_callback,
  90244. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90245. FLAC__StreamDecoderErrorCallback error_callback,
  90246. void *client_data
  90247. );
  90248. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90249. *
  90250. * This flavor of initialization sets up the decoder to decode from a
  90251. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90252. * client. For decoding from a plain file via filename or open FILE*,
  90253. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90254. * provide a simpler interface.
  90255. *
  90256. * This function should be called after FLAC__stream_decoder_new() and
  90257. * FLAC__stream_decoder_set_*() but before any of the
  90258. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90259. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90260. * if initialization succeeded.
  90261. *
  90262. * \note Support for Ogg FLAC in the library is optional. If this
  90263. * library has been built without support for Ogg FLAC, this function
  90264. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90265. *
  90266. * \param decoder An uninitialized decoder instance.
  90267. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90268. * pointer must not be \c NULL.
  90269. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90270. * pointer may be \c NULL if seeking is not
  90271. * supported. If \a seek_callback is not \c NULL then a
  90272. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90273. * Alternatively, a dummy seek callback that just
  90274. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90275. * may also be supplied, all though this is slightly
  90276. * less efficient for the decoder.
  90277. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90278. * pointer may be \c NULL if not supported by the client. If
  90279. * \a seek_callback is not \c NULL then a
  90280. * \a tell_callback must also be supplied.
  90281. * Alternatively, a dummy tell callback that just
  90282. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90283. * may also be supplied, all though this is slightly
  90284. * less efficient for the decoder.
  90285. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90286. * pointer may be \c NULL if not supported by the client. If
  90287. * \a seek_callback is not \c NULL then a
  90288. * \a length_callback must also be supplied.
  90289. * Alternatively, a dummy length callback that just
  90290. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90291. * may also be supplied, all though this is slightly
  90292. * less efficient for the decoder.
  90293. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90294. * pointer may be \c NULL if not supported by the client. If
  90295. * \a seek_callback is not \c NULL then a
  90296. * \a eof_callback must also be supplied.
  90297. * Alternatively, a dummy length callback that just
  90298. * returns \c false
  90299. * may also be supplied, all though this is slightly
  90300. * less efficient for the decoder.
  90301. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90302. * pointer must not be \c NULL.
  90303. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90304. * pointer may be \c NULL if the callback is not
  90305. * desired.
  90306. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90307. * pointer must not be \c NULL.
  90308. * \param client_data This value will be supplied to callbacks in their
  90309. * \a client_data argument.
  90310. * \assert
  90311. * \code decoder != NULL \endcode
  90312. * \retval FLAC__StreamDecoderInitStatus
  90313. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90314. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90315. */
  90316. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90317. FLAC__StreamDecoder *decoder,
  90318. FLAC__StreamDecoderReadCallback read_callback,
  90319. FLAC__StreamDecoderSeekCallback seek_callback,
  90320. FLAC__StreamDecoderTellCallback tell_callback,
  90321. FLAC__StreamDecoderLengthCallback length_callback,
  90322. FLAC__StreamDecoderEofCallback eof_callback,
  90323. FLAC__StreamDecoderWriteCallback write_callback,
  90324. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90325. FLAC__StreamDecoderErrorCallback error_callback,
  90326. void *client_data
  90327. );
  90328. /** Initialize the decoder instance to decode native FLAC files.
  90329. *
  90330. * This flavor of initialization sets up the decoder to decode from a
  90331. * plain native FLAC file. For non-stdio streams, you must use
  90332. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90333. *
  90334. * This function should be called after FLAC__stream_decoder_new() and
  90335. * FLAC__stream_decoder_set_*() but before any of the
  90336. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90337. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90338. * if initialization succeeded.
  90339. *
  90340. * \param decoder An uninitialized decoder instance.
  90341. * \param file An open FLAC file. The file should have been
  90342. * opened with mode \c "rb" and rewound. The file
  90343. * becomes owned by the decoder and should not be
  90344. * manipulated by the client while decoding.
  90345. * Unless \a file is \c stdin, it will be closed
  90346. * when FLAC__stream_decoder_finish() is called.
  90347. * Note however that seeking will not work when
  90348. * decoding from \c stdout since it is not seekable.
  90349. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90350. * pointer must not be \c NULL.
  90351. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90352. * pointer may be \c NULL if the callback is not
  90353. * desired.
  90354. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90355. * pointer must not be \c NULL.
  90356. * \param client_data This value will be supplied to callbacks in their
  90357. * \a client_data argument.
  90358. * \assert
  90359. * \code decoder != NULL \endcode
  90360. * \code file != NULL \endcode
  90361. * \retval FLAC__StreamDecoderInitStatus
  90362. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90363. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90364. */
  90365. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90366. FLAC__StreamDecoder *decoder,
  90367. FILE *file,
  90368. FLAC__StreamDecoderWriteCallback write_callback,
  90369. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90370. FLAC__StreamDecoderErrorCallback error_callback,
  90371. void *client_data
  90372. );
  90373. /** Initialize the decoder instance to decode Ogg FLAC files.
  90374. *
  90375. * This flavor of initialization sets up the decoder to decode from a
  90376. * plain Ogg FLAC file. For non-stdio streams, you must use
  90377. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90378. *
  90379. * This function should be called after FLAC__stream_decoder_new() and
  90380. * FLAC__stream_decoder_set_*() but before any of the
  90381. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90382. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90383. * if initialization succeeded.
  90384. *
  90385. * \note Support for Ogg FLAC in the library is optional. If this
  90386. * library has been built without support for Ogg FLAC, this function
  90387. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90388. *
  90389. * \param decoder An uninitialized decoder instance.
  90390. * \param file An open FLAC file. The file should have been
  90391. * opened with mode \c "rb" and rewound. The file
  90392. * becomes owned by the decoder and should not be
  90393. * manipulated by the client while decoding.
  90394. * Unless \a file is \c stdin, it will be closed
  90395. * when FLAC__stream_decoder_finish() is called.
  90396. * Note however that seeking will not work when
  90397. * decoding from \c stdout since it is not seekable.
  90398. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90399. * pointer must not be \c NULL.
  90400. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90401. * pointer may be \c NULL if the callback is not
  90402. * desired.
  90403. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90404. * pointer must not be \c NULL.
  90405. * \param client_data This value will be supplied to callbacks in their
  90406. * \a client_data argument.
  90407. * \assert
  90408. * \code decoder != NULL \endcode
  90409. * \code file != NULL \endcode
  90410. * \retval FLAC__StreamDecoderInitStatus
  90411. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90412. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90413. */
  90414. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90415. FLAC__StreamDecoder *decoder,
  90416. FILE *file,
  90417. FLAC__StreamDecoderWriteCallback write_callback,
  90418. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90419. FLAC__StreamDecoderErrorCallback error_callback,
  90420. void *client_data
  90421. );
  90422. /** Initialize the decoder instance to decode native FLAC files.
  90423. *
  90424. * This flavor of initialization sets up the decoder to decode from a plain
  90425. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90426. * example, with Unicode filenames on Windows), you must use
  90427. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90428. * and provide callbacks for the I/O.
  90429. *
  90430. * This function should be called after FLAC__stream_decoder_new() and
  90431. * FLAC__stream_decoder_set_*() but before any of the
  90432. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90433. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90434. * if initialization succeeded.
  90435. *
  90436. * \param decoder An uninitialized decoder instance.
  90437. * \param filename The name of the file to decode from. The file will
  90438. * be opened with fopen(). Use \c NULL to decode from
  90439. * \c stdin. Note that \c stdin is not seekable.
  90440. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90441. * pointer must not be \c NULL.
  90442. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90443. * pointer may be \c NULL if the callback is not
  90444. * desired.
  90445. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90446. * pointer must not be \c NULL.
  90447. * \param client_data This value will be supplied to callbacks in their
  90448. * \a client_data argument.
  90449. * \assert
  90450. * \code decoder != NULL \endcode
  90451. * \retval FLAC__StreamDecoderInitStatus
  90452. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90453. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90454. */
  90455. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90456. FLAC__StreamDecoder *decoder,
  90457. const char *filename,
  90458. FLAC__StreamDecoderWriteCallback write_callback,
  90459. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90460. FLAC__StreamDecoderErrorCallback error_callback,
  90461. void *client_data
  90462. );
  90463. /** Initialize the decoder instance to decode Ogg FLAC files.
  90464. *
  90465. * This flavor of initialization sets up the decoder to decode from a plain
  90466. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90467. * example, with Unicode filenames on Windows), you must use
  90468. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90469. * and provide callbacks for the I/O.
  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. * \note Support for Ogg FLAC in the library is optional. If this
  90478. * library has been built without support for Ogg FLAC, this function
  90479. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90480. *
  90481. * \param decoder An uninitialized decoder instance.
  90482. * \param filename The name of the file to decode from. The file will
  90483. * be opened with fopen(). Use \c NULL to decode from
  90484. * \c stdin. Note that \c stdin is not seekable.
  90485. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90486. * pointer must not be \c NULL.
  90487. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90488. * pointer may be \c NULL if the callback is not
  90489. * desired.
  90490. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90491. * pointer must not be \c NULL.
  90492. * \param client_data This value will be supplied to callbacks in their
  90493. * \a client_data argument.
  90494. * \assert
  90495. * \code decoder != NULL \endcode
  90496. * \retval FLAC__StreamDecoderInitStatus
  90497. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90498. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90499. */
  90500. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90501. FLAC__StreamDecoder *decoder,
  90502. const char *filename,
  90503. FLAC__StreamDecoderWriteCallback write_callback,
  90504. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90505. FLAC__StreamDecoderErrorCallback error_callback,
  90506. void *client_data
  90507. );
  90508. /** Finish the decoding process.
  90509. * Flushes the decoding buffer, releases resources, resets the decoder
  90510. * settings to their defaults, and returns the decoder state to
  90511. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90512. *
  90513. * In the event of a prematurely-terminated decode, it is not strictly
  90514. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90515. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90516. * with a FLAC__stream_decoder_finish().
  90517. *
  90518. * \param decoder An uninitialized decoder instance.
  90519. * \assert
  90520. * \code decoder != NULL \endcode
  90521. * \retval FLAC__bool
  90522. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90523. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90524. * signature does not match the one computed by the decoder; else
  90525. * \c true.
  90526. */
  90527. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90528. /** Flush the stream input.
  90529. * The decoder's input buffer will be cleared and the state set to
  90530. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90531. * off MD5 checking.
  90532. *
  90533. * \param decoder A decoder instance.
  90534. * \assert
  90535. * \code decoder != NULL \endcode
  90536. * \retval FLAC__bool
  90537. * \c true if successful, else \c false if a memory allocation
  90538. * error occurs (in which case the state will be set to
  90539. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90540. */
  90541. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90542. /** Reset the decoding process.
  90543. * The decoder's input buffer will be cleared and the state set to
  90544. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90545. * FLAC__stream_decoder_finish() except that the settings are
  90546. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90547. * before decoding again. MD5 checking will be restored to its original
  90548. * setting.
  90549. *
  90550. * If the decoder is seekable, or was initialized with
  90551. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90552. * the decoder will also attempt to seek to the beginning of the file.
  90553. * If this rewind fails, this function will return \c false. It follows
  90554. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90555. * \c stdin.
  90556. *
  90557. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90558. * and is not seekable (i.e. no seek callback was provided or the seek
  90559. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90560. * is the duty of the client to start feeding data from the beginning of
  90561. * the stream on the next FLAC__stream_decoder_process() or
  90562. * FLAC__stream_decoder_process_interleaved() call.
  90563. *
  90564. * \param decoder A decoder instance.
  90565. * \assert
  90566. * \code decoder != NULL \endcode
  90567. * \retval FLAC__bool
  90568. * \c true if successful, else \c false if a memory allocation occurs
  90569. * (in which case the state will be set to
  90570. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90571. * occurs (the state will be unchanged).
  90572. */
  90573. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90574. /** Decode one metadata block or audio frame.
  90575. * This version instructs the decoder to decode a either a single metadata
  90576. * block or a single frame and stop, unless the callbacks return a fatal
  90577. * error or the read callback returns
  90578. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90579. *
  90580. * As the decoder needs more input it will call the read callback.
  90581. * Depending on what was decoded, the metadata or write callback will be
  90582. * called with the decoded metadata block or audio frame.
  90583. *
  90584. * Unless there is a fatal read error or end of stream, this function
  90585. * will return once one whole frame is decoded. In other words, if the
  90586. * stream is not synchronized or points to a corrupt frame header, the
  90587. * decoder will continue to try and resync until it gets to a valid
  90588. * frame, then decode one frame, then return. If the decoder points to
  90589. * a frame whose frame CRC in the frame footer does not match the
  90590. * computed frame CRC, this function will issue a
  90591. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90592. * error callback, and return, having decoded one complete, although
  90593. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90594. * correct length to the write callback.)
  90595. *
  90596. * \param decoder An initialized decoder instance.
  90597. * \assert
  90598. * \code decoder != NULL \endcode
  90599. * \retval FLAC__bool
  90600. * \c false if any fatal read, write, or memory allocation error
  90601. * occurred (meaning decoding must stop), else \c true; for more
  90602. * information about the decoder, check the decoder state with
  90603. * FLAC__stream_decoder_get_state().
  90604. */
  90605. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90606. /** Decode until the end of the metadata.
  90607. * This version instructs the decoder to decode from the current position
  90608. * and continue until all the metadata has been read, or until the
  90609. * callbacks return a fatal error or the read callback returns
  90610. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90611. *
  90612. * As the decoder needs more input it will call the read callback.
  90613. * As each metadata block is decoded, the metadata callback will be called
  90614. * with the decoded metadata.
  90615. *
  90616. * \param decoder An initialized decoder instance.
  90617. * \assert
  90618. * \code decoder != NULL \endcode
  90619. * \retval FLAC__bool
  90620. * \c false if any fatal read, write, or memory allocation error
  90621. * occurred (meaning decoding must stop), else \c true; for more
  90622. * information about the decoder, check the decoder state with
  90623. * FLAC__stream_decoder_get_state().
  90624. */
  90625. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90626. /** Decode until the end of the stream.
  90627. * This version instructs the decoder to decode from the current position
  90628. * and continue until the end of stream (the read callback returns
  90629. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90630. * callbacks return a fatal error.
  90631. *
  90632. * As the decoder needs more input it will call the read callback.
  90633. * As each metadata block and frame is decoded, the metadata or write
  90634. * callback will be called with the decoded metadata or frame.
  90635. *
  90636. * \param decoder An initialized decoder instance.
  90637. * \assert
  90638. * \code decoder != NULL \endcode
  90639. * \retval FLAC__bool
  90640. * \c false if any fatal read, write, or memory allocation error
  90641. * occurred (meaning decoding must stop), else \c true; for more
  90642. * information about the decoder, check the decoder state with
  90643. * FLAC__stream_decoder_get_state().
  90644. */
  90645. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90646. /** Skip one audio frame.
  90647. * This version instructs the decoder to 'skip' a single frame and stop,
  90648. * unless the callbacks return a fatal error or the read callback returns
  90649. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90650. *
  90651. * The decoding flow is the same as what occurs when
  90652. * FLAC__stream_decoder_process_single() is called to process an audio
  90653. * frame, except that this function does not decode the parsed data into
  90654. * PCM or call the write callback. The integrity of the frame is still
  90655. * checked the same way as in the other process functions.
  90656. *
  90657. * This function will return once one whole frame is skipped, in the
  90658. * same way that FLAC__stream_decoder_process_single() will return once
  90659. * one whole frame is decoded.
  90660. *
  90661. * This function can be used in more quickly determining FLAC frame
  90662. * boundaries when decoding of the actual data is not needed, for
  90663. * example when an application is separating a FLAC stream into frames
  90664. * for editing or storing in a container. To do this, the application
  90665. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90666. * to the next frame, then use
  90667. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90668. * boundary.
  90669. *
  90670. * This function should only be called when the stream has advanced
  90671. * past all the metadata, otherwise it will return \c false.
  90672. *
  90673. * \param decoder An initialized decoder instance not in a metadata
  90674. * state.
  90675. * \assert
  90676. * \code decoder != NULL \endcode
  90677. * \retval FLAC__bool
  90678. * \c false if any fatal read, write, or memory allocation error
  90679. * occurred (meaning decoding must stop), or if the decoder
  90680. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90681. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90682. * information about the decoder, check the decoder state with
  90683. * FLAC__stream_decoder_get_state().
  90684. */
  90685. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90686. /** Flush the input and seek to an absolute sample.
  90687. * Decoding will resume at the given sample. Note that because of
  90688. * this, the next write callback may contain a partial block. The
  90689. * client must support seeking the input or this function will fail
  90690. * and return \c false. Furthermore, if the decoder state is
  90691. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90692. * with FLAC__stream_decoder_flush() or reset with
  90693. * FLAC__stream_decoder_reset() before decoding can continue.
  90694. *
  90695. * \param decoder A decoder instance.
  90696. * \param sample The target sample number to seek to.
  90697. * \assert
  90698. * \code decoder != NULL \endcode
  90699. * \retval FLAC__bool
  90700. * \c true if successful, else \c false.
  90701. */
  90702. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90703. /* \} */
  90704. #ifdef __cplusplus
  90705. }
  90706. #endif
  90707. #endif
  90708. /*** End of inlined file: stream_decoder.h ***/
  90709. /*** Start of inlined file: stream_encoder.h ***/
  90710. #ifndef FLAC__STREAM_ENCODER_H
  90711. #define FLAC__STREAM_ENCODER_H
  90712. #include <stdio.h> /* for FILE */
  90713. #ifdef __cplusplus
  90714. extern "C" {
  90715. #endif
  90716. /** \file include/FLAC/stream_encoder.h
  90717. *
  90718. * \brief
  90719. * This module contains the functions which implement the stream
  90720. * encoder.
  90721. *
  90722. * See the detailed documentation in the
  90723. * \link flac_stream_encoder stream encoder \endlink module.
  90724. */
  90725. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90726. * \ingroup flac
  90727. *
  90728. * \brief
  90729. * This module describes the encoder layers provided by libFLAC.
  90730. *
  90731. * The stream encoder can be used to encode complete streams either to the
  90732. * client via callbacks, or directly to a file, depending on how it is
  90733. * initialized. When encoding via callbacks, the client provides a write
  90734. * callback which will be called whenever FLAC data is ready to be written.
  90735. * If the client also supplies a seek callback, the encoder will also
  90736. * automatically handle the writing back of metadata discovered while
  90737. * encoding, like stream info, seek points offsets, etc. When encoding to
  90738. * a file, the client needs only supply a filename or open \c FILE* and an
  90739. * optional progress callback for periodic notification of progress; the
  90740. * write and seek callbacks are supplied internally. For more info see the
  90741. * \link flac_stream_encoder stream encoder \endlink module.
  90742. */
  90743. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90744. * \ingroup flac_encoder
  90745. *
  90746. * \brief
  90747. * This module contains the functions which implement the stream
  90748. * encoder.
  90749. *
  90750. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90751. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90752. *
  90753. * The basic usage of this encoder is as follows:
  90754. * - The program creates an instance of an encoder using
  90755. * FLAC__stream_encoder_new().
  90756. * - The program overrides the default settings using
  90757. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90758. * functions should be called:
  90759. * - FLAC__stream_encoder_set_channels()
  90760. * - FLAC__stream_encoder_set_bits_per_sample()
  90761. * - FLAC__stream_encoder_set_sample_rate()
  90762. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90763. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90764. * - If the application wants to control the compression level or set its own
  90765. * metadata, then the following should also be called:
  90766. * - FLAC__stream_encoder_set_compression_level()
  90767. * - FLAC__stream_encoder_set_verify()
  90768. * - FLAC__stream_encoder_set_metadata()
  90769. * - The rest of the set functions should only be called if the client needs
  90770. * exact control over how the audio is compressed; thorough understanding
  90771. * of the FLAC format is necessary to achieve good results.
  90772. * - The program initializes the instance to validate the settings and
  90773. * prepare for encoding using
  90774. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90775. * or FLAC__stream_encoder_init_file() for native FLAC
  90776. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90777. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90778. * - The program calls FLAC__stream_encoder_process() or
  90779. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90780. * subsequently calls the callbacks when there is encoder data ready
  90781. * to be written.
  90782. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90783. * which causes the encoder to encode any data still in its input pipe,
  90784. * update the metadata with the final encoding statistics if output
  90785. * seeking is possible, and finally reset the encoder to the
  90786. * uninitialized state.
  90787. * - The instance may be used again or deleted with
  90788. * FLAC__stream_encoder_delete().
  90789. *
  90790. * In more detail, the stream encoder functions similarly to the
  90791. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90792. * callbacks and more options. Typically the client will create a new
  90793. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90794. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90795. * calling one of the FLAC__stream_encoder_init_*() functions.
  90796. *
  90797. * Unlike the decoders, the stream encoder has many options that can
  90798. * affect the speed and compression ratio. When setting these parameters
  90799. * you should have some basic knowledge of the format (see the
  90800. * <A HREF="../documentation.html#format">user-level documentation</A>
  90801. * or the <A HREF="../format.html">formal description</A>). The
  90802. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90803. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90804. * functions will do this, so make sure to pay attention to the state
  90805. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90806. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90807. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90808. * the constructor.
  90809. *
  90810. * There are three initialization functions for native FLAC, one for
  90811. * setting up the encoder to encode FLAC data to the client via
  90812. * callbacks, and two for encoding directly to a file.
  90813. *
  90814. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90815. * You must also supply a write callback which will be called anytime
  90816. * there is raw encoded data to write. If the client can seek the output
  90817. * it is best to also supply seek and tell callbacks, as this allows the
  90818. * encoder to go back after encoding is finished to write back
  90819. * information that was collected while encoding, like seek point offsets,
  90820. * frame sizes, etc.
  90821. *
  90822. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90823. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90824. * filename or open \c FILE*; the encoder will handle all the callbacks
  90825. * internally. You may also supply a progress callback for periodic
  90826. * notification of the encoding progress.
  90827. *
  90828. * There are three similarly-named init functions for encoding to Ogg
  90829. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90830. * library has been built with Ogg support.
  90831. *
  90832. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90833. * call the write callback several times, once with the \c fLaC signature,
  90834. * and once for each encoded metadata block. Note that for Ogg FLAC
  90835. * encoding you will usually get at least twice the number of callbacks than
  90836. * with native FLAC, one for the Ogg page header and one for the page body.
  90837. *
  90838. * After initializing the instance, the client may feed audio data to the
  90839. * encoder in one of two ways:
  90840. *
  90841. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90842. * will pass an array of pointers to buffers, one for each channel, to
  90843. * the encoder, each of the same length. The samples need not be
  90844. * block-aligned, but each channel should have the same number of samples.
  90845. * - Channel interleaved, through
  90846. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90847. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90848. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90849. * Again, the samples need not be block-aligned but they must be
  90850. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90851. * the last value channelN_sampleM.
  90852. *
  90853. * Note that for either process call, each sample in the buffers should be a
  90854. * signed integer, right-justified to the resolution set by
  90855. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90856. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90857. *
  90858. * When the client is finished encoding data, it calls
  90859. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90860. * data still in its input pipe, and call the metadata callback with the
  90861. * final encoding statistics. Then the instance may be deleted with
  90862. * FLAC__stream_encoder_delete() or initialized again to encode another
  90863. * stream.
  90864. *
  90865. * For programs that write their own metadata, but that do not know the
  90866. * actual metadata until after encoding, it is advantageous to instruct
  90867. * the encoder to write a PADDING block of the correct size, so that
  90868. * instead of rewriting the whole stream after encoding, the program can
  90869. * just overwrite the PADDING block. If only the maximum size of the
  90870. * metadata is known, the program can write a slightly larger padding
  90871. * block, then split it after encoding.
  90872. *
  90873. * Make sure you understand how lengths are calculated. All FLAC metadata
  90874. * blocks have a 4 byte header which contains the type and length. This
  90875. * length does not include the 4 bytes of the header. See the format page
  90876. * for the specification of metadata blocks and their lengths.
  90877. *
  90878. * \note
  90879. * If you are writing the FLAC data to a file via callbacks, make sure it
  90880. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90881. * after the first encoding pass, the encoder will try to seek back to the
  90882. * beginning of the stream, to the STREAMINFO block, to write some data
  90883. * there. (If using FLAC__stream_encoder_init*_file() or
  90884. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90885. *
  90886. * \note
  90887. * The "set" functions may only be called when the encoder is in the
  90888. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90889. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90890. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90891. * return \c true, otherwise \c false.
  90892. *
  90893. * \note
  90894. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90895. * defaults.
  90896. *
  90897. * \{
  90898. */
  90899. /** State values for a FLAC__StreamEncoder.
  90900. *
  90901. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90902. *
  90903. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90904. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90905. * must be deleted with FLAC__stream_encoder_delete().
  90906. */
  90907. typedef enum {
  90908. FLAC__STREAM_ENCODER_OK = 0,
  90909. /**< The encoder is in the normal OK state and samples can be processed. */
  90910. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90911. /**< The encoder is in the uninitialized state; one of the
  90912. * FLAC__stream_encoder_init_*() functions must be called before samples
  90913. * can be processed.
  90914. */
  90915. FLAC__STREAM_ENCODER_OGG_ERROR,
  90916. /**< An error occurred in the underlying Ogg layer. */
  90917. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90918. /**< An error occurred in the underlying verify stream decoder;
  90919. * check FLAC__stream_encoder_get_verify_decoder_state().
  90920. */
  90921. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90922. /**< The verify decoder detected a mismatch between the original
  90923. * audio signal and the decoded audio signal.
  90924. */
  90925. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90926. /**< One of the callbacks returned a fatal error. */
  90927. FLAC__STREAM_ENCODER_IO_ERROR,
  90928. /**< An I/O error occurred while opening/reading/writing a file.
  90929. * Check \c errno.
  90930. */
  90931. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90932. /**< An error occurred while writing the stream; usually, the
  90933. * write_callback returned an error.
  90934. */
  90935. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90936. /**< Memory allocation failed. */
  90937. } FLAC__StreamEncoderState;
  90938. /** Maps a FLAC__StreamEncoderState to a C string.
  90939. *
  90940. * Using a FLAC__StreamEncoderState as the index to this array
  90941. * will give the string equivalent. The contents should not be modified.
  90942. */
  90943. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90944. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90945. */
  90946. typedef enum {
  90947. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90948. /**< Initialization was successful. */
  90949. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90950. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90951. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90952. /**< The library was not compiled with support for the given container
  90953. * format.
  90954. */
  90955. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90956. /**< A required callback was not supplied. */
  90957. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90958. /**< The encoder has an invalid setting for number of channels. */
  90959. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90960. /**< The encoder has an invalid setting for bits-per-sample.
  90961. * FLAC supports 4-32 bps but the reference encoder currently supports
  90962. * only up to 24 bps.
  90963. */
  90964. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90965. /**< The encoder has an invalid setting for the input sample rate. */
  90966. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90967. /**< The encoder has an invalid setting for the block size. */
  90968. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90969. /**< The encoder has an invalid setting for the maximum LPC order. */
  90970. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90971. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90972. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90973. /**< The specified block size is less than the maximum LPC order. */
  90974. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90975. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90976. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90977. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90978. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90979. * - One of the metadata blocks contains an undefined type
  90980. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90981. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90982. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90983. */
  90984. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90985. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90986. * already initialized, usually because
  90987. * FLAC__stream_encoder_finish() was not called.
  90988. */
  90989. } FLAC__StreamEncoderInitStatus;
  90990. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90991. *
  90992. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90993. * will give the string equivalent. The contents should not be modified.
  90994. */
  90995. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90996. /** Return values for the FLAC__StreamEncoder read callback.
  90997. */
  90998. typedef enum {
  90999. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91000. /**< The read was OK and decoding can continue. */
  91001. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91002. /**< The read was attempted at the end of the stream. */
  91003. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91004. /**< An unrecoverable error occurred. */
  91005. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91006. /**< Client does not support reading back from the output. */
  91007. } FLAC__StreamEncoderReadStatus;
  91008. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91009. *
  91010. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91011. * will give the string equivalent. The contents should not be modified.
  91012. */
  91013. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91014. /** Return values for the FLAC__StreamEncoder write callback.
  91015. */
  91016. typedef enum {
  91017. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91018. /**< The write was OK and encoding can continue. */
  91019. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91020. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91021. } FLAC__StreamEncoderWriteStatus;
  91022. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91023. *
  91024. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91025. * will give the string equivalent. The contents should not be modified.
  91026. */
  91027. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91028. /** Return values for the FLAC__StreamEncoder seek callback.
  91029. */
  91030. typedef enum {
  91031. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91032. /**< The seek was OK and encoding can continue. */
  91033. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91034. /**< An unrecoverable error occurred. */
  91035. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91036. /**< Client does not support seeking. */
  91037. } FLAC__StreamEncoderSeekStatus;
  91038. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91039. *
  91040. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91041. * will give the string equivalent. The contents should not be modified.
  91042. */
  91043. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91044. /** Return values for the FLAC__StreamEncoder tell callback.
  91045. */
  91046. typedef enum {
  91047. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91048. /**< The tell was OK and encoding can continue. */
  91049. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91050. /**< An unrecoverable error occurred. */
  91051. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91052. /**< Client does not support seeking. */
  91053. } FLAC__StreamEncoderTellStatus;
  91054. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91055. *
  91056. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91057. * will give the string equivalent. The contents should not be modified.
  91058. */
  91059. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91060. /***********************************************************************
  91061. *
  91062. * class FLAC__StreamEncoder
  91063. *
  91064. ***********************************************************************/
  91065. struct FLAC__StreamEncoderProtected;
  91066. struct FLAC__StreamEncoderPrivate;
  91067. /** The opaque structure definition for the stream encoder type.
  91068. * See the \link flac_stream_encoder stream encoder module \endlink
  91069. * for a detailed description.
  91070. */
  91071. typedef struct {
  91072. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91073. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91074. } FLAC__StreamEncoder;
  91075. /** Signature for the read callback.
  91076. *
  91077. * A function pointer matching this signature must be passed to
  91078. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91079. * The supplied function will be called when the encoder needs to read back
  91080. * encoded data. This happens during the metadata callback, when the encoder
  91081. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91082. * while encoding. The address of the buffer to be filled is supplied, along
  91083. * with the number of bytes the buffer can hold. The callback may choose to
  91084. * supply less data and modify the byte count but must be careful not to
  91085. * overflow the buffer. The callback then returns a status code chosen from
  91086. * FLAC__StreamEncoderReadStatus.
  91087. *
  91088. * Here is an example of a read callback for stdio streams:
  91089. * \code
  91090. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91091. * {
  91092. * FILE *file = ((MyClientData*)client_data)->file;
  91093. * if(*bytes > 0) {
  91094. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91095. * if(ferror(file))
  91096. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91097. * else if(*bytes == 0)
  91098. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91099. * else
  91100. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91101. * }
  91102. * else
  91103. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91104. * }
  91105. * \endcode
  91106. *
  91107. * \note In general, FLAC__StreamEncoder functions which change the
  91108. * state should not be called on the \a encoder while in the callback.
  91109. *
  91110. * \param encoder The encoder instance calling the callback.
  91111. * \param buffer A pointer to a location for the callee to store
  91112. * data to be encoded.
  91113. * \param bytes A pointer to the size of the buffer. On entry
  91114. * to the callback, it contains the maximum number
  91115. * of bytes that may be stored in \a buffer. The
  91116. * callee must set it to the actual number of bytes
  91117. * stored (0 in case of error or end-of-stream) before
  91118. * returning.
  91119. * \param client_data The callee's client data set through
  91120. * FLAC__stream_encoder_set_client_data().
  91121. * \retval FLAC__StreamEncoderReadStatus
  91122. * The callee's return status.
  91123. */
  91124. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91125. /** Signature for the write callback.
  91126. *
  91127. * A function pointer matching this signature must be passed to
  91128. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91129. * by the encoder anytime there is raw encoded data ready to write. It may
  91130. * include metadata mixed with encoded audio frames and the data is not
  91131. * guaranteed to be aligned on frame or metadata block boundaries.
  91132. *
  91133. * The only duty of the callback is to write out the \a bytes worth of data
  91134. * in \a buffer to the current position in the output stream. The arguments
  91135. * \a samples and \a current_frame are purely informational. If \a samples
  91136. * is greater than \c 0, then \a current_frame will hold the current frame
  91137. * number that is being written; otherwise it indicates that the write
  91138. * callback is being called to write metadata.
  91139. *
  91140. * \note
  91141. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91142. * write callback will be called twice when writing each audio
  91143. * frame; once for the page header, and once for the page body.
  91144. * When writing the page header, the \a samples argument to the
  91145. * write callback will be \c 0.
  91146. *
  91147. * \note In general, FLAC__StreamEncoder functions which change the
  91148. * state should not be called on the \a encoder while in the callback.
  91149. *
  91150. * \param encoder The encoder instance calling the callback.
  91151. * \param buffer An array of encoded data of length \a bytes.
  91152. * \param bytes The byte length of \a buffer.
  91153. * \param samples The number of samples encoded by \a buffer.
  91154. * \c 0 has a special meaning; see above.
  91155. * \param current_frame The number of the current frame being encoded.
  91156. * \param client_data The callee's client data set through
  91157. * FLAC__stream_encoder_init_*().
  91158. * \retval FLAC__StreamEncoderWriteStatus
  91159. * The callee's return status.
  91160. */
  91161. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91162. /** Signature for the seek callback.
  91163. *
  91164. * A function pointer matching this signature may be passed to
  91165. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91166. * when the encoder needs to seek the output stream. The encoder will pass
  91167. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91168. *
  91169. * Here is an example of a seek callback for stdio streams:
  91170. * \code
  91171. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91172. * {
  91173. * FILE *file = ((MyClientData*)client_data)->file;
  91174. * if(file == stdin)
  91175. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91176. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91177. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91178. * else
  91179. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91180. * }
  91181. * \endcode
  91182. *
  91183. * \note In general, FLAC__StreamEncoder functions which change the
  91184. * state should not be called on the \a encoder while in the callback.
  91185. *
  91186. * \param encoder The encoder instance calling the callback.
  91187. * \param absolute_byte_offset The offset from the beginning of the stream
  91188. * to seek to.
  91189. * \param client_data The callee's client data set through
  91190. * FLAC__stream_encoder_init_*().
  91191. * \retval FLAC__StreamEncoderSeekStatus
  91192. * The callee's return status.
  91193. */
  91194. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91195. /** Signature for the tell callback.
  91196. *
  91197. * A function pointer matching this signature may be passed to
  91198. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91199. * when the encoder needs to know the current position of the output stream.
  91200. *
  91201. * \warning
  91202. * The callback must return the true current byte offset of the output to
  91203. * which the encoder is writing. If you are buffering the output, make
  91204. * sure and take this into account. If you are writing directly to a
  91205. * FILE* from your write callback, ftell() is sufficient. If you are
  91206. * writing directly to a file descriptor from your write callback, you
  91207. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91208. * these points to rewrite metadata after encoding.
  91209. *
  91210. * Here is an example of a tell callback for stdio streams:
  91211. * \code
  91212. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91213. * {
  91214. * FILE *file = ((MyClientData*)client_data)->file;
  91215. * off_t pos;
  91216. * if(file == stdin)
  91217. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91218. * else if((pos = ftello(file)) < 0)
  91219. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91220. * else {
  91221. * *absolute_byte_offset = (FLAC__uint64)pos;
  91222. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91223. * }
  91224. * }
  91225. * \endcode
  91226. *
  91227. * \note In general, FLAC__StreamEncoder functions which change the
  91228. * state should not be called on the \a encoder while in the callback.
  91229. *
  91230. * \param encoder The encoder instance calling the callback.
  91231. * \param absolute_byte_offset The address at which to store the current
  91232. * position of the output.
  91233. * \param client_data The callee's client data set through
  91234. * FLAC__stream_encoder_init_*().
  91235. * \retval FLAC__StreamEncoderTellStatus
  91236. * The callee's return status.
  91237. */
  91238. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91239. /** Signature for the metadata callback.
  91240. *
  91241. * A function pointer matching this signature may be passed to
  91242. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91243. * once at the end of encoding with the populated STREAMINFO structure. This
  91244. * is so the client can seek back to the beginning of the file and write the
  91245. * STREAMINFO block with the correct statistics after encoding (like
  91246. * minimum/maximum frame size and total samples).
  91247. *
  91248. * \note In general, FLAC__StreamEncoder functions which change the
  91249. * state should not be called on the \a encoder while in the callback.
  91250. *
  91251. * \param encoder The encoder instance calling the callback.
  91252. * \param metadata The final populated STREAMINFO block.
  91253. * \param client_data The callee's client data set through
  91254. * FLAC__stream_encoder_init_*().
  91255. */
  91256. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91257. /** Signature for the progress callback.
  91258. *
  91259. * A function pointer matching this signature may be passed to
  91260. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91261. * The supplied function will be called when the encoder has finished
  91262. * writing a frame. The \c total_frames_estimate argument to the
  91263. * callback will be based on the value from
  91264. * FLAC__stream_encoder_set_total_samples_estimate().
  91265. *
  91266. * \note In general, FLAC__StreamEncoder functions which change the
  91267. * state should not be called on the \a encoder while in the callback.
  91268. *
  91269. * \param encoder The encoder instance calling the callback.
  91270. * \param bytes_written Bytes written so far.
  91271. * \param samples_written Samples written so far.
  91272. * \param frames_written Frames written so far.
  91273. * \param total_frames_estimate The estimate of the total number of
  91274. * frames to be written.
  91275. * \param client_data The callee's client data set through
  91276. * FLAC__stream_encoder_init_*().
  91277. */
  91278. 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);
  91279. /***********************************************************************
  91280. *
  91281. * Class constructor/destructor
  91282. *
  91283. ***********************************************************************/
  91284. /** Create a new stream encoder instance. The instance is created with
  91285. * default settings; see the individual FLAC__stream_encoder_set_*()
  91286. * functions for each setting's default.
  91287. *
  91288. * \retval FLAC__StreamEncoder*
  91289. * \c NULL if there was an error allocating memory, else the new instance.
  91290. */
  91291. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91292. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91293. *
  91294. * \param encoder A pointer to an existing encoder.
  91295. * \assert
  91296. * \code encoder != NULL \endcode
  91297. */
  91298. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91299. /***********************************************************************
  91300. *
  91301. * Public class method prototypes
  91302. *
  91303. ***********************************************************************/
  91304. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91305. *
  91306. * \note
  91307. * This does not need to be set for native FLAC encoding.
  91308. *
  91309. * \note
  91310. * It is recommended to set a serial number explicitly as the default of '0'
  91311. * may collide with other streams.
  91312. *
  91313. * \default \c 0
  91314. * \param encoder An encoder instance to set.
  91315. * \param serial_number See above.
  91316. * \assert
  91317. * \code encoder != NULL \endcode
  91318. * \retval FLAC__bool
  91319. * \c false if the encoder is already initialized, else \c true.
  91320. */
  91321. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91322. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91323. * encoded output by feeding it through an internal decoder and comparing
  91324. * the original signal against the decoded signal. If a mismatch occurs,
  91325. * the process call will return \c false. Note that this will slow the
  91326. * encoding process by the extra time required for decoding and comparison.
  91327. *
  91328. * \default \c false
  91329. * \param encoder An encoder instance to set.
  91330. * \param value Flag value (see above).
  91331. * \assert
  91332. * \code encoder != NULL \endcode
  91333. * \retval FLAC__bool
  91334. * \c false if the encoder is already initialized, else \c true.
  91335. */
  91336. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91337. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91338. * the encoder will comply with the Subset and will check the
  91339. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91340. * comply. If \c false, the settings may take advantage of the full
  91341. * range that the format allows.
  91342. *
  91343. * Make sure you know what it entails before setting this to \c false.
  91344. *
  91345. * \default \c true
  91346. * \param encoder An encoder instance to set.
  91347. * \param value Flag value (see above).
  91348. * \assert
  91349. * \code encoder != NULL \endcode
  91350. * \retval FLAC__bool
  91351. * \c false if the encoder is already initialized, else \c true.
  91352. */
  91353. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91354. /** Set the number of channels to be encoded.
  91355. *
  91356. * \default \c 2
  91357. * \param encoder An encoder instance to set.
  91358. * \param value See above.
  91359. * \assert
  91360. * \code encoder != NULL \endcode
  91361. * \retval FLAC__bool
  91362. * \c false if the encoder is already initialized, else \c true.
  91363. */
  91364. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91365. /** Set the sample resolution of the input to be encoded.
  91366. *
  91367. * \warning
  91368. * Do not feed the encoder data that is wider than the value you
  91369. * set here or you will generate an invalid stream.
  91370. *
  91371. * \default \c 16
  91372. * \param encoder An encoder instance to set.
  91373. * \param value See above.
  91374. * \assert
  91375. * \code encoder != NULL \endcode
  91376. * \retval FLAC__bool
  91377. * \c false if the encoder is already initialized, else \c true.
  91378. */
  91379. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91380. /** Set the sample rate (in Hz) of the input to be encoded.
  91381. *
  91382. * \default \c 44100
  91383. * \param encoder An encoder instance to set.
  91384. * \param value See above.
  91385. * \assert
  91386. * \code encoder != NULL \endcode
  91387. * \retval FLAC__bool
  91388. * \c false if the encoder is already initialized, else \c true.
  91389. */
  91390. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91391. /** Set the compression level
  91392. *
  91393. * The compression level is roughly proportional to the amount of effort
  91394. * the encoder expends to compress the file. A higher level usually
  91395. * means more computation but higher compression. The default level is
  91396. * suitable for most applications.
  91397. *
  91398. * Currently the levels range from \c 0 (fastest, least compression) to
  91399. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91400. * treated as \c 8.
  91401. *
  91402. * This function automatically calls the following other \c _set_
  91403. * functions with appropriate values, so the client does not need to
  91404. * unless it specifically wants to override them:
  91405. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91406. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91407. * - FLAC__stream_encoder_set_apodization()
  91408. * - FLAC__stream_encoder_set_max_lpc_order()
  91409. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91410. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91411. * - FLAC__stream_encoder_set_do_escape_coding()
  91412. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91413. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91414. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91415. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91416. *
  91417. * The actual values set for each level are:
  91418. * <table>
  91419. * <tr>
  91420. * <td><b>level</b><td>
  91421. * <td>do mid-side stereo<td>
  91422. * <td>loose mid-side stereo<td>
  91423. * <td>apodization<td>
  91424. * <td>max lpc order<td>
  91425. * <td>qlp coeff precision<td>
  91426. * <td>qlp coeff prec search<td>
  91427. * <td>escape coding<td>
  91428. * <td>exhaustive model search<td>
  91429. * <td>min residual partition order<td>
  91430. * <td>max residual partition order<td>
  91431. * <td>rice parameter search dist<td>
  91432. * </tr>
  91433. * <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>
  91434. * <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>
  91435. * <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>
  91436. * <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>
  91437. * <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>
  91438. * <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>
  91439. * <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>
  91440. * <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>
  91441. * <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>
  91442. * </table>
  91443. *
  91444. * \default \c 5
  91445. * \param encoder An encoder instance to set.
  91446. * \param value See above.
  91447. * \assert
  91448. * \code encoder != NULL \endcode
  91449. * \retval FLAC__bool
  91450. * \c false if the encoder is already initialized, else \c true.
  91451. */
  91452. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91453. /** Set the blocksize to use while encoding.
  91454. *
  91455. * The number of samples to use per frame. Use \c 0 to let the encoder
  91456. * estimate a blocksize; this is usually best.
  91457. *
  91458. * \default \c 0
  91459. * \param encoder An encoder instance to set.
  91460. * \param value See above.
  91461. * \assert
  91462. * \code encoder != NULL \endcode
  91463. * \retval FLAC__bool
  91464. * \c false if the encoder is already initialized, else \c true.
  91465. */
  91466. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91467. /** Set to \c true to enable mid-side encoding on stereo input. The
  91468. * number of channels must be 2 for this to have any effect. Set to
  91469. * \c false to use only independent channel coding.
  91470. *
  91471. * \default \c false
  91472. * \param encoder An encoder instance to set.
  91473. * \param value Flag value (see above).
  91474. * \assert
  91475. * \code encoder != NULL \endcode
  91476. * \retval FLAC__bool
  91477. * \c false if the encoder is already initialized, else \c true.
  91478. */
  91479. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91480. /** Set to \c true to enable adaptive switching between mid-side and
  91481. * left-right encoding on stereo input. Set to \c false to use
  91482. * exhaustive searching. Setting this to \c true requires
  91483. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91484. * \c true in order to have any effect.
  91485. *
  91486. * \default \c false
  91487. * \param encoder An encoder instance to set.
  91488. * \param value Flag value (see above).
  91489. * \assert
  91490. * \code encoder != NULL \endcode
  91491. * \retval FLAC__bool
  91492. * \c false if the encoder is already initialized, else \c true.
  91493. */
  91494. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91495. /** Sets the apodization function(s) the encoder will use when windowing
  91496. * audio data for LPC analysis.
  91497. *
  91498. * The \a specification is a plain ASCII string which specifies exactly
  91499. * which functions to use. There may be more than one (up to 32),
  91500. * separated by \c ';' characters. Some functions take one or more
  91501. * comma-separated arguments in parentheses.
  91502. *
  91503. * The available functions are \c bartlett, \c bartlett_hann,
  91504. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91505. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91506. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91507. *
  91508. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91509. * (0<STDDEV<=0.5).
  91510. *
  91511. * For \c tukey(P), P specifies the fraction of the window that is
  91512. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91513. * corresponds to \c hann.
  91514. *
  91515. * Example specifications are \c "blackman" or
  91516. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91517. *
  91518. * Any function that is specified erroneously is silently dropped. Up
  91519. * to 32 functions are kept, the rest are dropped. If the specification
  91520. * is empty the encoder defaults to \c "tukey(0.5)".
  91521. *
  91522. * When more than one function is specified, then for every subframe the
  91523. * encoder will try each of them separately and choose the window that
  91524. * results in the smallest compressed subframe.
  91525. *
  91526. * Note that each function specified causes the encoder to occupy a
  91527. * floating point array in which to store the window.
  91528. *
  91529. * \default \c "tukey(0.5)"
  91530. * \param encoder An encoder instance to set.
  91531. * \param specification See above.
  91532. * \assert
  91533. * \code encoder != NULL \endcode
  91534. * \code specification != NULL \endcode
  91535. * \retval FLAC__bool
  91536. * \c false if the encoder is already initialized, else \c true.
  91537. */
  91538. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91539. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91540. *
  91541. * \default \c 0
  91542. * \param encoder An encoder instance to set.
  91543. * \param value See above.
  91544. * \assert
  91545. * \code encoder != NULL \endcode
  91546. * \retval FLAC__bool
  91547. * \c false if the encoder is already initialized, else \c true.
  91548. */
  91549. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91550. /** Set the precision, in bits, of the quantized linear predictor
  91551. * coefficients, or \c 0 to let the encoder select it based on the
  91552. * blocksize.
  91553. *
  91554. * \note
  91555. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91556. * be less than 32.
  91557. *
  91558. * \default \c 0
  91559. * \param encoder An encoder instance to set.
  91560. * \param value See above.
  91561. * \assert
  91562. * \code encoder != NULL \endcode
  91563. * \retval FLAC__bool
  91564. * \c false if the encoder is already initialized, else \c true.
  91565. */
  91566. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91567. /** Set to \c false to use only the specified quantized linear predictor
  91568. * coefficient precision, or \c true to search neighboring precision
  91569. * values and use the best one.
  91570. *
  91571. * \default \c false
  91572. * \param encoder An encoder instance to set.
  91573. * \param value See above.
  91574. * \assert
  91575. * \code encoder != NULL \endcode
  91576. * \retval FLAC__bool
  91577. * \c false if the encoder is already initialized, else \c true.
  91578. */
  91579. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91580. /** Deprecated. Setting this value has no effect.
  91581. *
  91582. * \default \c false
  91583. * \param encoder An encoder instance to set.
  91584. * \param value See above.
  91585. * \assert
  91586. * \code encoder != NULL \endcode
  91587. * \retval FLAC__bool
  91588. * \c false if the encoder is already initialized, else \c true.
  91589. */
  91590. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91591. /** Set to \c false to let the encoder estimate the best model order
  91592. * based on the residual signal energy, or \c true to force the
  91593. * encoder to evaluate all order models and select the best.
  91594. *
  91595. * \default \c false
  91596. * \param encoder An encoder instance to set.
  91597. * \param value See above.
  91598. * \assert
  91599. * \code encoder != NULL \endcode
  91600. * \retval FLAC__bool
  91601. * \c false if the encoder is already initialized, else \c true.
  91602. */
  91603. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91604. /** Set the minimum partition order to search when coding the residual.
  91605. * This is used in tandem with
  91606. * FLAC__stream_encoder_set_max_residual_partition_order().
  91607. *
  91608. * The partition order determines the context size in the residual.
  91609. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91610. *
  91611. * Set both min and max values to \c 0 to force a single context,
  91612. * whose Rice parameter is based on the residual signal variance.
  91613. * Otherwise, set a min and max order, and the encoder will search
  91614. * all orders, using the mean of each context for its Rice parameter,
  91615. * and use the best.
  91616. *
  91617. * \default \c 0
  91618. * \param encoder An encoder instance to set.
  91619. * \param value See above.
  91620. * \assert
  91621. * \code encoder != NULL \endcode
  91622. * \retval FLAC__bool
  91623. * \c false if the encoder is already initialized, else \c true.
  91624. */
  91625. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91626. /** Set the maximum partition order to search when coding the residual.
  91627. * This is used in tandem with
  91628. * FLAC__stream_encoder_set_min_residual_partition_order().
  91629. *
  91630. * The partition order determines the context size in the residual.
  91631. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91632. *
  91633. * Set both min and max values to \c 0 to force a single context,
  91634. * whose Rice parameter is based on the residual signal variance.
  91635. * Otherwise, set a min and max order, and the encoder will search
  91636. * all orders, using the mean of each context for its Rice parameter,
  91637. * and use the best.
  91638. *
  91639. * \default \c 0
  91640. * \param encoder An encoder instance to set.
  91641. * \param value See above.
  91642. * \assert
  91643. * \code encoder != NULL \endcode
  91644. * \retval FLAC__bool
  91645. * \c false if the encoder is already initialized, else \c true.
  91646. */
  91647. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91648. /** Deprecated. Setting this value has no effect.
  91649. *
  91650. * \default \c 0
  91651. * \param encoder An encoder instance to set.
  91652. * \param value See above.
  91653. * \assert
  91654. * \code encoder != NULL \endcode
  91655. * \retval FLAC__bool
  91656. * \c false if the encoder is already initialized, else \c true.
  91657. */
  91658. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91659. /** Set an estimate of the total samples that will be encoded.
  91660. * This is merely an estimate and may be set to \c 0 if unknown.
  91661. * This value will be written to the STREAMINFO block before encoding,
  91662. * and can remove the need for the caller to rewrite the value later
  91663. * if the value is known before encoding.
  91664. *
  91665. * \default \c 0
  91666. * \param encoder An encoder instance to set.
  91667. * \param value See above.
  91668. * \assert
  91669. * \code encoder != NULL \endcode
  91670. * \retval FLAC__bool
  91671. * \c false if the encoder is already initialized, else \c true.
  91672. */
  91673. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91674. /** Set the metadata blocks to be emitted to the stream before encoding.
  91675. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91676. * array of pointers to metadata blocks. The array is non-const since
  91677. * the encoder may need to change the \a is_last flag inside them, and
  91678. * in some cases update seek point offsets. Otherwise, the encoder will
  91679. * not modify or free the blocks. It is up to the caller to free the
  91680. * metadata blocks after encoding finishes.
  91681. *
  91682. * \note
  91683. * The encoder stores only copies of the pointers in the \a metadata array;
  91684. * the metadata blocks themselves must survive at least until after
  91685. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91686. *
  91687. * \note
  91688. * The STREAMINFO block is always written and no STREAMINFO block may
  91689. * occur in the supplied array.
  91690. *
  91691. * \note
  91692. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91693. * in the \a metadata array, but the client has specified that it does not
  91694. * support seeking, then the SEEKTABLE will be written verbatim. However
  91695. * by itself this is not very useful as the client will not know the stream
  91696. * offsets for the seekpoints ahead of time. In order to get a proper
  91697. * seektable the client must support seeking. See next note.
  91698. *
  91699. * \note
  91700. * SEEKTABLE blocks are handled specially. Since you will not know
  91701. * the values for the seek point stream offsets, you should pass in
  91702. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91703. * required sample numbers (or placeholder points), with \c 0 for the
  91704. * \a frame_samples and \a stream_offset fields for each point. If the
  91705. * client has specified that it supports seeking by providing a seek
  91706. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91707. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91708. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91709. * then while it is encoding the encoder will fill the stream offsets in
  91710. * for you and when encoding is finished, it will seek back and write the
  91711. * real values into the SEEKTABLE block in the stream. There are helper
  91712. * routines for manipulating seektable template blocks; see metadata.h:
  91713. * FLAC__metadata_object_seektable_template_*(). If the client does
  91714. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91715. * will slow down or remove the ability to seek in the FLAC stream.
  91716. *
  91717. * \note
  91718. * The encoder instance \b will modify the first \c SEEKTABLE block
  91719. * as it transforms the template to a valid seektable while encoding,
  91720. * but it is still up to the caller to free all metadata blocks after
  91721. * encoding.
  91722. *
  91723. * \note
  91724. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91725. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91726. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91727. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91728. * block is present in the \a metadata array, libFLAC will write an
  91729. * empty one, containing only the vendor string.
  91730. *
  91731. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91732. * the second metadata block of the stream. The encoder already supplies
  91733. * the STREAMINFO block automatically. If \a metadata does not contain a
  91734. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91735. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91736. * first, the init function will reorder \a metadata by moving the
  91737. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91738. * blocks will remain as they were.
  91739. *
  91740. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91741. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91742. * return \c false.
  91743. *
  91744. * \default \c NULL, 0
  91745. * \param encoder An encoder instance to set.
  91746. * \param metadata See above.
  91747. * \param num_blocks See above.
  91748. * \assert
  91749. * \code encoder != NULL \endcode
  91750. * \retval FLAC__bool
  91751. * \c false if the encoder is already initialized, else \c true.
  91752. * \c false if the encoder is already initialized, or if
  91753. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91754. */
  91755. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91756. /** Get the current encoder state.
  91757. *
  91758. * \param encoder An encoder instance to query.
  91759. * \assert
  91760. * \code encoder != NULL \endcode
  91761. * \retval FLAC__StreamEncoderState
  91762. * The current encoder state.
  91763. */
  91764. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91765. /** Get the state of the verify stream decoder.
  91766. * Useful when the stream encoder state is
  91767. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91768. *
  91769. * \param encoder An encoder instance to query.
  91770. * \assert
  91771. * \code encoder != NULL \endcode
  91772. * \retval FLAC__StreamDecoderState
  91773. * The verify stream decoder state.
  91774. */
  91775. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91776. /** Get the current encoder state as a C string.
  91777. * This version automatically resolves
  91778. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91779. * verify decoder's state.
  91780. *
  91781. * \param encoder A encoder instance to query.
  91782. * \assert
  91783. * \code encoder != NULL \endcode
  91784. * \retval const char *
  91785. * The encoder state as a C string. Do not modify the contents.
  91786. */
  91787. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91788. /** Get relevant values about the nature of a verify decoder error.
  91789. * Useful when the stream encoder state is
  91790. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91791. * be addresses in which the stats will be returned, or NULL if value
  91792. * is not desired.
  91793. *
  91794. * \param encoder An encoder instance to query.
  91795. * \param absolute_sample The absolute sample number of the mismatch.
  91796. * \param frame_number The number of the frame in which the mismatch occurred.
  91797. * \param channel The channel in which the mismatch occurred.
  91798. * \param sample The number of the sample (relative to the frame) in
  91799. * which the mismatch occurred.
  91800. * \param expected The expected value for the sample in question.
  91801. * \param got The actual value returned by the decoder.
  91802. * \assert
  91803. * \code encoder != NULL \endcode
  91804. */
  91805. 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);
  91806. /** Get the "verify" flag.
  91807. *
  91808. * \param encoder An encoder instance to query.
  91809. * \assert
  91810. * \code encoder != NULL \endcode
  91811. * \retval FLAC__bool
  91812. * See FLAC__stream_encoder_set_verify().
  91813. */
  91814. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91815. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91816. *
  91817. * \param encoder An encoder instance to query.
  91818. * \assert
  91819. * \code encoder != NULL \endcode
  91820. * \retval FLAC__bool
  91821. * See FLAC__stream_encoder_set_streamable_subset().
  91822. */
  91823. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91824. /** Get the number of input channels being processed.
  91825. *
  91826. * \param encoder An encoder instance to query.
  91827. * \assert
  91828. * \code encoder != NULL \endcode
  91829. * \retval unsigned
  91830. * See FLAC__stream_encoder_set_channels().
  91831. */
  91832. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91833. /** Get the input sample resolution setting.
  91834. *
  91835. * \param encoder An encoder instance to query.
  91836. * \assert
  91837. * \code encoder != NULL \endcode
  91838. * \retval unsigned
  91839. * See FLAC__stream_encoder_set_bits_per_sample().
  91840. */
  91841. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91842. /** Get the input sample rate setting.
  91843. *
  91844. * \param encoder An encoder instance to query.
  91845. * \assert
  91846. * \code encoder != NULL \endcode
  91847. * \retval unsigned
  91848. * See FLAC__stream_encoder_set_sample_rate().
  91849. */
  91850. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91851. /** Get the blocksize setting.
  91852. *
  91853. * \param encoder An encoder instance to query.
  91854. * \assert
  91855. * \code encoder != NULL \endcode
  91856. * \retval unsigned
  91857. * See FLAC__stream_encoder_set_blocksize().
  91858. */
  91859. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91860. /** Get the "mid/side stereo coding" flag.
  91861. *
  91862. * \param encoder An encoder instance to query.
  91863. * \assert
  91864. * \code encoder != NULL \endcode
  91865. * \retval FLAC__bool
  91866. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91867. */
  91868. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91869. /** Get the "adaptive mid/side switching" flag.
  91870. *
  91871. * \param encoder An encoder instance to query.
  91872. * \assert
  91873. * \code encoder != NULL \endcode
  91874. * \retval FLAC__bool
  91875. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91876. */
  91877. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91878. /** Get the maximum LPC order setting.
  91879. *
  91880. * \param encoder An encoder instance to query.
  91881. * \assert
  91882. * \code encoder != NULL \endcode
  91883. * \retval unsigned
  91884. * See FLAC__stream_encoder_set_max_lpc_order().
  91885. */
  91886. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91887. /** Get the quantized linear predictor coefficient precision setting.
  91888. *
  91889. * \param encoder An encoder instance to query.
  91890. * \assert
  91891. * \code encoder != NULL \endcode
  91892. * \retval unsigned
  91893. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91894. */
  91895. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91896. /** Get the qlp coefficient precision search flag.
  91897. *
  91898. * \param encoder An encoder instance to query.
  91899. * \assert
  91900. * \code encoder != NULL \endcode
  91901. * \retval FLAC__bool
  91902. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91903. */
  91904. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91905. /** Get the "escape coding" flag.
  91906. *
  91907. * \param encoder An encoder instance to query.
  91908. * \assert
  91909. * \code encoder != NULL \endcode
  91910. * \retval FLAC__bool
  91911. * See FLAC__stream_encoder_set_do_escape_coding().
  91912. */
  91913. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91914. /** Get the exhaustive model search flag.
  91915. *
  91916. * \param encoder An encoder instance to query.
  91917. * \assert
  91918. * \code encoder != NULL \endcode
  91919. * \retval FLAC__bool
  91920. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91921. */
  91922. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91923. /** Get the minimum residual partition order setting.
  91924. *
  91925. * \param encoder An encoder instance to query.
  91926. * \assert
  91927. * \code encoder != NULL \endcode
  91928. * \retval unsigned
  91929. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91930. */
  91931. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91932. /** Get maximum residual partition order setting.
  91933. *
  91934. * \param encoder An encoder instance to query.
  91935. * \assert
  91936. * \code encoder != NULL \endcode
  91937. * \retval unsigned
  91938. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91939. */
  91940. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91941. /** Get the Rice parameter search distance setting.
  91942. *
  91943. * \param encoder An encoder instance to query.
  91944. * \assert
  91945. * \code encoder != NULL \endcode
  91946. * \retval unsigned
  91947. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91948. */
  91949. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91950. /** Get the previously set estimate of the total samples to be encoded.
  91951. * The encoder merely mimics back the value given to
  91952. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91953. * other way of knowing how many samples the client will encode.
  91954. *
  91955. * \param encoder An encoder instance to set.
  91956. * \assert
  91957. * \code encoder != NULL \endcode
  91958. * \retval FLAC__uint64
  91959. * See FLAC__stream_encoder_get_total_samples_estimate().
  91960. */
  91961. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91962. /** Initialize the encoder instance to encode native FLAC streams.
  91963. *
  91964. * This flavor of initialization sets up the encoder to encode to a
  91965. * native FLAC stream. I/O is performed via callbacks to the client.
  91966. * For encoding to a plain file via filename or open \c FILE*,
  91967. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91968. * provide a simpler interface.
  91969. *
  91970. * This function should be called after FLAC__stream_encoder_new() and
  91971. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91972. * or FLAC__stream_encoder_process_interleaved().
  91973. * initialization succeeded.
  91974. *
  91975. * The call to FLAC__stream_encoder_init_stream() currently will also
  91976. * immediately call the write callback several times, once with the \c fLaC
  91977. * signature, and once for each encoded metadata block.
  91978. *
  91979. * \param encoder An uninitialized encoder instance.
  91980. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91981. * pointer must not be \c NULL.
  91982. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91983. * pointer may be \c NULL if seeking is not
  91984. * supported. The encoder uses seeking to go back
  91985. * and write some some stream statistics to the
  91986. * STREAMINFO block; this is recommended but not
  91987. * necessary to create a valid FLAC stream. If
  91988. * \a seek_callback is not \c NULL then a
  91989. * \a tell_callback must also be supplied.
  91990. * Alternatively, a dummy seek callback that just
  91991. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91992. * may also be supplied, all though this is slightly
  91993. * less efficient for the encoder.
  91994. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91995. * pointer may be \c NULL if seeking is not
  91996. * supported. If \a seek_callback is \c NULL then
  91997. * this argument will be ignored. If
  91998. * \a seek_callback is not \c NULL then a
  91999. * \a tell_callback must also be supplied.
  92000. * Alternatively, a dummy tell callback that just
  92001. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92002. * may also be supplied, all though this is slightly
  92003. * less efficient for the encoder.
  92004. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92005. * pointer may be \c NULL if the callback is not
  92006. * desired. If the client provides a seek callback,
  92007. * this function is not necessary as the encoder
  92008. * will automatically seek back and update the
  92009. * STREAMINFO block. It may also be \c NULL if the
  92010. * client does not support seeking, since it will
  92011. * have no way of going back to update the
  92012. * STREAMINFO. However the client can still supply
  92013. * a callback if it would like to know the details
  92014. * from the STREAMINFO.
  92015. * \param client_data This value will be supplied to callbacks in their
  92016. * \a client_data argument.
  92017. * \assert
  92018. * \code encoder != NULL \endcode
  92019. * \retval FLAC__StreamEncoderInitStatus
  92020. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92021. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92022. */
  92023. 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);
  92024. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92025. *
  92026. * This flavor of initialization sets up the encoder to encode to a FLAC
  92027. * stream in an Ogg container. I/O is performed via callbacks to the
  92028. * client. For encoding to a plain file via filename or open \c FILE*,
  92029. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92030. * provide a simpler interface.
  92031. *
  92032. * This function should be called after FLAC__stream_encoder_new() and
  92033. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92034. * or FLAC__stream_encoder_process_interleaved().
  92035. * initialization succeeded.
  92036. *
  92037. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92038. * immediately call the write callback several times to write the metadata
  92039. * packets.
  92040. *
  92041. * \param encoder An uninitialized encoder instance.
  92042. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92043. * pointer must not be \c NULL if \a seek_callback
  92044. * is non-NULL since they are both needed to be
  92045. * able to write data back to the Ogg FLAC stream
  92046. * in the post-encode phase.
  92047. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92048. * pointer must not be \c NULL.
  92049. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92050. * pointer may be \c NULL if seeking is not
  92051. * supported. The encoder uses seeking to go back
  92052. * and write some some stream statistics to the
  92053. * STREAMINFO block; this is recommended but not
  92054. * necessary to create a valid FLAC stream. If
  92055. * \a seek_callback is not \c NULL then a
  92056. * \a tell_callback must also be supplied.
  92057. * Alternatively, a dummy seek callback that just
  92058. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92059. * may also be supplied, all though this is slightly
  92060. * less efficient for the encoder.
  92061. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92062. * pointer may be \c NULL if seeking is not
  92063. * supported. If \a seek_callback is \c NULL then
  92064. * this argument will be ignored. If
  92065. * \a seek_callback is not \c NULL then a
  92066. * \a tell_callback must also be supplied.
  92067. * Alternatively, a dummy tell callback that just
  92068. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92069. * may also be supplied, all though this is slightly
  92070. * less efficient for the encoder.
  92071. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92072. * pointer may be \c NULL if the callback is not
  92073. * desired. If the client provides a seek callback,
  92074. * this function is not necessary as the encoder
  92075. * will automatically seek back and update the
  92076. * STREAMINFO block. It may also be \c NULL if the
  92077. * client does not support seeking, since it will
  92078. * have no way of going back to update the
  92079. * STREAMINFO. However the client can still supply
  92080. * a callback if it would like to know the details
  92081. * from the STREAMINFO.
  92082. * \param client_data This value will be supplied to callbacks in their
  92083. * \a client_data argument.
  92084. * \assert
  92085. * \code encoder != NULL \endcode
  92086. * \retval FLAC__StreamEncoderInitStatus
  92087. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92088. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92089. */
  92090. 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);
  92091. /** Initialize the encoder instance to encode native FLAC files.
  92092. *
  92093. * This flavor of initialization sets up the encoder to encode to a
  92094. * plain native FLAC file. For non-stdio streams, you must use
  92095. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92096. *
  92097. * This function should be called after FLAC__stream_encoder_new() and
  92098. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92099. * or FLAC__stream_encoder_process_interleaved().
  92100. * initialization succeeded.
  92101. *
  92102. * \param encoder An uninitialized encoder instance.
  92103. * \param file An open file. The file should have been opened
  92104. * with mode \c "w+b" and rewound. The file
  92105. * becomes owned by the encoder and should not be
  92106. * manipulated by the client while encoding.
  92107. * Unless \a file is \c stdout, it will be closed
  92108. * when FLAC__stream_encoder_finish() is called.
  92109. * Note however that a proper SEEKTABLE cannot be
  92110. * created when encoding to \c stdout since it is
  92111. * not seekable.
  92112. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92113. * pointer may be \c NULL if the callback is not
  92114. * desired.
  92115. * \param client_data This value will be supplied to callbacks in their
  92116. * \a client_data argument.
  92117. * \assert
  92118. * \code encoder != NULL \endcode
  92119. * \code file != NULL \endcode
  92120. * \retval FLAC__StreamEncoderInitStatus
  92121. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92122. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92123. */
  92124. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92125. /** Initialize the encoder instance to encode Ogg FLAC files.
  92126. *
  92127. * This flavor of initialization sets up the encoder to encode to a
  92128. * plain Ogg FLAC file. For non-stdio streams, you must use
  92129. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92130. *
  92131. * This function should be called after FLAC__stream_encoder_new() and
  92132. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92133. * or FLAC__stream_encoder_process_interleaved().
  92134. * initialization succeeded.
  92135. *
  92136. * \param encoder An uninitialized encoder instance.
  92137. * \param file An open file. The file should have been opened
  92138. * with mode \c "w+b" and rewound. The file
  92139. * becomes owned by the encoder and should not be
  92140. * manipulated by the client while encoding.
  92141. * Unless \a file is \c stdout, it will be closed
  92142. * when FLAC__stream_encoder_finish() is called.
  92143. * Note however that a proper SEEKTABLE cannot be
  92144. * created when encoding to \c stdout since it is
  92145. * not seekable.
  92146. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92147. * pointer may be \c NULL if the callback is not
  92148. * desired.
  92149. * \param client_data This value will be supplied to callbacks in their
  92150. * \a client_data argument.
  92151. * \assert
  92152. * \code encoder != NULL \endcode
  92153. * \code file != NULL \endcode
  92154. * \retval FLAC__StreamEncoderInitStatus
  92155. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92156. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92157. */
  92158. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92159. /** Initialize the encoder instance to encode native FLAC files.
  92160. *
  92161. * This flavor of initialization sets up the encoder to encode to a plain
  92162. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92163. * with Unicode filenames on Windows), you must use
  92164. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92165. * and provide callbacks for the I/O.
  92166. *
  92167. * This function should be called after FLAC__stream_encoder_new() and
  92168. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92169. * or FLAC__stream_encoder_process_interleaved().
  92170. * initialization succeeded.
  92171. *
  92172. * \param encoder An uninitialized encoder instance.
  92173. * \param filename The name of the file to encode to. The file will
  92174. * be opened with fopen(). Use \c NULL to encode to
  92175. * \c stdout. Note however that a proper SEEKTABLE
  92176. * cannot be created when encoding to \c stdout since
  92177. * it is not seekable.
  92178. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92179. * pointer may be \c NULL if the callback is not
  92180. * desired.
  92181. * \param client_data This value will be supplied to callbacks in their
  92182. * \a client_data argument.
  92183. * \assert
  92184. * \code encoder != NULL \endcode
  92185. * \retval FLAC__StreamEncoderInitStatus
  92186. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92187. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92188. */
  92189. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92190. /** Initialize the encoder instance to encode Ogg FLAC files.
  92191. *
  92192. * This flavor of initialization sets up the encoder to encode to a plain
  92193. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92194. * with Unicode filenames on Windows), you must use
  92195. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92196. * and provide callbacks for the I/O.
  92197. *
  92198. * This function should be called after FLAC__stream_encoder_new() and
  92199. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92200. * or FLAC__stream_encoder_process_interleaved().
  92201. * initialization succeeded.
  92202. *
  92203. * \param encoder An uninitialized encoder instance.
  92204. * \param filename The name of the file to encode to. The file will
  92205. * be opened with fopen(). Use \c NULL to encode to
  92206. * \c stdout. Note however that a proper SEEKTABLE
  92207. * cannot be created when encoding to \c stdout since
  92208. * it is not seekable.
  92209. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92210. * pointer may be \c NULL if the callback is not
  92211. * desired.
  92212. * \param client_data This value will be supplied to callbacks in their
  92213. * \a client_data argument.
  92214. * \assert
  92215. * \code encoder != NULL \endcode
  92216. * \retval FLAC__StreamEncoderInitStatus
  92217. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92218. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92219. */
  92220. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92221. /** Finish the encoding process.
  92222. * Flushes the encoding buffer, releases resources, resets the encoder
  92223. * settings to their defaults, and returns the encoder state to
  92224. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92225. * one or more write callbacks before returning, and will generate
  92226. * a metadata callback.
  92227. *
  92228. * Note that in the course of processing the last frame, errors can
  92229. * occur, so the caller should be sure to check the return value to
  92230. * ensure the file was encoded properly.
  92231. *
  92232. * In the event of a prematurely-terminated encode, it is not strictly
  92233. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92234. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92235. * with a FLAC__stream_encoder_finish().
  92236. *
  92237. * \param encoder An uninitialized encoder instance.
  92238. * \assert
  92239. * \code encoder != NULL \endcode
  92240. * \retval FLAC__bool
  92241. * \c false if an error occurred processing the last frame; or if verify
  92242. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92243. * verify mismatch; else \c true. If \c false, caller should check the
  92244. * state with FLAC__stream_encoder_get_state() for more information
  92245. * about the error.
  92246. */
  92247. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92248. /** Submit data for encoding.
  92249. * This version allows you to supply the input data via an array of
  92250. * pointers, each pointer pointing to an array of \a samples samples
  92251. * representing one channel. The samples need not be block-aligned,
  92252. * but each channel should have the same number of samples. Each sample
  92253. * should be a signed integer, right-justified to the resolution set by
  92254. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92255. * resolution is 16 bits per sample, the samples should all be in the
  92256. * range [-32768,32767].
  92257. *
  92258. * For applications where channel order is important, channels must
  92259. * follow the order as described in the
  92260. * <A HREF="../format.html#frame_header">frame header</A>.
  92261. *
  92262. * \param encoder An initialized encoder instance in the OK state.
  92263. * \param buffer An array of pointers to each channel's signal.
  92264. * \param samples The number of samples in one channel.
  92265. * \assert
  92266. * \code encoder != NULL \endcode
  92267. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92268. * \retval FLAC__bool
  92269. * \c true if successful, else \c false; in this case, check the
  92270. * encoder state with FLAC__stream_encoder_get_state() to see what
  92271. * went wrong.
  92272. */
  92273. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92274. /** Submit data for encoding.
  92275. * This version allows you to supply the input data where the channels
  92276. * are interleaved into a single array (i.e. channel0_sample0,
  92277. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92278. * The samples need not be block-aligned but they must be
  92279. * sample-aligned, i.e. the first value should be channel0_sample0
  92280. * and the last value channelN_sampleM. Each sample should be a signed
  92281. * integer, right-justified to the resolution set by
  92282. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92283. * resolution is 16 bits per sample, the samples should all be in the
  92284. * range [-32768,32767].
  92285. *
  92286. * For applications where channel order is important, channels must
  92287. * follow the order as described in the
  92288. * <A HREF="../format.html#frame_header">frame header</A>.
  92289. *
  92290. * \param encoder An initialized encoder instance in the OK state.
  92291. * \param buffer An array of channel-interleaved data (see above).
  92292. * \param samples The number of samples in one channel, the same as for
  92293. * FLAC__stream_encoder_process(). For example, if
  92294. * encoding two channels, \c 1000 \a samples corresponds
  92295. * to a \a buffer of 2000 values.
  92296. * \assert
  92297. * \code encoder != NULL \endcode
  92298. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92299. * \retval FLAC__bool
  92300. * \c true if successful, else \c false; in this case, check the
  92301. * encoder state with FLAC__stream_encoder_get_state() to see what
  92302. * went wrong.
  92303. */
  92304. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92305. /* \} */
  92306. #ifdef __cplusplus
  92307. }
  92308. #endif
  92309. #endif
  92310. /*** End of inlined file: stream_encoder.h ***/
  92311. #ifdef _MSC_VER
  92312. /* OPT: an MSVC built-in would be better */
  92313. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92314. {
  92315. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92316. return (x>>16) | (x<<16);
  92317. }
  92318. #endif
  92319. #if defined(_MSC_VER) && defined(_X86_)
  92320. /* OPT: an MSVC built-in would be better */
  92321. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92322. {
  92323. __asm {
  92324. mov edx, start
  92325. mov ecx, len
  92326. test ecx, ecx
  92327. loop1:
  92328. jz done1
  92329. mov eax, [edx]
  92330. bswap eax
  92331. mov [edx], eax
  92332. add edx, 4
  92333. dec ecx
  92334. jmp short loop1
  92335. done1:
  92336. }
  92337. }
  92338. #endif
  92339. /** \mainpage
  92340. *
  92341. * \section intro Introduction
  92342. *
  92343. * This is the documentation for the FLAC C and C++ APIs. It is
  92344. * highly interconnected; this introduction should give you a top
  92345. * level idea of the structure and how to find the information you
  92346. * need. As a prerequisite you should have at least a basic
  92347. * knowledge of the FLAC format, documented
  92348. * <A HREF="../format.html">here</A>.
  92349. *
  92350. * \section c_api FLAC C API
  92351. *
  92352. * The FLAC C API is the interface to libFLAC, a set of structures
  92353. * describing the components of FLAC streams, and functions for
  92354. * encoding and decoding streams, as well as manipulating FLAC
  92355. * metadata in files. The public include files will be installed
  92356. * in your include area (for example /usr/include/FLAC/...).
  92357. *
  92358. * By writing a little code and linking against libFLAC, it is
  92359. * relatively easy to add FLAC support to another program. The
  92360. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92361. * Complete source code of libFLAC as well as the command-line
  92362. * encoder and plugins is available and is a useful source of
  92363. * examples.
  92364. *
  92365. * Aside from encoders and decoders, libFLAC provides a powerful
  92366. * metadata interface for manipulating metadata in FLAC files. It
  92367. * allows the user to add, delete, and modify FLAC metadata blocks
  92368. * and it can automatically take advantage of PADDING blocks to avoid
  92369. * rewriting the entire FLAC file when changing the size of the
  92370. * metadata.
  92371. *
  92372. * libFLAC usually only requires the standard C library and C math
  92373. * library. In particular, threading is not used so there is no
  92374. * dependency on a thread library. However, libFLAC does not use
  92375. * global variables and should be thread-safe.
  92376. *
  92377. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92378. * However the metadata editing interfaces currently have limited
  92379. * read-only support for Ogg FLAC files.
  92380. *
  92381. * \section cpp_api FLAC C++ API
  92382. *
  92383. * The FLAC C++ API is a set of classes that encapsulate the
  92384. * structures and functions in libFLAC. They provide slightly more
  92385. * functionality with respect to metadata but are otherwise
  92386. * equivalent. For the most part, they share the same usage as
  92387. * their counterparts in libFLAC, and the FLAC C API documentation
  92388. * can be used as a supplement. The public include files
  92389. * for the C++ API will be installed in your include area (for
  92390. * example /usr/include/FLAC++/...).
  92391. *
  92392. * libFLAC++ is also licensed under
  92393. * <A HREF="../license.html">Xiph's BSD license</A>.
  92394. *
  92395. * \section getting_started Getting Started
  92396. *
  92397. * A good starting point for learning the API is to browse through
  92398. * the <A HREF="modules.html">modules</A>. Modules are logical
  92399. * groupings of related functions or classes, which correspond roughly
  92400. * to header files or sections of header files. Each module includes a
  92401. * detailed description of the general usage of its functions or
  92402. * classes.
  92403. *
  92404. * From there you can go on to look at the documentation of
  92405. * individual functions. You can see different views of the individual
  92406. * functions through the links in top bar across this page.
  92407. *
  92408. * If you prefer a more hands-on approach, you can jump right to some
  92409. * <A HREF="../documentation_example_code.html">example code</A>.
  92410. *
  92411. * \section porting_guide Porting Guide
  92412. *
  92413. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92414. * has been introduced which gives detailed instructions on how to
  92415. * port your code to newer versions of FLAC.
  92416. *
  92417. * \section embedded_developers Embedded Developers
  92418. *
  92419. * libFLAC has grown larger over time as more functionality has been
  92420. * included, but much of it may be unnecessary for a particular embedded
  92421. * implementation. Unused parts may be pruned by some simple editing of
  92422. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92423. * metadata interface are all independent from each other.
  92424. *
  92425. * It is easiest to just describe the dependencies:
  92426. *
  92427. * - All modules depend on the \link flac_format Format \endlink module.
  92428. * - The decoders and encoders depend on the bitbuffer.
  92429. * - The decoder is independent of the encoder. The encoder uses the
  92430. * decoder because of the verify feature, but this can be removed if
  92431. * not needed.
  92432. * - Parts of the metadata interface require the stream decoder (but not
  92433. * the encoder).
  92434. * - Ogg support is selectable through the compile time macro
  92435. * \c FLAC__HAS_OGG.
  92436. *
  92437. * For example, if your application only requires the stream decoder, no
  92438. * encoder, and no metadata interface, you can remove the stream encoder
  92439. * and the metadata interface, which will greatly reduce the size of the
  92440. * library.
  92441. *
  92442. * Also, there are several places in the libFLAC code with comments marked
  92443. * with "OPT:" where a #define can be changed to enable code that might be
  92444. * faster on a specific platform. Experimenting with these can yield faster
  92445. * binaries.
  92446. */
  92447. /** \defgroup porting Porting Guide for New Versions
  92448. *
  92449. * This module describes differences in the library interfaces from
  92450. * version to version. It assists in the porting of code that uses
  92451. * the libraries to newer versions of FLAC.
  92452. *
  92453. * One simple facility for making porting easier that has been added
  92454. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92455. * library's includes (e.g. \c include/FLAC/export.h). The
  92456. * \c #defines mirror the libraries'
  92457. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92458. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92459. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92460. * These can be used to support multiple versions of an API during the
  92461. * transition phase, e.g.
  92462. *
  92463. * \code
  92464. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92465. * legacy code
  92466. * #else
  92467. * new code
  92468. * #endif
  92469. * \endcode
  92470. *
  92471. * The the source will work for multiple versions and the legacy code can
  92472. * easily be removed when the transition is complete.
  92473. *
  92474. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92475. * include/FLAC/export.h), which can be used to determine whether or not
  92476. * the library has been compiled with support for Ogg FLAC. This is
  92477. * simpler than trying to call an Ogg init function and catching the
  92478. * error.
  92479. */
  92480. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92481. * \ingroup porting
  92482. *
  92483. * \brief
  92484. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92485. *
  92486. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92487. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92488. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92489. * decoding layers and three encoding layers have been merged into a
  92490. * single stream decoder and stream encoder. That is, the functionality
  92491. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92492. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92493. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92494. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92495. * is there is now a single API that can be used to encode or decode
  92496. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92497. * on both seekable and non-seekable streams.
  92498. *
  92499. * Instead of creating an encoder or decoder of a certain layer, now the
  92500. * client will always create a FLAC__StreamEncoder or
  92501. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92502. * initialization function. For example, for the decoder,
  92503. * FLAC__stream_decoder_init() has been replaced by
  92504. * FLAC__stream_decoder_init_stream(). This init function takes
  92505. * callbacks for the I/O, and the seeking callbacks are optional. This
  92506. * allows the client to use the same object for seekable and
  92507. * non-seekable streams. For decoding a FLAC file directly, the client
  92508. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92509. * and fewer callbacks; most of the other callbacks are supplied
  92510. * internally. For situations where fopen()ing by filename is not
  92511. * possible (e.g. Unicode filenames on Windows) the client can instead
  92512. * open the file itself and supply the FILE* to
  92513. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92514. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92515. * Since the callbacks and client data are now passed to the init
  92516. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92517. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92518. * rest of the calls to the decoder are the same as before.
  92519. *
  92520. * There are counterpart init functions for Ogg FLAC, e.g.
  92521. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92522. * and callbacks are the same as for native FLAC.
  92523. *
  92524. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92525. * been set up like so:
  92526. *
  92527. * \code
  92528. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92529. * if(decoder == NULL) do_something;
  92530. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92531. * [... other settings ...]
  92532. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92533. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92534. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92535. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92536. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92537. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92538. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92539. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92540. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92541. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92542. * \endcode
  92543. *
  92544. * In FLAC 1.1.3 it is like this:
  92545. *
  92546. * \code
  92547. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92548. * if(decoder == NULL) do_something;
  92549. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92550. * [... other settings ...]
  92551. * if(FLAC__stream_decoder_init_stream(
  92552. * decoder,
  92553. * my_read_callback,
  92554. * my_seek_callback, // or NULL
  92555. * my_tell_callback, // or NULL
  92556. * my_length_callback, // or NULL
  92557. * my_eof_callback, // or NULL
  92558. * my_write_callback,
  92559. * my_metadata_callback, // or NULL
  92560. * my_error_callback,
  92561. * my_client_data
  92562. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92563. * \endcode
  92564. *
  92565. * or you could do;
  92566. *
  92567. * \code
  92568. * [...]
  92569. * FILE *file = fopen("somefile.flac","rb");
  92570. * if(file == NULL) do_somthing;
  92571. * if(FLAC__stream_decoder_init_FILE(
  92572. * decoder,
  92573. * file,
  92574. * my_write_callback,
  92575. * my_metadata_callback, // or NULL
  92576. * my_error_callback,
  92577. * my_client_data
  92578. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92579. * \endcode
  92580. *
  92581. * or just:
  92582. *
  92583. * \code
  92584. * [...]
  92585. * if(FLAC__stream_decoder_init_file(
  92586. * decoder,
  92587. * "somefile.flac",
  92588. * my_write_callback,
  92589. * my_metadata_callback, // or NULL
  92590. * my_error_callback,
  92591. * my_client_data
  92592. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92593. * \endcode
  92594. *
  92595. * Another small change to the decoder is in how it handles unparseable
  92596. * streams. Before, when the decoder found an unparseable stream
  92597. * (reserved for when the decoder encounters a stream from a future
  92598. * encoder that it can't parse), it changed the state to
  92599. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92600. * drops sync and calls the error callback with a new error code
  92601. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92602. * more robust. If your error callback does not discriminate on the the
  92603. * error state, your code does not need to be changed.
  92604. *
  92605. * The encoder now has a new setting:
  92606. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92607. * method used to window the data before LPC analysis. You only need to
  92608. * add a call to this function if the default is not suitable. There
  92609. * are also two new convenience functions that may be useful:
  92610. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92611. * FLAC__metadata_get_cuesheet().
  92612. *
  92613. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92614. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92615. * is now \c size_t instead of \c unsigned.
  92616. */
  92617. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92618. * \ingroup porting
  92619. *
  92620. * \brief
  92621. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92622. *
  92623. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92624. * There was a slight change in the implementation of
  92625. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92626. * of the \a metadata array of pointers so the client no longer needs
  92627. * to maintain it after the call. The objects themselves that are
  92628. * pointed to by the array are still not copied though and must be
  92629. * maintained until the call to FLAC__stream_encoder_finish().
  92630. */
  92631. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92632. * \ingroup porting
  92633. *
  92634. * \brief
  92635. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92636. *
  92637. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92638. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92639. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92640. *
  92641. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92642. * has changed to reflect the conversion of one of the reserved bits
  92643. * into active use. It used to be \c 2 and now is \c 1. However the
  92644. * FLAC frame header length has not changed, so to skip the proper
  92645. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92646. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92647. */
  92648. /** \defgroup flac FLAC C API
  92649. *
  92650. * The FLAC C API is the interface to libFLAC, a set of structures
  92651. * describing the components of FLAC streams, and functions for
  92652. * encoding and decoding streams, as well as manipulating FLAC
  92653. * metadata in files.
  92654. *
  92655. * You should start with the format components as all other modules
  92656. * are dependent on it.
  92657. */
  92658. #endif
  92659. /*** End of inlined file: all.h ***/
  92660. /*** Start of inlined file: bitmath.c ***/
  92661. /*** Start of inlined file: juce_FlacHeader.h ***/
  92662. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92663. // tasks..
  92664. #define VERSION "1.2.1"
  92665. #define FLAC__NO_DLL 1
  92666. #if JUCE_MSVC
  92667. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92668. #endif
  92669. #if JUCE_MAC
  92670. #define FLAC__SYS_DARWIN 1
  92671. #endif
  92672. /*** End of inlined file: juce_FlacHeader.h ***/
  92673. #if JUCE_USE_FLAC
  92674. #if HAVE_CONFIG_H
  92675. # include <config.h>
  92676. #endif
  92677. /*** Start of inlined file: bitmath.h ***/
  92678. #ifndef FLAC__PRIVATE__BITMATH_H
  92679. #define FLAC__PRIVATE__BITMATH_H
  92680. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92681. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92682. unsigned FLAC__bitmath_silog2(int v);
  92683. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92684. #endif
  92685. /*** End of inlined file: bitmath.h ***/
  92686. /* An example of what FLAC__bitmath_ilog2() computes:
  92687. *
  92688. * ilog2( 0) = assertion failure
  92689. * ilog2( 1) = 0
  92690. * ilog2( 2) = 1
  92691. * ilog2( 3) = 1
  92692. * ilog2( 4) = 2
  92693. * ilog2( 5) = 2
  92694. * ilog2( 6) = 2
  92695. * ilog2( 7) = 2
  92696. * ilog2( 8) = 3
  92697. * ilog2( 9) = 3
  92698. * ilog2(10) = 3
  92699. * ilog2(11) = 3
  92700. * ilog2(12) = 3
  92701. * ilog2(13) = 3
  92702. * ilog2(14) = 3
  92703. * ilog2(15) = 3
  92704. * ilog2(16) = 4
  92705. * ilog2(17) = 4
  92706. * ilog2(18) = 4
  92707. */
  92708. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92709. {
  92710. unsigned l = 0;
  92711. FLAC__ASSERT(v > 0);
  92712. while(v >>= 1)
  92713. l++;
  92714. return l;
  92715. }
  92716. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92717. {
  92718. unsigned l = 0;
  92719. FLAC__ASSERT(v > 0);
  92720. while(v >>= 1)
  92721. l++;
  92722. return l;
  92723. }
  92724. /* An example of what FLAC__bitmath_silog2() computes:
  92725. *
  92726. * silog2(-10) = 5
  92727. * silog2(- 9) = 5
  92728. * silog2(- 8) = 4
  92729. * silog2(- 7) = 4
  92730. * silog2(- 6) = 4
  92731. * silog2(- 5) = 4
  92732. * silog2(- 4) = 3
  92733. * silog2(- 3) = 3
  92734. * silog2(- 2) = 2
  92735. * silog2(- 1) = 2
  92736. * silog2( 0) = 0
  92737. * silog2( 1) = 2
  92738. * silog2( 2) = 3
  92739. * silog2( 3) = 3
  92740. * silog2( 4) = 4
  92741. * silog2( 5) = 4
  92742. * silog2( 6) = 4
  92743. * silog2( 7) = 4
  92744. * silog2( 8) = 5
  92745. * silog2( 9) = 5
  92746. * silog2( 10) = 5
  92747. */
  92748. unsigned FLAC__bitmath_silog2(int v)
  92749. {
  92750. while(1) {
  92751. if(v == 0) {
  92752. return 0;
  92753. }
  92754. else if(v > 0) {
  92755. unsigned l = 0;
  92756. while(v) {
  92757. l++;
  92758. v >>= 1;
  92759. }
  92760. return l+1;
  92761. }
  92762. else if(v == -1) {
  92763. return 2;
  92764. }
  92765. else {
  92766. v++;
  92767. v = -v;
  92768. }
  92769. }
  92770. }
  92771. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92772. {
  92773. while(1) {
  92774. if(v == 0) {
  92775. return 0;
  92776. }
  92777. else if(v > 0) {
  92778. unsigned l = 0;
  92779. while(v) {
  92780. l++;
  92781. v >>= 1;
  92782. }
  92783. return l+1;
  92784. }
  92785. else if(v == -1) {
  92786. return 2;
  92787. }
  92788. else {
  92789. v++;
  92790. v = -v;
  92791. }
  92792. }
  92793. }
  92794. #endif
  92795. /*** End of inlined file: bitmath.c ***/
  92796. /*** Start of inlined file: bitreader.c ***/
  92797. /*** Start of inlined file: juce_FlacHeader.h ***/
  92798. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92799. // tasks..
  92800. #define VERSION "1.2.1"
  92801. #define FLAC__NO_DLL 1
  92802. #if JUCE_MSVC
  92803. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92804. #endif
  92805. #if JUCE_MAC
  92806. #define FLAC__SYS_DARWIN 1
  92807. #endif
  92808. /*** End of inlined file: juce_FlacHeader.h ***/
  92809. #if JUCE_USE_FLAC
  92810. #if HAVE_CONFIG_H
  92811. # include <config.h>
  92812. #endif
  92813. #include <stdlib.h> /* for malloc() */
  92814. #include <string.h> /* for memcpy(), memset() */
  92815. #ifdef _MSC_VER
  92816. #include <winsock.h> /* for ntohl() */
  92817. #elif defined FLAC__SYS_DARWIN
  92818. #include <machine/endian.h> /* for ntohl() */
  92819. #elif defined __MINGW32__
  92820. #include <winsock.h> /* for ntohl() */
  92821. #else
  92822. #include <netinet/in.h> /* for ntohl() */
  92823. #endif
  92824. /*** Start of inlined file: bitreader.h ***/
  92825. #ifndef FLAC__PRIVATE__BITREADER_H
  92826. #define FLAC__PRIVATE__BITREADER_H
  92827. #include <stdio.h> /* for FILE */
  92828. /*** Start of inlined file: cpu.h ***/
  92829. #ifndef FLAC__PRIVATE__CPU_H
  92830. #define FLAC__PRIVATE__CPU_H
  92831. #ifdef HAVE_CONFIG_H
  92832. #include <config.h>
  92833. #endif
  92834. typedef enum {
  92835. FLAC__CPUINFO_TYPE_IA32,
  92836. FLAC__CPUINFO_TYPE_PPC,
  92837. FLAC__CPUINFO_TYPE_UNKNOWN
  92838. } FLAC__CPUInfo_Type;
  92839. typedef struct {
  92840. FLAC__bool cpuid;
  92841. FLAC__bool bswap;
  92842. FLAC__bool cmov;
  92843. FLAC__bool mmx;
  92844. FLAC__bool fxsr;
  92845. FLAC__bool sse;
  92846. FLAC__bool sse2;
  92847. FLAC__bool sse3;
  92848. FLAC__bool ssse3;
  92849. FLAC__bool _3dnow;
  92850. FLAC__bool ext3dnow;
  92851. FLAC__bool extmmx;
  92852. } FLAC__CPUInfo_IA32;
  92853. typedef struct {
  92854. FLAC__bool altivec;
  92855. FLAC__bool ppc64;
  92856. } FLAC__CPUInfo_PPC;
  92857. typedef struct {
  92858. FLAC__bool use_asm;
  92859. FLAC__CPUInfo_Type type;
  92860. union {
  92861. FLAC__CPUInfo_IA32 ia32;
  92862. FLAC__CPUInfo_PPC ppc;
  92863. } data;
  92864. } FLAC__CPUInfo;
  92865. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92866. #ifndef FLAC__NO_ASM
  92867. #ifdef FLAC__CPU_IA32
  92868. #ifdef FLAC__HAS_NASM
  92869. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92870. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92871. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92872. #endif
  92873. #endif
  92874. #endif
  92875. #endif
  92876. /*** End of inlined file: cpu.h ***/
  92877. /*
  92878. * opaque structure definition
  92879. */
  92880. struct FLAC__BitReader;
  92881. typedef struct FLAC__BitReader FLAC__BitReader;
  92882. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92883. /*
  92884. * construction, deletion, initialization, etc functions
  92885. */
  92886. FLAC__BitReader *FLAC__bitreader_new(void);
  92887. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92888. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92889. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92890. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92891. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92892. /*
  92893. * CRC functions
  92894. */
  92895. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92896. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92897. /*
  92898. * info functions
  92899. */
  92900. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92901. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92902. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92903. /*
  92904. * read functions
  92905. */
  92906. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92907. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92908. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92909. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92910. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92911. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92912. 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! */
  92913. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92914. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92915. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92916. #ifndef FLAC__NO_ASM
  92917. # ifdef FLAC__CPU_IA32
  92918. # ifdef FLAC__HAS_NASM
  92919. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92920. # endif
  92921. # endif
  92922. #endif
  92923. #if 0 /* UNUSED */
  92924. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92925. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92926. #endif
  92927. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92928. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92929. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92930. #endif
  92931. /*** End of inlined file: bitreader.h ***/
  92932. /*** Start of inlined file: crc.h ***/
  92933. #ifndef FLAC__PRIVATE__CRC_H
  92934. #define FLAC__PRIVATE__CRC_H
  92935. /* 8 bit CRC generator, MSB shifted first
  92936. ** polynomial = x^8 + x^2 + x^1 + x^0
  92937. ** init = 0
  92938. */
  92939. extern FLAC__byte const FLAC__crc8_table[256];
  92940. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92941. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92942. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92943. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92944. /* 16 bit CRC generator, MSB shifted first
  92945. ** polynomial = x^16 + x^15 + x^2 + x^0
  92946. ** init = 0
  92947. */
  92948. extern unsigned FLAC__crc16_table[256];
  92949. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92950. /* this alternate may be faster on some systems/compilers */
  92951. #if 0
  92952. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92953. #endif
  92954. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92955. #endif
  92956. /*** End of inlined file: crc.h ***/
  92957. /* Things should be fastest when this matches the machine word size */
  92958. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92959. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92960. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92961. typedef FLAC__uint32 brword;
  92962. #define FLAC__BYTES_PER_WORD 4
  92963. #define FLAC__BITS_PER_WORD 32
  92964. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92965. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92966. #if WORDS_BIGENDIAN
  92967. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92968. #else
  92969. #if defined (_MSC_VER) && defined (_X86_)
  92970. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92971. #else
  92972. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92973. #endif
  92974. #endif
  92975. /* counts the # of zero MSBs in a word */
  92976. #define COUNT_ZERO_MSBS(word) ( \
  92977. (word) <= 0xffff ? \
  92978. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92979. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92980. )
  92981. /* this alternate might be slightly faster on some systems/compilers: */
  92982. #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])) )
  92983. /*
  92984. * This should be at least twice as large as the largest number of words
  92985. * required to represent any 'number' (in any encoding) you are going to
  92986. * read. With FLAC this is on the order of maybe a few hundred bits.
  92987. * If the buffer is smaller than that, the decoder won't be able to read
  92988. * in a whole number that is in a variable length encoding (e.g. Rice).
  92989. * But to be practical it should be at least 1K bytes.
  92990. *
  92991. * Increase this number to decrease the number of read callbacks, at the
  92992. * expense of using more memory. Or decrease for the reverse effect,
  92993. * keeping in mind the limit from the first paragraph. The optimal size
  92994. * also depends on the CPU cache size and other factors; some twiddling
  92995. * may be necessary to squeeze out the best performance.
  92996. */
  92997. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92998. static const unsigned char byte_to_unary_table[] = {
  92999. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93000. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93001. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93002. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93003. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93004. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93005. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93006. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93015. };
  93016. #ifdef min
  93017. #undef min
  93018. #endif
  93019. #define min(x,y) ((x)<(y)?(x):(y))
  93020. #ifdef max
  93021. #undef max
  93022. #endif
  93023. #define max(x,y) ((x)>(y)?(x):(y))
  93024. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93025. #ifdef _MSC_VER
  93026. #define FLAC__U64L(x) x
  93027. #else
  93028. #define FLAC__U64L(x) x##LLU
  93029. #endif
  93030. #ifndef FLaC__INLINE
  93031. #define FLaC__INLINE
  93032. #endif
  93033. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93034. struct FLAC__BitReader {
  93035. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93036. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93037. brword *buffer;
  93038. unsigned capacity; /* in words */
  93039. unsigned words; /* # of completed words in buffer */
  93040. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93041. unsigned consumed_words; /* #words ... */
  93042. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93043. unsigned read_crc16; /* the running frame CRC */
  93044. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93045. FLAC__BitReaderReadCallback read_callback;
  93046. void *client_data;
  93047. FLAC__CPUInfo cpu_info;
  93048. };
  93049. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93050. {
  93051. register unsigned crc = br->read_crc16;
  93052. #if FLAC__BYTES_PER_WORD == 4
  93053. switch(br->crc16_align) {
  93054. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93055. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93056. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93057. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93058. }
  93059. #elif FLAC__BYTES_PER_WORD == 8
  93060. switch(br->crc16_align) {
  93061. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93062. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93063. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93064. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93065. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93066. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93067. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93068. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93069. }
  93070. #else
  93071. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93072. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93073. br->read_crc16 = crc;
  93074. #endif
  93075. br->crc16_align = 0;
  93076. }
  93077. /* would be static except it needs to be called by asm routines */
  93078. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93079. {
  93080. unsigned start, end;
  93081. size_t bytes;
  93082. FLAC__byte *target;
  93083. /* first shift the unconsumed buffer data toward the front as much as possible */
  93084. if(br->consumed_words > 0) {
  93085. start = br->consumed_words;
  93086. end = br->words + (br->bytes? 1:0);
  93087. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93088. br->words -= start;
  93089. br->consumed_words = 0;
  93090. }
  93091. /*
  93092. * set the target for reading, taking into account word alignment and endianness
  93093. */
  93094. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93095. if(bytes == 0)
  93096. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93097. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93098. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93099. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93100. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93101. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93102. * ^^-------target, bytes=3
  93103. * on LE machines, have to byteswap the odd tail word so nothing is
  93104. * overwritten:
  93105. */
  93106. #if WORDS_BIGENDIAN
  93107. #else
  93108. if(br->bytes)
  93109. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93110. #endif
  93111. /* now it looks like:
  93112. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93113. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93114. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93115. * ^^-------target, bytes=3
  93116. */
  93117. /* read in the data; note that the callback may return a smaller number of bytes */
  93118. if(!br->read_callback(target, &bytes, br->client_data))
  93119. return false;
  93120. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93121. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93122. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93123. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93124. * now have to byteswap on LE machines:
  93125. */
  93126. #if WORDS_BIGENDIAN
  93127. #else
  93128. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93129. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93130. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93131. start = br->words;
  93132. local_swap32_block_(br->buffer + start, end - start);
  93133. }
  93134. else
  93135. # endif
  93136. for(start = br->words; start < end; start++)
  93137. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93138. #endif
  93139. /* now it looks like:
  93140. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93141. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93142. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93143. * finally we'll update the reader values:
  93144. */
  93145. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93146. br->words = end / FLAC__BYTES_PER_WORD;
  93147. br->bytes = end % FLAC__BYTES_PER_WORD;
  93148. return true;
  93149. }
  93150. /***********************************************************************
  93151. *
  93152. * Class constructor/destructor
  93153. *
  93154. ***********************************************************************/
  93155. FLAC__BitReader *FLAC__bitreader_new(void)
  93156. {
  93157. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93158. /* calloc() implies:
  93159. memset(br, 0, sizeof(FLAC__BitReader));
  93160. br->buffer = 0;
  93161. br->capacity = 0;
  93162. br->words = br->bytes = 0;
  93163. br->consumed_words = br->consumed_bits = 0;
  93164. br->read_callback = 0;
  93165. br->client_data = 0;
  93166. */
  93167. return br;
  93168. }
  93169. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93170. {
  93171. FLAC__ASSERT(0 != br);
  93172. FLAC__bitreader_free(br);
  93173. free(br);
  93174. }
  93175. /***********************************************************************
  93176. *
  93177. * Public class methods
  93178. *
  93179. ***********************************************************************/
  93180. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93181. {
  93182. FLAC__ASSERT(0 != br);
  93183. br->words = br->bytes = 0;
  93184. br->consumed_words = br->consumed_bits = 0;
  93185. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93186. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93187. if(br->buffer == 0)
  93188. return false;
  93189. br->read_callback = rcb;
  93190. br->client_data = cd;
  93191. br->cpu_info = cpu;
  93192. return true;
  93193. }
  93194. void FLAC__bitreader_free(FLAC__BitReader *br)
  93195. {
  93196. FLAC__ASSERT(0 != br);
  93197. if(0 != br->buffer)
  93198. free(br->buffer);
  93199. br->buffer = 0;
  93200. br->capacity = 0;
  93201. br->words = br->bytes = 0;
  93202. br->consumed_words = br->consumed_bits = 0;
  93203. br->read_callback = 0;
  93204. br->client_data = 0;
  93205. }
  93206. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93207. {
  93208. br->words = br->bytes = 0;
  93209. br->consumed_words = br->consumed_bits = 0;
  93210. return true;
  93211. }
  93212. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93213. {
  93214. unsigned i, j;
  93215. if(br == 0) {
  93216. fprintf(out, "bitreader is NULL\n");
  93217. }
  93218. else {
  93219. 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);
  93220. for(i = 0; i < br->words; i++) {
  93221. fprintf(out, "%08X: ", i);
  93222. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93223. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93224. fprintf(out, ".");
  93225. else
  93226. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93227. fprintf(out, "\n");
  93228. }
  93229. if(br->bytes > 0) {
  93230. fprintf(out, "%08X: ", i);
  93231. for(j = 0; j < br->bytes*8; j++)
  93232. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93233. fprintf(out, ".");
  93234. else
  93235. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93236. fprintf(out, "\n");
  93237. }
  93238. }
  93239. }
  93240. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93241. {
  93242. FLAC__ASSERT(0 != br);
  93243. FLAC__ASSERT(0 != br->buffer);
  93244. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93245. br->read_crc16 = (unsigned)seed;
  93246. br->crc16_align = br->consumed_bits;
  93247. }
  93248. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93249. {
  93250. FLAC__ASSERT(0 != br);
  93251. FLAC__ASSERT(0 != br->buffer);
  93252. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93253. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93254. /* CRC any tail bytes in a partially-consumed word */
  93255. if(br->consumed_bits) {
  93256. const brword tail = br->buffer[br->consumed_words];
  93257. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93258. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93259. }
  93260. return br->read_crc16;
  93261. }
  93262. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93263. {
  93264. return ((br->consumed_bits & 7) == 0);
  93265. }
  93266. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93267. {
  93268. return 8 - (br->consumed_bits & 7);
  93269. }
  93270. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93271. {
  93272. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93273. }
  93274. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93275. {
  93276. FLAC__ASSERT(0 != br);
  93277. FLAC__ASSERT(0 != br->buffer);
  93278. FLAC__ASSERT(bits <= 32);
  93279. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93280. FLAC__ASSERT(br->consumed_words <= br->words);
  93281. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93282. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93283. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93284. *val = 0;
  93285. return true;
  93286. }
  93287. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93288. if(!bitreader_read_from_client_(br))
  93289. return false;
  93290. }
  93291. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93292. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93293. if(br->consumed_bits) {
  93294. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93295. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93296. const brword word = br->buffer[br->consumed_words];
  93297. if(bits < n) {
  93298. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93299. br->consumed_bits += bits;
  93300. return true;
  93301. }
  93302. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93303. bits -= n;
  93304. crc16_update_word_(br, word);
  93305. br->consumed_words++;
  93306. br->consumed_bits = 0;
  93307. 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 */
  93308. *val <<= bits;
  93309. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93310. br->consumed_bits = bits;
  93311. }
  93312. return true;
  93313. }
  93314. else {
  93315. const brword word = br->buffer[br->consumed_words];
  93316. if(bits < FLAC__BITS_PER_WORD) {
  93317. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93318. br->consumed_bits = bits;
  93319. return true;
  93320. }
  93321. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93322. *val = word;
  93323. crc16_update_word_(br, word);
  93324. br->consumed_words++;
  93325. return true;
  93326. }
  93327. }
  93328. else {
  93329. /* in this case we're starting our read at a partial tail word;
  93330. * the reader has guaranteed that we have at least 'bits' bits
  93331. * available to read, which makes this case simpler.
  93332. */
  93333. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93334. if(br->consumed_bits) {
  93335. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93336. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93337. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93338. br->consumed_bits += bits;
  93339. return true;
  93340. }
  93341. else {
  93342. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93343. br->consumed_bits += bits;
  93344. return true;
  93345. }
  93346. }
  93347. }
  93348. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93349. {
  93350. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93351. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93352. return false;
  93353. /* sign-extend: */
  93354. *val <<= (32-bits);
  93355. *val >>= (32-bits);
  93356. return true;
  93357. }
  93358. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93359. {
  93360. FLAC__uint32 hi, lo;
  93361. if(bits > 32) {
  93362. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93363. return false;
  93364. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93365. return false;
  93366. *val = hi;
  93367. *val <<= 32;
  93368. *val |= lo;
  93369. }
  93370. else {
  93371. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93372. return false;
  93373. *val = lo;
  93374. }
  93375. return true;
  93376. }
  93377. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93378. {
  93379. FLAC__uint32 x8, x32 = 0;
  93380. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93381. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93382. return false;
  93383. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93384. return false;
  93385. x32 |= (x8 << 8);
  93386. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93387. return false;
  93388. x32 |= (x8 << 16);
  93389. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93390. return false;
  93391. x32 |= (x8 << 24);
  93392. *val = x32;
  93393. return true;
  93394. }
  93395. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93396. {
  93397. /*
  93398. * OPT: a faster implementation is possible but probably not that useful
  93399. * since this is only called a couple of times in the metadata readers.
  93400. */
  93401. FLAC__ASSERT(0 != br);
  93402. FLAC__ASSERT(0 != br->buffer);
  93403. if(bits > 0) {
  93404. const unsigned n = br->consumed_bits & 7;
  93405. unsigned m;
  93406. FLAC__uint32 x;
  93407. if(n != 0) {
  93408. m = min(8-n, bits);
  93409. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93410. return false;
  93411. bits -= m;
  93412. }
  93413. m = bits / 8;
  93414. if(m > 0) {
  93415. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93416. return false;
  93417. bits %= 8;
  93418. }
  93419. if(bits > 0) {
  93420. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93421. return false;
  93422. }
  93423. }
  93424. return true;
  93425. }
  93426. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93427. {
  93428. FLAC__uint32 x;
  93429. FLAC__ASSERT(0 != br);
  93430. FLAC__ASSERT(0 != br->buffer);
  93431. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93432. /* step 1: skip over partial head word to get word aligned */
  93433. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93434. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93435. return false;
  93436. nvals--;
  93437. }
  93438. if(0 == nvals)
  93439. return true;
  93440. /* step 2: skip whole words in chunks */
  93441. while(nvals >= FLAC__BYTES_PER_WORD) {
  93442. if(br->consumed_words < br->words) {
  93443. br->consumed_words++;
  93444. nvals -= FLAC__BYTES_PER_WORD;
  93445. }
  93446. else if(!bitreader_read_from_client_(br))
  93447. return false;
  93448. }
  93449. /* step 3: skip any remainder from partial tail bytes */
  93450. while(nvals) {
  93451. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93452. return false;
  93453. nvals--;
  93454. }
  93455. return true;
  93456. }
  93457. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93458. {
  93459. FLAC__uint32 x;
  93460. FLAC__ASSERT(0 != br);
  93461. FLAC__ASSERT(0 != br->buffer);
  93462. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93463. /* step 1: read from partial head word to get word aligned */
  93464. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93465. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93466. return false;
  93467. *val++ = (FLAC__byte)x;
  93468. nvals--;
  93469. }
  93470. if(0 == nvals)
  93471. return true;
  93472. /* step 2: read whole words in chunks */
  93473. while(nvals >= FLAC__BYTES_PER_WORD) {
  93474. if(br->consumed_words < br->words) {
  93475. const brword word = br->buffer[br->consumed_words++];
  93476. #if FLAC__BYTES_PER_WORD == 4
  93477. val[0] = (FLAC__byte)(word >> 24);
  93478. val[1] = (FLAC__byte)(word >> 16);
  93479. val[2] = (FLAC__byte)(word >> 8);
  93480. val[3] = (FLAC__byte)word;
  93481. #elif FLAC__BYTES_PER_WORD == 8
  93482. val[0] = (FLAC__byte)(word >> 56);
  93483. val[1] = (FLAC__byte)(word >> 48);
  93484. val[2] = (FLAC__byte)(word >> 40);
  93485. val[3] = (FLAC__byte)(word >> 32);
  93486. val[4] = (FLAC__byte)(word >> 24);
  93487. val[5] = (FLAC__byte)(word >> 16);
  93488. val[6] = (FLAC__byte)(word >> 8);
  93489. val[7] = (FLAC__byte)word;
  93490. #else
  93491. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93492. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93493. #endif
  93494. val += FLAC__BYTES_PER_WORD;
  93495. nvals -= FLAC__BYTES_PER_WORD;
  93496. }
  93497. else if(!bitreader_read_from_client_(br))
  93498. return false;
  93499. }
  93500. /* step 3: read any remainder from partial tail bytes */
  93501. while(nvals) {
  93502. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93503. return false;
  93504. *val++ = (FLAC__byte)x;
  93505. nvals--;
  93506. }
  93507. return true;
  93508. }
  93509. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93510. #if 0 /* slow but readable version */
  93511. {
  93512. unsigned bit;
  93513. FLAC__ASSERT(0 != br);
  93514. FLAC__ASSERT(0 != br->buffer);
  93515. *val = 0;
  93516. while(1) {
  93517. if(!FLAC__bitreader_read_bit(br, &bit))
  93518. return false;
  93519. if(bit)
  93520. break;
  93521. else
  93522. *val++;
  93523. }
  93524. return true;
  93525. }
  93526. #else
  93527. {
  93528. unsigned i;
  93529. FLAC__ASSERT(0 != br);
  93530. FLAC__ASSERT(0 != br->buffer);
  93531. *val = 0;
  93532. while(1) {
  93533. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93534. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93535. if(b) {
  93536. i = COUNT_ZERO_MSBS(b);
  93537. *val += i;
  93538. i++;
  93539. br->consumed_bits += i;
  93540. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93541. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93542. br->consumed_words++;
  93543. br->consumed_bits = 0;
  93544. }
  93545. return true;
  93546. }
  93547. else {
  93548. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93549. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93550. br->consumed_words++;
  93551. br->consumed_bits = 0;
  93552. /* didn't find stop bit yet, have to keep going... */
  93553. }
  93554. }
  93555. /* at this point we've eaten up all the whole words; have to try
  93556. * reading through any tail bytes before calling the read callback.
  93557. * this is a repeat of the above logic adjusted for the fact we
  93558. * don't have a whole word. note though if the client is feeding
  93559. * us data a byte at a time (unlikely), br->consumed_bits may not
  93560. * be zero.
  93561. */
  93562. if(br->bytes) {
  93563. const unsigned end = br->bytes * 8;
  93564. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93565. if(b) {
  93566. i = COUNT_ZERO_MSBS(b);
  93567. *val += i;
  93568. i++;
  93569. br->consumed_bits += i;
  93570. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93571. return true;
  93572. }
  93573. else {
  93574. *val += end - br->consumed_bits;
  93575. br->consumed_bits += end;
  93576. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93577. /* didn't find stop bit yet, have to keep going... */
  93578. }
  93579. }
  93580. if(!bitreader_read_from_client_(br))
  93581. return false;
  93582. }
  93583. }
  93584. #endif
  93585. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93586. {
  93587. FLAC__uint32 lsbs = 0, msbs = 0;
  93588. unsigned uval;
  93589. FLAC__ASSERT(0 != br);
  93590. FLAC__ASSERT(0 != br->buffer);
  93591. FLAC__ASSERT(parameter <= 31);
  93592. /* read the unary MSBs and end bit */
  93593. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93594. return false;
  93595. /* read the binary LSBs */
  93596. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93597. return false;
  93598. /* compose the value */
  93599. uval = (msbs << parameter) | lsbs;
  93600. if(uval & 1)
  93601. *val = -((int)(uval >> 1)) - 1;
  93602. else
  93603. *val = (int)(uval >> 1);
  93604. return true;
  93605. }
  93606. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93607. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93608. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93609. /* OPT: possibly faster version for use with MSVC */
  93610. #ifdef _MSC_VER
  93611. {
  93612. unsigned i;
  93613. unsigned uval = 0;
  93614. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93615. /* try and get br->consumed_words and br->consumed_bits into register;
  93616. * must remember to flush them back to *br before calling other
  93617. * bitwriter functions that use them, and before returning */
  93618. register unsigned cwords;
  93619. register unsigned cbits;
  93620. FLAC__ASSERT(0 != br);
  93621. FLAC__ASSERT(0 != br->buffer);
  93622. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93623. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93624. FLAC__ASSERT(parameter < 32);
  93625. /* 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 */
  93626. if(nvals == 0)
  93627. return true;
  93628. cbits = br->consumed_bits;
  93629. cwords = br->consumed_words;
  93630. while(1) {
  93631. /* read unary part */
  93632. while(1) {
  93633. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93634. brword b = br->buffer[cwords] << cbits;
  93635. if(b) {
  93636. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93637. __asm {
  93638. bsr eax, b
  93639. not eax
  93640. and eax, 31
  93641. mov i, eax
  93642. }
  93643. #else
  93644. i = COUNT_ZERO_MSBS(b);
  93645. #endif
  93646. uval += i;
  93647. bits = parameter;
  93648. i++;
  93649. cbits += i;
  93650. if(cbits == FLAC__BITS_PER_WORD) {
  93651. crc16_update_word_(br, br->buffer[cwords]);
  93652. cwords++;
  93653. cbits = 0;
  93654. }
  93655. goto break1;
  93656. }
  93657. else {
  93658. uval += FLAC__BITS_PER_WORD - cbits;
  93659. crc16_update_word_(br, br->buffer[cwords]);
  93660. cwords++;
  93661. cbits = 0;
  93662. /* didn't find stop bit yet, have to keep going... */
  93663. }
  93664. }
  93665. /* at this point we've eaten up all the whole words; have to try
  93666. * reading through any tail bytes before calling the read callback.
  93667. * this is a repeat of the above logic adjusted for the fact we
  93668. * don't have a whole word. note though if the client is feeding
  93669. * us data a byte at a time (unlikely), br->consumed_bits may not
  93670. * be zero.
  93671. */
  93672. if(br->bytes) {
  93673. const unsigned end = br->bytes * 8;
  93674. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93675. if(b) {
  93676. i = COUNT_ZERO_MSBS(b);
  93677. uval += i;
  93678. bits = parameter;
  93679. i++;
  93680. cbits += i;
  93681. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93682. goto break1;
  93683. }
  93684. else {
  93685. uval += end - cbits;
  93686. cbits += end;
  93687. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93688. /* didn't find stop bit yet, have to keep going... */
  93689. }
  93690. }
  93691. /* flush registers and read; bitreader_read_from_client_() does
  93692. * not touch br->consumed_bits at all but we still need to set
  93693. * it in case it fails and we have to return false.
  93694. */
  93695. br->consumed_bits = cbits;
  93696. br->consumed_words = cwords;
  93697. if(!bitreader_read_from_client_(br))
  93698. return false;
  93699. cwords = br->consumed_words;
  93700. }
  93701. break1:
  93702. /* read binary part */
  93703. FLAC__ASSERT(cwords <= br->words);
  93704. if(bits) {
  93705. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93706. /* flush registers and read; bitreader_read_from_client_() does
  93707. * not touch br->consumed_bits at all but we still need to set
  93708. * it in case it fails and we have to return false.
  93709. */
  93710. br->consumed_bits = cbits;
  93711. br->consumed_words = cwords;
  93712. if(!bitreader_read_from_client_(br))
  93713. return false;
  93714. cwords = br->consumed_words;
  93715. }
  93716. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93717. if(cbits) {
  93718. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93719. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93720. const brword word = br->buffer[cwords];
  93721. if(bits < n) {
  93722. uval <<= bits;
  93723. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93724. cbits += bits;
  93725. goto break2;
  93726. }
  93727. uval <<= n;
  93728. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93729. bits -= n;
  93730. crc16_update_word_(br, word);
  93731. cwords++;
  93732. cbits = 0;
  93733. 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 */
  93734. uval <<= bits;
  93735. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93736. cbits = bits;
  93737. }
  93738. goto break2;
  93739. }
  93740. else {
  93741. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93742. uval <<= bits;
  93743. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93744. cbits = bits;
  93745. goto break2;
  93746. }
  93747. }
  93748. else {
  93749. /* in this case we're starting our read at a partial tail word;
  93750. * the reader has guaranteed that we have at least 'bits' bits
  93751. * available to read, which makes this case simpler.
  93752. */
  93753. uval <<= bits;
  93754. if(cbits) {
  93755. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93756. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93757. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93758. cbits += bits;
  93759. goto break2;
  93760. }
  93761. else {
  93762. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93763. cbits += bits;
  93764. goto break2;
  93765. }
  93766. }
  93767. }
  93768. break2:
  93769. /* compose the value */
  93770. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93771. /* are we done? */
  93772. --nvals;
  93773. if(nvals == 0) {
  93774. br->consumed_bits = cbits;
  93775. br->consumed_words = cwords;
  93776. return true;
  93777. }
  93778. uval = 0;
  93779. ++vals;
  93780. }
  93781. }
  93782. #else
  93783. {
  93784. unsigned i;
  93785. unsigned uval = 0;
  93786. /* try and get br->consumed_words and br->consumed_bits into register;
  93787. * must remember to flush them back to *br before calling other
  93788. * bitwriter functions that use them, and before returning */
  93789. register unsigned cwords;
  93790. register unsigned cbits;
  93791. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93792. FLAC__ASSERT(0 != br);
  93793. FLAC__ASSERT(0 != br->buffer);
  93794. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93795. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93796. FLAC__ASSERT(parameter < 32);
  93797. /* 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 */
  93798. if(nvals == 0)
  93799. return true;
  93800. cbits = br->consumed_bits;
  93801. cwords = br->consumed_words;
  93802. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93803. while(1) {
  93804. /* read unary part */
  93805. while(1) {
  93806. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93807. brword b = br->buffer[cwords] << cbits;
  93808. if(b) {
  93809. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93810. asm volatile (
  93811. "bsrl %1, %0;"
  93812. "notl %0;"
  93813. "andl $31, %0;"
  93814. : "=r"(i)
  93815. : "r"(b)
  93816. );
  93817. #else
  93818. i = COUNT_ZERO_MSBS(b);
  93819. #endif
  93820. uval += i;
  93821. cbits += i;
  93822. cbits++; /* skip over stop bit */
  93823. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93824. crc16_update_word_(br, br->buffer[cwords]);
  93825. cwords++;
  93826. cbits = 0;
  93827. }
  93828. goto break1;
  93829. }
  93830. else {
  93831. uval += FLAC__BITS_PER_WORD - cbits;
  93832. crc16_update_word_(br, br->buffer[cwords]);
  93833. cwords++;
  93834. cbits = 0;
  93835. /* didn't find stop bit yet, have to keep going... */
  93836. }
  93837. }
  93838. /* at this point we've eaten up all the whole words; have to try
  93839. * reading through any tail bytes before calling the read callback.
  93840. * this is a repeat of the above logic adjusted for the fact we
  93841. * don't have a whole word. note though if the client is feeding
  93842. * us data a byte at a time (unlikely), br->consumed_bits may not
  93843. * be zero.
  93844. */
  93845. if(br->bytes) {
  93846. const unsigned end = br->bytes * 8;
  93847. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93848. if(b) {
  93849. i = COUNT_ZERO_MSBS(b);
  93850. uval += i;
  93851. cbits += i;
  93852. cbits++; /* skip over stop bit */
  93853. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93854. goto break1;
  93855. }
  93856. else {
  93857. uval += end - cbits;
  93858. cbits += end;
  93859. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93860. /* didn't find stop bit yet, have to keep going... */
  93861. }
  93862. }
  93863. /* flush registers and read; bitreader_read_from_client_() does
  93864. * not touch br->consumed_bits at all but we still need to set
  93865. * it in case it fails and we have to return false.
  93866. */
  93867. br->consumed_bits = cbits;
  93868. br->consumed_words = cwords;
  93869. if(!bitreader_read_from_client_(br))
  93870. return false;
  93871. cwords = br->consumed_words;
  93872. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93873. /* + uval to offset our count by the # of unary bits already
  93874. * consumed before the read, because we will add these back
  93875. * in all at once at break1
  93876. */
  93877. }
  93878. break1:
  93879. ucbits -= uval;
  93880. ucbits--; /* account for stop bit */
  93881. /* read binary part */
  93882. FLAC__ASSERT(cwords <= br->words);
  93883. if(parameter) {
  93884. while(ucbits < parameter) {
  93885. /* flush registers and read; bitreader_read_from_client_() does
  93886. * not touch br->consumed_bits at all but we still need to set
  93887. * it in case it fails and we have to return false.
  93888. */
  93889. br->consumed_bits = cbits;
  93890. br->consumed_words = cwords;
  93891. if(!bitreader_read_from_client_(br))
  93892. return false;
  93893. cwords = br->consumed_words;
  93894. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93895. }
  93896. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93897. if(cbits) {
  93898. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93899. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93900. const brword word = br->buffer[cwords];
  93901. if(parameter < n) {
  93902. uval <<= parameter;
  93903. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93904. cbits += parameter;
  93905. }
  93906. else {
  93907. uval <<= n;
  93908. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93909. crc16_update_word_(br, word);
  93910. cwords++;
  93911. cbits = parameter - n;
  93912. 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 */
  93913. uval <<= cbits;
  93914. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93915. }
  93916. }
  93917. }
  93918. else {
  93919. cbits = parameter;
  93920. uval <<= parameter;
  93921. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93922. }
  93923. }
  93924. else {
  93925. /* in this case we're starting our read at a partial tail word;
  93926. * the reader has guaranteed that we have at least 'parameter'
  93927. * bits available to read, which makes this case simpler.
  93928. */
  93929. uval <<= parameter;
  93930. if(cbits) {
  93931. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93932. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93933. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93934. cbits += parameter;
  93935. }
  93936. else {
  93937. cbits = parameter;
  93938. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93939. }
  93940. }
  93941. }
  93942. ucbits -= parameter;
  93943. /* compose the value */
  93944. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93945. /* are we done? */
  93946. --nvals;
  93947. if(nvals == 0) {
  93948. br->consumed_bits = cbits;
  93949. br->consumed_words = cwords;
  93950. return true;
  93951. }
  93952. uval = 0;
  93953. ++vals;
  93954. }
  93955. }
  93956. #endif
  93957. #if 0 /* UNUSED */
  93958. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93959. {
  93960. FLAC__uint32 lsbs = 0, msbs = 0;
  93961. unsigned bit, uval, k;
  93962. FLAC__ASSERT(0 != br);
  93963. FLAC__ASSERT(0 != br->buffer);
  93964. k = FLAC__bitmath_ilog2(parameter);
  93965. /* read the unary MSBs and end bit */
  93966. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93967. return false;
  93968. /* read the binary LSBs */
  93969. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93970. return false;
  93971. if(parameter == 1u<<k) {
  93972. /* compose the value */
  93973. uval = (msbs << k) | lsbs;
  93974. }
  93975. else {
  93976. unsigned d = (1 << (k+1)) - parameter;
  93977. if(lsbs >= d) {
  93978. if(!FLAC__bitreader_read_bit(br, &bit))
  93979. return false;
  93980. lsbs <<= 1;
  93981. lsbs |= bit;
  93982. lsbs -= d;
  93983. }
  93984. /* compose the value */
  93985. uval = msbs * parameter + lsbs;
  93986. }
  93987. /* unfold unsigned to signed */
  93988. if(uval & 1)
  93989. *val = -((int)(uval >> 1)) - 1;
  93990. else
  93991. *val = (int)(uval >> 1);
  93992. return true;
  93993. }
  93994. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93995. {
  93996. FLAC__uint32 lsbs, msbs = 0;
  93997. unsigned bit, k;
  93998. FLAC__ASSERT(0 != br);
  93999. FLAC__ASSERT(0 != br->buffer);
  94000. k = FLAC__bitmath_ilog2(parameter);
  94001. /* read the unary MSBs and end bit */
  94002. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94003. return false;
  94004. /* read the binary LSBs */
  94005. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94006. return false;
  94007. if(parameter == 1u<<k) {
  94008. /* compose the value */
  94009. *val = (msbs << k) | lsbs;
  94010. }
  94011. else {
  94012. unsigned d = (1 << (k+1)) - parameter;
  94013. if(lsbs >= d) {
  94014. if(!FLAC__bitreader_read_bit(br, &bit))
  94015. return false;
  94016. lsbs <<= 1;
  94017. lsbs |= bit;
  94018. lsbs -= d;
  94019. }
  94020. /* compose the value */
  94021. *val = msbs * parameter + lsbs;
  94022. }
  94023. return true;
  94024. }
  94025. #endif /* UNUSED */
  94026. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94027. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94028. {
  94029. FLAC__uint32 v = 0;
  94030. FLAC__uint32 x;
  94031. unsigned i;
  94032. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94033. return false;
  94034. if(raw)
  94035. raw[(*rawlen)++] = (FLAC__byte)x;
  94036. if(!(x & 0x80)) { /* 0xxxxxxx */
  94037. v = x;
  94038. i = 0;
  94039. }
  94040. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94041. v = x & 0x1F;
  94042. i = 1;
  94043. }
  94044. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94045. v = x & 0x0F;
  94046. i = 2;
  94047. }
  94048. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94049. v = x & 0x07;
  94050. i = 3;
  94051. }
  94052. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94053. v = x & 0x03;
  94054. i = 4;
  94055. }
  94056. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94057. v = x & 0x01;
  94058. i = 5;
  94059. }
  94060. else {
  94061. *val = 0xffffffff;
  94062. return true;
  94063. }
  94064. for( ; i; i--) {
  94065. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94066. return false;
  94067. if(raw)
  94068. raw[(*rawlen)++] = (FLAC__byte)x;
  94069. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94070. *val = 0xffffffff;
  94071. return true;
  94072. }
  94073. v <<= 6;
  94074. v |= (x & 0x3F);
  94075. }
  94076. *val = v;
  94077. return true;
  94078. }
  94079. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94080. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94081. {
  94082. FLAC__uint64 v = 0;
  94083. FLAC__uint32 x;
  94084. unsigned i;
  94085. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94086. return false;
  94087. if(raw)
  94088. raw[(*rawlen)++] = (FLAC__byte)x;
  94089. if(!(x & 0x80)) { /* 0xxxxxxx */
  94090. v = x;
  94091. i = 0;
  94092. }
  94093. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94094. v = x & 0x1F;
  94095. i = 1;
  94096. }
  94097. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94098. v = x & 0x0F;
  94099. i = 2;
  94100. }
  94101. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94102. v = x & 0x07;
  94103. i = 3;
  94104. }
  94105. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94106. v = x & 0x03;
  94107. i = 4;
  94108. }
  94109. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94110. v = x & 0x01;
  94111. i = 5;
  94112. }
  94113. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94114. v = 0;
  94115. i = 6;
  94116. }
  94117. else {
  94118. *val = FLAC__U64L(0xffffffffffffffff);
  94119. return true;
  94120. }
  94121. for( ; i; i--) {
  94122. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94123. return false;
  94124. if(raw)
  94125. raw[(*rawlen)++] = (FLAC__byte)x;
  94126. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94127. *val = FLAC__U64L(0xffffffffffffffff);
  94128. return true;
  94129. }
  94130. v <<= 6;
  94131. v |= (x & 0x3F);
  94132. }
  94133. *val = v;
  94134. return true;
  94135. }
  94136. #endif
  94137. /*** End of inlined file: bitreader.c ***/
  94138. /*** Start of inlined file: bitwriter.c ***/
  94139. /*** Start of inlined file: juce_FlacHeader.h ***/
  94140. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94141. // tasks..
  94142. #define VERSION "1.2.1"
  94143. #define FLAC__NO_DLL 1
  94144. #if JUCE_MSVC
  94145. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94146. #endif
  94147. #if JUCE_MAC
  94148. #define FLAC__SYS_DARWIN 1
  94149. #endif
  94150. /*** End of inlined file: juce_FlacHeader.h ***/
  94151. #if JUCE_USE_FLAC
  94152. #if HAVE_CONFIG_H
  94153. # include <config.h>
  94154. #endif
  94155. #include <stdlib.h> /* for malloc() */
  94156. #include <string.h> /* for memcpy(), memset() */
  94157. #ifdef _MSC_VER
  94158. #include <winsock.h> /* for ntohl() */
  94159. #elif defined FLAC__SYS_DARWIN
  94160. #include <machine/endian.h> /* for ntohl() */
  94161. #elif defined __MINGW32__
  94162. #include <winsock.h> /* for ntohl() */
  94163. #else
  94164. #include <netinet/in.h> /* for ntohl() */
  94165. #endif
  94166. #if 0 /* UNUSED */
  94167. #endif
  94168. /*** Start of inlined file: bitwriter.h ***/
  94169. #ifndef FLAC__PRIVATE__BITWRITER_H
  94170. #define FLAC__PRIVATE__BITWRITER_H
  94171. #include <stdio.h> /* for FILE */
  94172. /*
  94173. * opaque structure definition
  94174. */
  94175. struct FLAC__BitWriter;
  94176. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94177. /*
  94178. * construction, deletion, initialization, etc functions
  94179. */
  94180. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94181. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94182. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94183. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94184. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94185. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94186. /*
  94187. * CRC functions
  94188. *
  94189. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94190. */
  94191. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94192. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94193. /*
  94194. * info functions
  94195. */
  94196. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94197. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94198. /*
  94199. * direct buffer access
  94200. *
  94201. * there may be no calls on the bitwriter between get and release.
  94202. * the bitwriter continues to own the returned buffer.
  94203. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94204. */
  94205. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94206. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94207. /*
  94208. * write functions
  94209. */
  94210. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94211. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94212. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94213. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94214. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94215. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94216. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94217. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94218. #if 0 /* UNUSED */
  94219. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94220. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94221. #endif
  94222. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94223. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94224. #if 0 /* UNUSED */
  94225. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94226. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94227. #endif
  94228. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94229. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94230. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94231. #endif
  94232. /*** End of inlined file: bitwriter.h ***/
  94233. /*** Start of inlined file: alloc.h ***/
  94234. #ifndef FLAC__SHARE__ALLOC_H
  94235. #define FLAC__SHARE__ALLOC_H
  94236. #if HAVE_CONFIG_H
  94237. # include <config.h>
  94238. #endif
  94239. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94240. * before #including this file, otherwise SIZE_MAX might not be defined
  94241. */
  94242. #include <limits.h> /* for SIZE_MAX */
  94243. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94244. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94245. #endif
  94246. #include <stdlib.h> /* for size_t, malloc(), etc */
  94247. #ifndef SIZE_MAX
  94248. # ifndef SIZE_T_MAX
  94249. # ifdef _MSC_VER
  94250. # define SIZE_T_MAX UINT_MAX
  94251. # else
  94252. # error
  94253. # endif
  94254. # endif
  94255. # define SIZE_MAX SIZE_T_MAX
  94256. #endif
  94257. #ifndef FLaC__INLINE
  94258. #define FLaC__INLINE
  94259. #endif
  94260. /* avoid malloc()ing 0 bytes, see:
  94261. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94262. */
  94263. static FLaC__INLINE void *safe_malloc_(size_t size)
  94264. {
  94265. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94266. if(!size)
  94267. size++;
  94268. return malloc(size);
  94269. }
  94270. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94271. {
  94272. if(!nmemb || !size)
  94273. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94274. return calloc(nmemb, size);
  94275. }
  94276. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94277. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94278. {
  94279. size2 += size1;
  94280. if(size2 < size1)
  94281. return 0;
  94282. return safe_malloc_(size2);
  94283. }
  94284. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94285. {
  94286. size2 += size1;
  94287. if(size2 < size1)
  94288. return 0;
  94289. size3 += size2;
  94290. if(size3 < size2)
  94291. return 0;
  94292. return safe_malloc_(size3);
  94293. }
  94294. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94295. {
  94296. size2 += size1;
  94297. if(size2 < size1)
  94298. return 0;
  94299. size3 += size2;
  94300. if(size3 < size2)
  94301. return 0;
  94302. size4 += size3;
  94303. if(size4 < size3)
  94304. return 0;
  94305. return safe_malloc_(size4);
  94306. }
  94307. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94308. #if 0
  94309. needs support for cases where sizeof(size_t) != 4
  94310. {
  94311. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94312. if(sizeof(size_t) == 4) {
  94313. if ((double)size1 * (double)size2 < 4294967296.0)
  94314. return malloc(size1*size2);
  94315. }
  94316. return 0;
  94317. }
  94318. #else
  94319. /* better? */
  94320. {
  94321. if(!size1 || !size2)
  94322. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94323. if(size1 > SIZE_MAX / size2)
  94324. return 0;
  94325. return malloc(size1*size2);
  94326. }
  94327. #endif
  94328. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94329. {
  94330. if(!size1 || !size2 || !size3)
  94331. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94332. if(size1 > SIZE_MAX / size2)
  94333. return 0;
  94334. size1 *= size2;
  94335. if(size1 > SIZE_MAX / size3)
  94336. return 0;
  94337. return malloc(size1*size3);
  94338. }
  94339. /* size1*size2 + size3 */
  94340. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94341. {
  94342. if(!size1 || !size2)
  94343. return safe_malloc_(size3);
  94344. if(size1 > SIZE_MAX / size2)
  94345. return 0;
  94346. return safe_malloc_add_2op_(size1*size2, size3);
  94347. }
  94348. /* size1 * (size2 + size3) */
  94349. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94350. {
  94351. if(!size1 || (!size2 && !size3))
  94352. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94353. size2 += size3;
  94354. if(size2 < size3)
  94355. return 0;
  94356. return safe_malloc_mul_2op_(size1, size2);
  94357. }
  94358. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94359. {
  94360. size2 += size1;
  94361. if(size2 < size1)
  94362. return 0;
  94363. return realloc(ptr, size2);
  94364. }
  94365. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94366. {
  94367. size2 += size1;
  94368. if(size2 < size1)
  94369. return 0;
  94370. size3 += size2;
  94371. if(size3 < size2)
  94372. return 0;
  94373. return realloc(ptr, size3);
  94374. }
  94375. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94376. {
  94377. size2 += size1;
  94378. if(size2 < size1)
  94379. return 0;
  94380. size3 += size2;
  94381. if(size3 < size2)
  94382. return 0;
  94383. size4 += size3;
  94384. if(size4 < size3)
  94385. return 0;
  94386. return realloc(ptr, size4);
  94387. }
  94388. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94389. {
  94390. if(!size1 || !size2)
  94391. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94392. if(size1 > SIZE_MAX / size2)
  94393. return 0;
  94394. return realloc(ptr, size1*size2);
  94395. }
  94396. /* size1 * (size2 + size3) */
  94397. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94398. {
  94399. if(!size1 || (!size2 && !size3))
  94400. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94401. size2 += size3;
  94402. if(size2 < size3)
  94403. return 0;
  94404. return safe_realloc_mul_2op_(ptr, size1, size2);
  94405. }
  94406. #endif
  94407. /*** End of inlined file: alloc.h ***/
  94408. /* Things should be fastest when this matches the machine word size */
  94409. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94410. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94411. typedef FLAC__uint32 bwword;
  94412. #define FLAC__BYTES_PER_WORD 4
  94413. #define FLAC__BITS_PER_WORD 32
  94414. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94415. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94416. #if WORDS_BIGENDIAN
  94417. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94418. #else
  94419. #ifdef _MSC_VER
  94420. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94421. #else
  94422. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94423. #endif
  94424. #endif
  94425. /*
  94426. * The default capacity here doesn't matter too much. The buffer always grows
  94427. * to hold whatever is written to it. Usually the encoder will stop adding at
  94428. * a frame or metadata block, then write that out and clear the buffer for the
  94429. * next one.
  94430. */
  94431. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94432. /* When growing, increment 4K at a time */
  94433. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94434. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94435. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94436. #ifdef min
  94437. #undef min
  94438. #endif
  94439. #define min(x,y) ((x)<(y)?(x):(y))
  94440. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94441. #ifdef _MSC_VER
  94442. #define FLAC__U64L(x) x
  94443. #else
  94444. #define FLAC__U64L(x) x##LLU
  94445. #endif
  94446. #ifndef FLaC__INLINE
  94447. #define FLaC__INLINE
  94448. #endif
  94449. struct FLAC__BitWriter {
  94450. bwword *buffer;
  94451. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94452. unsigned capacity; /* capacity of buffer in words */
  94453. unsigned words; /* # of complete words in buffer */
  94454. unsigned bits; /* # of used bits in accum */
  94455. };
  94456. /* * WATCHOUT: The current implementation only grows the buffer. */
  94457. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94458. {
  94459. unsigned new_capacity;
  94460. bwword *new_buffer;
  94461. FLAC__ASSERT(0 != bw);
  94462. FLAC__ASSERT(0 != bw->buffer);
  94463. /* calculate total words needed to store 'bits_to_add' additional bits */
  94464. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94465. /* it's possible (due to pessimism in the growth estimation that
  94466. * leads to this call) that we don't actually need to grow
  94467. */
  94468. if(bw->capacity >= new_capacity)
  94469. return true;
  94470. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94471. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94472. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94473. /* make sure we got everything right */
  94474. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94475. FLAC__ASSERT(new_capacity > bw->capacity);
  94476. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94477. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94478. if(new_buffer == 0)
  94479. return false;
  94480. bw->buffer = new_buffer;
  94481. bw->capacity = new_capacity;
  94482. return true;
  94483. }
  94484. /***********************************************************************
  94485. *
  94486. * Class constructor/destructor
  94487. *
  94488. ***********************************************************************/
  94489. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94490. {
  94491. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94492. /* note that calloc() sets all members to 0 for us */
  94493. return bw;
  94494. }
  94495. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94496. {
  94497. FLAC__ASSERT(0 != bw);
  94498. FLAC__bitwriter_free(bw);
  94499. free(bw);
  94500. }
  94501. /***********************************************************************
  94502. *
  94503. * Public class methods
  94504. *
  94505. ***********************************************************************/
  94506. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94507. {
  94508. FLAC__ASSERT(0 != bw);
  94509. bw->words = bw->bits = 0;
  94510. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94511. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94512. if(bw->buffer == 0)
  94513. return false;
  94514. return true;
  94515. }
  94516. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94517. {
  94518. FLAC__ASSERT(0 != bw);
  94519. if(0 != bw->buffer)
  94520. free(bw->buffer);
  94521. bw->buffer = 0;
  94522. bw->capacity = 0;
  94523. bw->words = bw->bits = 0;
  94524. }
  94525. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94526. {
  94527. bw->words = bw->bits = 0;
  94528. }
  94529. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94530. {
  94531. unsigned i, j;
  94532. if(bw == 0) {
  94533. fprintf(out, "bitwriter is NULL\n");
  94534. }
  94535. else {
  94536. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94537. for(i = 0; i < bw->words; i++) {
  94538. fprintf(out, "%08X: ", i);
  94539. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94540. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94541. fprintf(out, "\n");
  94542. }
  94543. if(bw->bits > 0) {
  94544. fprintf(out, "%08X: ", i);
  94545. for(j = 0; j < bw->bits; j++)
  94546. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94547. fprintf(out, "\n");
  94548. }
  94549. }
  94550. }
  94551. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94552. {
  94553. const FLAC__byte *buffer;
  94554. size_t bytes;
  94555. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94556. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94557. return false;
  94558. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94559. FLAC__bitwriter_release_buffer(bw);
  94560. return true;
  94561. }
  94562. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94563. {
  94564. const FLAC__byte *buffer;
  94565. size_t bytes;
  94566. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94567. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94568. return false;
  94569. *crc = FLAC__crc8(buffer, bytes);
  94570. FLAC__bitwriter_release_buffer(bw);
  94571. return true;
  94572. }
  94573. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94574. {
  94575. return ((bw->bits & 7) == 0);
  94576. }
  94577. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94578. {
  94579. return FLAC__TOTAL_BITS(bw);
  94580. }
  94581. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94582. {
  94583. FLAC__ASSERT((bw->bits & 7) == 0);
  94584. /* double protection */
  94585. if(bw->bits & 7)
  94586. return false;
  94587. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94588. if(bw->bits) {
  94589. FLAC__ASSERT(bw->words <= bw->capacity);
  94590. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94591. return false;
  94592. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94593. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94594. }
  94595. /* now we can just return what we have */
  94596. *buffer = (FLAC__byte*)bw->buffer;
  94597. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94598. return true;
  94599. }
  94600. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94601. {
  94602. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94603. * get-mode' flag could be added everywhere and then cleared here
  94604. */
  94605. (void)bw;
  94606. }
  94607. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94608. {
  94609. unsigned n;
  94610. FLAC__ASSERT(0 != bw);
  94611. FLAC__ASSERT(0 != bw->buffer);
  94612. if(bits == 0)
  94613. return true;
  94614. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94615. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94616. return false;
  94617. /* first part gets to word alignment */
  94618. if(bw->bits) {
  94619. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94620. bw->accum <<= n;
  94621. bits -= n;
  94622. bw->bits += n;
  94623. if(bw->bits == FLAC__BITS_PER_WORD) {
  94624. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94625. bw->bits = 0;
  94626. }
  94627. else
  94628. return true;
  94629. }
  94630. /* do whole words */
  94631. while(bits >= FLAC__BITS_PER_WORD) {
  94632. bw->buffer[bw->words++] = 0;
  94633. bits -= FLAC__BITS_PER_WORD;
  94634. }
  94635. /* do any leftovers */
  94636. if(bits > 0) {
  94637. bw->accum = 0;
  94638. bw->bits = bits;
  94639. }
  94640. return true;
  94641. }
  94642. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94643. {
  94644. register unsigned left;
  94645. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94646. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94647. FLAC__ASSERT(0 != bw);
  94648. FLAC__ASSERT(0 != bw->buffer);
  94649. FLAC__ASSERT(bits <= 32);
  94650. if(bits == 0)
  94651. return true;
  94652. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94653. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94654. return false;
  94655. left = FLAC__BITS_PER_WORD - bw->bits;
  94656. if(bits < left) {
  94657. bw->accum <<= bits;
  94658. bw->accum |= val;
  94659. bw->bits += bits;
  94660. }
  94661. 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 */
  94662. bw->accum <<= left;
  94663. bw->accum |= val >> (bw->bits = bits - left);
  94664. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94665. bw->accum = val;
  94666. }
  94667. else {
  94668. bw->accum = val;
  94669. bw->bits = 0;
  94670. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94671. }
  94672. return true;
  94673. }
  94674. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94675. {
  94676. /* zero-out unused bits */
  94677. if(bits < 32)
  94678. val &= (~(0xffffffff << bits));
  94679. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94680. }
  94681. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94682. {
  94683. /* this could be a little faster but it's not used for much */
  94684. if(bits > 32) {
  94685. return
  94686. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94687. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94688. }
  94689. else
  94690. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94691. }
  94692. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94693. {
  94694. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94695. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94696. return false;
  94697. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94698. return false;
  94699. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94700. return false;
  94701. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94702. return false;
  94703. return true;
  94704. }
  94705. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94706. {
  94707. unsigned i;
  94708. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94709. for(i = 0; i < nvals; i++) {
  94710. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94711. return false;
  94712. }
  94713. return true;
  94714. }
  94715. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94716. {
  94717. if(val < 32)
  94718. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94719. else
  94720. return
  94721. FLAC__bitwriter_write_zeroes(bw, val) &&
  94722. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94723. }
  94724. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94725. {
  94726. FLAC__uint32 uval;
  94727. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94728. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94729. uval = (val<<1) ^ (val>>31);
  94730. return 1 + parameter + (uval >> parameter);
  94731. }
  94732. #if 0 /* UNUSED */
  94733. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94734. {
  94735. unsigned bits, msbs, uval;
  94736. unsigned k;
  94737. FLAC__ASSERT(parameter > 0);
  94738. /* fold signed to unsigned */
  94739. if(val < 0)
  94740. uval = (unsigned)(((-(++val)) << 1) + 1);
  94741. else
  94742. uval = (unsigned)(val << 1);
  94743. k = FLAC__bitmath_ilog2(parameter);
  94744. if(parameter == 1u<<k) {
  94745. FLAC__ASSERT(k <= 30);
  94746. msbs = uval >> k;
  94747. bits = 1 + k + msbs;
  94748. }
  94749. else {
  94750. unsigned q, r, d;
  94751. d = (1 << (k+1)) - parameter;
  94752. q = uval / parameter;
  94753. r = uval - (q * parameter);
  94754. bits = 1 + q + k;
  94755. if(r >= d)
  94756. bits++;
  94757. }
  94758. return bits;
  94759. }
  94760. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94761. {
  94762. unsigned bits, msbs;
  94763. unsigned k;
  94764. FLAC__ASSERT(parameter > 0);
  94765. k = FLAC__bitmath_ilog2(parameter);
  94766. if(parameter == 1u<<k) {
  94767. FLAC__ASSERT(k <= 30);
  94768. msbs = uval >> k;
  94769. bits = 1 + k + msbs;
  94770. }
  94771. else {
  94772. unsigned q, r, d;
  94773. d = (1 << (k+1)) - parameter;
  94774. q = uval / parameter;
  94775. r = uval - (q * parameter);
  94776. bits = 1 + q + k;
  94777. if(r >= d)
  94778. bits++;
  94779. }
  94780. return bits;
  94781. }
  94782. #endif /* UNUSED */
  94783. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94784. {
  94785. unsigned total_bits, interesting_bits, msbs;
  94786. FLAC__uint32 uval, pattern;
  94787. FLAC__ASSERT(0 != bw);
  94788. FLAC__ASSERT(0 != bw->buffer);
  94789. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94790. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94791. uval = (val<<1) ^ (val>>31);
  94792. msbs = uval >> parameter;
  94793. interesting_bits = 1 + parameter;
  94794. total_bits = interesting_bits + msbs;
  94795. pattern = 1 << parameter; /* the unary end bit */
  94796. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94797. if(total_bits <= 32)
  94798. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94799. else
  94800. return
  94801. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94802. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94803. }
  94804. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94805. {
  94806. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94807. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94808. FLAC__uint32 uval;
  94809. unsigned left;
  94810. const unsigned lsbits = 1 + parameter;
  94811. unsigned msbits;
  94812. FLAC__ASSERT(0 != bw);
  94813. FLAC__ASSERT(0 != bw->buffer);
  94814. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94815. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94816. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94817. while(nvals) {
  94818. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94819. uval = (*vals<<1) ^ (*vals>>31);
  94820. msbits = uval >> parameter;
  94821. #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) */
  94822. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94823. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94824. bw->bits = bw->bits + msbits + lsbits;
  94825. uval |= mask1; /* set stop bit */
  94826. uval &= mask2; /* mask off unused top bits */
  94827. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94828. bw->accum <<= msbits;
  94829. bw->accum <<= lsbits;
  94830. bw->accum |= uval;
  94831. if(bw->bits == FLAC__BITS_PER_WORD) {
  94832. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94833. bw->bits = 0;
  94834. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94835. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94836. FLAC__ASSERT(bw->capacity == bw->words);
  94837. return false;
  94838. }
  94839. }
  94840. }
  94841. else {
  94842. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94843. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94844. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94845. bw->bits = bw->bits + msbits + lsbits;
  94846. uval |= mask1; /* set stop bit */
  94847. uval &= mask2; /* mask off unused top bits */
  94848. bw->accum <<= msbits + lsbits;
  94849. bw->accum |= uval;
  94850. }
  94851. else {
  94852. #endif
  94853. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94854. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94855. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94856. return false;
  94857. if(msbits) {
  94858. /* first part gets to word alignment */
  94859. if(bw->bits) {
  94860. left = FLAC__BITS_PER_WORD - bw->bits;
  94861. if(msbits < left) {
  94862. bw->accum <<= msbits;
  94863. bw->bits += msbits;
  94864. goto break1;
  94865. }
  94866. else {
  94867. bw->accum <<= left;
  94868. msbits -= left;
  94869. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94870. bw->bits = 0;
  94871. }
  94872. }
  94873. /* do whole words */
  94874. while(msbits >= FLAC__BITS_PER_WORD) {
  94875. bw->buffer[bw->words++] = 0;
  94876. msbits -= FLAC__BITS_PER_WORD;
  94877. }
  94878. /* do any leftovers */
  94879. if(msbits > 0) {
  94880. bw->accum = 0;
  94881. bw->bits = msbits;
  94882. }
  94883. }
  94884. break1:
  94885. uval |= mask1; /* set stop bit */
  94886. uval &= mask2; /* mask off unused top bits */
  94887. left = FLAC__BITS_PER_WORD - bw->bits;
  94888. if(lsbits < left) {
  94889. bw->accum <<= lsbits;
  94890. bw->accum |= uval;
  94891. bw->bits += lsbits;
  94892. }
  94893. else {
  94894. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94895. * be > lsbits (because of previous assertions) so it would have
  94896. * triggered the (lsbits<left) case above.
  94897. */
  94898. FLAC__ASSERT(bw->bits);
  94899. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94900. bw->accum <<= left;
  94901. bw->accum |= uval >> (bw->bits = lsbits - left);
  94902. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94903. bw->accum = uval;
  94904. }
  94905. #if 1
  94906. }
  94907. #endif
  94908. vals++;
  94909. nvals--;
  94910. }
  94911. return true;
  94912. }
  94913. #if 0 /* UNUSED */
  94914. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94915. {
  94916. unsigned total_bits, msbs, uval;
  94917. unsigned k;
  94918. FLAC__ASSERT(0 != bw);
  94919. FLAC__ASSERT(0 != bw->buffer);
  94920. FLAC__ASSERT(parameter > 0);
  94921. /* fold signed to unsigned */
  94922. if(val < 0)
  94923. uval = (unsigned)(((-(++val)) << 1) + 1);
  94924. else
  94925. uval = (unsigned)(val << 1);
  94926. k = FLAC__bitmath_ilog2(parameter);
  94927. if(parameter == 1u<<k) {
  94928. unsigned pattern;
  94929. FLAC__ASSERT(k <= 30);
  94930. msbs = uval >> k;
  94931. total_bits = 1 + k + msbs;
  94932. pattern = 1 << k; /* the unary end bit */
  94933. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94934. if(total_bits <= 32) {
  94935. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94936. return false;
  94937. }
  94938. else {
  94939. /* write the unary MSBs */
  94940. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94941. return false;
  94942. /* write the unary end bit and binary LSBs */
  94943. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94944. return false;
  94945. }
  94946. }
  94947. else {
  94948. unsigned q, r, d;
  94949. d = (1 << (k+1)) - parameter;
  94950. q = uval / parameter;
  94951. r = uval - (q * parameter);
  94952. /* write the unary MSBs */
  94953. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94954. return false;
  94955. /* write the unary end bit */
  94956. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94957. return false;
  94958. /* write the binary LSBs */
  94959. if(r >= d) {
  94960. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94961. return false;
  94962. }
  94963. else {
  94964. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94965. return false;
  94966. }
  94967. }
  94968. return true;
  94969. }
  94970. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94971. {
  94972. unsigned total_bits, msbs;
  94973. unsigned k;
  94974. FLAC__ASSERT(0 != bw);
  94975. FLAC__ASSERT(0 != bw->buffer);
  94976. FLAC__ASSERT(parameter > 0);
  94977. k = FLAC__bitmath_ilog2(parameter);
  94978. if(parameter == 1u<<k) {
  94979. unsigned pattern;
  94980. FLAC__ASSERT(k <= 30);
  94981. msbs = uval >> k;
  94982. total_bits = 1 + k + msbs;
  94983. pattern = 1 << k; /* the unary end bit */
  94984. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94985. if(total_bits <= 32) {
  94986. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94987. return false;
  94988. }
  94989. else {
  94990. /* write the unary MSBs */
  94991. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94992. return false;
  94993. /* write the unary end bit and binary LSBs */
  94994. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94995. return false;
  94996. }
  94997. }
  94998. else {
  94999. unsigned q, r, d;
  95000. d = (1 << (k+1)) - parameter;
  95001. q = uval / parameter;
  95002. r = uval - (q * parameter);
  95003. /* write the unary MSBs */
  95004. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95005. return false;
  95006. /* write the unary end bit */
  95007. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95008. return false;
  95009. /* write the binary LSBs */
  95010. if(r >= d) {
  95011. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95012. return false;
  95013. }
  95014. else {
  95015. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95016. return false;
  95017. }
  95018. }
  95019. return true;
  95020. }
  95021. #endif /* UNUSED */
  95022. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95023. {
  95024. FLAC__bool ok = 1;
  95025. FLAC__ASSERT(0 != bw);
  95026. FLAC__ASSERT(0 != bw->buffer);
  95027. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95028. if(val < 0x80) {
  95029. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95030. }
  95031. else if(val < 0x800) {
  95032. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95033. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95034. }
  95035. else if(val < 0x10000) {
  95036. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95037. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95038. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95039. }
  95040. else if(val < 0x200000) {
  95041. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95042. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95043. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95044. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95045. }
  95046. else if(val < 0x4000000) {
  95047. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95048. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95049. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95050. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95051. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95052. }
  95053. else {
  95054. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95055. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95056. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95057. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95058. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95059. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95060. }
  95061. return ok;
  95062. }
  95063. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95064. {
  95065. FLAC__bool ok = 1;
  95066. FLAC__ASSERT(0 != bw);
  95067. FLAC__ASSERT(0 != bw->buffer);
  95068. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95069. if(val < 0x80) {
  95070. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95071. }
  95072. else if(val < 0x800) {
  95073. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95074. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95075. }
  95076. else if(val < 0x10000) {
  95077. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95078. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95079. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95080. }
  95081. else if(val < 0x200000) {
  95082. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95083. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95084. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95085. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95086. }
  95087. else if(val < 0x4000000) {
  95088. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95089. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95090. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95091. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95092. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95093. }
  95094. else if(val < 0x80000000) {
  95095. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95096. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95097. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95098. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95099. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95100. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95101. }
  95102. else {
  95103. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95104. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95105. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95106. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95107. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95108. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95109. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95110. }
  95111. return ok;
  95112. }
  95113. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95114. {
  95115. /* 0-pad to byte boundary */
  95116. if(bw->bits & 7u)
  95117. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95118. else
  95119. return true;
  95120. }
  95121. #endif
  95122. /*** End of inlined file: bitwriter.c ***/
  95123. /*** Start of inlined file: cpu.c ***/
  95124. /*** Start of inlined file: juce_FlacHeader.h ***/
  95125. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95126. // tasks..
  95127. #define VERSION "1.2.1"
  95128. #define FLAC__NO_DLL 1
  95129. #if JUCE_MSVC
  95130. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95131. #endif
  95132. #if JUCE_MAC
  95133. #define FLAC__SYS_DARWIN 1
  95134. #endif
  95135. /*** End of inlined file: juce_FlacHeader.h ***/
  95136. #if JUCE_USE_FLAC
  95137. #if HAVE_CONFIG_H
  95138. # include <config.h>
  95139. #endif
  95140. #include <stdlib.h>
  95141. #include <stdio.h>
  95142. #if defined FLAC__CPU_IA32
  95143. # include <signal.h>
  95144. #elif defined FLAC__CPU_PPC
  95145. # if !defined FLAC__NO_ASM
  95146. # if defined FLAC__SYS_DARWIN
  95147. # include <sys/sysctl.h>
  95148. # include <mach/mach.h>
  95149. # include <mach/mach_host.h>
  95150. # include <mach/host_info.h>
  95151. # include <mach/machine.h>
  95152. # ifndef CPU_SUBTYPE_POWERPC_970
  95153. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95154. # endif
  95155. # else /* FLAC__SYS_DARWIN */
  95156. # include <signal.h>
  95157. # include <setjmp.h>
  95158. static sigjmp_buf jmpbuf;
  95159. static volatile sig_atomic_t canjump = 0;
  95160. static void sigill_handler (int sig)
  95161. {
  95162. if (!canjump) {
  95163. signal (sig, SIG_DFL);
  95164. raise (sig);
  95165. }
  95166. canjump = 0;
  95167. siglongjmp (jmpbuf, 1);
  95168. }
  95169. # endif /* FLAC__SYS_DARWIN */
  95170. # endif /* FLAC__NO_ASM */
  95171. #endif /* FLAC__CPU_PPC */
  95172. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95173. #include <sys/param.h>
  95174. #include <sys/sysctl.h>
  95175. #include <machine/cpu.h>
  95176. #endif
  95177. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95178. #include <sys/types.h>
  95179. #include <sys/sysctl.h>
  95180. #endif
  95181. #if defined(__APPLE__)
  95182. /* how to get sysctlbyname()? */
  95183. #endif
  95184. /* these are flags in EDX of CPUID AX=00000001 */
  95185. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95186. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95187. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95188. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95189. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95190. /* these are flags in ECX of CPUID AX=00000001 */
  95191. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95192. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95193. /* these are flags in EDX of CPUID AX=80000001 */
  95194. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95195. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95196. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95197. /*
  95198. * Extra stuff needed for detection of OS support for SSE on IA-32
  95199. */
  95200. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95201. # if defined(__linux__)
  95202. /*
  95203. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95204. * modify the return address to jump over the offending SSE instruction
  95205. * and also the operation following it that indicates the instruction
  95206. * executed successfully. In this way we use no global variables and
  95207. * stay thread-safe.
  95208. *
  95209. * 3 + 3 + 6:
  95210. * 3 bytes for "xorps xmm0,xmm0"
  95211. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95212. * 6 bytes extra in case our estimate is wrong
  95213. * 12 bytes puts us in the NOP "landing zone"
  95214. */
  95215. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95216. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95217. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95218. {
  95219. (void)signal;
  95220. sc.eip += 3 + 3 + 6;
  95221. }
  95222. # else
  95223. # include <sys/ucontext.h>
  95224. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95225. {
  95226. (void)signal, (void)si;
  95227. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95228. }
  95229. # endif
  95230. # elif defined(_MSC_VER)
  95231. # include <windows.h>
  95232. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95233. # ifdef USE_TRY_CATCH_FLAVOR
  95234. # else
  95235. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95236. {
  95237. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95238. ep->ContextRecord->Eip += 3 + 3 + 6;
  95239. return EXCEPTION_CONTINUE_EXECUTION;
  95240. }
  95241. return EXCEPTION_CONTINUE_SEARCH;
  95242. }
  95243. # endif
  95244. # endif
  95245. #endif
  95246. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95247. {
  95248. /*
  95249. * IA32-specific
  95250. */
  95251. #ifdef FLAC__CPU_IA32
  95252. info->type = FLAC__CPUINFO_TYPE_IA32;
  95253. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95254. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95255. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95256. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95257. info->data.ia32.cmov = false;
  95258. info->data.ia32.mmx = false;
  95259. info->data.ia32.fxsr = false;
  95260. info->data.ia32.sse = false;
  95261. info->data.ia32.sse2 = false;
  95262. info->data.ia32.sse3 = false;
  95263. info->data.ia32.ssse3 = false;
  95264. info->data.ia32._3dnow = false;
  95265. info->data.ia32.ext3dnow = false;
  95266. info->data.ia32.extmmx = false;
  95267. if(info->data.ia32.cpuid) {
  95268. /* http://www.sandpile.org/ia32/cpuid.htm */
  95269. FLAC__uint32 flags_edx, flags_ecx;
  95270. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95271. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95272. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95273. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95274. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95275. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95276. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95277. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95278. #ifdef FLAC__USE_3DNOW
  95279. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95280. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95281. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95282. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95283. #else
  95284. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95285. #endif
  95286. #ifdef DEBUG
  95287. fprintf(stderr, "CPU info (IA-32):\n");
  95288. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95289. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95290. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95291. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95292. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95293. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95294. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95295. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95296. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95297. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95298. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95299. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95300. #endif
  95301. /*
  95302. * now have to check for OS support of SSE/SSE2
  95303. */
  95304. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95305. #if defined FLAC__NO_SSE_OS
  95306. /* assume user knows better than us; turn it off */
  95307. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95308. #elif defined FLAC__SSE_OS
  95309. /* assume user knows better than us; leave as detected above */
  95310. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95311. int sse = 0;
  95312. size_t len;
  95313. /* at least one of these must work: */
  95314. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95315. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95316. if(!sse)
  95317. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95318. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95319. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95320. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95321. size_t len = sizeof(val);
  95322. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95323. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95324. else { /* double-check SSE2 */
  95325. mib[1] = CPU_SSE2;
  95326. len = sizeof(val);
  95327. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95328. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95329. }
  95330. # else
  95331. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95332. # endif
  95333. #elif defined(__linux__)
  95334. int sse = 0;
  95335. struct sigaction sigill_save;
  95336. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95337. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95338. #else
  95339. struct sigaction sigill_sse;
  95340. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95341. __sigemptyset(&sigill_sse.sa_mask);
  95342. 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 */
  95343. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95344. #endif
  95345. {
  95346. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95347. /* see sigill_handler_sse_os() for an explanation of the following: */
  95348. asm volatile (
  95349. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95350. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95351. "incl %0\n\t" /* SIGILL handler will jump over this */
  95352. /* landing zone */
  95353. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95354. "nop\n\t"
  95355. "nop\n\t"
  95356. "nop\n\t"
  95357. "nop\n\t"
  95358. "nop\n\t"
  95359. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95360. "nop\n\t"
  95361. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95362. : "=r"(sse)
  95363. : "r"(sse)
  95364. );
  95365. sigaction(SIGILL, &sigill_save, NULL);
  95366. }
  95367. if(!sse)
  95368. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95369. #elif defined(_MSC_VER)
  95370. # ifdef USE_TRY_CATCH_FLAVOR
  95371. _try {
  95372. __asm {
  95373. # if _MSC_VER <= 1200
  95374. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95375. _emit 0x0F
  95376. _emit 0x57
  95377. _emit 0xC0
  95378. # else
  95379. xorps xmm0,xmm0
  95380. # endif
  95381. }
  95382. }
  95383. _except(EXCEPTION_EXECUTE_HANDLER) {
  95384. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95385. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95386. }
  95387. # else
  95388. int sse = 0;
  95389. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95390. /* see GCC version above for explanation */
  95391. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95392. /* http://www.codeproject.com/cpp/gccasm.asp */
  95393. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95394. __asm {
  95395. # if _MSC_VER <= 1200
  95396. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95397. _emit 0x0F
  95398. _emit 0x57
  95399. _emit 0xC0
  95400. # else
  95401. xorps xmm0,xmm0
  95402. # endif
  95403. inc sse
  95404. nop
  95405. nop
  95406. nop
  95407. nop
  95408. nop
  95409. nop
  95410. nop
  95411. nop
  95412. nop
  95413. }
  95414. SetUnhandledExceptionFilter(save);
  95415. if(!sse)
  95416. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95417. # endif
  95418. #else
  95419. /* no way to test, disable to be safe */
  95420. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95421. #endif
  95422. #ifdef DEBUG
  95423. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95424. #endif
  95425. }
  95426. }
  95427. #else
  95428. info->use_asm = false;
  95429. #endif
  95430. /*
  95431. * PPC-specific
  95432. */
  95433. #elif defined FLAC__CPU_PPC
  95434. info->type = FLAC__CPUINFO_TYPE_PPC;
  95435. # if !defined FLAC__NO_ASM
  95436. info->use_asm = true;
  95437. # ifdef FLAC__USE_ALTIVEC
  95438. # if defined FLAC__SYS_DARWIN
  95439. {
  95440. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95441. size_t len = sizeof(val);
  95442. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95443. }
  95444. {
  95445. host_basic_info_data_t hostInfo;
  95446. mach_msg_type_number_t infoCount;
  95447. infoCount = HOST_BASIC_INFO_COUNT;
  95448. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95449. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95450. }
  95451. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95452. {
  95453. /* no Darwin, do it the brute-force way */
  95454. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95455. info->data.ppc.altivec = 0;
  95456. info->data.ppc.ppc64 = 0;
  95457. signal (SIGILL, sigill_handler);
  95458. canjump = 0;
  95459. if (!sigsetjmp (jmpbuf, 1)) {
  95460. canjump = 1;
  95461. asm volatile (
  95462. "mtspr 256, %0\n\t"
  95463. "vand %%v0, %%v0, %%v0"
  95464. :
  95465. : "r" (-1)
  95466. );
  95467. info->data.ppc.altivec = 1;
  95468. }
  95469. canjump = 0;
  95470. if (!sigsetjmp (jmpbuf, 1)) {
  95471. int x = 0;
  95472. canjump = 1;
  95473. /* PPC64 hardware implements the cntlzd instruction */
  95474. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95475. info->data.ppc.ppc64 = 1;
  95476. }
  95477. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95478. }
  95479. # endif
  95480. # else /* !FLAC__USE_ALTIVEC */
  95481. info->data.ppc.altivec = 0;
  95482. info->data.ppc.ppc64 = 0;
  95483. # endif
  95484. # else
  95485. info->use_asm = false;
  95486. # endif
  95487. /*
  95488. * unknown CPI
  95489. */
  95490. #else
  95491. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95492. info->use_asm = false;
  95493. #endif
  95494. }
  95495. #endif
  95496. /*** End of inlined file: cpu.c ***/
  95497. /*** Start of inlined file: crc.c ***/
  95498. /*** Start of inlined file: juce_FlacHeader.h ***/
  95499. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95500. // tasks..
  95501. #define VERSION "1.2.1"
  95502. #define FLAC__NO_DLL 1
  95503. #if JUCE_MSVC
  95504. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95505. #endif
  95506. #if JUCE_MAC
  95507. #define FLAC__SYS_DARWIN 1
  95508. #endif
  95509. /*** End of inlined file: juce_FlacHeader.h ***/
  95510. #if JUCE_USE_FLAC
  95511. #if HAVE_CONFIG_H
  95512. # include <config.h>
  95513. #endif
  95514. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95515. FLAC__byte const FLAC__crc8_table[256] = {
  95516. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95517. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95518. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95519. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95520. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95521. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95522. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95523. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95524. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95525. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95526. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95527. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95528. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95529. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95530. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95531. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95532. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95533. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95534. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95535. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95536. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95537. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95538. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95539. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95540. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95541. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95542. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95543. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95544. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95545. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95546. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95547. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95548. };
  95549. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95550. unsigned FLAC__crc16_table[256] = {
  95551. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95552. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95553. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95554. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95555. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95556. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95557. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95558. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95559. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95560. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95561. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95562. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95563. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95564. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95565. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95566. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95567. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95568. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95569. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95570. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95571. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95572. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95573. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95574. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95575. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95576. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95577. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95578. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95579. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95580. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95581. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95582. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95583. };
  95584. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95585. {
  95586. *crc = FLAC__crc8_table[*crc ^ data];
  95587. }
  95588. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95589. {
  95590. while(len--)
  95591. *crc = FLAC__crc8_table[*crc ^ *data++];
  95592. }
  95593. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95594. {
  95595. FLAC__uint8 crc = 0;
  95596. while(len--)
  95597. crc = FLAC__crc8_table[crc ^ *data++];
  95598. return crc;
  95599. }
  95600. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95601. {
  95602. unsigned crc = 0;
  95603. while(len--)
  95604. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95605. return crc;
  95606. }
  95607. #endif
  95608. /*** End of inlined file: crc.c ***/
  95609. /*** Start of inlined file: fixed.c ***/
  95610. /*** Start of inlined file: juce_FlacHeader.h ***/
  95611. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95612. // tasks..
  95613. #define VERSION "1.2.1"
  95614. #define FLAC__NO_DLL 1
  95615. #if JUCE_MSVC
  95616. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95617. #endif
  95618. #if JUCE_MAC
  95619. #define FLAC__SYS_DARWIN 1
  95620. #endif
  95621. /*** End of inlined file: juce_FlacHeader.h ***/
  95622. #if JUCE_USE_FLAC
  95623. #if HAVE_CONFIG_H
  95624. # include <config.h>
  95625. #endif
  95626. #include <math.h>
  95627. #include <string.h>
  95628. /*** Start of inlined file: fixed.h ***/
  95629. #ifndef FLAC__PRIVATE__FIXED_H
  95630. #define FLAC__PRIVATE__FIXED_H
  95631. #ifdef HAVE_CONFIG_H
  95632. #include <config.h>
  95633. #endif
  95634. /*** Start of inlined file: float.h ***/
  95635. #ifndef FLAC__PRIVATE__FLOAT_H
  95636. #define FLAC__PRIVATE__FLOAT_H
  95637. #ifdef HAVE_CONFIG_H
  95638. #include <config.h>
  95639. #endif
  95640. /*
  95641. * These typedefs make it easier to ensure that integer versions of
  95642. * the library really only contain integer operations. All the code
  95643. * in libFLAC should use FLAC__float and FLAC__double in place of
  95644. * float and double, and be protected by checks of the macro
  95645. * FLAC__INTEGER_ONLY_LIBRARY.
  95646. *
  95647. * FLAC__real is the basic floating point type used in LPC analysis.
  95648. */
  95649. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95650. typedef double FLAC__double;
  95651. typedef float FLAC__float;
  95652. /*
  95653. * WATCHOUT: changing FLAC__real will change the signatures of many
  95654. * functions that have assembly language equivalents and break them.
  95655. */
  95656. typedef float FLAC__real;
  95657. #else
  95658. /*
  95659. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95660. * for the integer part and lower 16 bits for the fractional part.
  95661. */
  95662. typedef FLAC__int32 FLAC__fixedpoint;
  95663. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95664. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95665. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95666. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95667. extern const FLAC__fixedpoint FLAC__FP_E;
  95668. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95669. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95670. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95671. /*
  95672. * FLAC__fixedpoint_log2()
  95673. * --------------------------------------------------------------------
  95674. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95675. * algorithm by Knuth for x >= 1.0
  95676. *
  95677. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95678. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95679. *
  95680. * 'precision' roughly limits the number of iterations that are done;
  95681. * use (unsigned)(-1) for maximum precision.
  95682. *
  95683. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95684. * function will punt and return 0.
  95685. *
  95686. * The return value will also have 'fracbits' fractional bits.
  95687. */
  95688. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95689. #endif
  95690. #endif
  95691. /*** End of inlined file: float.h ***/
  95692. /*** Start of inlined file: format.h ***/
  95693. #ifndef FLAC__PRIVATE__FORMAT_H
  95694. #define FLAC__PRIVATE__FORMAT_H
  95695. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95696. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95697. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95698. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95699. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95700. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95701. #endif
  95702. /*** End of inlined file: format.h ***/
  95703. /*
  95704. * FLAC__fixed_compute_best_predictor()
  95705. * --------------------------------------------------------------------
  95706. * Compute the best fixed predictor and the expected bits-per-sample
  95707. * of the residual signal for each order. The _wide() version uses
  95708. * 64-bit integers which is statistically necessary when bits-per-
  95709. * sample + log2(blocksize) > 30
  95710. *
  95711. * IN data[0,data_len-1]
  95712. * IN data_len
  95713. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95714. */
  95715. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95716. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95717. # ifndef FLAC__NO_ASM
  95718. # ifdef FLAC__CPU_IA32
  95719. # ifdef FLAC__HAS_NASM
  95720. 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]);
  95721. # endif
  95722. # endif
  95723. # endif
  95724. 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]);
  95725. #else
  95726. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95727. 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]);
  95728. #endif
  95729. /*
  95730. * FLAC__fixed_compute_residual()
  95731. * --------------------------------------------------------------------
  95732. * Compute the residual signal obtained from sutracting the predicted
  95733. * signal from the original.
  95734. *
  95735. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95736. * IN data_len length of original signal
  95737. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95738. * OUT residual[0,data_len-1] residual signal
  95739. */
  95740. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95741. /*
  95742. * FLAC__fixed_restore_signal()
  95743. * --------------------------------------------------------------------
  95744. * Restore the original signal by summing the residual and the
  95745. * predictor.
  95746. *
  95747. * IN residual[0,data_len-1] residual signal
  95748. * IN data_len length of original signal
  95749. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95750. * *** IMPORTANT: the caller must pass in the historical samples:
  95751. * IN data[-order,-1] previously-reconstructed historical samples
  95752. * OUT data[0,data_len-1] original signal
  95753. */
  95754. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95755. #endif
  95756. /*** End of inlined file: fixed.h ***/
  95757. #ifndef M_LN2
  95758. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95759. #define M_LN2 0.69314718055994530942
  95760. #endif
  95761. #ifdef min
  95762. #undef min
  95763. #endif
  95764. #define min(x,y) ((x) < (y)? (x) : (y))
  95765. #ifdef local_abs
  95766. #undef local_abs
  95767. #endif
  95768. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95769. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95770. /* rbps stands for residual bits per sample
  95771. *
  95772. * (ln(2) * err)
  95773. * rbps = log (-----------)
  95774. * 2 ( n )
  95775. */
  95776. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95777. {
  95778. FLAC__uint32 rbps;
  95779. unsigned bits; /* the number of bits required to represent a number */
  95780. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95781. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95782. FLAC__ASSERT(err > 0);
  95783. FLAC__ASSERT(n > 0);
  95784. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95785. if(err <= n)
  95786. return 0;
  95787. /*
  95788. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95789. * These allow us later to know we won't lose too much precision in the
  95790. * fixed-point division (err<<fracbits)/n.
  95791. */
  95792. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95793. err <<= fracbits;
  95794. err /= n;
  95795. /* err now holds err/n with fracbits fractional bits */
  95796. /*
  95797. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95798. * our purposes.
  95799. */
  95800. FLAC__ASSERT(err > 0);
  95801. bits = FLAC__bitmath_ilog2(err)+1;
  95802. if(bits > 16) {
  95803. err >>= (bits-16);
  95804. fracbits -= (bits-16);
  95805. }
  95806. rbps = (FLAC__uint32)err;
  95807. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95808. rbps *= FLAC__FP_LN2;
  95809. fracbits += 16;
  95810. FLAC__ASSERT(fracbits >= 0);
  95811. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95812. {
  95813. const int f = fracbits & 3;
  95814. if(f) {
  95815. rbps >>= f;
  95816. fracbits -= f;
  95817. }
  95818. }
  95819. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95820. if(rbps == 0)
  95821. return 0;
  95822. /*
  95823. * The return value must have 16 fractional bits. Since the whole part
  95824. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95825. * must be >= -3, these assertion allows us to be able to shift rbps
  95826. * left if necessary to get 16 fracbits without losing any bits of the
  95827. * whole part of rbps.
  95828. *
  95829. * There is a slight chance due to accumulated error that the whole part
  95830. * will require 6 bits, so we use 6 in the assertion. Really though as
  95831. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95832. */
  95833. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95834. FLAC__ASSERT(fracbits >= -3);
  95835. /* now shift the decimal point into place */
  95836. if(fracbits < 16)
  95837. return rbps << (16-fracbits);
  95838. else if(fracbits > 16)
  95839. return rbps >> (fracbits-16);
  95840. else
  95841. return rbps;
  95842. }
  95843. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95844. {
  95845. FLAC__uint32 rbps;
  95846. unsigned bits; /* the number of bits required to represent a number */
  95847. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95848. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95849. FLAC__ASSERT(err > 0);
  95850. FLAC__ASSERT(n > 0);
  95851. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95852. if(err <= n)
  95853. return 0;
  95854. /*
  95855. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95856. * These allow us later to know we won't lose too much precision in the
  95857. * fixed-point division (err<<fracbits)/n.
  95858. */
  95859. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95860. err <<= fracbits;
  95861. err /= n;
  95862. /* err now holds err/n with fracbits fractional bits */
  95863. /*
  95864. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95865. * our purposes.
  95866. */
  95867. FLAC__ASSERT(err > 0);
  95868. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95869. if(bits > 16) {
  95870. err >>= (bits-16);
  95871. fracbits -= (bits-16);
  95872. }
  95873. rbps = (FLAC__uint32)err;
  95874. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95875. rbps *= FLAC__FP_LN2;
  95876. fracbits += 16;
  95877. FLAC__ASSERT(fracbits >= 0);
  95878. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95879. {
  95880. const int f = fracbits & 3;
  95881. if(f) {
  95882. rbps >>= f;
  95883. fracbits -= f;
  95884. }
  95885. }
  95886. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95887. if(rbps == 0)
  95888. return 0;
  95889. /*
  95890. * The return value must have 16 fractional bits. Since the whole part
  95891. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95892. * must be >= -3, these assertion allows us to be able to shift rbps
  95893. * left if necessary to get 16 fracbits without losing any bits of the
  95894. * whole part of rbps.
  95895. *
  95896. * There is a slight chance due to accumulated error that the whole part
  95897. * will require 6 bits, so we use 6 in the assertion. Really though as
  95898. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95899. */
  95900. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95901. FLAC__ASSERT(fracbits >= -3);
  95902. /* now shift the decimal point into place */
  95903. if(fracbits < 16)
  95904. return rbps << (16-fracbits);
  95905. else if(fracbits > 16)
  95906. return rbps >> (fracbits-16);
  95907. else
  95908. return rbps;
  95909. }
  95910. #endif
  95911. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95912. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95913. #else
  95914. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95915. #endif
  95916. {
  95917. FLAC__int32 last_error_0 = data[-1];
  95918. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95919. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95920. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95921. FLAC__int32 error, save;
  95922. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95923. unsigned i, order;
  95924. for(i = 0; i < data_len; i++) {
  95925. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95926. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95927. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95928. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95929. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95930. }
  95931. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95932. order = 0;
  95933. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95934. order = 1;
  95935. else if(total_error_2 < min(total_error_3, total_error_4))
  95936. order = 2;
  95937. else if(total_error_3 < total_error_4)
  95938. order = 3;
  95939. else
  95940. order = 4;
  95941. /* Estimate the expected number of bits per residual signal sample. */
  95942. /* 'total_error*' is linearly related to the variance of the residual */
  95943. /* signal, so we use it directly to compute E(|x|) */
  95944. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95945. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95946. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95947. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95948. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95949. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95950. 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);
  95951. 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);
  95952. 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);
  95953. 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);
  95954. 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);
  95955. #else
  95956. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95957. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95958. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95959. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95960. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95961. #endif
  95962. return order;
  95963. }
  95964. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95965. 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])
  95966. #else
  95967. 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])
  95968. #endif
  95969. {
  95970. FLAC__int32 last_error_0 = data[-1];
  95971. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95972. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95973. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95974. FLAC__int32 error, save;
  95975. /* total_error_* are 64-bits to avoid overflow when encoding
  95976. * erratic signals when the bits-per-sample and blocksize are
  95977. * large.
  95978. */
  95979. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95980. unsigned i, order;
  95981. for(i = 0; i < data_len; i++) {
  95982. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95983. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95984. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95985. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95986. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95987. }
  95988. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95989. order = 0;
  95990. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95991. order = 1;
  95992. else if(total_error_2 < min(total_error_3, total_error_4))
  95993. order = 2;
  95994. else if(total_error_3 < total_error_4)
  95995. order = 3;
  95996. else
  95997. order = 4;
  95998. /* Estimate the expected number of bits per residual signal sample. */
  95999. /* 'total_error*' is linearly related to the variance of the residual */
  96000. /* signal, so we use it directly to compute E(|x|) */
  96001. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96002. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96003. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96004. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96005. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96006. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96007. #if defined _MSC_VER || defined __MINGW32__
  96008. /* with MSVC you have to spoon feed it the casting */
  96009. 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);
  96010. 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);
  96011. 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);
  96012. 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);
  96013. 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);
  96014. #else
  96015. 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);
  96016. 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);
  96017. 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);
  96018. 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);
  96019. 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);
  96020. #endif
  96021. #else
  96022. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96023. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96024. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96025. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96026. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96027. #endif
  96028. return order;
  96029. }
  96030. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96031. {
  96032. const int idata_len = (int)data_len;
  96033. int i;
  96034. switch(order) {
  96035. case 0:
  96036. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96037. memcpy(residual, data, sizeof(residual[0])*data_len);
  96038. break;
  96039. case 1:
  96040. for(i = 0; i < idata_len; i++)
  96041. residual[i] = data[i] - data[i-1];
  96042. break;
  96043. case 2:
  96044. for(i = 0; i < idata_len; i++)
  96045. #if 1 /* OPT: may be faster with some compilers on some systems */
  96046. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96047. #else
  96048. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96049. #endif
  96050. break;
  96051. case 3:
  96052. for(i = 0; i < idata_len; i++)
  96053. #if 1 /* OPT: may be faster with some compilers on some systems */
  96054. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96055. #else
  96056. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96057. #endif
  96058. break;
  96059. case 4:
  96060. for(i = 0; i < idata_len; i++)
  96061. #if 1 /* OPT: may be faster with some compilers on some systems */
  96062. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96063. #else
  96064. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96065. #endif
  96066. break;
  96067. default:
  96068. FLAC__ASSERT(0);
  96069. }
  96070. }
  96071. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96072. {
  96073. int i, idata_len = (int)data_len;
  96074. switch(order) {
  96075. case 0:
  96076. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96077. memcpy(data, residual, sizeof(residual[0])*data_len);
  96078. break;
  96079. case 1:
  96080. for(i = 0; i < idata_len; i++)
  96081. data[i] = residual[i] + data[i-1];
  96082. break;
  96083. case 2:
  96084. for(i = 0; i < idata_len; i++)
  96085. #if 1 /* OPT: may be faster with some compilers on some systems */
  96086. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96087. #else
  96088. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96089. #endif
  96090. break;
  96091. case 3:
  96092. for(i = 0; i < idata_len; i++)
  96093. #if 1 /* OPT: may be faster with some compilers on some systems */
  96094. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96095. #else
  96096. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96097. #endif
  96098. break;
  96099. case 4:
  96100. for(i = 0; i < idata_len; i++)
  96101. #if 1 /* OPT: may be faster with some compilers on some systems */
  96102. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96103. #else
  96104. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96105. #endif
  96106. break;
  96107. default:
  96108. FLAC__ASSERT(0);
  96109. }
  96110. }
  96111. #endif
  96112. /*** End of inlined file: fixed.c ***/
  96113. /*** Start of inlined file: float.c ***/
  96114. /*** Start of inlined file: juce_FlacHeader.h ***/
  96115. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96116. // tasks..
  96117. #define VERSION "1.2.1"
  96118. #define FLAC__NO_DLL 1
  96119. #if JUCE_MSVC
  96120. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96121. #endif
  96122. #if JUCE_MAC
  96123. #define FLAC__SYS_DARWIN 1
  96124. #endif
  96125. /*** End of inlined file: juce_FlacHeader.h ***/
  96126. #if JUCE_USE_FLAC
  96127. #if HAVE_CONFIG_H
  96128. # include <config.h>
  96129. #endif
  96130. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96131. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96132. #ifdef _MSC_VER
  96133. #define FLAC__U64L(x) x
  96134. #else
  96135. #define FLAC__U64L(x) x##LLU
  96136. #endif
  96137. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96138. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96139. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96140. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96141. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96142. /* Lookup tables for Knuth's logarithm algorithm */
  96143. #define LOG2_LOOKUP_PRECISION 16
  96144. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96145. {
  96146. /*
  96147. * 0 fraction bits
  96148. */
  96149. /* undefined */ 0x00000000,
  96150. /* lg(2/1) = */ 0x00000001,
  96151. /* lg(4/3) = */ 0x00000000,
  96152. /* lg(8/7) = */ 0x00000000,
  96153. /* lg(16/15) = */ 0x00000000,
  96154. /* lg(32/31) = */ 0x00000000,
  96155. /* lg(64/63) = */ 0x00000000,
  96156. /* lg(128/127) = */ 0x00000000,
  96157. /* lg(256/255) = */ 0x00000000,
  96158. /* lg(512/511) = */ 0x00000000,
  96159. /* lg(1024/1023) = */ 0x00000000,
  96160. /* lg(2048/2047) = */ 0x00000000,
  96161. /* lg(4096/4095) = */ 0x00000000,
  96162. /* lg(8192/8191) = */ 0x00000000,
  96163. /* lg(16384/16383) = */ 0x00000000,
  96164. /* lg(32768/32767) = */ 0x00000000
  96165. },
  96166. {
  96167. /*
  96168. * 4 fraction bits
  96169. */
  96170. /* undefined */ 0x00000000,
  96171. /* lg(2/1) = */ 0x00000010,
  96172. /* lg(4/3) = */ 0x00000007,
  96173. /* lg(8/7) = */ 0x00000003,
  96174. /* lg(16/15) = */ 0x00000001,
  96175. /* lg(32/31) = */ 0x00000001,
  96176. /* lg(64/63) = */ 0x00000000,
  96177. /* lg(128/127) = */ 0x00000000,
  96178. /* lg(256/255) = */ 0x00000000,
  96179. /* lg(512/511) = */ 0x00000000,
  96180. /* lg(1024/1023) = */ 0x00000000,
  96181. /* lg(2048/2047) = */ 0x00000000,
  96182. /* lg(4096/4095) = */ 0x00000000,
  96183. /* lg(8192/8191) = */ 0x00000000,
  96184. /* lg(16384/16383) = */ 0x00000000,
  96185. /* lg(32768/32767) = */ 0x00000000
  96186. },
  96187. {
  96188. /*
  96189. * 8 fraction bits
  96190. */
  96191. /* undefined */ 0x00000000,
  96192. /* lg(2/1) = */ 0x00000100,
  96193. /* lg(4/3) = */ 0x0000006a,
  96194. /* lg(8/7) = */ 0x00000031,
  96195. /* lg(16/15) = */ 0x00000018,
  96196. /* lg(32/31) = */ 0x0000000c,
  96197. /* lg(64/63) = */ 0x00000006,
  96198. /* lg(128/127) = */ 0x00000003,
  96199. /* lg(256/255) = */ 0x00000001,
  96200. /* lg(512/511) = */ 0x00000001,
  96201. /* lg(1024/1023) = */ 0x00000000,
  96202. /* lg(2048/2047) = */ 0x00000000,
  96203. /* lg(4096/4095) = */ 0x00000000,
  96204. /* lg(8192/8191) = */ 0x00000000,
  96205. /* lg(16384/16383) = */ 0x00000000,
  96206. /* lg(32768/32767) = */ 0x00000000
  96207. },
  96208. {
  96209. /*
  96210. * 12 fraction bits
  96211. */
  96212. /* undefined */ 0x00000000,
  96213. /* lg(2/1) = */ 0x00001000,
  96214. /* lg(4/3) = */ 0x000006a4,
  96215. /* lg(8/7) = */ 0x00000315,
  96216. /* lg(16/15) = */ 0x0000017d,
  96217. /* lg(32/31) = */ 0x000000bc,
  96218. /* lg(64/63) = */ 0x0000005d,
  96219. /* lg(128/127) = */ 0x0000002e,
  96220. /* lg(256/255) = */ 0x00000017,
  96221. /* lg(512/511) = */ 0x0000000c,
  96222. /* lg(1024/1023) = */ 0x00000006,
  96223. /* lg(2048/2047) = */ 0x00000003,
  96224. /* lg(4096/4095) = */ 0x00000001,
  96225. /* lg(8192/8191) = */ 0x00000001,
  96226. /* lg(16384/16383) = */ 0x00000000,
  96227. /* lg(32768/32767) = */ 0x00000000
  96228. },
  96229. {
  96230. /*
  96231. * 16 fraction bits
  96232. */
  96233. /* undefined */ 0x00000000,
  96234. /* lg(2/1) = */ 0x00010000,
  96235. /* lg(4/3) = */ 0x00006a40,
  96236. /* lg(8/7) = */ 0x00003151,
  96237. /* lg(16/15) = */ 0x000017d6,
  96238. /* lg(32/31) = */ 0x00000bba,
  96239. /* lg(64/63) = */ 0x000005d1,
  96240. /* lg(128/127) = */ 0x000002e6,
  96241. /* lg(256/255) = */ 0x00000172,
  96242. /* lg(512/511) = */ 0x000000b9,
  96243. /* lg(1024/1023) = */ 0x0000005c,
  96244. /* lg(2048/2047) = */ 0x0000002e,
  96245. /* lg(4096/4095) = */ 0x00000017,
  96246. /* lg(8192/8191) = */ 0x0000000c,
  96247. /* lg(16384/16383) = */ 0x00000006,
  96248. /* lg(32768/32767) = */ 0x00000003
  96249. },
  96250. {
  96251. /*
  96252. * 20 fraction bits
  96253. */
  96254. /* undefined */ 0x00000000,
  96255. /* lg(2/1) = */ 0x00100000,
  96256. /* lg(4/3) = */ 0x0006a3fe,
  96257. /* lg(8/7) = */ 0x00031513,
  96258. /* lg(16/15) = */ 0x00017d60,
  96259. /* lg(32/31) = */ 0x0000bb9d,
  96260. /* lg(64/63) = */ 0x00005d10,
  96261. /* lg(128/127) = */ 0x00002e59,
  96262. /* lg(256/255) = */ 0x00001721,
  96263. /* lg(512/511) = */ 0x00000b8e,
  96264. /* lg(1024/1023) = */ 0x000005c6,
  96265. /* lg(2048/2047) = */ 0x000002e3,
  96266. /* lg(4096/4095) = */ 0x00000171,
  96267. /* lg(8192/8191) = */ 0x000000b9,
  96268. /* lg(16384/16383) = */ 0x0000005c,
  96269. /* lg(32768/32767) = */ 0x0000002e
  96270. },
  96271. {
  96272. /*
  96273. * 24 fraction bits
  96274. */
  96275. /* undefined */ 0x00000000,
  96276. /* lg(2/1) = */ 0x01000000,
  96277. /* lg(4/3) = */ 0x006a3fe6,
  96278. /* lg(8/7) = */ 0x00315130,
  96279. /* lg(16/15) = */ 0x0017d605,
  96280. /* lg(32/31) = */ 0x000bb9ca,
  96281. /* lg(64/63) = */ 0x0005d0fc,
  96282. /* lg(128/127) = */ 0x0002e58f,
  96283. /* lg(256/255) = */ 0x0001720e,
  96284. /* lg(512/511) = */ 0x0000b8d8,
  96285. /* lg(1024/1023) = */ 0x00005c61,
  96286. /* lg(2048/2047) = */ 0x00002e2d,
  96287. /* lg(4096/4095) = */ 0x00001716,
  96288. /* lg(8192/8191) = */ 0x00000b8b,
  96289. /* lg(16384/16383) = */ 0x000005c5,
  96290. /* lg(32768/32767) = */ 0x000002e3
  96291. },
  96292. {
  96293. /*
  96294. * 28 fraction bits
  96295. */
  96296. /* undefined */ 0x00000000,
  96297. /* lg(2/1) = */ 0x10000000,
  96298. /* lg(4/3) = */ 0x06a3fe5c,
  96299. /* lg(8/7) = */ 0x03151301,
  96300. /* lg(16/15) = */ 0x017d6049,
  96301. /* lg(32/31) = */ 0x00bb9ca6,
  96302. /* lg(64/63) = */ 0x005d0fba,
  96303. /* lg(128/127) = */ 0x002e58f7,
  96304. /* lg(256/255) = */ 0x001720da,
  96305. /* lg(512/511) = */ 0x000b8d87,
  96306. /* lg(1024/1023) = */ 0x0005c60b,
  96307. /* lg(2048/2047) = */ 0x0002e2d7,
  96308. /* lg(4096/4095) = */ 0x00017160,
  96309. /* lg(8192/8191) = */ 0x0000b8ad,
  96310. /* lg(16384/16383) = */ 0x00005c56,
  96311. /* lg(32768/32767) = */ 0x00002e2b
  96312. }
  96313. };
  96314. #if 0
  96315. static const FLAC__uint64 log2_lookup_wide[] = {
  96316. {
  96317. /*
  96318. * 32 fraction bits
  96319. */
  96320. /* undefined */ 0x00000000,
  96321. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96322. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96323. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96324. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96325. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96326. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96327. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96328. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96329. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96330. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96331. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96332. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96333. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96334. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96335. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96336. },
  96337. {
  96338. /*
  96339. * 48 fraction bits
  96340. */
  96341. /* undefined */ 0x00000000,
  96342. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96343. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96344. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96345. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96346. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96347. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96348. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96349. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96350. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96351. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96352. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96353. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96354. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96355. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96356. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96357. }
  96358. };
  96359. #endif
  96360. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96361. {
  96362. const FLAC__uint32 ONE = (1u << fracbits);
  96363. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96364. FLAC__ASSERT(fracbits < 32);
  96365. FLAC__ASSERT((fracbits & 0x3) == 0);
  96366. if(x < ONE)
  96367. return 0;
  96368. if(precision > LOG2_LOOKUP_PRECISION)
  96369. precision = LOG2_LOOKUP_PRECISION;
  96370. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96371. {
  96372. FLAC__uint32 y = 0;
  96373. FLAC__uint32 z = x >> 1, k = 1;
  96374. while (x > ONE && k < precision) {
  96375. if (x - z >= ONE) {
  96376. x -= z;
  96377. z = x >> k;
  96378. y += table[k];
  96379. }
  96380. else {
  96381. z >>= 1;
  96382. k++;
  96383. }
  96384. }
  96385. return y;
  96386. }
  96387. }
  96388. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96389. #endif
  96390. /*** End of inlined file: float.c ***/
  96391. /*** Start of inlined file: format.c ***/
  96392. /*** Start of inlined file: juce_FlacHeader.h ***/
  96393. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96394. // tasks..
  96395. #define VERSION "1.2.1"
  96396. #define FLAC__NO_DLL 1
  96397. #if JUCE_MSVC
  96398. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96399. #endif
  96400. #if JUCE_MAC
  96401. #define FLAC__SYS_DARWIN 1
  96402. #endif
  96403. /*** End of inlined file: juce_FlacHeader.h ***/
  96404. #if JUCE_USE_FLAC
  96405. #if HAVE_CONFIG_H
  96406. # include <config.h>
  96407. #endif
  96408. #include <stdio.h>
  96409. #include <stdlib.h> /* for qsort() */
  96410. #include <string.h> /* for memset() */
  96411. #ifndef FLaC__INLINE
  96412. #define FLaC__INLINE
  96413. #endif
  96414. #ifdef min
  96415. #undef min
  96416. #endif
  96417. #define min(a,b) ((a)<(b)?(a):(b))
  96418. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96419. #ifdef _MSC_VER
  96420. #define FLAC__U64L(x) x
  96421. #else
  96422. #define FLAC__U64L(x) x##LLU
  96423. #endif
  96424. /* VERSION should come from configure */
  96425. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96426. ;
  96427. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96428. /* yet one more hack because of MSVC6: */
  96429. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96430. #else
  96431. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96432. #endif
  96433. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96434. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96435. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96436. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96437. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96438. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96439. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96440. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96441. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96442. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96443. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96444. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96445. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96446. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96447. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96448. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96449. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96450. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96451. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96452. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96453. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96454. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96455. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96456. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96457. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96458. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96459. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96460. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96461. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96462. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96463. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96464. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96465. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96466. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96467. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96468. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96469. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96470. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96471. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96472. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96473. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96474. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96475. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96476. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96477. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96478. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96479. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96480. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96481. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96482. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96483. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96484. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96485. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96486. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96487. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96488. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96489. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96490. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96491. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96492. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96493. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96494. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96495. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96496. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96497. "PARTITIONED_RICE",
  96498. "PARTITIONED_RICE2"
  96499. };
  96500. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96501. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96502. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96503. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96504. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96505. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96506. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96507. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96508. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96509. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96510. "CONSTANT",
  96511. "VERBATIM",
  96512. "FIXED",
  96513. "LPC"
  96514. };
  96515. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96516. "INDEPENDENT",
  96517. "LEFT_SIDE",
  96518. "RIGHT_SIDE",
  96519. "MID_SIDE"
  96520. };
  96521. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96522. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96523. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96524. };
  96525. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96526. "STREAMINFO",
  96527. "PADDING",
  96528. "APPLICATION",
  96529. "SEEKTABLE",
  96530. "VORBIS_COMMENT",
  96531. "CUESHEET",
  96532. "PICTURE"
  96533. };
  96534. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96535. "Other",
  96536. "32x32 pixels 'file icon' (PNG only)",
  96537. "Other file icon",
  96538. "Cover (front)",
  96539. "Cover (back)",
  96540. "Leaflet page",
  96541. "Media (e.g. label side of CD)",
  96542. "Lead artist/lead performer/soloist",
  96543. "Artist/performer",
  96544. "Conductor",
  96545. "Band/Orchestra",
  96546. "Composer",
  96547. "Lyricist/text writer",
  96548. "Recording Location",
  96549. "During recording",
  96550. "During performance",
  96551. "Movie/video screen capture",
  96552. "A bright coloured fish",
  96553. "Illustration",
  96554. "Band/artist logotype",
  96555. "Publisher/Studio logotype"
  96556. };
  96557. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96558. {
  96559. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96560. return false;
  96561. }
  96562. else
  96563. return true;
  96564. }
  96565. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96566. {
  96567. if(
  96568. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96569. (
  96570. sample_rate >= (1u << 16) &&
  96571. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96572. )
  96573. ) {
  96574. return false;
  96575. }
  96576. else
  96577. return true;
  96578. }
  96579. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96580. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96581. {
  96582. unsigned i;
  96583. FLAC__uint64 prev_sample_number = 0;
  96584. FLAC__bool got_prev = false;
  96585. FLAC__ASSERT(0 != seek_table);
  96586. for(i = 0; i < seek_table->num_points; i++) {
  96587. if(got_prev) {
  96588. if(
  96589. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96590. seek_table->points[i].sample_number <= prev_sample_number
  96591. )
  96592. return false;
  96593. }
  96594. prev_sample_number = seek_table->points[i].sample_number;
  96595. got_prev = true;
  96596. }
  96597. return true;
  96598. }
  96599. /* used as the sort predicate for qsort() */
  96600. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96601. {
  96602. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96603. if(l->sample_number == r->sample_number)
  96604. return 0;
  96605. else if(l->sample_number < r->sample_number)
  96606. return -1;
  96607. else
  96608. return 1;
  96609. }
  96610. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96611. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96612. {
  96613. unsigned i, j;
  96614. FLAC__bool first;
  96615. FLAC__ASSERT(0 != seek_table);
  96616. /* sort the seekpoints */
  96617. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96618. /* uniquify the seekpoints */
  96619. first = true;
  96620. for(i = j = 0; i < seek_table->num_points; i++) {
  96621. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96622. if(!first) {
  96623. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96624. continue;
  96625. }
  96626. }
  96627. first = false;
  96628. seek_table->points[j++] = seek_table->points[i];
  96629. }
  96630. for(i = j; i < seek_table->num_points; i++) {
  96631. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96632. seek_table->points[i].stream_offset = 0;
  96633. seek_table->points[i].frame_samples = 0;
  96634. }
  96635. return j;
  96636. }
  96637. /*
  96638. * also disallows non-shortest-form encodings, c.f.
  96639. * http://www.unicode.org/versions/corrigendum1.html
  96640. * and a more clear explanation at the end of this section:
  96641. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96642. */
  96643. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96644. {
  96645. FLAC__ASSERT(0 != utf8);
  96646. if ((utf8[0] & 0x80) == 0) {
  96647. return 1;
  96648. }
  96649. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96650. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96651. return 0;
  96652. return 2;
  96653. }
  96654. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96655. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96656. return 0;
  96657. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96658. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96659. return 0;
  96660. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96661. return 0;
  96662. return 3;
  96663. }
  96664. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96665. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96666. return 0;
  96667. return 4;
  96668. }
  96669. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96670. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96671. return 0;
  96672. return 5;
  96673. }
  96674. 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) {
  96675. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96676. return 0;
  96677. return 6;
  96678. }
  96679. else {
  96680. return 0;
  96681. }
  96682. }
  96683. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96684. {
  96685. char c;
  96686. for(c = *name; c; c = *(++name))
  96687. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96688. return false;
  96689. return true;
  96690. }
  96691. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96692. {
  96693. if(length == (unsigned)(-1)) {
  96694. while(*value) {
  96695. unsigned n = utf8len_(value);
  96696. if(n == 0)
  96697. return false;
  96698. value += n;
  96699. }
  96700. }
  96701. else {
  96702. const FLAC__byte *end = value + length;
  96703. while(value < end) {
  96704. unsigned n = utf8len_(value);
  96705. if(n == 0)
  96706. return false;
  96707. value += n;
  96708. }
  96709. if(value != end)
  96710. return false;
  96711. }
  96712. return true;
  96713. }
  96714. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96715. {
  96716. const FLAC__byte *s, *end;
  96717. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96718. if(*s < 0x20 || *s > 0x7D)
  96719. return false;
  96720. }
  96721. if(s == end)
  96722. return false;
  96723. s++; /* skip '=' */
  96724. while(s < end) {
  96725. unsigned n = utf8len_(s);
  96726. if(n == 0)
  96727. return false;
  96728. s += n;
  96729. }
  96730. if(s != end)
  96731. return false;
  96732. return true;
  96733. }
  96734. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96735. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96736. {
  96737. unsigned i, j;
  96738. if(check_cd_da_subset) {
  96739. if(cue_sheet->lead_in < 2 * 44100) {
  96740. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96741. return false;
  96742. }
  96743. if(cue_sheet->lead_in % 588 != 0) {
  96744. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96745. return false;
  96746. }
  96747. }
  96748. if(cue_sheet->num_tracks == 0) {
  96749. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96750. return false;
  96751. }
  96752. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96753. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96754. return false;
  96755. }
  96756. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96757. if(cue_sheet->tracks[i].number == 0) {
  96758. if(violation) *violation = "cue sheet may not have a track number 0";
  96759. return false;
  96760. }
  96761. if(check_cd_da_subset) {
  96762. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96763. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96764. return false;
  96765. }
  96766. }
  96767. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96768. if(violation) {
  96769. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96770. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96771. else
  96772. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96773. }
  96774. return false;
  96775. }
  96776. if(i < cue_sheet->num_tracks - 1) {
  96777. if(cue_sheet->tracks[i].num_indices == 0) {
  96778. if(violation) *violation = "cue sheet track must have at least one index point";
  96779. return false;
  96780. }
  96781. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96782. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96783. return false;
  96784. }
  96785. }
  96786. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96787. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96788. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96789. return false;
  96790. }
  96791. if(j > 0) {
  96792. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96793. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96794. return false;
  96795. }
  96796. }
  96797. }
  96798. }
  96799. return true;
  96800. }
  96801. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96802. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96803. {
  96804. char *p;
  96805. FLAC__byte *b;
  96806. for(p = picture->mime_type; *p; p++) {
  96807. if(*p < 0x20 || *p > 0x7e) {
  96808. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96809. return false;
  96810. }
  96811. }
  96812. for(b = picture->description; *b; ) {
  96813. unsigned n = utf8len_(b);
  96814. if(n == 0) {
  96815. if(violation) *violation = "description string must be valid UTF-8";
  96816. return false;
  96817. }
  96818. b += n;
  96819. }
  96820. return true;
  96821. }
  96822. /*
  96823. * These routines are private to libFLAC
  96824. */
  96825. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96826. {
  96827. return
  96828. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96829. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96830. blocksize,
  96831. predictor_order
  96832. );
  96833. }
  96834. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96835. {
  96836. unsigned max_rice_partition_order = 0;
  96837. while(!(blocksize & 1)) {
  96838. max_rice_partition_order++;
  96839. blocksize >>= 1;
  96840. }
  96841. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96842. }
  96843. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96844. {
  96845. unsigned max_rice_partition_order = limit;
  96846. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96847. max_rice_partition_order--;
  96848. FLAC__ASSERT(
  96849. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96850. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96851. );
  96852. return max_rice_partition_order;
  96853. }
  96854. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96855. {
  96856. FLAC__ASSERT(0 != object);
  96857. object->parameters = 0;
  96858. object->raw_bits = 0;
  96859. object->capacity_by_order = 0;
  96860. }
  96861. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96862. {
  96863. FLAC__ASSERT(0 != object);
  96864. if(0 != object->parameters)
  96865. free(object->parameters);
  96866. if(0 != object->raw_bits)
  96867. free(object->raw_bits);
  96868. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96869. }
  96870. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96871. {
  96872. FLAC__ASSERT(0 != object);
  96873. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96874. if(object->capacity_by_order < max_partition_order) {
  96875. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96876. return false;
  96877. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96878. return false;
  96879. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96880. object->capacity_by_order = max_partition_order;
  96881. }
  96882. return true;
  96883. }
  96884. #endif
  96885. /*** End of inlined file: format.c ***/
  96886. /*** Start of inlined file: lpc_flac.c ***/
  96887. /*** Start of inlined file: juce_FlacHeader.h ***/
  96888. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96889. // tasks..
  96890. #define VERSION "1.2.1"
  96891. #define FLAC__NO_DLL 1
  96892. #if JUCE_MSVC
  96893. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96894. #endif
  96895. #if JUCE_MAC
  96896. #define FLAC__SYS_DARWIN 1
  96897. #endif
  96898. /*** End of inlined file: juce_FlacHeader.h ***/
  96899. #if JUCE_USE_FLAC
  96900. #if HAVE_CONFIG_H
  96901. # include <config.h>
  96902. #endif
  96903. #include <math.h>
  96904. /*** Start of inlined file: lpc.h ***/
  96905. #ifndef FLAC__PRIVATE__LPC_H
  96906. #define FLAC__PRIVATE__LPC_H
  96907. #ifdef HAVE_CONFIG_H
  96908. #include <config.h>
  96909. #endif
  96910. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96911. /*
  96912. * FLAC__lpc_window_data()
  96913. * --------------------------------------------------------------------
  96914. * Applies the given window to the data.
  96915. * OPT: asm implementation
  96916. *
  96917. * IN in[0,data_len-1]
  96918. * IN window[0,data_len-1]
  96919. * OUT out[0,lag-1]
  96920. * IN data_len
  96921. */
  96922. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96923. /*
  96924. * FLAC__lpc_compute_autocorrelation()
  96925. * --------------------------------------------------------------------
  96926. * Compute the autocorrelation for lags between 0 and lag-1.
  96927. * Assumes data[] outside of [0,data_len-1] == 0.
  96928. * Asserts that lag > 0.
  96929. *
  96930. * IN data[0,data_len-1]
  96931. * IN data_len
  96932. * IN 0 < lag <= data_len
  96933. * OUT autoc[0,lag-1]
  96934. */
  96935. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96936. #ifndef FLAC__NO_ASM
  96937. # ifdef FLAC__CPU_IA32
  96938. # ifdef FLAC__HAS_NASM
  96939. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96940. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96941. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96942. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96943. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96944. # endif
  96945. # endif
  96946. #endif
  96947. /*
  96948. * FLAC__lpc_compute_lp_coefficients()
  96949. * --------------------------------------------------------------------
  96950. * Computes LP coefficients for orders 1..max_order.
  96951. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96952. * and there is no point in calculating a predictor.
  96953. *
  96954. * IN autoc[0,max_order] autocorrelation values
  96955. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96956. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96957. * *** IMPORTANT:
  96958. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96959. * OUT error[0,max_order-1] error for each order (more
  96960. * specifically, the variance of
  96961. * the error signal times # of
  96962. * samples in the signal)
  96963. *
  96964. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96965. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96966. * in lp_coeff[7][0,7], etc.
  96967. */
  96968. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96969. /*
  96970. * FLAC__lpc_quantize_coefficients()
  96971. * --------------------------------------------------------------------
  96972. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96973. * must be less than 32 (sizeof(FLAC__int32)*8).
  96974. *
  96975. * IN lp_coeff[0,order-1] LP coefficients
  96976. * IN order LP order
  96977. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96978. * desired precision (in bits, including sign
  96979. * bit) of largest coefficient
  96980. * OUT qlp_coeff[0,order-1] quantized coefficients
  96981. * OUT shift # of bits to shift right to get approximated
  96982. * LP coefficients. NOTE: could be negative.
  96983. * RETURN 0 => quantization OK
  96984. * 1 => coefficients require too much shifting for *shift to
  96985. * fit in the LPC subframe header. 'shift' is unset.
  96986. * 2 => coefficients are all zero, which is bad. 'shift' is
  96987. * unset.
  96988. */
  96989. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96990. /*
  96991. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96992. * --------------------------------------------------------------------
  96993. * Compute the residual signal obtained from sutracting the predicted
  96994. * signal from the original.
  96995. *
  96996. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96997. * IN data_len length of original signal
  96998. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96999. * IN order > 0 LP order
  97000. * IN lp_quantization quantization of LP coefficients in bits
  97001. * OUT residual[0,data_len-1] residual signal
  97002. */
  97003. 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[]);
  97004. 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[]);
  97005. #ifndef FLAC__NO_ASM
  97006. # ifdef FLAC__CPU_IA32
  97007. # ifdef FLAC__HAS_NASM
  97008. 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[]);
  97009. 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[]);
  97010. # endif
  97011. # endif
  97012. #endif
  97013. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97014. /*
  97015. * FLAC__lpc_restore_signal()
  97016. * --------------------------------------------------------------------
  97017. * Restore the original signal by summing the residual and the
  97018. * predictor.
  97019. *
  97020. * IN residual[0,data_len-1] residual signal
  97021. * IN data_len length of original signal
  97022. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97023. * IN order > 0 LP order
  97024. * IN lp_quantization quantization of LP coefficients in bits
  97025. * *** IMPORTANT: the caller must pass in the historical samples:
  97026. * IN data[-order,-1] previously-reconstructed historical samples
  97027. * OUT data[0,data_len-1] original signal
  97028. */
  97029. 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[]);
  97030. 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[]);
  97031. #ifndef FLAC__NO_ASM
  97032. # ifdef FLAC__CPU_IA32
  97033. # ifdef FLAC__HAS_NASM
  97034. 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[]);
  97035. 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[]);
  97036. # endif /* FLAC__HAS_NASM */
  97037. # elif defined FLAC__CPU_PPC
  97038. 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[]);
  97039. 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[]);
  97040. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97041. #endif /* FLAC__NO_ASM */
  97042. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97043. /*
  97044. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97045. * --------------------------------------------------------------------
  97046. * Compute the expected number of bits per residual signal sample
  97047. * based on the LP error (which is related to the residual variance).
  97048. *
  97049. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97050. * IN total_samples > 0 # of samples in residual signal
  97051. * RETURN expected bits per sample
  97052. */
  97053. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97054. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97055. /*
  97056. * FLAC__lpc_compute_best_order()
  97057. * --------------------------------------------------------------------
  97058. * Compute the best order from the array of signal errors returned
  97059. * during coefficient computation.
  97060. *
  97061. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97062. * IN max_order > 0 max LP order
  97063. * IN total_samples > 0 # of samples in residual signal
  97064. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97065. * (includes warmup sample size and quantized LP coefficient)
  97066. * RETURN [1,max_order] best order
  97067. */
  97068. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97069. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97070. #endif
  97071. /*** End of inlined file: lpc.h ***/
  97072. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97073. #include <stdio.h>
  97074. #endif
  97075. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97076. #ifndef M_LN2
  97077. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97078. #define M_LN2 0.69314718055994530942
  97079. #endif
  97080. /* OPT: #undef'ing this may improve the speed on some architectures */
  97081. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97082. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97083. {
  97084. unsigned i;
  97085. for(i = 0; i < data_len; i++)
  97086. out[i] = in[i] * window[i];
  97087. }
  97088. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97089. {
  97090. /* a readable, but slower, version */
  97091. #if 0
  97092. FLAC__real d;
  97093. unsigned i;
  97094. FLAC__ASSERT(lag > 0);
  97095. FLAC__ASSERT(lag <= data_len);
  97096. /*
  97097. * Technically we should subtract the mean first like so:
  97098. * for(i = 0; i < data_len; i++)
  97099. * data[i] -= mean;
  97100. * but it appears not to make enough of a difference to matter, and
  97101. * most signals are already closely centered around zero
  97102. */
  97103. while(lag--) {
  97104. for(i = lag, d = 0.0; i < data_len; i++)
  97105. d += data[i] * data[i - lag];
  97106. autoc[lag] = d;
  97107. }
  97108. #endif
  97109. /*
  97110. * this version tends to run faster because of better data locality
  97111. * ('data_len' is usually much larger than 'lag')
  97112. */
  97113. FLAC__real d;
  97114. unsigned sample, coeff;
  97115. const unsigned limit = data_len - lag;
  97116. FLAC__ASSERT(lag > 0);
  97117. FLAC__ASSERT(lag <= data_len);
  97118. for(coeff = 0; coeff < lag; coeff++)
  97119. autoc[coeff] = 0.0;
  97120. for(sample = 0; sample <= limit; sample++) {
  97121. d = data[sample];
  97122. for(coeff = 0; coeff < lag; coeff++)
  97123. autoc[coeff] += d * data[sample+coeff];
  97124. }
  97125. for(; sample < data_len; sample++) {
  97126. d = data[sample];
  97127. for(coeff = 0; coeff < data_len - sample; coeff++)
  97128. autoc[coeff] += d * data[sample+coeff];
  97129. }
  97130. }
  97131. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97132. {
  97133. unsigned i, j;
  97134. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97135. FLAC__ASSERT(0 != max_order);
  97136. FLAC__ASSERT(0 < *max_order);
  97137. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97138. FLAC__ASSERT(autoc[0] != 0.0);
  97139. err = autoc[0];
  97140. for(i = 0; i < *max_order; i++) {
  97141. /* Sum up this iteration's reflection coefficient. */
  97142. r = -autoc[i+1];
  97143. for(j = 0; j < i; j++)
  97144. r -= lpc[j] * autoc[i-j];
  97145. ref[i] = (r/=err);
  97146. /* Update LPC coefficients and total error. */
  97147. lpc[i]=r;
  97148. for(j = 0; j < (i>>1); j++) {
  97149. FLAC__double tmp = lpc[j];
  97150. lpc[j] += r * lpc[i-1-j];
  97151. lpc[i-1-j] += r * tmp;
  97152. }
  97153. if(i & 1)
  97154. lpc[j] += lpc[j] * r;
  97155. err *= (1.0 - r * r);
  97156. /* save this order */
  97157. for(j = 0; j <= i; j++)
  97158. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97159. error[i] = err;
  97160. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97161. if(err == 0.0) {
  97162. *max_order = i+1;
  97163. return;
  97164. }
  97165. }
  97166. }
  97167. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97168. {
  97169. unsigned i;
  97170. FLAC__double cmax;
  97171. FLAC__int32 qmax, qmin;
  97172. FLAC__ASSERT(precision > 0);
  97173. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97174. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97175. precision--;
  97176. qmax = 1 << precision;
  97177. qmin = -qmax;
  97178. qmax--;
  97179. /* calc cmax = max( |lp_coeff[i]| ) */
  97180. cmax = 0.0;
  97181. for(i = 0; i < order; i++) {
  97182. const FLAC__double d = fabs(lp_coeff[i]);
  97183. if(d > cmax)
  97184. cmax = d;
  97185. }
  97186. if(cmax <= 0.0) {
  97187. /* => coefficients are all 0, which means our constant-detect didn't work */
  97188. return 2;
  97189. }
  97190. else {
  97191. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97192. const int min_shiftlimit = -max_shiftlimit - 1;
  97193. int log2cmax;
  97194. (void)frexp(cmax, &log2cmax);
  97195. log2cmax--;
  97196. *shift = (int)precision - log2cmax - 1;
  97197. if(*shift > max_shiftlimit)
  97198. *shift = max_shiftlimit;
  97199. else if(*shift < min_shiftlimit)
  97200. return 1;
  97201. }
  97202. if(*shift >= 0) {
  97203. FLAC__double error = 0.0;
  97204. FLAC__int32 q;
  97205. for(i = 0; i < order; i++) {
  97206. error += lp_coeff[i] * (1 << *shift);
  97207. #if 1 /* unfortunately lround() is C99 */
  97208. if(error >= 0.0)
  97209. q = (FLAC__int32)(error + 0.5);
  97210. else
  97211. q = (FLAC__int32)(error - 0.5);
  97212. #else
  97213. q = lround(error);
  97214. #endif
  97215. #ifdef FLAC__OVERFLOW_DETECT
  97216. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97217. 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]);
  97218. else if(q < qmin)
  97219. 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]);
  97220. #endif
  97221. if(q > qmax)
  97222. q = qmax;
  97223. else if(q < qmin)
  97224. q = qmin;
  97225. error -= q;
  97226. qlp_coeff[i] = q;
  97227. }
  97228. }
  97229. /* negative shift is very rare but due to design flaw, negative shift is
  97230. * a NOP in the decoder, so it must be handled specially by scaling down
  97231. * coeffs
  97232. */
  97233. else {
  97234. const int nshift = -(*shift);
  97235. FLAC__double error = 0.0;
  97236. FLAC__int32 q;
  97237. #ifdef DEBUG
  97238. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97239. #endif
  97240. for(i = 0; i < order; i++) {
  97241. error += lp_coeff[i] / (1 << nshift);
  97242. #if 1 /* unfortunately lround() is C99 */
  97243. if(error >= 0.0)
  97244. q = (FLAC__int32)(error + 0.5);
  97245. else
  97246. q = (FLAC__int32)(error - 0.5);
  97247. #else
  97248. q = lround(error);
  97249. #endif
  97250. #ifdef FLAC__OVERFLOW_DETECT
  97251. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97252. 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]);
  97253. else if(q < qmin)
  97254. 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]);
  97255. #endif
  97256. if(q > qmax)
  97257. q = qmax;
  97258. else if(q < qmin)
  97259. q = qmin;
  97260. error -= q;
  97261. qlp_coeff[i] = q;
  97262. }
  97263. *shift = 0;
  97264. }
  97265. return 0;
  97266. }
  97267. 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[])
  97268. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97269. {
  97270. FLAC__int64 sumo;
  97271. unsigned i, j;
  97272. FLAC__int32 sum;
  97273. const FLAC__int32 *history;
  97274. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97275. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97276. for(i=0;i<order;i++)
  97277. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97278. fprintf(stderr,"\n");
  97279. #endif
  97280. FLAC__ASSERT(order > 0);
  97281. for(i = 0; i < data_len; i++) {
  97282. sumo = 0;
  97283. sum = 0;
  97284. history = data;
  97285. for(j = 0; j < order; j++) {
  97286. sum += qlp_coeff[j] * (*(--history));
  97287. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97288. #if defined _MSC_VER
  97289. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97290. 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);
  97291. #else
  97292. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97293. 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);
  97294. #endif
  97295. }
  97296. *(residual++) = *(data++) - (sum >> lp_quantization);
  97297. }
  97298. /* Here's a slower but clearer version:
  97299. for(i = 0; i < data_len; i++) {
  97300. sum = 0;
  97301. for(j = 0; j < order; j++)
  97302. sum += qlp_coeff[j] * data[i-j-1];
  97303. residual[i] = data[i] - (sum >> lp_quantization);
  97304. }
  97305. */
  97306. }
  97307. #else /* fully unrolled version for normal use */
  97308. {
  97309. int i;
  97310. FLAC__int32 sum;
  97311. FLAC__ASSERT(order > 0);
  97312. FLAC__ASSERT(order <= 32);
  97313. /*
  97314. * We do unique versions up to 12th order since that's the subset limit.
  97315. * Also they are roughly ordered to match frequency of occurrence to
  97316. * minimize branching.
  97317. */
  97318. if(order <= 12) {
  97319. if(order > 8) {
  97320. if(order > 10) {
  97321. if(order == 12) {
  97322. for(i = 0; i < (int)data_len; i++) {
  97323. sum = 0;
  97324. sum += qlp_coeff[11] * data[i-12];
  97325. sum += qlp_coeff[10] * data[i-11];
  97326. sum += qlp_coeff[9] * data[i-10];
  97327. sum += qlp_coeff[8] * data[i-9];
  97328. sum += qlp_coeff[7] * data[i-8];
  97329. sum += qlp_coeff[6] * data[i-7];
  97330. sum += qlp_coeff[5] * data[i-6];
  97331. sum += qlp_coeff[4] * data[i-5];
  97332. sum += qlp_coeff[3] * data[i-4];
  97333. sum += qlp_coeff[2] * data[i-3];
  97334. sum += qlp_coeff[1] * data[i-2];
  97335. sum += qlp_coeff[0] * data[i-1];
  97336. residual[i] = data[i] - (sum >> lp_quantization);
  97337. }
  97338. }
  97339. else { /* order == 11 */
  97340. for(i = 0; i < (int)data_len; i++) {
  97341. sum = 0;
  97342. sum += qlp_coeff[10] * data[i-11];
  97343. sum += qlp_coeff[9] * data[i-10];
  97344. sum += qlp_coeff[8] * data[i-9];
  97345. sum += qlp_coeff[7] * data[i-8];
  97346. sum += qlp_coeff[6] * data[i-7];
  97347. sum += qlp_coeff[5] * data[i-6];
  97348. sum += qlp_coeff[4] * data[i-5];
  97349. sum += qlp_coeff[3] * data[i-4];
  97350. sum += qlp_coeff[2] * data[i-3];
  97351. sum += qlp_coeff[1] * data[i-2];
  97352. sum += qlp_coeff[0] * data[i-1];
  97353. residual[i] = data[i] - (sum >> lp_quantization);
  97354. }
  97355. }
  97356. }
  97357. else {
  97358. if(order == 10) {
  97359. for(i = 0; i < (int)data_len; i++) {
  97360. sum = 0;
  97361. sum += qlp_coeff[9] * data[i-10];
  97362. sum += qlp_coeff[8] * data[i-9];
  97363. sum += qlp_coeff[7] * data[i-8];
  97364. sum += qlp_coeff[6] * data[i-7];
  97365. sum += qlp_coeff[5] * data[i-6];
  97366. sum += qlp_coeff[4] * data[i-5];
  97367. sum += qlp_coeff[3] * data[i-4];
  97368. sum += qlp_coeff[2] * data[i-3];
  97369. sum += qlp_coeff[1] * data[i-2];
  97370. sum += qlp_coeff[0] * data[i-1];
  97371. residual[i] = data[i] - (sum >> lp_quantization);
  97372. }
  97373. }
  97374. else { /* order == 9 */
  97375. for(i = 0; i < (int)data_len; i++) {
  97376. sum = 0;
  97377. sum += qlp_coeff[8] * data[i-9];
  97378. sum += qlp_coeff[7] * data[i-8];
  97379. sum += qlp_coeff[6] * data[i-7];
  97380. sum += qlp_coeff[5] * data[i-6];
  97381. sum += qlp_coeff[4] * data[i-5];
  97382. sum += qlp_coeff[3] * data[i-4];
  97383. sum += qlp_coeff[2] * data[i-3];
  97384. sum += qlp_coeff[1] * data[i-2];
  97385. sum += qlp_coeff[0] * data[i-1];
  97386. residual[i] = data[i] - (sum >> lp_quantization);
  97387. }
  97388. }
  97389. }
  97390. }
  97391. else if(order > 4) {
  97392. if(order > 6) {
  97393. if(order == 8) {
  97394. for(i = 0; i < (int)data_len; i++) {
  97395. sum = 0;
  97396. sum += qlp_coeff[7] * data[i-8];
  97397. sum += qlp_coeff[6] * data[i-7];
  97398. sum += qlp_coeff[5] * data[i-6];
  97399. sum += qlp_coeff[4] * data[i-5];
  97400. sum += qlp_coeff[3] * data[i-4];
  97401. sum += qlp_coeff[2] * data[i-3];
  97402. sum += qlp_coeff[1] * data[i-2];
  97403. sum += qlp_coeff[0] * data[i-1];
  97404. residual[i] = data[i] - (sum >> lp_quantization);
  97405. }
  97406. }
  97407. else { /* order == 7 */
  97408. for(i = 0; i < (int)data_len; i++) {
  97409. sum = 0;
  97410. sum += qlp_coeff[6] * data[i-7];
  97411. sum += qlp_coeff[5] * data[i-6];
  97412. sum += qlp_coeff[4] * data[i-5];
  97413. sum += qlp_coeff[3] * data[i-4];
  97414. sum += qlp_coeff[2] * data[i-3];
  97415. sum += qlp_coeff[1] * data[i-2];
  97416. sum += qlp_coeff[0] * data[i-1];
  97417. residual[i] = data[i] - (sum >> lp_quantization);
  97418. }
  97419. }
  97420. }
  97421. else {
  97422. if(order == 6) {
  97423. for(i = 0; i < (int)data_len; i++) {
  97424. sum = 0;
  97425. sum += qlp_coeff[5] * data[i-6];
  97426. sum += qlp_coeff[4] * data[i-5];
  97427. sum += qlp_coeff[3] * data[i-4];
  97428. sum += qlp_coeff[2] * data[i-3];
  97429. sum += qlp_coeff[1] * data[i-2];
  97430. sum += qlp_coeff[0] * data[i-1];
  97431. residual[i] = data[i] - (sum >> lp_quantization);
  97432. }
  97433. }
  97434. else { /* order == 5 */
  97435. for(i = 0; i < (int)data_len; i++) {
  97436. sum = 0;
  97437. sum += qlp_coeff[4] * data[i-5];
  97438. sum += qlp_coeff[3] * data[i-4];
  97439. sum += qlp_coeff[2] * data[i-3];
  97440. sum += qlp_coeff[1] * data[i-2];
  97441. sum += qlp_coeff[0] * data[i-1];
  97442. residual[i] = data[i] - (sum >> lp_quantization);
  97443. }
  97444. }
  97445. }
  97446. }
  97447. else {
  97448. if(order > 2) {
  97449. if(order == 4) {
  97450. for(i = 0; i < (int)data_len; i++) {
  97451. sum = 0;
  97452. sum += qlp_coeff[3] * data[i-4];
  97453. sum += qlp_coeff[2] * data[i-3];
  97454. sum += qlp_coeff[1] * data[i-2];
  97455. sum += qlp_coeff[0] * data[i-1];
  97456. residual[i] = data[i] - (sum >> lp_quantization);
  97457. }
  97458. }
  97459. else { /* order == 3 */
  97460. for(i = 0; i < (int)data_len; i++) {
  97461. sum = 0;
  97462. sum += qlp_coeff[2] * data[i-3];
  97463. sum += qlp_coeff[1] * data[i-2];
  97464. sum += qlp_coeff[0] * data[i-1];
  97465. residual[i] = data[i] - (sum >> lp_quantization);
  97466. }
  97467. }
  97468. }
  97469. else {
  97470. if(order == 2) {
  97471. for(i = 0; i < (int)data_len; i++) {
  97472. sum = 0;
  97473. sum += qlp_coeff[1] * data[i-2];
  97474. sum += qlp_coeff[0] * data[i-1];
  97475. residual[i] = data[i] - (sum >> lp_quantization);
  97476. }
  97477. }
  97478. else { /* order == 1 */
  97479. for(i = 0; i < (int)data_len; i++)
  97480. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97481. }
  97482. }
  97483. }
  97484. }
  97485. else { /* order > 12 */
  97486. for(i = 0; i < (int)data_len; i++) {
  97487. sum = 0;
  97488. switch(order) {
  97489. case 32: sum += qlp_coeff[31] * data[i-32];
  97490. case 31: sum += qlp_coeff[30] * data[i-31];
  97491. case 30: sum += qlp_coeff[29] * data[i-30];
  97492. case 29: sum += qlp_coeff[28] * data[i-29];
  97493. case 28: sum += qlp_coeff[27] * data[i-28];
  97494. case 27: sum += qlp_coeff[26] * data[i-27];
  97495. case 26: sum += qlp_coeff[25] * data[i-26];
  97496. case 25: sum += qlp_coeff[24] * data[i-25];
  97497. case 24: sum += qlp_coeff[23] * data[i-24];
  97498. case 23: sum += qlp_coeff[22] * data[i-23];
  97499. case 22: sum += qlp_coeff[21] * data[i-22];
  97500. case 21: sum += qlp_coeff[20] * data[i-21];
  97501. case 20: sum += qlp_coeff[19] * data[i-20];
  97502. case 19: sum += qlp_coeff[18] * data[i-19];
  97503. case 18: sum += qlp_coeff[17] * data[i-18];
  97504. case 17: sum += qlp_coeff[16] * data[i-17];
  97505. case 16: sum += qlp_coeff[15] * data[i-16];
  97506. case 15: sum += qlp_coeff[14] * data[i-15];
  97507. case 14: sum += qlp_coeff[13] * data[i-14];
  97508. case 13: sum += qlp_coeff[12] * data[i-13];
  97509. sum += qlp_coeff[11] * data[i-12];
  97510. sum += qlp_coeff[10] * data[i-11];
  97511. sum += qlp_coeff[ 9] * data[i-10];
  97512. sum += qlp_coeff[ 8] * data[i- 9];
  97513. sum += qlp_coeff[ 7] * data[i- 8];
  97514. sum += qlp_coeff[ 6] * data[i- 7];
  97515. sum += qlp_coeff[ 5] * data[i- 6];
  97516. sum += qlp_coeff[ 4] * data[i- 5];
  97517. sum += qlp_coeff[ 3] * data[i- 4];
  97518. sum += qlp_coeff[ 2] * data[i- 3];
  97519. sum += qlp_coeff[ 1] * data[i- 2];
  97520. sum += qlp_coeff[ 0] * data[i- 1];
  97521. }
  97522. residual[i] = data[i] - (sum >> lp_quantization);
  97523. }
  97524. }
  97525. }
  97526. #endif
  97527. 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[])
  97528. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97529. {
  97530. unsigned i, j;
  97531. FLAC__int64 sum;
  97532. const FLAC__int32 *history;
  97533. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97534. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97535. for(i=0;i<order;i++)
  97536. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97537. fprintf(stderr,"\n");
  97538. #endif
  97539. FLAC__ASSERT(order > 0);
  97540. for(i = 0; i < data_len; i++) {
  97541. sum = 0;
  97542. history = data;
  97543. for(j = 0; j < order; j++)
  97544. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97545. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97546. #if defined _MSC_VER
  97547. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97548. #else
  97549. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97550. #endif
  97551. break;
  97552. }
  97553. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97554. #if defined _MSC_VER
  97555. 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));
  97556. #else
  97557. 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)));
  97558. #endif
  97559. break;
  97560. }
  97561. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97562. }
  97563. }
  97564. #else /* fully unrolled version for normal use */
  97565. {
  97566. int i;
  97567. FLAC__int64 sum;
  97568. FLAC__ASSERT(order > 0);
  97569. FLAC__ASSERT(order <= 32);
  97570. /*
  97571. * We do unique versions up to 12th order since that's the subset limit.
  97572. * Also they are roughly ordered to match frequency of occurrence to
  97573. * minimize branching.
  97574. */
  97575. if(order <= 12) {
  97576. if(order > 8) {
  97577. if(order > 10) {
  97578. if(order == 12) {
  97579. for(i = 0; i < (int)data_len; i++) {
  97580. sum = 0;
  97581. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97582. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97583. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97584. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97585. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97586. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97587. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97588. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97589. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97590. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97591. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97592. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97593. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97594. }
  97595. }
  97596. else { /* order == 11 */
  97597. for(i = 0; i < (int)data_len; i++) {
  97598. sum = 0;
  97599. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97600. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97601. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97602. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97603. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97604. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97605. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97606. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97607. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97608. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97609. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97610. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97611. }
  97612. }
  97613. }
  97614. else {
  97615. if(order == 10) {
  97616. for(i = 0; i < (int)data_len; i++) {
  97617. sum = 0;
  97618. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97619. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97620. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97621. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97622. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97623. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97624. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97625. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97626. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97627. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97628. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97629. }
  97630. }
  97631. else { /* order == 9 */
  97632. for(i = 0; i < (int)data_len; i++) {
  97633. sum = 0;
  97634. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97635. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97636. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97637. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97638. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97639. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97640. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97641. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97642. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97643. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97644. }
  97645. }
  97646. }
  97647. }
  97648. else if(order > 4) {
  97649. if(order > 6) {
  97650. if(order == 8) {
  97651. for(i = 0; i < (int)data_len; i++) {
  97652. sum = 0;
  97653. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97654. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97655. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97656. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97657. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97658. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97659. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97660. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97661. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97662. }
  97663. }
  97664. else { /* order == 7 */
  97665. for(i = 0; i < (int)data_len; i++) {
  97666. sum = 0;
  97667. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97668. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97669. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97670. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97671. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97672. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97673. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97674. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97675. }
  97676. }
  97677. }
  97678. else {
  97679. if(order == 6) {
  97680. for(i = 0; i < (int)data_len; i++) {
  97681. sum = 0;
  97682. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97683. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97684. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97685. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97686. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97687. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97688. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97689. }
  97690. }
  97691. else { /* order == 5 */
  97692. for(i = 0; i < (int)data_len; i++) {
  97693. sum = 0;
  97694. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97695. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97696. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97697. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97698. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97699. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97700. }
  97701. }
  97702. }
  97703. }
  97704. else {
  97705. if(order > 2) {
  97706. if(order == 4) {
  97707. for(i = 0; i < (int)data_len; i++) {
  97708. sum = 0;
  97709. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97710. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97711. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97712. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97713. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97714. }
  97715. }
  97716. else { /* order == 3 */
  97717. for(i = 0; i < (int)data_len; i++) {
  97718. sum = 0;
  97719. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97720. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97721. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97722. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97723. }
  97724. }
  97725. }
  97726. else {
  97727. if(order == 2) {
  97728. for(i = 0; i < (int)data_len; i++) {
  97729. sum = 0;
  97730. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97731. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97732. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97733. }
  97734. }
  97735. else { /* order == 1 */
  97736. for(i = 0; i < (int)data_len; i++)
  97737. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97738. }
  97739. }
  97740. }
  97741. }
  97742. else { /* order > 12 */
  97743. for(i = 0; i < (int)data_len; i++) {
  97744. sum = 0;
  97745. switch(order) {
  97746. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97747. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97748. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97749. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97750. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97751. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97752. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97753. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97754. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97755. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97756. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97757. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97758. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97759. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97760. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97761. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97762. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97763. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97764. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97765. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97766. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97767. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97768. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97769. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97770. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97771. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97772. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97773. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97774. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97775. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97776. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97777. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97778. }
  97779. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97780. }
  97781. }
  97782. }
  97783. #endif
  97784. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97785. 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[])
  97786. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97787. {
  97788. FLAC__int64 sumo;
  97789. unsigned i, j;
  97790. FLAC__int32 sum;
  97791. const FLAC__int32 *r = residual, *history;
  97792. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97793. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97794. for(i=0;i<order;i++)
  97795. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97796. fprintf(stderr,"\n");
  97797. #endif
  97798. FLAC__ASSERT(order > 0);
  97799. for(i = 0; i < data_len; i++) {
  97800. sumo = 0;
  97801. sum = 0;
  97802. history = data;
  97803. for(j = 0; j < order; j++) {
  97804. sum += qlp_coeff[j] * (*(--history));
  97805. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97806. #if defined _MSC_VER
  97807. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97808. 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);
  97809. #else
  97810. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97811. 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);
  97812. #endif
  97813. }
  97814. *(data++) = *(r++) + (sum >> lp_quantization);
  97815. }
  97816. /* Here's a slower but clearer version:
  97817. for(i = 0; i < data_len; i++) {
  97818. sum = 0;
  97819. for(j = 0; j < order; j++)
  97820. sum += qlp_coeff[j] * data[i-j-1];
  97821. data[i] = residual[i] + (sum >> lp_quantization);
  97822. }
  97823. */
  97824. }
  97825. #else /* fully unrolled version for normal use */
  97826. {
  97827. int i;
  97828. FLAC__int32 sum;
  97829. FLAC__ASSERT(order > 0);
  97830. FLAC__ASSERT(order <= 32);
  97831. /*
  97832. * We do unique versions up to 12th order since that's the subset limit.
  97833. * Also they are roughly ordered to match frequency of occurrence to
  97834. * minimize branching.
  97835. */
  97836. if(order <= 12) {
  97837. if(order > 8) {
  97838. if(order > 10) {
  97839. if(order == 12) {
  97840. for(i = 0; i < (int)data_len; i++) {
  97841. sum = 0;
  97842. sum += qlp_coeff[11] * data[i-12];
  97843. sum += qlp_coeff[10] * data[i-11];
  97844. sum += qlp_coeff[9] * data[i-10];
  97845. sum += qlp_coeff[8] * data[i-9];
  97846. sum += qlp_coeff[7] * data[i-8];
  97847. sum += qlp_coeff[6] * data[i-7];
  97848. sum += qlp_coeff[5] * data[i-6];
  97849. sum += qlp_coeff[4] * data[i-5];
  97850. sum += qlp_coeff[3] * data[i-4];
  97851. sum += qlp_coeff[2] * data[i-3];
  97852. sum += qlp_coeff[1] * data[i-2];
  97853. sum += qlp_coeff[0] * data[i-1];
  97854. data[i] = residual[i] + (sum >> lp_quantization);
  97855. }
  97856. }
  97857. else { /* order == 11 */
  97858. for(i = 0; i < (int)data_len; i++) {
  97859. sum = 0;
  97860. sum += qlp_coeff[10] * data[i-11];
  97861. sum += qlp_coeff[9] * data[i-10];
  97862. sum += qlp_coeff[8] * data[i-9];
  97863. sum += qlp_coeff[7] * data[i-8];
  97864. sum += qlp_coeff[6] * data[i-7];
  97865. sum += qlp_coeff[5] * data[i-6];
  97866. sum += qlp_coeff[4] * data[i-5];
  97867. sum += qlp_coeff[3] * data[i-4];
  97868. sum += qlp_coeff[2] * data[i-3];
  97869. sum += qlp_coeff[1] * data[i-2];
  97870. sum += qlp_coeff[0] * data[i-1];
  97871. data[i] = residual[i] + (sum >> lp_quantization);
  97872. }
  97873. }
  97874. }
  97875. else {
  97876. if(order == 10) {
  97877. for(i = 0; i < (int)data_len; i++) {
  97878. sum = 0;
  97879. sum += qlp_coeff[9] * data[i-10];
  97880. sum += qlp_coeff[8] * data[i-9];
  97881. sum += qlp_coeff[7] * data[i-8];
  97882. sum += qlp_coeff[6] * data[i-7];
  97883. sum += qlp_coeff[5] * data[i-6];
  97884. sum += qlp_coeff[4] * data[i-5];
  97885. sum += qlp_coeff[3] * data[i-4];
  97886. sum += qlp_coeff[2] * data[i-3];
  97887. sum += qlp_coeff[1] * data[i-2];
  97888. sum += qlp_coeff[0] * data[i-1];
  97889. data[i] = residual[i] + (sum >> lp_quantization);
  97890. }
  97891. }
  97892. else { /* order == 9 */
  97893. for(i = 0; i < (int)data_len; i++) {
  97894. sum = 0;
  97895. sum += qlp_coeff[8] * data[i-9];
  97896. sum += qlp_coeff[7] * data[i-8];
  97897. sum += qlp_coeff[6] * data[i-7];
  97898. sum += qlp_coeff[5] * data[i-6];
  97899. sum += qlp_coeff[4] * data[i-5];
  97900. sum += qlp_coeff[3] * data[i-4];
  97901. sum += qlp_coeff[2] * data[i-3];
  97902. sum += qlp_coeff[1] * data[i-2];
  97903. sum += qlp_coeff[0] * data[i-1];
  97904. data[i] = residual[i] + (sum >> lp_quantization);
  97905. }
  97906. }
  97907. }
  97908. }
  97909. else if(order > 4) {
  97910. if(order > 6) {
  97911. if(order == 8) {
  97912. for(i = 0; i < (int)data_len; i++) {
  97913. sum = 0;
  97914. sum += qlp_coeff[7] * data[i-8];
  97915. sum += qlp_coeff[6] * data[i-7];
  97916. sum += qlp_coeff[5] * data[i-6];
  97917. sum += qlp_coeff[4] * data[i-5];
  97918. sum += qlp_coeff[3] * data[i-4];
  97919. sum += qlp_coeff[2] * data[i-3];
  97920. sum += qlp_coeff[1] * data[i-2];
  97921. sum += qlp_coeff[0] * data[i-1];
  97922. data[i] = residual[i] + (sum >> lp_quantization);
  97923. }
  97924. }
  97925. else { /* order == 7 */
  97926. for(i = 0; i < (int)data_len; i++) {
  97927. sum = 0;
  97928. sum += qlp_coeff[6] * data[i-7];
  97929. sum += qlp_coeff[5] * data[i-6];
  97930. sum += qlp_coeff[4] * data[i-5];
  97931. sum += qlp_coeff[3] * data[i-4];
  97932. sum += qlp_coeff[2] * data[i-3];
  97933. sum += qlp_coeff[1] * data[i-2];
  97934. sum += qlp_coeff[0] * data[i-1];
  97935. data[i] = residual[i] + (sum >> lp_quantization);
  97936. }
  97937. }
  97938. }
  97939. else {
  97940. if(order == 6) {
  97941. for(i = 0; i < (int)data_len; i++) {
  97942. sum = 0;
  97943. sum += qlp_coeff[5] * data[i-6];
  97944. sum += qlp_coeff[4] * data[i-5];
  97945. sum += qlp_coeff[3] * data[i-4];
  97946. sum += qlp_coeff[2] * data[i-3];
  97947. sum += qlp_coeff[1] * data[i-2];
  97948. sum += qlp_coeff[0] * data[i-1];
  97949. data[i] = residual[i] + (sum >> lp_quantization);
  97950. }
  97951. }
  97952. else { /* order == 5 */
  97953. for(i = 0; i < (int)data_len; i++) {
  97954. sum = 0;
  97955. sum += qlp_coeff[4] * data[i-5];
  97956. sum += qlp_coeff[3] * data[i-4];
  97957. sum += qlp_coeff[2] * data[i-3];
  97958. sum += qlp_coeff[1] * data[i-2];
  97959. sum += qlp_coeff[0] * data[i-1];
  97960. data[i] = residual[i] + (sum >> lp_quantization);
  97961. }
  97962. }
  97963. }
  97964. }
  97965. else {
  97966. if(order > 2) {
  97967. if(order == 4) {
  97968. for(i = 0; i < (int)data_len; i++) {
  97969. sum = 0;
  97970. sum += qlp_coeff[3] * data[i-4];
  97971. sum += qlp_coeff[2] * data[i-3];
  97972. sum += qlp_coeff[1] * data[i-2];
  97973. sum += qlp_coeff[0] * data[i-1];
  97974. data[i] = residual[i] + (sum >> lp_quantization);
  97975. }
  97976. }
  97977. else { /* order == 3 */
  97978. for(i = 0; i < (int)data_len; i++) {
  97979. sum = 0;
  97980. sum += qlp_coeff[2] * data[i-3];
  97981. sum += qlp_coeff[1] * data[i-2];
  97982. sum += qlp_coeff[0] * data[i-1];
  97983. data[i] = residual[i] + (sum >> lp_quantization);
  97984. }
  97985. }
  97986. }
  97987. else {
  97988. if(order == 2) {
  97989. for(i = 0; i < (int)data_len; i++) {
  97990. sum = 0;
  97991. sum += qlp_coeff[1] * data[i-2];
  97992. sum += qlp_coeff[0] * data[i-1];
  97993. data[i] = residual[i] + (sum >> lp_quantization);
  97994. }
  97995. }
  97996. else { /* order == 1 */
  97997. for(i = 0; i < (int)data_len; i++)
  97998. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97999. }
  98000. }
  98001. }
  98002. }
  98003. else { /* order > 12 */
  98004. for(i = 0; i < (int)data_len; i++) {
  98005. sum = 0;
  98006. switch(order) {
  98007. case 32: sum += qlp_coeff[31] * data[i-32];
  98008. case 31: sum += qlp_coeff[30] * data[i-31];
  98009. case 30: sum += qlp_coeff[29] * data[i-30];
  98010. case 29: sum += qlp_coeff[28] * data[i-29];
  98011. case 28: sum += qlp_coeff[27] * data[i-28];
  98012. case 27: sum += qlp_coeff[26] * data[i-27];
  98013. case 26: sum += qlp_coeff[25] * data[i-26];
  98014. case 25: sum += qlp_coeff[24] * data[i-25];
  98015. case 24: sum += qlp_coeff[23] * data[i-24];
  98016. case 23: sum += qlp_coeff[22] * data[i-23];
  98017. case 22: sum += qlp_coeff[21] * data[i-22];
  98018. case 21: sum += qlp_coeff[20] * data[i-21];
  98019. case 20: sum += qlp_coeff[19] * data[i-20];
  98020. case 19: sum += qlp_coeff[18] * data[i-19];
  98021. case 18: sum += qlp_coeff[17] * data[i-18];
  98022. case 17: sum += qlp_coeff[16] * data[i-17];
  98023. case 16: sum += qlp_coeff[15] * data[i-16];
  98024. case 15: sum += qlp_coeff[14] * data[i-15];
  98025. case 14: sum += qlp_coeff[13] * data[i-14];
  98026. case 13: sum += qlp_coeff[12] * data[i-13];
  98027. sum += qlp_coeff[11] * data[i-12];
  98028. sum += qlp_coeff[10] * data[i-11];
  98029. sum += qlp_coeff[ 9] * data[i-10];
  98030. sum += qlp_coeff[ 8] * data[i- 9];
  98031. sum += qlp_coeff[ 7] * data[i- 8];
  98032. sum += qlp_coeff[ 6] * data[i- 7];
  98033. sum += qlp_coeff[ 5] * data[i- 6];
  98034. sum += qlp_coeff[ 4] * data[i- 5];
  98035. sum += qlp_coeff[ 3] * data[i- 4];
  98036. sum += qlp_coeff[ 2] * data[i- 3];
  98037. sum += qlp_coeff[ 1] * data[i- 2];
  98038. sum += qlp_coeff[ 0] * data[i- 1];
  98039. }
  98040. data[i] = residual[i] + (sum >> lp_quantization);
  98041. }
  98042. }
  98043. }
  98044. #endif
  98045. 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[])
  98046. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98047. {
  98048. unsigned i, j;
  98049. FLAC__int64 sum;
  98050. const FLAC__int32 *r = residual, *history;
  98051. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98052. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98053. for(i=0;i<order;i++)
  98054. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98055. fprintf(stderr,"\n");
  98056. #endif
  98057. FLAC__ASSERT(order > 0);
  98058. for(i = 0; i < data_len; i++) {
  98059. sum = 0;
  98060. history = data;
  98061. for(j = 0; j < order; j++)
  98062. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98063. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98064. #ifdef _MSC_VER
  98065. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98066. #else
  98067. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98068. #endif
  98069. break;
  98070. }
  98071. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98072. #ifdef _MSC_VER
  98073. 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));
  98074. #else
  98075. 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)));
  98076. #endif
  98077. break;
  98078. }
  98079. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98080. }
  98081. }
  98082. #else /* fully unrolled version for normal use */
  98083. {
  98084. int i;
  98085. FLAC__int64 sum;
  98086. FLAC__ASSERT(order > 0);
  98087. FLAC__ASSERT(order <= 32);
  98088. /*
  98089. * We do unique versions up to 12th order since that's the subset limit.
  98090. * Also they are roughly ordered to match frequency of occurrence to
  98091. * minimize branching.
  98092. */
  98093. if(order <= 12) {
  98094. if(order > 8) {
  98095. if(order > 10) {
  98096. if(order == 12) {
  98097. for(i = 0; i < (int)data_len; i++) {
  98098. sum = 0;
  98099. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98100. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98101. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98102. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98103. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98104. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98105. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98106. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98107. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98108. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98109. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98110. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98111. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98112. }
  98113. }
  98114. else { /* order == 11 */
  98115. for(i = 0; i < (int)data_len; i++) {
  98116. sum = 0;
  98117. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98118. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98119. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98120. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98121. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98122. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98123. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98124. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98125. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98126. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98127. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98128. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98129. }
  98130. }
  98131. }
  98132. else {
  98133. if(order == 10) {
  98134. for(i = 0; i < (int)data_len; i++) {
  98135. sum = 0;
  98136. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98137. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98138. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98139. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98140. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98141. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98142. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98143. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98144. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98145. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98146. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98147. }
  98148. }
  98149. else { /* order == 9 */
  98150. for(i = 0; i < (int)data_len; i++) {
  98151. sum = 0;
  98152. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98153. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98154. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98155. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98156. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98157. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98158. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98159. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98160. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98161. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98162. }
  98163. }
  98164. }
  98165. }
  98166. else if(order > 4) {
  98167. if(order > 6) {
  98168. if(order == 8) {
  98169. for(i = 0; i < (int)data_len; i++) {
  98170. sum = 0;
  98171. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98172. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98173. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98174. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98175. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98176. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98177. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98178. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98179. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98180. }
  98181. }
  98182. else { /* order == 7 */
  98183. for(i = 0; i < (int)data_len; i++) {
  98184. sum = 0;
  98185. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98186. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98187. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98188. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98189. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98190. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98191. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98192. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98193. }
  98194. }
  98195. }
  98196. else {
  98197. if(order == 6) {
  98198. for(i = 0; i < (int)data_len; i++) {
  98199. sum = 0;
  98200. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98201. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98202. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98203. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98204. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98205. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98206. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98207. }
  98208. }
  98209. else { /* order == 5 */
  98210. for(i = 0; i < (int)data_len; i++) {
  98211. sum = 0;
  98212. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98213. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98214. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98215. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98216. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98217. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98218. }
  98219. }
  98220. }
  98221. }
  98222. else {
  98223. if(order > 2) {
  98224. if(order == 4) {
  98225. for(i = 0; i < (int)data_len; i++) {
  98226. sum = 0;
  98227. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98228. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98229. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98230. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98231. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98232. }
  98233. }
  98234. else { /* order == 3 */
  98235. for(i = 0; i < (int)data_len; i++) {
  98236. sum = 0;
  98237. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98238. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98239. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98240. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98241. }
  98242. }
  98243. }
  98244. else {
  98245. if(order == 2) {
  98246. for(i = 0; i < (int)data_len; i++) {
  98247. sum = 0;
  98248. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98249. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98250. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98251. }
  98252. }
  98253. else { /* order == 1 */
  98254. for(i = 0; i < (int)data_len; i++)
  98255. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98256. }
  98257. }
  98258. }
  98259. }
  98260. else { /* order > 12 */
  98261. for(i = 0; i < (int)data_len; i++) {
  98262. sum = 0;
  98263. switch(order) {
  98264. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98265. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98266. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98267. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98268. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98269. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98270. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98271. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98272. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98273. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98274. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98275. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98276. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98277. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98278. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98279. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98280. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98281. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98282. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98283. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98284. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98285. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98286. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98287. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98288. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98289. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98290. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98291. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98292. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98293. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98294. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98295. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98296. }
  98297. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98298. }
  98299. }
  98300. }
  98301. #endif
  98302. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98303. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98304. {
  98305. FLAC__double error_scale;
  98306. FLAC__ASSERT(total_samples > 0);
  98307. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98308. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98309. }
  98310. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98311. {
  98312. if(lpc_error > 0.0) {
  98313. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98314. if(bps >= 0.0)
  98315. return bps;
  98316. else
  98317. return 0.0;
  98318. }
  98319. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98320. return 1e32;
  98321. }
  98322. else {
  98323. return 0.0;
  98324. }
  98325. }
  98326. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98327. {
  98328. 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 */
  98329. FLAC__double bits, best_bits, error_scale;
  98330. FLAC__ASSERT(max_order > 0);
  98331. FLAC__ASSERT(total_samples > 0);
  98332. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98333. best_index = 0;
  98334. best_bits = (unsigned)(-1);
  98335. for(index = 0, order = 1; index < max_order; index++, order++) {
  98336. 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);
  98337. if(bits < best_bits) {
  98338. best_index = index;
  98339. best_bits = bits;
  98340. }
  98341. }
  98342. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98343. }
  98344. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98345. #endif
  98346. /*** End of inlined file: lpc_flac.c ***/
  98347. /*** Start of inlined file: md5.c ***/
  98348. /*** Start of inlined file: juce_FlacHeader.h ***/
  98349. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98350. // tasks..
  98351. #define VERSION "1.2.1"
  98352. #define FLAC__NO_DLL 1
  98353. #if JUCE_MSVC
  98354. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98355. #endif
  98356. #if JUCE_MAC
  98357. #define FLAC__SYS_DARWIN 1
  98358. #endif
  98359. /*** End of inlined file: juce_FlacHeader.h ***/
  98360. #if JUCE_USE_FLAC
  98361. #if HAVE_CONFIG_H
  98362. # include <config.h>
  98363. #endif
  98364. #include <stdlib.h> /* for malloc() */
  98365. #include <string.h> /* for memcpy() */
  98366. /*** Start of inlined file: md5.h ***/
  98367. #ifndef FLAC__PRIVATE__MD5_H
  98368. #define FLAC__PRIVATE__MD5_H
  98369. /*
  98370. * This is the header file for the MD5 message-digest algorithm.
  98371. * The algorithm is due to Ron Rivest. This code was
  98372. * written by Colin Plumb in 1993, no copyright is claimed.
  98373. * This code is in the public domain; do with it what you wish.
  98374. *
  98375. * Equivalent code is available from RSA Data Security, Inc.
  98376. * This code has been tested against that, and is equivalent,
  98377. * except that you don't need to include two pages of legalese
  98378. * with every copy.
  98379. *
  98380. * To compute the message digest of a chunk of bytes, declare an
  98381. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98382. * needed on buffers full of bytes, and then call MD5Final, which
  98383. * will fill a supplied 16-byte array with the digest.
  98384. *
  98385. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98386. * header definitions; now uses stuff from dpkg's config.h
  98387. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98388. * Still in the public domain.
  98389. *
  98390. * Josh Coalson: made some changes to integrate with libFLAC.
  98391. * Still in the public domain, with no warranty.
  98392. */
  98393. typedef struct {
  98394. FLAC__uint32 in[16];
  98395. FLAC__uint32 buf[4];
  98396. FLAC__uint32 bytes[2];
  98397. FLAC__byte *internal_buf;
  98398. size_t capacity;
  98399. } FLAC__MD5Context;
  98400. void FLAC__MD5Init(FLAC__MD5Context *context);
  98401. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98402. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98403. #endif
  98404. /*** End of inlined file: md5.h ***/
  98405. #ifndef FLaC__INLINE
  98406. #define FLaC__INLINE
  98407. #endif
  98408. /*
  98409. * This code implements the MD5 message-digest algorithm.
  98410. * The algorithm is due to Ron Rivest. This code was
  98411. * written by Colin Plumb in 1993, no copyright is claimed.
  98412. * This code is in the public domain; do with it what you wish.
  98413. *
  98414. * Equivalent code is available from RSA Data Security, Inc.
  98415. * This code has been tested against that, and is equivalent,
  98416. * except that you don't need to include two pages of legalese
  98417. * with every copy.
  98418. *
  98419. * To compute the message digest of a chunk of bytes, declare an
  98420. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98421. * needed on buffers full of bytes, and then call MD5Final, which
  98422. * will fill a supplied 16-byte array with the digest.
  98423. *
  98424. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98425. * definitions; now uses stuff from dpkg's config.h.
  98426. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98427. * Still in the public domain.
  98428. *
  98429. * Josh Coalson: made some changes to integrate with libFLAC.
  98430. * Still in the public domain.
  98431. */
  98432. /* The four core functions - F1 is optimized somewhat */
  98433. /* #define F1(x, y, z) (x & y | ~x & z) */
  98434. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98435. #define F2(x, y, z) F1(z, x, y)
  98436. #define F3(x, y, z) (x ^ y ^ z)
  98437. #define F4(x, y, z) (y ^ (x | ~z))
  98438. /* This is the central step in the MD5 algorithm. */
  98439. #define MD5STEP(f,w,x,y,z,in,s) \
  98440. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98441. /*
  98442. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98443. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98444. * the data and converts bytes into longwords for this routine.
  98445. */
  98446. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98447. {
  98448. register FLAC__uint32 a, b, c, d;
  98449. a = buf[0];
  98450. b = buf[1];
  98451. c = buf[2];
  98452. d = buf[3];
  98453. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98454. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98455. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98456. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98457. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98458. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98459. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98460. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98461. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98462. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98463. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98464. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98465. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98466. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98467. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98468. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98469. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98470. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98471. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98472. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98473. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98474. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98475. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98476. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98477. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98478. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98479. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98480. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98481. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98482. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98483. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98484. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98485. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98486. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98487. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98488. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98489. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98490. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98491. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98492. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98493. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98494. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98495. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98496. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98497. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98498. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98499. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98500. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98501. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98502. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98503. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98504. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98505. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98506. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98507. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98508. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98509. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98510. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98511. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98512. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98513. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98514. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98515. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98516. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98517. buf[0] += a;
  98518. buf[1] += b;
  98519. buf[2] += c;
  98520. buf[3] += d;
  98521. }
  98522. #if WORDS_BIGENDIAN
  98523. //@@@@@@ OPT: use bswap/intrinsics
  98524. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98525. {
  98526. register FLAC__uint32 x;
  98527. do {
  98528. x = *buf;
  98529. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98530. *buf++ = (x >> 16) | (x << 16);
  98531. } while (--words);
  98532. }
  98533. static void byteSwapX16(FLAC__uint32 *buf)
  98534. {
  98535. register FLAC__uint32 x;
  98536. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98537. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98538. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98539. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98540. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98541. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98542. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98543. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98544. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98545. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98546. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98547. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98548. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98549. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98550. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98551. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98552. }
  98553. #else
  98554. #define byteSwap(buf, words)
  98555. #define byteSwapX16(buf)
  98556. #endif
  98557. /*
  98558. * Update context to reflect the concatenation of another buffer full
  98559. * of bytes.
  98560. */
  98561. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98562. {
  98563. FLAC__uint32 t;
  98564. /* Update byte count */
  98565. t = ctx->bytes[0];
  98566. if ((ctx->bytes[0] = t + len) < t)
  98567. ctx->bytes[1]++; /* Carry from low to high */
  98568. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98569. if (t > len) {
  98570. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98571. return;
  98572. }
  98573. /* First chunk is an odd size */
  98574. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98575. byteSwapX16(ctx->in);
  98576. FLAC__MD5Transform(ctx->buf, ctx->in);
  98577. buf += t;
  98578. len -= t;
  98579. /* Process data in 64-byte chunks */
  98580. while (len >= 64) {
  98581. memcpy(ctx->in, buf, 64);
  98582. byteSwapX16(ctx->in);
  98583. FLAC__MD5Transform(ctx->buf, ctx->in);
  98584. buf += 64;
  98585. len -= 64;
  98586. }
  98587. /* Handle any remaining bytes of data. */
  98588. memcpy(ctx->in, buf, len);
  98589. }
  98590. /*
  98591. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98592. * initialization constants.
  98593. */
  98594. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98595. {
  98596. ctx->buf[0] = 0x67452301;
  98597. ctx->buf[1] = 0xefcdab89;
  98598. ctx->buf[2] = 0x98badcfe;
  98599. ctx->buf[3] = 0x10325476;
  98600. ctx->bytes[0] = 0;
  98601. ctx->bytes[1] = 0;
  98602. ctx->internal_buf = 0;
  98603. ctx->capacity = 0;
  98604. }
  98605. /*
  98606. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98607. * 1 0* (64-bit count of bits processed, MSB-first)
  98608. */
  98609. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98610. {
  98611. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98612. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98613. /* Set the first char of padding to 0x80. There is always room. */
  98614. *p++ = 0x80;
  98615. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98616. count = 56 - 1 - count;
  98617. if (count < 0) { /* Padding forces an extra block */
  98618. memset(p, 0, count + 8);
  98619. byteSwapX16(ctx->in);
  98620. FLAC__MD5Transform(ctx->buf, ctx->in);
  98621. p = (FLAC__byte *)ctx->in;
  98622. count = 56;
  98623. }
  98624. memset(p, 0, count);
  98625. byteSwap(ctx->in, 14);
  98626. /* Append length in bits and transform */
  98627. ctx->in[14] = ctx->bytes[0] << 3;
  98628. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98629. FLAC__MD5Transform(ctx->buf, ctx->in);
  98630. byteSwap(ctx->buf, 4);
  98631. memcpy(digest, ctx->buf, 16);
  98632. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98633. if(0 != ctx->internal_buf) {
  98634. free(ctx->internal_buf);
  98635. ctx->internal_buf = 0;
  98636. ctx->capacity = 0;
  98637. }
  98638. }
  98639. /*
  98640. * Convert the incoming audio signal to a byte stream
  98641. */
  98642. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98643. {
  98644. unsigned channel, sample;
  98645. register FLAC__int32 a_word;
  98646. register FLAC__byte *buf_ = buf;
  98647. #if WORDS_BIGENDIAN
  98648. #else
  98649. if(channels == 2 && bytes_per_sample == 2) {
  98650. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98651. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98652. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98653. *buf1_ = (FLAC__int16)signal[1][sample];
  98654. }
  98655. else if(channels == 1 && bytes_per_sample == 2) {
  98656. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98657. for(sample = 0; sample < samples; sample++)
  98658. *buf1_++ = (FLAC__int16)signal[0][sample];
  98659. }
  98660. else
  98661. #endif
  98662. if(bytes_per_sample == 2) {
  98663. if(channels == 2) {
  98664. for(sample = 0; sample < samples; sample++) {
  98665. a_word = signal[0][sample];
  98666. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98667. *buf_++ = (FLAC__byte)a_word;
  98668. a_word = signal[1][sample];
  98669. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98670. *buf_++ = (FLAC__byte)a_word;
  98671. }
  98672. }
  98673. else if(channels == 1) {
  98674. for(sample = 0; sample < samples; sample++) {
  98675. a_word = signal[0][sample];
  98676. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98677. *buf_++ = (FLAC__byte)a_word;
  98678. }
  98679. }
  98680. else {
  98681. for(sample = 0; sample < samples; sample++) {
  98682. for(channel = 0; channel < channels; channel++) {
  98683. a_word = signal[channel][sample];
  98684. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98685. *buf_++ = (FLAC__byte)a_word;
  98686. }
  98687. }
  98688. }
  98689. }
  98690. else if(bytes_per_sample == 3) {
  98691. if(channels == 2) {
  98692. for(sample = 0; sample < samples; sample++) {
  98693. a_word = signal[0][sample];
  98694. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98695. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98696. *buf_++ = (FLAC__byte)a_word;
  98697. a_word = signal[1][sample];
  98698. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98699. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98700. *buf_++ = (FLAC__byte)a_word;
  98701. }
  98702. }
  98703. else if(channels == 1) {
  98704. for(sample = 0; sample < samples; sample++) {
  98705. a_word = signal[0][sample];
  98706. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98707. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98708. *buf_++ = (FLAC__byte)a_word;
  98709. }
  98710. }
  98711. else {
  98712. for(sample = 0; sample < samples; sample++) {
  98713. for(channel = 0; channel < channels; channel++) {
  98714. a_word = signal[channel][sample];
  98715. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98716. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98717. *buf_++ = (FLAC__byte)a_word;
  98718. }
  98719. }
  98720. }
  98721. }
  98722. else if(bytes_per_sample == 1) {
  98723. if(channels == 2) {
  98724. for(sample = 0; sample < samples; sample++) {
  98725. a_word = signal[0][sample];
  98726. *buf_++ = (FLAC__byte)a_word;
  98727. a_word = signal[1][sample];
  98728. *buf_++ = (FLAC__byte)a_word;
  98729. }
  98730. }
  98731. else if(channels == 1) {
  98732. for(sample = 0; sample < samples; sample++) {
  98733. a_word = signal[0][sample];
  98734. *buf_++ = (FLAC__byte)a_word;
  98735. }
  98736. }
  98737. else {
  98738. for(sample = 0; sample < samples; sample++) {
  98739. for(channel = 0; channel < channels; channel++) {
  98740. a_word = signal[channel][sample];
  98741. *buf_++ = (FLAC__byte)a_word;
  98742. }
  98743. }
  98744. }
  98745. }
  98746. else { /* bytes_per_sample == 4, maybe optimize more later */
  98747. for(sample = 0; sample < samples; sample++) {
  98748. for(channel = 0; channel < channels; channel++) {
  98749. a_word = signal[channel][sample];
  98750. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98751. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98752. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98753. *buf_++ = (FLAC__byte)a_word;
  98754. }
  98755. }
  98756. }
  98757. }
  98758. /*
  98759. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98760. */
  98761. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98762. {
  98763. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98764. /* overflow check */
  98765. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98766. return false;
  98767. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98768. return false;
  98769. if(ctx->capacity < bytes_needed) {
  98770. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98771. if(0 == tmp) {
  98772. free(ctx->internal_buf);
  98773. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98774. return false;
  98775. }
  98776. ctx->internal_buf = tmp;
  98777. ctx->capacity = bytes_needed;
  98778. }
  98779. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98780. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98781. return true;
  98782. }
  98783. #endif
  98784. /*** End of inlined file: md5.c ***/
  98785. /*** Start of inlined file: memory.c ***/
  98786. /*** Start of inlined file: juce_FlacHeader.h ***/
  98787. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98788. // tasks..
  98789. #define VERSION "1.2.1"
  98790. #define FLAC__NO_DLL 1
  98791. #if JUCE_MSVC
  98792. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98793. #endif
  98794. #if JUCE_MAC
  98795. #define FLAC__SYS_DARWIN 1
  98796. #endif
  98797. /*** End of inlined file: juce_FlacHeader.h ***/
  98798. #if JUCE_USE_FLAC
  98799. #if HAVE_CONFIG_H
  98800. # include <config.h>
  98801. #endif
  98802. /*** Start of inlined file: memory.h ***/
  98803. #ifndef FLAC__PRIVATE__MEMORY_H
  98804. #define FLAC__PRIVATE__MEMORY_H
  98805. #ifdef HAVE_CONFIG_H
  98806. #include <config.h>
  98807. #endif
  98808. #include <stdlib.h> /* for size_t */
  98809. /* Returns the unaligned address returned by malloc.
  98810. * Use free() on this address to deallocate.
  98811. */
  98812. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98813. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98814. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98815. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98816. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98817. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98818. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98819. #endif
  98820. #endif
  98821. /*** End of inlined file: memory.h ***/
  98822. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98823. {
  98824. void *x;
  98825. FLAC__ASSERT(0 != aligned_address);
  98826. #ifdef FLAC__ALIGN_MALLOC_DATA
  98827. /* align on 32-byte (256-bit) boundary */
  98828. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98829. #ifdef SIZEOF_VOIDP
  98830. #if SIZEOF_VOIDP == 4
  98831. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98832. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98833. #elif SIZEOF_VOIDP == 8
  98834. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98835. #else
  98836. # error Unsupported sizeof(void*)
  98837. #endif
  98838. #else
  98839. /* there's got to be a better way to do this right for all archs */
  98840. if(sizeof(void*) == sizeof(unsigned))
  98841. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98842. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98843. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98844. else
  98845. return 0;
  98846. #endif
  98847. #else
  98848. x = safe_malloc_(bytes);
  98849. *aligned_address = x;
  98850. #endif
  98851. return x;
  98852. }
  98853. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98854. {
  98855. FLAC__int32 *pu; /* unaligned pointer */
  98856. union { /* union needed to comply with C99 pointer aliasing rules */
  98857. FLAC__int32 *pa; /* aligned pointer */
  98858. void *pv; /* aligned pointer alias */
  98859. } u;
  98860. FLAC__ASSERT(elements > 0);
  98861. FLAC__ASSERT(0 != unaligned_pointer);
  98862. FLAC__ASSERT(0 != aligned_pointer);
  98863. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98864. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98865. if(0 == pu) {
  98866. return false;
  98867. }
  98868. else {
  98869. if(*unaligned_pointer != 0)
  98870. free(*unaligned_pointer);
  98871. *unaligned_pointer = pu;
  98872. *aligned_pointer = u.pa;
  98873. return true;
  98874. }
  98875. }
  98876. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98877. {
  98878. FLAC__uint32 *pu; /* unaligned pointer */
  98879. union { /* union needed to comply with C99 pointer aliasing rules */
  98880. FLAC__uint32 *pa; /* aligned pointer */
  98881. void *pv; /* aligned pointer alias */
  98882. } u;
  98883. FLAC__ASSERT(elements > 0);
  98884. FLAC__ASSERT(0 != unaligned_pointer);
  98885. FLAC__ASSERT(0 != aligned_pointer);
  98886. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98887. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98888. if(0 == pu) {
  98889. return false;
  98890. }
  98891. else {
  98892. if(*unaligned_pointer != 0)
  98893. free(*unaligned_pointer);
  98894. *unaligned_pointer = pu;
  98895. *aligned_pointer = u.pa;
  98896. return true;
  98897. }
  98898. }
  98899. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98900. {
  98901. FLAC__uint64 *pu; /* unaligned pointer */
  98902. union { /* union needed to comply with C99 pointer aliasing rules */
  98903. FLAC__uint64 *pa; /* aligned pointer */
  98904. void *pv; /* aligned pointer alias */
  98905. } u;
  98906. FLAC__ASSERT(elements > 0);
  98907. FLAC__ASSERT(0 != unaligned_pointer);
  98908. FLAC__ASSERT(0 != aligned_pointer);
  98909. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98910. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98911. if(0 == pu) {
  98912. return false;
  98913. }
  98914. else {
  98915. if(*unaligned_pointer != 0)
  98916. free(*unaligned_pointer);
  98917. *unaligned_pointer = pu;
  98918. *aligned_pointer = u.pa;
  98919. return true;
  98920. }
  98921. }
  98922. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98923. {
  98924. unsigned *pu; /* unaligned pointer */
  98925. union { /* union needed to comply with C99 pointer aliasing rules */
  98926. unsigned *pa; /* aligned pointer */
  98927. void *pv; /* aligned pointer alias */
  98928. } u;
  98929. FLAC__ASSERT(elements > 0);
  98930. FLAC__ASSERT(0 != unaligned_pointer);
  98931. FLAC__ASSERT(0 != aligned_pointer);
  98932. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98933. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98934. if(0 == pu) {
  98935. return false;
  98936. }
  98937. else {
  98938. if(*unaligned_pointer != 0)
  98939. free(*unaligned_pointer);
  98940. *unaligned_pointer = pu;
  98941. *aligned_pointer = u.pa;
  98942. return true;
  98943. }
  98944. }
  98945. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98946. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98947. {
  98948. FLAC__real *pu; /* unaligned pointer */
  98949. union { /* union needed to comply with C99 pointer aliasing rules */
  98950. FLAC__real *pa; /* aligned pointer */
  98951. void *pv; /* aligned pointer alias */
  98952. } u;
  98953. FLAC__ASSERT(elements > 0);
  98954. FLAC__ASSERT(0 != unaligned_pointer);
  98955. FLAC__ASSERT(0 != aligned_pointer);
  98956. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98957. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98958. if(0 == pu) {
  98959. return false;
  98960. }
  98961. else {
  98962. if(*unaligned_pointer != 0)
  98963. free(*unaligned_pointer);
  98964. *unaligned_pointer = pu;
  98965. *aligned_pointer = u.pa;
  98966. return true;
  98967. }
  98968. }
  98969. #endif
  98970. #endif
  98971. /*** End of inlined file: memory.c ***/
  98972. /*** Start of inlined file: stream_decoder.c ***/
  98973. /*** Start of inlined file: juce_FlacHeader.h ***/
  98974. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98975. // tasks..
  98976. #define VERSION "1.2.1"
  98977. #define FLAC__NO_DLL 1
  98978. #if JUCE_MSVC
  98979. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98980. #endif
  98981. #if JUCE_MAC
  98982. #define FLAC__SYS_DARWIN 1
  98983. #endif
  98984. /*** End of inlined file: juce_FlacHeader.h ***/
  98985. #if JUCE_USE_FLAC
  98986. #if HAVE_CONFIG_H
  98987. # include <config.h>
  98988. #endif
  98989. #if defined _MSC_VER || defined __MINGW32__
  98990. #include <io.h> /* for _setmode() */
  98991. #include <fcntl.h> /* for _O_BINARY */
  98992. #endif
  98993. #if defined __CYGWIN__ || defined __EMX__
  98994. #include <io.h> /* for setmode(), O_BINARY */
  98995. #include <fcntl.h> /* for _O_BINARY */
  98996. #endif
  98997. #include <stdio.h>
  98998. #include <stdlib.h> /* for malloc() */
  98999. #include <string.h> /* for memset/memcpy() */
  99000. #include <sys/stat.h> /* for stat() */
  99001. #include <sys/types.h> /* for off_t */
  99002. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99003. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99004. #define fseeko fseek
  99005. #define ftello ftell
  99006. #endif
  99007. #endif
  99008. /*** Start of inlined file: stream_decoder.h ***/
  99009. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99010. #define FLAC__PROTECTED__STREAM_DECODER_H
  99011. #if FLAC__HAS_OGG
  99012. #include "include/private/ogg_decoder_aspect.h"
  99013. #endif
  99014. typedef struct FLAC__StreamDecoderProtected {
  99015. FLAC__StreamDecoderState state;
  99016. unsigned channels;
  99017. FLAC__ChannelAssignment channel_assignment;
  99018. unsigned bits_per_sample;
  99019. unsigned sample_rate; /* in Hz */
  99020. unsigned blocksize; /* in samples (per channel) */
  99021. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99022. #if FLAC__HAS_OGG
  99023. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99024. #endif
  99025. } FLAC__StreamDecoderProtected;
  99026. /*
  99027. * return the number of input bytes consumed
  99028. */
  99029. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99030. #endif
  99031. /*** End of inlined file: stream_decoder.h ***/
  99032. #ifdef max
  99033. #undef max
  99034. #endif
  99035. #define max(a,b) ((a)>(b)?(a):(b))
  99036. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99037. #ifdef _MSC_VER
  99038. #define FLAC__U64L(x) x
  99039. #else
  99040. #define FLAC__U64L(x) x##LLU
  99041. #endif
  99042. /* technically this should be in an "export.c" but this is convenient enough */
  99043. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99044. #if FLAC__HAS_OGG
  99045. 1
  99046. #else
  99047. 0
  99048. #endif
  99049. ;
  99050. /***********************************************************************
  99051. *
  99052. * Private static data
  99053. *
  99054. ***********************************************************************/
  99055. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99056. /***********************************************************************
  99057. *
  99058. * Private class method prototypes
  99059. *
  99060. ***********************************************************************/
  99061. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99062. static FILE *get_binary_stdin_(void);
  99063. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99064. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99065. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99066. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99067. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99068. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99069. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99070. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99071. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99072. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99073. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99074. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99075. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99076. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99077. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99078. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99079. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99080. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99081. 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);
  99082. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99083. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99084. #if FLAC__HAS_OGG
  99085. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99086. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99087. #endif
  99088. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99089. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99090. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99091. #if FLAC__HAS_OGG
  99092. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99093. #endif
  99094. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99095. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99096. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99097. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99098. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99099. /***********************************************************************
  99100. *
  99101. * Private class data
  99102. *
  99103. ***********************************************************************/
  99104. typedef struct FLAC__StreamDecoderPrivate {
  99105. #if FLAC__HAS_OGG
  99106. FLAC__bool is_ogg;
  99107. #endif
  99108. FLAC__StreamDecoderReadCallback read_callback;
  99109. FLAC__StreamDecoderSeekCallback seek_callback;
  99110. FLAC__StreamDecoderTellCallback tell_callback;
  99111. FLAC__StreamDecoderLengthCallback length_callback;
  99112. FLAC__StreamDecoderEofCallback eof_callback;
  99113. FLAC__StreamDecoderWriteCallback write_callback;
  99114. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99115. FLAC__StreamDecoderErrorCallback error_callback;
  99116. /* generic 32-bit datapath: */
  99117. 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[]);
  99118. /* generic 64-bit datapath: */
  99119. 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[]);
  99120. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99121. 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[]);
  99122. /* 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: */
  99123. 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[]);
  99124. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99125. void *client_data;
  99126. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99127. FLAC__BitReader *input;
  99128. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99129. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99130. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99131. unsigned output_capacity, output_channels;
  99132. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99133. FLAC__uint64 samples_decoded;
  99134. FLAC__bool has_stream_info, has_seek_table;
  99135. FLAC__StreamMetadata stream_info;
  99136. FLAC__StreamMetadata seek_table;
  99137. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99138. FLAC__byte *metadata_filter_ids;
  99139. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99140. FLAC__Frame frame;
  99141. FLAC__bool cached; /* true if there is a byte in lookahead */
  99142. FLAC__CPUInfo cpuinfo;
  99143. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99144. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99145. /* unaligned (original) pointers to allocated data */
  99146. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99147. 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 */
  99148. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99149. FLAC__bool is_seeking;
  99150. FLAC__MD5Context md5context;
  99151. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99152. /* (the rest of these are only used for seeking) */
  99153. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99154. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99155. FLAC__uint64 target_sample;
  99156. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99157. #if FLAC__HAS_OGG
  99158. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99159. #endif
  99160. } FLAC__StreamDecoderPrivate;
  99161. /***********************************************************************
  99162. *
  99163. * Public static class data
  99164. *
  99165. ***********************************************************************/
  99166. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99167. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99168. "FLAC__STREAM_DECODER_READ_METADATA",
  99169. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99170. "FLAC__STREAM_DECODER_READ_FRAME",
  99171. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99172. "FLAC__STREAM_DECODER_OGG_ERROR",
  99173. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99174. "FLAC__STREAM_DECODER_ABORTED",
  99175. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99176. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99177. };
  99178. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99179. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99180. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99181. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99182. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99183. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99184. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99185. };
  99186. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99187. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99188. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99189. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99190. };
  99191. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99192. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99193. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99194. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99195. };
  99196. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99197. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99198. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99199. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99200. };
  99201. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99202. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99203. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99204. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99205. };
  99206. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99207. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99208. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99209. };
  99210. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99211. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99212. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99213. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99214. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99215. };
  99216. /***********************************************************************
  99217. *
  99218. * Class constructor/destructor
  99219. *
  99220. ***********************************************************************/
  99221. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99222. {
  99223. FLAC__StreamDecoder *decoder;
  99224. unsigned i;
  99225. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99226. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99227. if(decoder == 0) {
  99228. return 0;
  99229. }
  99230. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99231. if(decoder->protected_ == 0) {
  99232. free(decoder);
  99233. return 0;
  99234. }
  99235. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99236. if(decoder->private_ == 0) {
  99237. free(decoder->protected_);
  99238. free(decoder);
  99239. return 0;
  99240. }
  99241. decoder->private_->input = FLAC__bitreader_new();
  99242. if(decoder->private_->input == 0) {
  99243. free(decoder->private_);
  99244. free(decoder->protected_);
  99245. free(decoder);
  99246. return 0;
  99247. }
  99248. decoder->private_->metadata_filter_ids_capacity = 16;
  99249. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99250. FLAC__bitreader_delete(decoder->private_->input);
  99251. free(decoder->private_);
  99252. free(decoder->protected_);
  99253. free(decoder);
  99254. return 0;
  99255. }
  99256. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99257. decoder->private_->output[i] = 0;
  99258. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99259. }
  99260. decoder->private_->output_capacity = 0;
  99261. decoder->private_->output_channels = 0;
  99262. decoder->private_->has_seek_table = false;
  99263. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99264. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99265. decoder->private_->file = 0;
  99266. set_defaults_dec(decoder);
  99267. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99268. return decoder;
  99269. }
  99270. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99271. {
  99272. unsigned i;
  99273. FLAC__ASSERT(0 != decoder);
  99274. FLAC__ASSERT(0 != decoder->protected_);
  99275. FLAC__ASSERT(0 != decoder->private_);
  99276. FLAC__ASSERT(0 != decoder->private_->input);
  99277. (void)FLAC__stream_decoder_finish(decoder);
  99278. if(0 != decoder->private_->metadata_filter_ids)
  99279. free(decoder->private_->metadata_filter_ids);
  99280. FLAC__bitreader_delete(decoder->private_->input);
  99281. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99282. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99283. free(decoder->private_);
  99284. free(decoder->protected_);
  99285. free(decoder);
  99286. }
  99287. /***********************************************************************
  99288. *
  99289. * Public class methods
  99290. *
  99291. ***********************************************************************/
  99292. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99293. FLAC__StreamDecoder *decoder,
  99294. FLAC__StreamDecoderReadCallback read_callback,
  99295. FLAC__StreamDecoderSeekCallback seek_callback,
  99296. FLAC__StreamDecoderTellCallback tell_callback,
  99297. FLAC__StreamDecoderLengthCallback length_callback,
  99298. FLAC__StreamDecoderEofCallback eof_callback,
  99299. FLAC__StreamDecoderWriteCallback write_callback,
  99300. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99301. FLAC__StreamDecoderErrorCallback error_callback,
  99302. void *client_data,
  99303. FLAC__bool is_ogg
  99304. )
  99305. {
  99306. FLAC__ASSERT(0 != decoder);
  99307. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99308. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99309. #if !FLAC__HAS_OGG
  99310. if(is_ogg)
  99311. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99312. #endif
  99313. if(
  99314. 0 == read_callback ||
  99315. 0 == write_callback ||
  99316. 0 == error_callback ||
  99317. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99318. )
  99319. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99320. #if FLAC__HAS_OGG
  99321. decoder->private_->is_ogg = is_ogg;
  99322. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99323. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99324. #endif
  99325. /*
  99326. * get the CPU info and set the function pointers
  99327. */
  99328. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99329. /* first default to the non-asm routines */
  99330. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99331. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99332. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99333. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99334. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99335. /* now override with asm where appropriate */
  99336. #ifndef FLAC__NO_ASM
  99337. if(decoder->private_->cpuinfo.use_asm) {
  99338. #ifdef FLAC__CPU_IA32
  99339. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99340. #ifdef FLAC__HAS_NASM
  99341. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99342. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99343. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99344. #endif
  99345. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99346. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99347. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99348. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99349. }
  99350. else {
  99351. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99352. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99353. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99354. }
  99355. #endif
  99356. #elif defined FLAC__CPU_PPC
  99357. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99358. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99359. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99360. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99361. }
  99362. #endif
  99363. }
  99364. #endif
  99365. /* from here on, errors are fatal */
  99366. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99367. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99368. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99369. }
  99370. decoder->private_->read_callback = read_callback;
  99371. decoder->private_->seek_callback = seek_callback;
  99372. decoder->private_->tell_callback = tell_callback;
  99373. decoder->private_->length_callback = length_callback;
  99374. decoder->private_->eof_callback = eof_callback;
  99375. decoder->private_->write_callback = write_callback;
  99376. decoder->private_->metadata_callback = metadata_callback;
  99377. decoder->private_->error_callback = error_callback;
  99378. decoder->private_->client_data = client_data;
  99379. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99380. decoder->private_->samples_decoded = 0;
  99381. decoder->private_->has_stream_info = false;
  99382. decoder->private_->cached = false;
  99383. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99384. decoder->private_->is_seeking = false;
  99385. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99386. if(!FLAC__stream_decoder_reset(decoder)) {
  99387. /* above call sets the state for us */
  99388. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99389. }
  99390. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99391. }
  99392. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99393. FLAC__StreamDecoder *decoder,
  99394. FLAC__StreamDecoderReadCallback read_callback,
  99395. FLAC__StreamDecoderSeekCallback seek_callback,
  99396. FLAC__StreamDecoderTellCallback tell_callback,
  99397. FLAC__StreamDecoderLengthCallback length_callback,
  99398. FLAC__StreamDecoderEofCallback eof_callback,
  99399. FLAC__StreamDecoderWriteCallback write_callback,
  99400. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99401. FLAC__StreamDecoderErrorCallback error_callback,
  99402. void *client_data
  99403. )
  99404. {
  99405. return init_stream_internal_dec(
  99406. decoder,
  99407. read_callback,
  99408. seek_callback,
  99409. tell_callback,
  99410. length_callback,
  99411. eof_callback,
  99412. write_callback,
  99413. metadata_callback,
  99414. error_callback,
  99415. client_data,
  99416. /*is_ogg=*/false
  99417. );
  99418. }
  99419. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99420. FLAC__StreamDecoder *decoder,
  99421. FLAC__StreamDecoderReadCallback read_callback,
  99422. FLAC__StreamDecoderSeekCallback seek_callback,
  99423. FLAC__StreamDecoderTellCallback tell_callback,
  99424. FLAC__StreamDecoderLengthCallback length_callback,
  99425. FLAC__StreamDecoderEofCallback eof_callback,
  99426. FLAC__StreamDecoderWriteCallback write_callback,
  99427. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99428. FLAC__StreamDecoderErrorCallback error_callback,
  99429. void *client_data
  99430. )
  99431. {
  99432. return init_stream_internal_dec(
  99433. decoder,
  99434. read_callback,
  99435. seek_callback,
  99436. tell_callback,
  99437. length_callback,
  99438. eof_callback,
  99439. write_callback,
  99440. metadata_callback,
  99441. error_callback,
  99442. client_data,
  99443. /*is_ogg=*/true
  99444. );
  99445. }
  99446. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99447. FLAC__StreamDecoder *decoder,
  99448. FILE *file,
  99449. FLAC__StreamDecoderWriteCallback write_callback,
  99450. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99451. FLAC__StreamDecoderErrorCallback error_callback,
  99452. void *client_data,
  99453. FLAC__bool is_ogg
  99454. )
  99455. {
  99456. FLAC__ASSERT(0 != decoder);
  99457. FLAC__ASSERT(0 != file);
  99458. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99459. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99460. if(0 == write_callback || 0 == error_callback)
  99461. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99462. /*
  99463. * To make sure that our file does not go unclosed after an error, we
  99464. * must assign the FILE pointer before any further error can occur in
  99465. * this routine.
  99466. */
  99467. if(file == stdin)
  99468. file = get_binary_stdin_(); /* just to be safe */
  99469. decoder->private_->file = file;
  99470. return init_stream_internal_dec(
  99471. decoder,
  99472. file_read_callback_dec,
  99473. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99474. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99475. decoder->private_->file == stdin? 0: file_length_callback_,
  99476. file_eof_callback_,
  99477. write_callback,
  99478. metadata_callback,
  99479. error_callback,
  99480. client_data,
  99481. is_ogg
  99482. );
  99483. }
  99484. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99485. FLAC__StreamDecoder *decoder,
  99486. FILE *file,
  99487. FLAC__StreamDecoderWriteCallback write_callback,
  99488. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99489. FLAC__StreamDecoderErrorCallback error_callback,
  99490. void *client_data
  99491. )
  99492. {
  99493. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99494. }
  99495. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99496. FLAC__StreamDecoder *decoder,
  99497. FILE *file,
  99498. FLAC__StreamDecoderWriteCallback write_callback,
  99499. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99500. FLAC__StreamDecoderErrorCallback error_callback,
  99501. void *client_data
  99502. )
  99503. {
  99504. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99505. }
  99506. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99507. FLAC__StreamDecoder *decoder,
  99508. const char *filename,
  99509. FLAC__StreamDecoderWriteCallback write_callback,
  99510. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99511. FLAC__StreamDecoderErrorCallback error_callback,
  99512. void *client_data,
  99513. FLAC__bool is_ogg
  99514. )
  99515. {
  99516. FILE *file;
  99517. FLAC__ASSERT(0 != decoder);
  99518. /*
  99519. * To make sure that our file does not go unclosed after an error, we
  99520. * have to do the same entrance checks here that are later performed
  99521. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99522. */
  99523. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99524. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99525. if(0 == write_callback || 0 == error_callback)
  99526. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99527. file = filename? fopen(filename, "rb") : stdin;
  99528. if(0 == file)
  99529. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99530. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99531. }
  99532. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99533. FLAC__StreamDecoder *decoder,
  99534. const char *filename,
  99535. FLAC__StreamDecoderWriteCallback write_callback,
  99536. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99537. FLAC__StreamDecoderErrorCallback error_callback,
  99538. void *client_data
  99539. )
  99540. {
  99541. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99542. }
  99543. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99544. FLAC__StreamDecoder *decoder,
  99545. const char *filename,
  99546. FLAC__StreamDecoderWriteCallback write_callback,
  99547. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99548. FLAC__StreamDecoderErrorCallback error_callback,
  99549. void *client_data
  99550. )
  99551. {
  99552. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99553. }
  99554. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99555. {
  99556. FLAC__bool md5_failed = false;
  99557. unsigned i;
  99558. FLAC__ASSERT(0 != decoder);
  99559. FLAC__ASSERT(0 != decoder->private_);
  99560. FLAC__ASSERT(0 != decoder->protected_);
  99561. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99562. return true;
  99563. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99564. * always call FLAC__MD5Final()
  99565. */
  99566. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99567. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99568. free(decoder->private_->seek_table.data.seek_table.points);
  99569. decoder->private_->seek_table.data.seek_table.points = 0;
  99570. decoder->private_->has_seek_table = false;
  99571. }
  99572. FLAC__bitreader_free(decoder->private_->input);
  99573. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99574. /* WATCHOUT:
  99575. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99576. * output arrays have a buffer of up to 3 zeroes in front
  99577. * (at negative indices) for alignment purposes; we use 4
  99578. * to keep the data well-aligned.
  99579. */
  99580. if(0 != decoder->private_->output[i]) {
  99581. free(decoder->private_->output[i]-4);
  99582. decoder->private_->output[i] = 0;
  99583. }
  99584. if(0 != decoder->private_->residual_unaligned[i]) {
  99585. free(decoder->private_->residual_unaligned[i]);
  99586. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99587. }
  99588. }
  99589. decoder->private_->output_capacity = 0;
  99590. decoder->private_->output_channels = 0;
  99591. #if FLAC__HAS_OGG
  99592. if(decoder->private_->is_ogg)
  99593. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99594. #endif
  99595. if(0 != decoder->private_->file) {
  99596. if(decoder->private_->file != stdin)
  99597. fclose(decoder->private_->file);
  99598. decoder->private_->file = 0;
  99599. }
  99600. if(decoder->private_->do_md5_checking) {
  99601. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99602. md5_failed = true;
  99603. }
  99604. decoder->private_->is_seeking = false;
  99605. set_defaults_dec(decoder);
  99606. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99607. return !md5_failed;
  99608. }
  99609. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99610. {
  99611. FLAC__ASSERT(0 != decoder);
  99612. FLAC__ASSERT(0 != decoder->private_);
  99613. FLAC__ASSERT(0 != decoder->protected_);
  99614. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99615. return false;
  99616. #if FLAC__HAS_OGG
  99617. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99618. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99619. return true;
  99620. #else
  99621. (void)value;
  99622. return false;
  99623. #endif
  99624. }
  99625. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99626. {
  99627. FLAC__ASSERT(0 != decoder);
  99628. FLAC__ASSERT(0 != decoder->protected_);
  99629. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99630. return false;
  99631. decoder->protected_->md5_checking = value;
  99632. return true;
  99633. }
  99634. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99635. {
  99636. FLAC__ASSERT(0 != decoder);
  99637. FLAC__ASSERT(0 != decoder->private_);
  99638. FLAC__ASSERT(0 != decoder->protected_);
  99639. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99640. /* double protection */
  99641. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99642. return false;
  99643. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99644. return false;
  99645. decoder->private_->metadata_filter[type] = true;
  99646. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99647. decoder->private_->metadata_filter_ids_count = 0;
  99648. return true;
  99649. }
  99650. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99651. {
  99652. FLAC__ASSERT(0 != decoder);
  99653. FLAC__ASSERT(0 != decoder->private_);
  99654. FLAC__ASSERT(0 != decoder->protected_);
  99655. FLAC__ASSERT(0 != id);
  99656. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99657. return false;
  99658. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99659. return true;
  99660. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99661. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99662. 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))) {
  99663. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99664. return false;
  99665. }
  99666. decoder->private_->metadata_filter_ids_capacity *= 2;
  99667. }
  99668. 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));
  99669. decoder->private_->metadata_filter_ids_count++;
  99670. return true;
  99671. }
  99672. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99673. {
  99674. unsigned i;
  99675. FLAC__ASSERT(0 != decoder);
  99676. FLAC__ASSERT(0 != decoder->private_);
  99677. FLAC__ASSERT(0 != decoder->protected_);
  99678. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99679. return false;
  99680. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99681. decoder->private_->metadata_filter[i] = true;
  99682. decoder->private_->metadata_filter_ids_count = 0;
  99683. return true;
  99684. }
  99685. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99686. {
  99687. FLAC__ASSERT(0 != decoder);
  99688. FLAC__ASSERT(0 != decoder->private_);
  99689. FLAC__ASSERT(0 != decoder->protected_);
  99690. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99691. /* double protection */
  99692. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99693. return false;
  99694. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99695. return false;
  99696. decoder->private_->metadata_filter[type] = false;
  99697. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99698. decoder->private_->metadata_filter_ids_count = 0;
  99699. return true;
  99700. }
  99701. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99702. {
  99703. FLAC__ASSERT(0 != decoder);
  99704. FLAC__ASSERT(0 != decoder->private_);
  99705. FLAC__ASSERT(0 != decoder->protected_);
  99706. FLAC__ASSERT(0 != id);
  99707. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99708. return false;
  99709. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99710. return true;
  99711. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99712. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99713. 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))) {
  99714. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99715. return false;
  99716. }
  99717. decoder->private_->metadata_filter_ids_capacity *= 2;
  99718. }
  99719. 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));
  99720. decoder->private_->metadata_filter_ids_count++;
  99721. return true;
  99722. }
  99723. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99724. {
  99725. FLAC__ASSERT(0 != decoder);
  99726. FLAC__ASSERT(0 != decoder->private_);
  99727. FLAC__ASSERT(0 != decoder->protected_);
  99728. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99729. return false;
  99730. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99731. decoder->private_->metadata_filter_ids_count = 0;
  99732. return true;
  99733. }
  99734. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99735. {
  99736. FLAC__ASSERT(0 != decoder);
  99737. FLAC__ASSERT(0 != decoder->protected_);
  99738. return decoder->protected_->state;
  99739. }
  99740. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99741. {
  99742. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99743. }
  99744. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99745. {
  99746. FLAC__ASSERT(0 != decoder);
  99747. FLAC__ASSERT(0 != decoder->protected_);
  99748. return decoder->protected_->md5_checking;
  99749. }
  99750. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99751. {
  99752. FLAC__ASSERT(0 != decoder);
  99753. FLAC__ASSERT(0 != decoder->protected_);
  99754. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99755. }
  99756. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99757. {
  99758. FLAC__ASSERT(0 != decoder);
  99759. FLAC__ASSERT(0 != decoder->protected_);
  99760. return decoder->protected_->channels;
  99761. }
  99762. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99763. {
  99764. FLAC__ASSERT(0 != decoder);
  99765. FLAC__ASSERT(0 != decoder->protected_);
  99766. return decoder->protected_->channel_assignment;
  99767. }
  99768. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99769. {
  99770. FLAC__ASSERT(0 != decoder);
  99771. FLAC__ASSERT(0 != decoder->protected_);
  99772. return decoder->protected_->bits_per_sample;
  99773. }
  99774. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99775. {
  99776. FLAC__ASSERT(0 != decoder);
  99777. FLAC__ASSERT(0 != decoder->protected_);
  99778. return decoder->protected_->sample_rate;
  99779. }
  99780. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99781. {
  99782. FLAC__ASSERT(0 != decoder);
  99783. FLAC__ASSERT(0 != decoder->protected_);
  99784. return decoder->protected_->blocksize;
  99785. }
  99786. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99787. {
  99788. FLAC__ASSERT(0 != decoder);
  99789. FLAC__ASSERT(0 != decoder->private_);
  99790. FLAC__ASSERT(0 != position);
  99791. #if FLAC__HAS_OGG
  99792. if(decoder->private_->is_ogg)
  99793. return false;
  99794. #endif
  99795. if(0 == decoder->private_->tell_callback)
  99796. return false;
  99797. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99798. return false;
  99799. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99800. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99801. return false;
  99802. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99803. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99804. return true;
  99805. }
  99806. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99807. {
  99808. FLAC__ASSERT(0 != decoder);
  99809. FLAC__ASSERT(0 != decoder->private_);
  99810. FLAC__ASSERT(0 != decoder->protected_);
  99811. decoder->private_->samples_decoded = 0;
  99812. decoder->private_->do_md5_checking = false;
  99813. #if FLAC__HAS_OGG
  99814. if(decoder->private_->is_ogg)
  99815. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99816. #endif
  99817. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99818. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99819. return false;
  99820. }
  99821. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99822. return true;
  99823. }
  99824. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99825. {
  99826. FLAC__ASSERT(0 != decoder);
  99827. FLAC__ASSERT(0 != decoder->private_);
  99828. FLAC__ASSERT(0 != decoder->protected_);
  99829. if(!FLAC__stream_decoder_flush(decoder)) {
  99830. /* above call sets the state for us */
  99831. return false;
  99832. }
  99833. #if FLAC__HAS_OGG
  99834. /*@@@ could go in !internal_reset_hack block below */
  99835. if(decoder->private_->is_ogg)
  99836. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99837. #endif
  99838. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99839. * (internal_reset_hack) don't try to rewind since we are already at
  99840. * the beginning of the stream and don't want to fail if the input is
  99841. * not seekable.
  99842. */
  99843. if(!decoder->private_->internal_reset_hack) {
  99844. if(decoder->private_->file == stdin)
  99845. return false; /* can't rewind stdin, reset fails */
  99846. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99847. return false; /* seekable and seek fails, reset fails */
  99848. }
  99849. else
  99850. decoder->private_->internal_reset_hack = false;
  99851. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99852. decoder->private_->has_stream_info = false;
  99853. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99854. free(decoder->private_->seek_table.data.seek_table.points);
  99855. decoder->private_->seek_table.data.seek_table.points = 0;
  99856. decoder->private_->has_seek_table = false;
  99857. }
  99858. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99859. /*
  99860. * This goes in reset() and not flush() because according to the spec, a
  99861. * fixed-blocksize stream must stay that way through the whole stream.
  99862. */
  99863. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99864. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99865. * is because md5 checking may be turned on to start and then turned off if
  99866. * a seek occurs. So we init the context here and finalize it in
  99867. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99868. * properly.
  99869. */
  99870. FLAC__MD5Init(&decoder->private_->md5context);
  99871. decoder->private_->first_frame_offset = 0;
  99872. decoder->private_->unparseable_frame_count = 0;
  99873. return true;
  99874. }
  99875. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99876. {
  99877. FLAC__bool got_a_frame;
  99878. FLAC__ASSERT(0 != decoder);
  99879. FLAC__ASSERT(0 != decoder->protected_);
  99880. while(1) {
  99881. switch(decoder->protected_->state) {
  99882. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99883. if(!find_metadata_(decoder))
  99884. return false; /* above function sets the status for us */
  99885. break;
  99886. case FLAC__STREAM_DECODER_READ_METADATA:
  99887. if(!read_metadata_(decoder))
  99888. return false; /* above function sets the status for us */
  99889. else
  99890. return true;
  99891. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99892. if(!frame_sync_(decoder))
  99893. return true; /* above function sets the status for us */
  99894. break;
  99895. case FLAC__STREAM_DECODER_READ_FRAME:
  99896. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99897. return false; /* above function sets the status for us */
  99898. if(got_a_frame)
  99899. return true; /* above function sets the status for us */
  99900. break;
  99901. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99902. case FLAC__STREAM_DECODER_ABORTED:
  99903. return true;
  99904. default:
  99905. FLAC__ASSERT(0);
  99906. return false;
  99907. }
  99908. }
  99909. }
  99910. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99911. {
  99912. FLAC__ASSERT(0 != decoder);
  99913. FLAC__ASSERT(0 != decoder->protected_);
  99914. while(1) {
  99915. switch(decoder->protected_->state) {
  99916. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99917. if(!find_metadata_(decoder))
  99918. return false; /* above function sets the status for us */
  99919. break;
  99920. case FLAC__STREAM_DECODER_READ_METADATA:
  99921. if(!read_metadata_(decoder))
  99922. return false; /* above function sets the status for us */
  99923. break;
  99924. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99925. case FLAC__STREAM_DECODER_READ_FRAME:
  99926. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99927. case FLAC__STREAM_DECODER_ABORTED:
  99928. return true;
  99929. default:
  99930. FLAC__ASSERT(0);
  99931. return false;
  99932. }
  99933. }
  99934. }
  99935. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99936. {
  99937. FLAC__bool dummy;
  99938. FLAC__ASSERT(0 != decoder);
  99939. FLAC__ASSERT(0 != decoder->protected_);
  99940. while(1) {
  99941. switch(decoder->protected_->state) {
  99942. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99943. if(!find_metadata_(decoder))
  99944. return false; /* above function sets the status for us */
  99945. break;
  99946. case FLAC__STREAM_DECODER_READ_METADATA:
  99947. if(!read_metadata_(decoder))
  99948. return false; /* above function sets the status for us */
  99949. break;
  99950. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99951. if(!frame_sync_(decoder))
  99952. return true; /* above function sets the status for us */
  99953. break;
  99954. case FLAC__STREAM_DECODER_READ_FRAME:
  99955. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99956. return false; /* above function sets the status for us */
  99957. break;
  99958. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99959. case FLAC__STREAM_DECODER_ABORTED:
  99960. return true;
  99961. default:
  99962. FLAC__ASSERT(0);
  99963. return false;
  99964. }
  99965. }
  99966. }
  99967. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99968. {
  99969. FLAC__bool got_a_frame;
  99970. FLAC__ASSERT(0 != decoder);
  99971. FLAC__ASSERT(0 != decoder->protected_);
  99972. while(1) {
  99973. switch(decoder->protected_->state) {
  99974. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99975. case FLAC__STREAM_DECODER_READ_METADATA:
  99976. return false; /* above function sets the status for us */
  99977. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99978. if(!frame_sync_(decoder))
  99979. return true; /* above function sets the status for us */
  99980. break;
  99981. case FLAC__STREAM_DECODER_READ_FRAME:
  99982. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99983. return false; /* above function sets the status for us */
  99984. if(got_a_frame)
  99985. return true; /* above function sets the status for us */
  99986. break;
  99987. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99988. case FLAC__STREAM_DECODER_ABORTED:
  99989. return true;
  99990. default:
  99991. FLAC__ASSERT(0);
  99992. return false;
  99993. }
  99994. }
  99995. }
  99996. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99997. {
  99998. FLAC__uint64 length;
  99999. FLAC__ASSERT(0 != decoder);
  100000. if(
  100001. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100002. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100003. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100004. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100005. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100006. )
  100007. return false;
  100008. if(0 == decoder->private_->seek_callback)
  100009. return false;
  100010. FLAC__ASSERT(decoder->private_->seek_callback);
  100011. FLAC__ASSERT(decoder->private_->tell_callback);
  100012. FLAC__ASSERT(decoder->private_->length_callback);
  100013. FLAC__ASSERT(decoder->private_->eof_callback);
  100014. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100015. return false;
  100016. decoder->private_->is_seeking = true;
  100017. /* turn off md5 checking if a seek is attempted */
  100018. decoder->private_->do_md5_checking = false;
  100019. /* 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) */
  100020. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100021. decoder->private_->is_seeking = false;
  100022. return false;
  100023. }
  100024. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100025. if(
  100026. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100027. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100028. ) {
  100029. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100030. /* above call sets the state for us */
  100031. decoder->private_->is_seeking = false;
  100032. return false;
  100033. }
  100034. /* check this again in case we didn't know total_samples the first time */
  100035. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100036. decoder->private_->is_seeking = false;
  100037. return false;
  100038. }
  100039. }
  100040. {
  100041. const FLAC__bool ok =
  100042. #if FLAC__HAS_OGG
  100043. decoder->private_->is_ogg?
  100044. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100045. #endif
  100046. seek_to_absolute_sample_(decoder, length, sample)
  100047. ;
  100048. decoder->private_->is_seeking = false;
  100049. return ok;
  100050. }
  100051. }
  100052. /***********************************************************************
  100053. *
  100054. * Protected class methods
  100055. *
  100056. ***********************************************************************/
  100057. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100058. {
  100059. FLAC__ASSERT(0 != decoder);
  100060. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100061. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100062. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100063. }
  100064. /***********************************************************************
  100065. *
  100066. * Private class methods
  100067. *
  100068. ***********************************************************************/
  100069. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100070. {
  100071. #if FLAC__HAS_OGG
  100072. decoder->private_->is_ogg = false;
  100073. #endif
  100074. decoder->private_->read_callback = 0;
  100075. decoder->private_->seek_callback = 0;
  100076. decoder->private_->tell_callback = 0;
  100077. decoder->private_->length_callback = 0;
  100078. decoder->private_->eof_callback = 0;
  100079. decoder->private_->write_callback = 0;
  100080. decoder->private_->metadata_callback = 0;
  100081. decoder->private_->error_callback = 0;
  100082. decoder->private_->client_data = 0;
  100083. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100084. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100085. decoder->private_->metadata_filter_ids_count = 0;
  100086. decoder->protected_->md5_checking = false;
  100087. #if FLAC__HAS_OGG
  100088. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100089. #endif
  100090. }
  100091. /*
  100092. * This will forcibly set stdin to binary mode (for OSes that require it)
  100093. */
  100094. FILE *get_binary_stdin_(void)
  100095. {
  100096. /* if something breaks here it is probably due to the presence or
  100097. * absence of an underscore before the identifiers 'setmode',
  100098. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100099. */
  100100. #if defined _MSC_VER || defined __MINGW32__
  100101. _setmode(_fileno(stdin), _O_BINARY);
  100102. #elif defined __CYGWIN__
  100103. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100104. setmode(_fileno(stdin), _O_BINARY);
  100105. #elif defined __EMX__
  100106. setmode(fileno(stdin), O_BINARY);
  100107. #endif
  100108. return stdin;
  100109. }
  100110. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100111. {
  100112. unsigned i;
  100113. FLAC__int32 *tmp;
  100114. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100115. return true;
  100116. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100117. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100118. if(0 != decoder->private_->output[i]) {
  100119. free(decoder->private_->output[i]-4);
  100120. decoder->private_->output[i] = 0;
  100121. }
  100122. if(0 != decoder->private_->residual_unaligned[i]) {
  100123. free(decoder->private_->residual_unaligned[i]);
  100124. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100125. }
  100126. }
  100127. for(i = 0; i < channels; i++) {
  100128. /* WATCHOUT:
  100129. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100130. * output arrays have a buffer of up to 3 zeroes in front
  100131. * (at negative indices) for alignment purposes; we use 4
  100132. * to keep the data well-aligned.
  100133. */
  100134. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100135. if(tmp == 0) {
  100136. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100137. return false;
  100138. }
  100139. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100140. decoder->private_->output[i] = tmp + 4;
  100141. /* WATCHOUT:
  100142. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100143. */
  100144. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100145. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100146. return false;
  100147. }
  100148. }
  100149. decoder->private_->output_capacity = size;
  100150. decoder->private_->output_channels = channels;
  100151. return true;
  100152. }
  100153. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100154. {
  100155. size_t i;
  100156. FLAC__ASSERT(0 != decoder);
  100157. FLAC__ASSERT(0 != decoder->private_);
  100158. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100159. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100160. return true;
  100161. return false;
  100162. }
  100163. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100164. {
  100165. FLAC__uint32 x;
  100166. unsigned i, id_;
  100167. FLAC__bool first = true;
  100168. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100169. for(i = id_ = 0; i < 4; ) {
  100170. if(decoder->private_->cached) {
  100171. x = (FLAC__uint32)decoder->private_->lookahead;
  100172. decoder->private_->cached = false;
  100173. }
  100174. else {
  100175. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100176. return false; /* read_callback_ sets the state for us */
  100177. }
  100178. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100179. first = true;
  100180. i++;
  100181. id_ = 0;
  100182. continue;
  100183. }
  100184. if(x == ID3V2_TAG_[id_]) {
  100185. id_++;
  100186. i = 0;
  100187. if(id_ == 3) {
  100188. if(!skip_id3v2_tag_(decoder))
  100189. return false; /* skip_id3v2_tag_ sets the state for us */
  100190. }
  100191. continue;
  100192. }
  100193. id_ = 0;
  100194. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100195. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100196. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100197. return false; /* read_callback_ sets the state for us */
  100198. /* 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 */
  100199. /* else we have to check if the second byte is the end of a sync code */
  100200. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100201. decoder->private_->lookahead = (FLAC__byte)x;
  100202. decoder->private_->cached = true;
  100203. }
  100204. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100205. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100206. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100207. return true;
  100208. }
  100209. }
  100210. i = 0;
  100211. if(first) {
  100212. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100213. first = false;
  100214. }
  100215. }
  100216. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100217. return true;
  100218. }
  100219. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100220. {
  100221. FLAC__bool is_last;
  100222. FLAC__uint32 i, x, type, length;
  100223. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100224. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100225. return false; /* read_callback_ sets the state for us */
  100226. is_last = x? true : false;
  100227. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100228. return false; /* read_callback_ sets the state for us */
  100229. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100230. return false; /* read_callback_ sets the state for us */
  100231. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100232. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100233. return false;
  100234. decoder->private_->has_stream_info = true;
  100235. 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))
  100236. decoder->private_->do_md5_checking = false;
  100237. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100238. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100239. }
  100240. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100241. if(!read_metadata_seektable_(decoder, is_last, length))
  100242. return false;
  100243. decoder->private_->has_seek_table = true;
  100244. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100245. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100246. }
  100247. else {
  100248. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100249. unsigned real_length = length;
  100250. FLAC__StreamMetadata block;
  100251. block.is_last = is_last;
  100252. block.type = (FLAC__MetadataType)type;
  100253. block.length = length;
  100254. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100255. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100256. return false; /* read_callback_ sets the state for us */
  100257. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100258. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100259. return false;
  100260. }
  100261. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100262. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100263. skip_it = !skip_it;
  100264. }
  100265. if(skip_it) {
  100266. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100267. return false; /* read_callback_ sets the state for us */
  100268. }
  100269. else {
  100270. switch(type) {
  100271. case FLAC__METADATA_TYPE_PADDING:
  100272. /* skip the padding bytes */
  100273. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100274. return false; /* read_callback_ sets the state for us */
  100275. break;
  100276. case FLAC__METADATA_TYPE_APPLICATION:
  100277. /* remember, we read the ID already */
  100278. if(real_length > 0) {
  100279. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100280. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100281. return false;
  100282. }
  100283. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100284. return false; /* read_callback_ sets the state for us */
  100285. }
  100286. else
  100287. block.data.application.data = 0;
  100288. break;
  100289. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100290. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100291. return false;
  100292. break;
  100293. case FLAC__METADATA_TYPE_CUESHEET:
  100294. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100295. return false;
  100296. break;
  100297. case FLAC__METADATA_TYPE_PICTURE:
  100298. if(!read_metadata_picture_(decoder, &block.data.picture))
  100299. return false;
  100300. break;
  100301. case FLAC__METADATA_TYPE_STREAMINFO:
  100302. case FLAC__METADATA_TYPE_SEEKTABLE:
  100303. FLAC__ASSERT(0);
  100304. break;
  100305. default:
  100306. if(real_length > 0) {
  100307. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100308. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100309. return false;
  100310. }
  100311. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100312. return false; /* read_callback_ sets the state for us */
  100313. }
  100314. else
  100315. block.data.unknown.data = 0;
  100316. break;
  100317. }
  100318. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100319. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100320. /* now we have to free any malloc()ed data in the block */
  100321. switch(type) {
  100322. case FLAC__METADATA_TYPE_PADDING:
  100323. break;
  100324. case FLAC__METADATA_TYPE_APPLICATION:
  100325. if(0 != block.data.application.data)
  100326. free(block.data.application.data);
  100327. break;
  100328. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100329. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100330. free(block.data.vorbis_comment.vendor_string.entry);
  100331. if(block.data.vorbis_comment.num_comments > 0)
  100332. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100333. if(0 != block.data.vorbis_comment.comments[i].entry)
  100334. free(block.data.vorbis_comment.comments[i].entry);
  100335. if(0 != block.data.vorbis_comment.comments)
  100336. free(block.data.vorbis_comment.comments);
  100337. break;
  100338. case FLAC__METADATA_TYPE_CUESHEET:
  100339. if(block.data.cue_sheet.num_tracks > 0)
  100340. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100341. if(0 != block.data.cue_sheet.tracks[i].indices)
  100342. free(block.data.cue_sheet.tracks[i].indices);
  100343. if(0 != block.data.cue_sheet.tracks)
  100344. free(block.data.cue_sheet.tracks);
  100345. break;
  100346. case FLAC__METADATA_TYPE_PICTURE:
  100347. if(0 != block.data.picture.mime_type)
  100348. free(block.data.picture.mime_type);
  100349. if(0 != block.data.picture.description)
  100350. free(block.data.picture.description);
  100351. if(0 != block.data.picture.data)
  100352. free(block.data.picture.data);
  100353. break;
  100354. case FLAC__METADATA_TYPE_STREAMINFO:
  100355. case FLAC__METADATA_TYPE_SEEKTABLE:
  100356. FLAC__ASSERT(0);
  100357. default:
  100358. if(0 != block.data.unknown.data)
  100359. free(block.data.unknown.data);
  100360. break;
  100361. }
  100362. }
  100363. }
  100364. if(is_last) {
  100365. /* if this fails, it's OK, it's just a hint for the seek routine */
  100366. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100367. decoder->private_->first_frame_offset = 0;
  100368. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100369. }
  100370. return true;
  100371. }
  100372. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100373. {
  100374. FLAC__uint32 x;
  100375. unsigned bits, used_bits = 0;
  100376. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100377. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100378. decoder->private_->stream_info.is_last = is_last;
  100379. decoder->private_->stream_info.length = length;
  100380. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100381. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100382. return false; /* read_callback_ sets the state for us */
  100383. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100384. used_bits += bits;
  100385. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100386. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100387. return false; /* read_callback_ sets the state for us */
  100388. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100389. used_bits += bits;
  100390. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100391. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100392. return false; /* read_callback_ sets the state for us */
  100393. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100394. used_bits += bits;
  100395. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100396. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100397. return false; /* read_callback_ sets the state for us */
  100398. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100399. used_bits += bits;
  100400. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100401. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100402. return false; /* read_callback_ sets the state for us */
  100403. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100404. used_bits += bits;
  100405. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100406. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100407. return false; /* read_callback_ sets the state for us */
  100408. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100409. used_bits += bits;
  100410. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100411. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100412. return false; /* read_callback_ sets the state for us */
  100413. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100414. used_bits += bits;
  100415. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100416. 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))
  100417. return false; /* read_callback_ sets the state for us */
  100418. used_bits += bits;
  100419. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100420. return false; /* read_callback_ sets the state for us */
  100421. used_bits += 16*8;
  100422. /* skip the rest of the block */
  100423. FLAC__ASSERT(used_bits % 8 == 0);
  100424. length -= (used_bits / 8);
  100425. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100426. return false; /* read_callback_ sets the state for us */
  100427. return true;
  100428. }
  100429. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100430. {
  100431. FLAC__uint32 i, x;
  100432. FLAC__uint64 xx;
  100433. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100434. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100435. decoder->private_->seek_table.is_last = is_last;
  100436. decoder->private_->seek_table.length = length;
  100437. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100438. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100439. 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)))) {
  100440. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100441. return false;
  100442. }
  100443. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100444. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100445. return false; /* read_callback_ sets the state for us */
  100446. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100447. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100448. return false; /* read_callback_ sets the state for us */
  100449. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100450. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100451. return false; /* read_callback_ sets the state for us */
  100452. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100453. }
  100454. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100455. /* if there is a partial point left, skip over it */
  100456. if(length > 0) {
  100457. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100458. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100459. return false; /* read_callback_ sets the state for us */
  100460. }
  100461. return true;
  100462. }
  100463. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100464. {
  100465. FLAC__uint32 i;
  100466. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100467. /* read vendor string */
  100468. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100469. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100470. return false; /* read_callback_ sets the state for us */
  100471. if(obj->vendor_string.length > 0) {
  100472. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100473. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100474. return false;
  100475. }
  100476. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100477. return false; /* read_callback_ sets the state for us */
  100478. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100479. }
  100480. else
  100481. obj->vendor_string.entry = 0;
  100482. /* read num comments */
  100483. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100484. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100485. return false; /* read_callback_ sets the state for us */
  100486. /* read comments */
  100487. if(obj->num_comments > 0) {
  100488. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100489. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100490. return false;
  100491. }
  100492. for(i = 0; i < obj->num_comments; i++) {
  100493. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100494. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100495. return false; /* read_callback_ sets the state for us */
  100496. if(obj->comments[i].length > 0) {
  100497. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100498. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100499. return false;
  100500. }
  100501. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100502. return false; /* read_callback_ sets the state for us */
  100503. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100504. }
  100505. else
  100506. obj->comments[i].entry = 0;
  100507. }
  100508. }
  100509. else {
  100510. obj->comments = 0;
  100511. }
  100512. return true;
  100513. }
  100514. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100515. {
  100516. FLAC__uint32 i, j, x;
  100517. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100518. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100519. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100520. 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))
  100521. return false; /* read_callback_ sets the state for us */
  100522. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100523. return false; /* read_callback_ sets the state for us */
  100524. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100525. return false; /* read_callback_ sets the state for us */
  100526. obj->is_cd = x? true : false;
  100527. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100528. return false; /* read_callback_ sets the state for us */
  100529. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100530. return false; /* read_callback_ sets the state for us */
  100531. obj->num_tracks = x;
  100532. if(obj->num_tracks > 0) {
  100533. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100534. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100535. return false;
  100536. }
  100537. for(i = 0; i < obj->num_tracks; i++) {
  100538. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100539. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100540. return false; /* read_callback_ sets the state for us */
  100541. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100542. return false; /* read_callback_ sets the state for us */
  100543. track->number = (FLAC__byte)x;
  100544. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100545. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100546. return false; /* read_callback_ sets the state for us */
  100547. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100548. return false; /* read_callback_ sets the state for us */
  100549. track->type = x;
  100550. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100551. return false; /* read_callback_ sets the state for us */
  100552. track->pre_emphasis = x;
  100553. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100554. return false; /* read_callback_ sets the state for us */
  100555. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100556. return false; /* read_callback_ sets the state for us */
  100557. track->num_indices = (FLAC__byte)x;
  100558. if(track->num_indices > 0) {
  100559. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100560. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100561. return false;
  100562. }
  100563. for(j = 0; j < track->num_indices; j++) {
  100564. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100565. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100566. return false; /* read_callback_ sets the state for us */
  100567. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100568. return false; /* read_callback_ sets the state for us */
  100569. index->number = (FLAC__byte)x;
  100570. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100571. return false; /* read_callback_ sets the state for us */
  100572. }
  100573. }
  100574. }
  100575. }
  100576. return true;
  100577. }
  100578. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100579. {
  100580. FLAC__uint32 x;
  100581. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100582. /* read type */
  100583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100584. return false; /* read_callback_ sets the state for us */
  100585. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100586. /* read MIME type */
  100587. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100588. return false; /* read_callback_ sets the state for us */
  100589. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100590. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100591. return false;
  100592. }
  100593. if(x > 0) {
  100594. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100595. return false; /* read_callback_ sets the state for us */
  100596. }
  100597. obj->mime_type[x] = '\0';
  100598. /* read description */
  100599. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100600. return false; /* read_callback_ sets the state for us */
  100601. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100602. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100603. return false;
  100604. }
  100605. if(x > 0) {
  100606. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100607. return false; /* read_callback_ sets the state for us */
  100608. }
  100609. obj->description[x] = '\0';
  100610. /* read width */
  100611. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100612. return false; /* read_callback_ sets the state for us */
  100613. /* read height */
  100614. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100615. return false; /* read_callback_ sets the state for us */
  100616. /* read depth */
  100617. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100618. return false; /* read_callback_ sets the state for us */
  100619. /* read colors */
  100620. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100621. return false; /* read_callback_ sets the state for us */
  100622. /* read data */
  100623. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100624. return false; /* read_callback_ sets the state for us */
  100625. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100626. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100627. return false;
  100628. }
  100629. if(obj->data_length > 0) {
  100630. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100631. return false; /* read_callback_ sets the state for us */
  100632. }
  100633. return true;
  100634. }
  100635. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100636. {
  100637. FLAC__uint32 x;
  100638. unsigned i, skip;
  100639. /* skip the version and flags bytes */
  100640. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100641. return false; /* read_callback_ sets the state for us */
  100642. /* get the size (in bytes) to skip */
  100643. skip = 0;
  100644. for(i = 0; i < 4; i++) {
  100645. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100646. return false; /* read_callback_ sets the state for us */
  100647. skip <<= 7;
  100648. skip |= (x & 0x7f);
  100649. }
  100650. /* skip the rest of the tag */
  100651. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100652. return false; /* read_callback_ sets the state for us */
  100653. return true;
  100654. }
  100655. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100656. {
  100657. FLAC__uint32 x;
  100658. FLAC__bool first = true;
  100659. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100660. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100661. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100662. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100663. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100664. return true;
  100665. }
  100666. }
  100667. /* make sure we're byte aligned */
  100668. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100669. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100670. return false; /* read_callback_ sets the state for us */
  100671. }
  100672. while(1) {
  100673. if(decoder->private_->cached) {
  100674. x = (FLAC__uint32)decoder->private_->lookahead;
  100675. decoder->private_->cached = false;
  100676. }
  100677. else {
  100678. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100679. return false; /* read_callback_ sets the state for us */
  100680. }
  100681. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100682. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100683. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100684. return false; /* read_callback_ sets the state for us */
  100685. /* 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 */
  100686. /* else we have to check if the second byte is the end of a sync code */
  100687. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100688. decoder->private_->lookahead = (FLAC__byte)x;
  100689. decoder->private_->cached = true;
  100690. }
  100691. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100692. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100693. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100694. return true;
  100695. }
  100696. }
  100697. if(first) {
  100698. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100699. first = false;
  100700. }
  100701. }
  100702. return true;
  100703. }
  100704. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100705. {
  100706. unsigned channel;
  100707. unsigned i;
  100708. FLAC__int32 mid, side;
  100709. unsigned frame_crc; /* the one we calculate from the input stream */
  100710. FLAC__uint32 x;
  100711. *got_a_frame = false;
  100712. /* init the CRC */
  100713. frame_crc = 0;
  100714. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100715. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100716. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100717. if(!read_frame_header_(decoder))
  100718. return false;
  100719. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100720. return true;
  100721. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100722. return false;
  100723. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100724. /*
  100725. * first figure the correct bits-per-sample of the subframe
  100726. */
  100727. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100728. switch(decoder->private_->frame.header.channel_assignment) {
  100729. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100730. /* no adjustment needed */
  100731. break;
  100732. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100733. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100734. if(channel == 1)
  100735. bps++;
  100736. break;
  100737. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100738. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100739. if(channel == 0)
  100740. bps++;
  100741. break;
  100742. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100743. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100744. if(channel == 1)
  100745. bps++;
  100746. break;
  100747. default:
  100748. FLAC__ASSERT(0);
  100749. }
  100750. /*
  100751. * now read it
  100752. */
  100753. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100754. return false;
  100755. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100756. return true;
  100757. }
  100758. if(!read_zero_padding_(decoder))
  100759. return false;
  100760. 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) */
  100761. return true;
  100762. /*
  100763. * Read the frame CRC-16 from the footer and check
  100764. */
  100765. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100766. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100767. return false; /* read_callback_ sets the state for us */
  100768. if(frame_crc == x) {
  100769. if(do_full_decode) {
  100770. /* Undo any special channel coding */
  100771. switch(decoder->private_->frame.header.channel_assignment) {
  100772. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100773. /* do nothing */
  100774. break;
  100775. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100776. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100777. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100778. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100779. break;
  100780. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100781. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100782. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100783. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100784. break;
  100785. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100786. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100787. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100788. #if 1
  100789. mid = decoder->private_->output[0][i];
  100790. side = decoder->private_->output[1][i];
  100791. mid <<= 1;
  100792. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100793. decoder->private_->output[0][i] = (mid + side) >> 1;
  100794. decoder->private_->output[1][i] = (mid - side) >> 1;
  100795. #else
  100796. /* OPT: without 'side' temp variable */
  100797. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100798. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100799. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100800. #endif
  100801. }
  100802. break;
  100803. default:
  100804. FLAC__ASSERT(0);
  100805. break;
  100806. }
  100807. }
  100808. }
  100809. else {
  100810. /* Bad frame, emit error and zero the output signal */
  100811. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100812. if(do_full_decode) {
  100813. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100814. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100815. }
  100816. }
  100817. }
  100818. *got_a_frame = true;
  100819. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100820. if(decoder->private_->next_fixed_block_size)
  100821. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100822. /* put the latest values into the public section of the decoder instance */
  100823. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100824. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100825. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100826. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100827. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100828. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100829. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100830. /* write it */
  100831. if(do_full_decode) {
  100832. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100833. return false;
  100834. }
  100835. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100836. return true;
  100837. }
  100838. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100839. {
  100840. FLAC__uint32 x;
  100841. FLAC__uint64 xx;
  100842. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100843. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100844. unsigned raw_header_len;
  100845. FLAC__bool is_unparseable = false;
  100846. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100847. /* init the raw header with the saved bits from synchronization */
  100848. raw_header[0] = decoder->private_->header_warmup[0];
  100849. raw_header[1] = decoder->private_->header_warmup[1];
  100850. raw_header_len = 2;
  100851. /* check to make sure that reserved bit is 0 */
  100852. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100853. is_unparseable = true;
  100854. /*
  100855. * Note that along the way as we read the header, we look for a sync
  100856. * code inside. If we find one it would indicate that our original
  100857. * sync was bad since there cannot be a sync code in a valid header.
  100858. *
  100859. * Three kinds of things can go wrong when reading the frame header:
  100860. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100861. * If we don't find a sync code, it can end up looking like we read
  100862. * a valid but unparseable header, until getting to the frame header
  100863. * CRC. Even then we could get a false positive on the CRC.
  100864. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100865. * future encoder).
  100866. * 3) We may be on a damaged frame which appears valid but unparseable.
  100867. *
  100868. * For all these reasons, we try and read a complete frame header as
  100869. * long as it seems valid, even if unparseable, up until the frame
  100870. * header CRC.
  100871. */
  100872. /*
  100873. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100874. */
  100875. for(i = 0; i < 2; i++) {
  100876. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100877. return false; /* read_callback_ sets the state for us */
  100878. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100879. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100880. decoder->private_->lookahead = (FLAC__byte)x;
  100881. decoder->private_->cached = true;
  100882. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100883. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100884. return true;
  100885. }
  100886. raw_header[raw_header_len++] = (FLAC__byte)x;
  100887. }
  100888. switch(x = raw_header[2] >> 4) {
  100889. case 0:
  100890. is_unparseable = true;
  100891. break;
  100892. case 1:
  100893. decoder->private_->frame.header.blocksize = 192;
  100894. break;
  100895. case 2:
  100896. case 3:
  100897. case 4:
  100898. case 5:
  100899. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100900. break;
  100901. case 6:
  100902. case 7:
  100903. blocksize_hint = x;
  100904. break;
  100905. case 8:
  100906. case 9:
  100907. case 10:
  100908. case 11:
  100909. case 12:
  100910. case 13:
  100911. case 14:
  100912. case 15:
  100913. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100914. break;
  100915. default:
  100916. FLAC__ASSERT(0);
  100917. break;
  100918. }
  100919. switch(x = raw_header[2] & 0x0f) {
  100920. case 0:
  100921. if(decoder->private_->has_stream_info)
  100922. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100923. else
  100924. is_unparseable = true;
  100925. break;
  100926. case 1:
  100927. decoder->private_->frame.header.sample_rate = 88200;
  100928. break;
  100929. case 2:
  100930. decoder->private_->frame.header.sample_rate = 176400;
  100931. break;
  100932. case 3:
  100933. decoder->private_->frame.header.sample_rate = 192000;
  100934. break;
  100935. case 4:
  100936. decoder->private_->frame.header.sample_rate = 8000;
  100937. break;
  100938. case 5:
  100939. decoder->private_->frame.header.sample_rate = 16000;
  100940. break;
  100941. case 6:
  100942. decoder->private_->frame.header.sample_rate = 22050;
  100943. break;
  100944. case 7:
  100945. decoder->private_->frame.header.sample_rate = 24000;
  100946. break;
  100947. case 8:
  100948. decoder->private_->frame.header.sample_rate = 32000;
  100949. break;
  100950. case 9:
  100951. decoder->private_->frame.header.sample_rate = 44100;
  100952. break;
  100953. case 10:
  100954. decoder->private_->frame.header.sample_rate = 48000;
  100955. break;
  100956. case 11:
  100957. decoder->private_->frame.header.sample_rate = 96000;
  100958. break;
  100959. case 12:
  100960. case 13:
  100961. case 14:
  100962. sample_rate_hint = x;
  100963. break;
  100964. case 15:
  100965. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100966. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100967. return true;
  100968. default:
  100969. FLAC__ASSERT(0);
  100970. }
  100971. x = (unsigned)(raw_header[3] >> 4);
  100972. if(x & 8) {
  100973. decoder->private_->frame.header.channels = 2;
  100974. switch(x & 7) {
  100975. case 0:
  100976. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100977. break;
  100978. case 1:
  100979. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100980. break;
  100981. case 2:
  100982. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100983. break;
  100984. default:
  100985. is_unparseable = true;
  100986. break;
  100987. }
  100988. }
  100989. else {
  100990. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100991. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100992. }
  100993. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100994. case 0:
  100995. if(decoder->private_->has_stream_info)
  100996. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100997. else
  100998. is_unparseable = true;
  100999. break;
  101000. case 1:
  101001. decoder->private_->frame.header.bits_per_sample = 8;
  101002. break;
  101003. case 2:
  101004. decoder->private_->frame.header.bits_per_sample = 12;
  101005. break;
  101006. case 4:
  101007. decoder->private_->frame.header.bits_per_sample = 16;
  101008. break;
  101009. case 5:
  101010. decoder->private_->frame.header.bits_per_sample = 20;
  101011. break;
  101012. case 6:
  101013. decoder->private_->frame.header.bits_per_sample = 24;
  101014. break;
  101015. case 3:
  101016. case 7:
  101017. is_unparseable = true;
  101018. break;
  101019. default:
  101020. FLAC__ASSERT(0);
  101021. break;
  101022. }
  101023. /* check to make sure that reserved bit is 0 */
  101024. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101025. is_unparseable = true;
  101026. /* read the frame's starting sample number (or frame number as the case may be) */
  101027. if(
  101028. raw_header[1] & 0x01 ||
  101029. /*@@@ 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 */
  101030. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101031. ) { /* variable blocksize */
  101032. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101033. return false; /* read_callback_ sets the state for us */
  101034. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101035. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101036. decoder->private_->cached = true;
  101037. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101038. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101039. return true;
  101040. }
  101041. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101042. decoder->private_->frame.header.number.sample_number = xx;
  101043. }
  101044. else { /* fixed blocksize */
  101045. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101046. return false; /* read_callback_ sets the state for us */
  101047. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101048. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101049. decoder->private_->cached = true;
  101050. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101051. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101052. return true;
  101053. }
  101054. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101055. decoder->private_->frame.header.number.frame_number = x;
  101056. }
  101057. if(blocksize_hint) {
  101058. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101059. return false; /* read_callback_ sets the state for us */
  101060. raw_header[raw_header_len++] = (FLAC__byte)x;
  101061. if(blocksize_hint == 7) {
  101062. FLAC__uint32 _x;
  101063. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101064. return false; /* read_callback_ sets the state for us */
  101065. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101066. x = (x << 8) | _x;
  101067. }
  101068. decoder->private_->frame.header.blocksize = x+1;
  101069. }
  101070. if(sample_rate_hint) {
  101071. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101072. return false; /* read_callback_ sets the state for us */
  101073. raw_header[raw_header_len++] = (FLAC__byte)x;
  101074. if(sample_rate_hint != 12) {
  101075. FLAC__uint32 _x;
  101076. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101077. return false; /* read_callback_ sets the state for us */
  101078. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101079. x = (x << 8) | _x;
  101080. }
  101081. if(sample_rate_hint == 12)
  101082. decoder->private_->frame.header.sample_rate = x*1000;
  101083. else if(sample_rate_hint == 13)
  101084. decoder->private_->frame.header.sample_rate = x;
  101085. else
  101086. decoder->private_->frame.header.sample_rate = x*10;
  101087. }
  101088. /* read the CRC-8 byte */
  101089. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101090. return false; /* read_callback_ sets the state for us */
  101091. crc8 = (FLAC__byte)x;
  101092. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101093. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101094. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101095. return true;
  101096. }
  101097. /* calculate the sample number from the frame number if needed */
  101098. decoder->private_->next_fixed_block_size = 0;
  101099. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101100. x = decoder->private_->frame.header.number.frame_number;
  101101. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101102. if(decoder->private_->fixed_block_size)
  101103. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101104. else if(decoder->private_->has_stream_info) {
  101105. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101106. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101107. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101108. }
  101109. else
  101110. is_unparseable = true;
  101111. }
  101112. else if(x == 0) {
  101113. decoder->private_->frame.header.number.sample_number = 0;
  101114. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101115. }
  101116. else {
  101117. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101118. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101119. }
  101120. }
  101121. if(is_unparseable) {
  101122. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101123. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101124. return true;
  101125. }
  101126. return true;
  101127. }
  101128. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101129. {
  101130. FLAC__uint32 x;
  101131. FLAC__bool wasted_bits;
  101132. unsigned i;
  101133. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101134. return false; /* read_callback_ sets the state for us */
  101135. wasted_bits = (x & 1);
  101136. x &= 0xfe;
  101137. if(wasted_bits) {
  101138. unsigned u;
  101139. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101140. return false; /* read_callback_ sets the state for us */
  101141. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101142. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101143. }
  101144. else
  101145. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101146. /*
  101147. * Lots of magic numbers here
  101148. */
  101149. if(x & 0x80) {
  101150. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101151. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101152. return true;
  101153. }
  101154. else if(x == 0) {
  101155. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101156. return false;
  101157. }
  101158. else if(x == 2) {
  101159. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101160. return false;
  101161. }
  101162. else if(x < 16) {
  101163. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101164. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101165. return true;
  101166. }
  101167. else if(x <= 24) {
  101168. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101169. return false;
  101170. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101171. return true;
  101172. }
  101173. else if(x < 64) {
  101174. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101175. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101176. return true;
  101177. }
  101178. else {
  101179. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101180. return false;
  101181. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101182. return true;
  101183. }
  101184. if(wasted_bits && do_full_decode) {
  101185. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101186. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101187. decoder->private_->output[channel][i] <<= x;
  101188. }
  101189. return true;
  101190. }
  101191. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101192. {
  101193. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101194. FLAC__int32 x;
  101195. unsigned i;
  101196. FLAC__int32 *output = decoder->private_->output[channel];
  101197. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101198. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101199. return false; /* read_callback_ sets the state for us */
  101200. subframe->value = x;
  101201. /* decode the subframe */
  101202. if(do_full_decode) {
  101203. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101204. output[i] = x;
  101205. }
  101206. return true;
  101207. }
  101208. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101209. {
  101210. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101211. FLAC__int32 i32;
  101212. FLAC__uint32 u32;
  101213. unsigned u;
  101214. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101215. subframe->residual = decoder->private_->residual[channel];
  101216. subframe->order = order;
  101217. /* read warm-up samples */
  101218. for(u = 0; u < order; u++) {
  101219. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101220. return false; /* read_callback_ sets the state for us */
  101221. subframe->warmup[u] = i32;
  101222. }
  101223. /* read entropy coding method info */
  101224. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101225. return false; /* read_callback_ sets the state for us */
  101226. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101227. switch(subframe->entropy_coding_method.type) {
  101228. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101229. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101230. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101231. return false; /* read_callback_ sets the state for us */
  101232. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101233. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101234. break;
  101235. default:
  101236. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101237. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101238. return true;
  101239. }
  101240. /* read residual */
  101241. switch(subframe->entropy_coding_method.type) {
  101242. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101243. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101244. 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))
  101245. return false;
  101246. break;
  101247. default:
  101248. FLAC__ASSERT(0);
  101249. }
  101250. /* decode the subframe */
  101251. if(do_full_decode) {
  101252. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101253. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101254. }
  101255. return true;
  101256. }
  101257. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101258. {
  101259. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101260. FLAC__int32 i32;
  101261. FLAC__uint32 u32;
  101262. unsigned u;
  101263. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101264. subframe->residual = decoder->private_->residual[channel];
  101265. subframe->order = order;
  101266. /* read warm-up samples */
  101267. for(u = 0; u < order; u++) {
  101268. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101269. return false; /* read_callback_ sets the state for us */
  101270. subframe->warmup[u] = i32;
  101271. }
  101272. /* read qlp coeff precision */
  101273. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101274. return false; /* read_callback_ sets the state for us */
  101275. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101276. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101277. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101278. return true;
  101279. }
  101280. subframe->qlp_coeff_precision = u32+1;
  101281. /* read qlp shift */
  101282. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101283. return false; /* read_callback_ sets the state for us */
  101284. subframe->quantization_level = i32;
  101285. /* read quantized lp coefficiencts */
  101286. for(u = 0; u < order; u++) {
  101287. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101288. return false; /* read_callback_ sets the state for us */
  101289. subframe->qlp_coeff[u] = i32;
  101290. }
  101291. /* read entropy coding method info */
  101292. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101293. return false; /* read_callback_ sets the state for us */
  101294. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101295. switch(subframe->entropy_coding_method.type) {
  101296. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101297. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101298. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101299. return false; /* read_callback_ sets the state for us */
  101300. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101301. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101302. break;
  101303. default:
  101304. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101305. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101306. return true;
  101307. }
  101308. /* read residual */
  101309. switch(subframe->entropy_coding_method.type) {
  101310. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101311. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101312. 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))
  101313. return false;
  101314. break;
  101315. default:
  101316. FLAC__ASSERT(0);
  101317. }
  101318. /* decode the subframe */
  101319. if(do_full_decode) {
  101320. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101321. /*@@@@@@ technically not pessimistic enough, should be more like
  101322. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101323. */
  101324. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101325. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101326. if(order <= 8)
  101327. 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);
  101328. else
  101329. 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);
  101330. }
  101331. else
  101332. 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);
  101333. else
  101334. 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);
  101335. }
  101336. return true;
  101337. }
  101338. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101339. {
  101340. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101341. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101342. unsigned i;
  101343. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101344. subframe->data = residual;
  101345. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101346. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101347. return false; /* read_callback_ sets the state for us */
  101348. residual[i] = x;
  101349. }
  101350. /* decode the subframe */
  101351. if(do_full_decode)
  101352. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101353. return true;
  101354. }
  101355. 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)
  101356. {
  101357. FLAC__uint32 rice_parameter;
  101358. int i;
  101359. unsigned partition, sample, u;
  101360. const unsigned partitions = 1u << partition_order;
  101361. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101362. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101363. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101364. /* sanity checks */
  101365. if(partition_order == 0) {
  101366. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101367. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101368. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101369. return true;
  101370. }
  101371. }
  101372. else {
  101373. if(partition_samples < predictor_order) {
  101374. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101375. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101376. return true;
  101377. }
  101378. }
  101379. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101380. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101381. return false;
  101382. }
  101383. sample = 0;
  101384. for(partition = 0; partition < partitions; partition++) {
  101385. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101386. return false; /* read_callback_ sets the state for us */
  101387. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101388. if(rice_parameter < pesc) {
  101389. partitioned_rice_contents->raw_bits[partition] = 0;
  101390. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101391. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101392. return false; /* read_callback_ sets the state for us */
  101393. sample += u;
  101394. }
  101395. else {
  101396. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101397. return false; /* read_callback_ sets the state for us */
  101398. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101399. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101400. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101401. return false; /* read_callback_ sets the state for us */
  101402. residual[sample] = i;
  101403. }
  101404. }
  101405. }
  101406. return true;
  101407. }
  101408. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101409. {
  101410. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101411. FLAC__uint32 zero = 0;
  101412. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101413. return false; /* read_callback_ sets the state for us */
  101414. if(zero != 0) {
  101415. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101416. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101417. }
  101418. }
  101419. return true;
  101420. }
  101421. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101422. {
  101423. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101424. if(
  101425. #if FLAC__HAS_OGG
  101426. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101427. !decoder->private_->is_ogg &&
  101428. #endif
  101429. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101430. ) {
  101431. *bytes = 0;
  101432. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101433. return false;
  101434. }
  101435. else if(*bytes > 0) {
  101436. /* While seeking, it is possible for our seek to land in the
  101437. * middle of audio data that looks exactly like a frame header
  101438. * from a future version of an encoder. When that happens, our
  101439. * error callback will get an
  101440. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101441. * unparseable_frame_count. But there is a remote possibility
  101442. * that it is properly synced at such a "future-codec frame",
  101443. * so to make sure, we wait to see many "unparseable" errors in
  101444. * a row before bailing out.
  101445. */
  101446. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101447. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101448. return false;
  101449. }
  101450. else {
  101451. const FLAC__StreamDecoderReadStatus status =
  101452. #if FLAC__HAS_OGG
  101453. decoder->private_->is_ogg?
  101454. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101455. #endif
  101456. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101457. ;
  101458. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101459. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101460. return false;
  101461. }
  101462. else if(*bytes == 0) {
  101463. if(
  101464. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101465. (
  101466. #if FLAC__HAS_OGG
  101467. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101468. !decoder->private_->is_ogg &&
  101469. #endif
  101470. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101471. )
  101472. ) {
  101473. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101474. return false;
  101475. }
  101476. else
  101477. return true;
  101478. }
  101479. else
  101480. return true;
  101481. }
  101482. }
  101483. else {
  101484. /* abort to avoid a deadlock */
  101485. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101486. return false;
  101487. }
  101488. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101489. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101490. * and at the same time hit the end of the stream (for example, seeking
  101491. * to a point that is after the beginning of the last Ogg page). There
  101492. * is no way to report an Ogg sync loss through the callbacks (see note
  101493. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101494. * So to keep the decoder from stopping at this point we gate the call
  101495. * to the eof_callback and let the Ogg decoder aspect set the
  101496. * end-of-stream state when it is needed.
  101497. */
  101498. }
  101499. #if FLAC__HAS_OGG
  101500. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101501. {
  101502. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101503. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101504. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101505. /* we don't really have a way to handle lost sync via read
  101506. * callback so we'll let it pass and let the underlying
  101507. * FLAC decoder catch the error
  101508. */
  101509. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101510. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101511. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101512. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101513. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101514. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101515. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101516. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101517. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101518. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101519. default:
  101520. FLAC__ASSERT(0);
  101521. /* double protection */
  101522. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101523. }
  101524. }
  101525. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101526. {
  101527. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101528. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101529. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101530. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101531. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101532. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101533. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101534. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101535. default:
  101536. /* double protection: */
  101537. FLAC__ASSERT(0);
  101538. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101539. }
  101540. }
  101541. #endif
  101542. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101543. {
  101544. if(decoder->private_->is_seeking) {
  101545. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101546. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101547. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101548. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101549. #if FLAC__HAS_OGG
  101550. decoder->private_->got_a_frame = true;
  101551. #endif
  101552. decoder->private_->last_frame = *frame; /* save the frame */
  101553. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101554. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101555. /* kick out of seek mode */
  101556. decoder->private_->is_seeking = false;
  101557. /* shift out the samples before target_sample */
  101558. if(delta > 0) {
  101559. unsigned channel;
  101560. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101561. for(channel = 0; channel < frame->header.channels; channel++)
  101562. newbuffer[channel] = buffer[channel] + delta;
  101563. decoder->private_->last_frame.header.blocksize -= delta;
  101564. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101565. /* write the relevant samples */
  101566. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101567. }
  101568. else {
  101569. /* write the relevant samples */
  101570. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101571. }
  101572. }
  101573. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101574. }
  101575. /*
  101576. * If we never got STREAMINFO, turn off MD5 checking to save
  101577. * cycles since we don't have a sum to compare to anyway
  101578. */
  101579. if(!decoder->private_->has_stream_info)
  101580. decoder->private_->do_md5_checking = false;
  101581. if(decoder->private_->do_md5_checking) {
  101582. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101583. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101584. }
  101585. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101586. }
  101587. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101588. {
  101589. if(!decoder->private_->is_seeking)
  101590. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101591. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101592. decoder->private_->unparseable_frame_count++;
  101593. }
  101594. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101595. {
  101596. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101597. FLAC__int64 pos = -1;
  101598. int i;
  101599. unsigned approx_bytes_per_frame;
  101600. FLAC__bool first_seek = true;
  101601. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101602. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101603. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101604. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101605. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101606. /* take these from the current frame in case they've changed mid-stream */
  101607. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101608. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101609. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101610. /* use values from stream info if we didn't decode a frame */
  101611. if(channels == 0)
  101612. channels = decoder->private_->stream_info.data.stream_info.channels;
  101613. if(bps == 0)
  101614. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101615. /* we are just guessing here */
  101616. if(max_framesize > 0)
  101617. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101618. /*
  101619. * Check if it's a known fixed-blocksize stream. Note that though
  101620. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101621. * never get a STREAMINFO block when decoding so the value of
  101622. * min_blocksize might be zero.
  101623. */
  101624. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101625. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101626. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101627. }
  101628. else
  101629. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101630. /*
  101631. * First, we set an upper and lower bound on where in the
  101632. * stream we will search. For now we assume the worst case
  101633. * scenario, which is our best guess at the beginning of
  101634. * the first frame and end of the stream.
  101635. */
  101636. lower_bound = first_frame_offset;
  101637. lower_bound_sample = 0;
  101638. upper_bound = stream_length;
  101639. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101640. /*
  101641. * Now we refine the bounds if we have a seektable with
  101642. * suitable points. Note that according to the spec they
  101643. * must be ordered by ascending sample number.
  101644. *
  101645. * Note: to protect against invalid seek tables we will ignore points
  101646. * that have frame_samples==0 or sample_number>=total_samples
  101647. */
  101648. if(seek_table) {
  101649. FLAC__uint64 new_lower_bound = lower_bound;
  101650. FLAC__uint64 new_upper_bound = upper_bound;
  101651. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101652. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101653. /* find the closest seek point <= target_sample, if it exists */
  101654. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101655. if(
  101656. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101657. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101658. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101659. seek_table->points[i].sample_number <= target_sample
  101660. )
  101661. break;
  101662. }
  101663. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101664. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101665. new_lower_bound_sample = seek_table->points[i].sample_number;
  101666. }
  101667. /* find the closest seek point > target_sample, if it exists */
  101668. for(i = 0; i < (int)seek_table->num_points; i++) {
  101669. if(
  101670. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101671. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101672. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101673. seek_table->points[i].sample_number > target_sample
  101674. )
  101675. break;
  101676. }
  101677. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101678. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101679. new_upper_bound_sample = seek_table->points[i].sample_number;
  101680. }
  101681. /* final protection against unsorted seek tables; keep original values if bogus */
  101682. if(new_upper_bound >= new_lower_bound) {
  101683. lower_bound = new_lower_bound;
  101684. upper_bound = new_upper_bound;
  101685. lower_bound_sample = new_lower_bound_sample;
  101686. upper_bound_sample = new_upper_bound_sample;
  101687. }
  101688. }
  101689. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101690. /* there are 2 insidious ways that the following equality occurs, which
  101691. * we need to fix:
  101692. * 1) total_samples is 0 (unknown) and target_sample is 0
  101693. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101694. * exactly equal to the last seek point in the seek table; this
  101695. * means there is no seek point above it, and upper_bound_samples
  101696. * remains equal to the estimate (of target_samples) we made above
  101697. * in either case it does not hurt to move upper_bound_sample up by 1
  101698. */
  101699. if(upper_bound_sample == lower_bound_sample)
  101700. upper_bound_sample++;
  101701. decoder->private_->target_sample = target_sample;
  101702. while(1) {
  101703. /* check if the bounds are still ok */
  101704. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101705. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101706. return false;
  101707. }
  101708. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101709. #if defined _MSC_VER || defined __MINGW32__
  101710. /* with VC++ you have to spoon feed it the casting */
  101711. 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;
  101712. #else
  101713. 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;
  101714. #endif
  101715. #else
  101716. /* a little less accurate: */
  101717. if(upper_bound - lower_bound < 0xffffffff)
  101718. 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;
  101719. else /* @@@ WATCHOUT, ~2TB limit */
  101720. 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;
  101721. #endif
  101722. if(pos >= (FLAC__int64)upper_bound)
  101723. pos = (FLAC__int64)upper_bound - 1;
  101724. if(pos < (FLAC__int64)lower_bound)
  101725. pos = (FLAC__int64)lower_bound;
  101726. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101727. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101728. return false;
  101729. }
  101730. if(!FLAC__stream_decoder_flush(decoder)) {
  101731. /* above call sets the state for us */
  101732. return false;
  101733. }
  101734. /* Now we need to get a frame. First we need to reset our
  101735. * unparseable_frame_count; if we get too many unparseable
  101736. * frames in a row, the read callback will return
  101737. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101738. * FLAC__stream_decoder_process_single() to return false.
  101739. */
  101740. decoder->private_->unparseable_frame_count = 0;
  101741. if(!FLAC__stream_decoder_process_single(decoder)) {
  101742. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101743. return false;
  101744. }
  101745. /* our write callback will change the state when it gets to the target frame */
  101746. /* 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 */
  101747. #if 0
  101748. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101749. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101750. break;
  101751. #endif
  101752. if(!decoder->private_->is_seeking)
  101753. break;
  101754. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101755. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101756. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101757. if (pos == (FLAC__int64)lower_bound) {
  101758. /* can't move back any more than the first frame, something is fatally wrong */
  101759. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101760. return false;
  101761. }
  101762. /* our last move backwards wasn't big enough, try again */
  101763. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101764. continue;
  101765. }
  101766. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101767. first_seek = false;
  101768. /* make sure we are not seeking in corrupted stream */
  101769. if (this_frame_sample < lower_bound_sample) {
  101770. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101771. return false;
  101772. }
  101773. /* we need to narrow the search */
  101774. if(target_sample < this_frame_sample) {
  101775. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101776. /*@@@@@@ what will decode position be if at end of stream? */
  101777. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101778. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101779. return false;
  101780. }
  101781. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101782. }
  101783. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101784. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101785. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101786. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101787. return false;
  101788. }
  101789. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101790. }
  101791. }
  101792. return true;
  101793. }
  101794. #if FLAC__HAS_OGG
  101795. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101796. {
  101797. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101798. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101799. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101800. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101801. FLAC__bool did_a_seek;
  101802. unsigned iteration = 0;
  101803. /* In the first iterations, we will calculate the target byte position
  101804. * by the distance from the target sample to left_sample and
  101805. * right_sample (let's call it "proportional search"). After that, we
  101806. * will switch to binary search.
  101807. */
  101808. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101809. /* We will switch to a linear search once our current sample is less
  101810. * than this number of samples ahead of the target sample
  101811. */
  101812. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101813. /* If the total number of samples is unknown, use a large value, and
  101814. * force binary search immediately.
  101815. */
  101816. if(right_sample == 0) {
  101817. right_sample = (FLAC__uint64)(-1);
  101818. BINARY_SEARCH_AFTER_ITERATION = 0;
  101819. }
  101820. decoder->private_->target_sample = target_sample;
  101821. for( ; ; iteration++) {
  101822. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101823. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101824. pos = (right_pos + left_pos) / 2;
  101825. }
  101826. else {
  101827. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101828. #if defined _MSC_VER || defined __MINGW32__
  101829. /* with MSVC you have to spoon feed it the casting */
  101830. 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));
  101831. #else
  101832. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101833. #endif
  101834. #else
  101835. /* a little less accurate: */
  101836. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101837. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101838. else /* @@@ WATCHOUT, ~2TB limit */
  101839. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101840. #endif
  101841. /* @@@ TODO: might want to limit pos to some distance
  101842. * before EOF, to make sure we land before the last frame,
  101843. * thereby getting a this_frame_sample and so having a better
  101844. * estimate.
  101845. */
  101846. }
  101847. /* physical seek */
  101848. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101849. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101850. return false;
  101851. }
  101852. if(!FLAC__stream_decoder_flush(decoder)) {
  101853. /* above call sets the state for us */
  101854. return false;
  101855. }
  101856. did_a_seek = true;
  101857. }
  101858. else
  101859. did_a_seek = false;
  101860. decoder->private_->got_a_frame = false;
  101861. if(!FLAC__stream_decoder_process_single(decoder)) {
  101862. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101863. return false;
  101864. }
  101865. if(!decoder->private_->got_a_frame) {
  101866. if(did_a_seek) {
  101867. /* this can happen if we seek to a point after the last frame; we drop
  101868. * to binary search right away in this case to avoid any wasted
  101869. * iterations of proportional search.
  101870. */
  101871. right_pos = pos;
  101872. BINARY_SEARCH_AFTER_ITERATION = 0;
  101873. }
  101874. else {
  101875. /* this can probably only happen if total_samples is unknown and the
  101876. * target_sample is past the end of the stream
  101877. */
  101878. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101879. return false;
  101880. }
  101881. }
  101882. /* our write callback will change the state when it gets to the target frame */
  101883. else if(!decoder->private_->is_seeking) {
  101884. break;
  101885. }
  101886. else {
  101887. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101888. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101889. if (did_a_seek) {
  101890. if (this_frame_sample <= target_sample) {
  101891. /* The 'equal' case should not happen, since
  101892. * FLAC__stream_decoder_process_single()
  101893. * should recognize that it has hit the
  101894. * target sample and we would exit through
  101895. * the 'break' above.
  101896. */
  101897. FLAC__ASSERT(this_frame_sample != target_sample);
  101898. left_sample = this_frame_sample;
  101899. /* sanity check to avoid infinite loop */
  101900. if (left_pos == pos) {
  101901. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101902. return false;
  101903. }
  101904. left_pos = pos;
  101905. }
  101906. else if(this_frame_sample > target_sample) {
  101907. right_sample = this_frame_sample;
  101908. /* sanity check to avoid infinite loop */
  101909. if (right_pos == pos) {
  101910. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101911. return false;
  101912. }
  101913. right_pos = pos;
  101914. }
  101915. }
  101916. }
  101917. }
  101918. return true;
  101919. }
  101920. #endif
  101921. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101922. {
  101923. (void)client_data;
  101924. if(*bytes > 0) {
  101925. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101926. if(ferror(decoder->private_->file))
  101927. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101928. else if(*bytes == 0)
  101929. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101930. else
  101931. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101932. }
  101933. else
  101934. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101935. }
  101936. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101937. {
  101938. (void)client_data;
  101939. if(decoder->private_->file == stdin)
  101940. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101941. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101942. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101943. else
  101944. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101945. }
  101946. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101947. {
  101948. off_t pos;
  101949. (void)client_data;
  101950. if(decoder->private_->file == stdin)
  101951. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101952. else if((pos = ftello(decoder->private_->file)) < 0)
  101953. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101954. else {
  101955. *absolute_byte_offset = (FLAC__uint64)pos;
  101956. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101957. }
  101958. }
  101959. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101960. {
  101961. struct stat filestats;
  101962. (void)client_data;
  101963. if(decoder->private_->file == stdin)
  101964. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101965. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101966. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101967. else {
  101968. *stream_length = (FLAC__uint64)filestats.st_size;
  101969. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101970. }
  101971. }
  101972. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101973. {
  101974. (void)client_data;
  101975. return feof(decoder->private_->file)? true : false;
  101976. }
  101977. #endif
  101978. /*** End of inlined file: stream_decoder.c ***/
  101979. /*** Start of inlined file: stream_encoder.c ***/
  101980. /*** Start of inlined file: juce_FlacHeader.h ***/
  101981. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101982. // tasks..
  101983. #define VERSION "1.2.1"
  101984. #define FLAC__NO_DLL 1
  101985. #if JUCE_MSVC
  101986. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101987. #endif
  101988. #if JUCE_MAC
  101989. #define FLAC__SYS_DARWIN 1
  101990. #endif
  101991. /*** End of inlined file: juce_FlacHeader.h ***/
  101992. #if JUCE_USE_FLAC
  101993. #if HAVE_CONFIG_H
  101994. # include <config.h>
  101995. #endif
  101996. #if defined _MSC_VER || defined __MINGW32__
  101997. #include <io.h> /* for _setmode() */
  101998. #include <fcntl.h> /* for _O_BINARY */
  101999. #endif
  102000. #if defined __CYGWIN__ || defined __EMX__
  102001. #include <io.h> /* for setmode(), O_BINARY */
  102002. #include <fcntl.h> /* for _O_BINARY */
  102003. #endif
  102004. #include <limits.h>
  102005. #include <stdio.h>
  102006. #include <stdlib.h> /* for malloc() */
  102007. #include <string.h> /* for memcpy() */
  102008. #include <sys/types.h> /* for off_t */
  102009. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102010. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102011. #define fseeko fseek
  102012. #define ftello ftell
  102013. #endif
  102014. #endif
  102015. /*** Start of inlined file: stream_encoder.h ***/
  102016. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102017. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102018. #if FLAC__HAS_OGG
  102019. #include "private/ogg_encoder_aspect.h"
  102020. #endif
  102021. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102022. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102023. typedef enum {
  102024. FLAC__APODIZATION_BARTLETT,
  102025. FLAC__APODIZATION_BARTLETT_HANN,
  102026. FLAC__APODIZATION_BLACKMAN,
  102027. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102028. FLAC__APODIZATION_CONNES,
  102029. FLAC__APODIZATION_FLATTOP,
  102030. FLAC__APODIZATION_GAUSS,
  102031. FLAC__APODIZATION_HAMMING,
  102032. FLAC__APODIZATION_HANN,
  102033. FLAC__APODIZATION_KAISER_BESSEL,
  102034. FLAC__APODIZATION_NUTTALL,
  102035. FLAC__APODIZATION_RECTANGLE,
  102036. FLAC__APODIZATION_TRIANGLE,
  102037. FLAC__APODIZATION_TUKEY,
  102038. FLAC__APODIZATION_WELCH
  102039. } FLAC__ApodizationFunction;
  102040. typedef struct {
  102041. FLAC__ApodizationFunction type;
  102042. union {
  102043. struct {
  102044. FLAC__real stddev;
  102045. } gauss;
  102046. struct {
  102047. FLAC__real p;
  102048. } tukey;
  102049. } parameters;
  102050. } FLAC__ApodizationSpecification;
  102051. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102052. typedef struct FLAC__StreamEncoderProtected {
  102053. FLAC__StreamEncoderState state;
  102054. FLAC__bool verify;
  102055. FLAC__bool streamable_subset;
  102056. FLAC__bool do_md5;
  102057. FLAC__bool do_mid_side_stereo;
  102058. FLAC__bool loose_mid_side_stereo;
  102059. unsigned channels;
  102060. unsigned bits_per_sample;
  102061. unsigned sample_rate;
  102062. unsigned blocksize;
  102063. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102064. unsigned num_apodizations;
  102065. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102066. #endif
  102067. unsigned max_lpc_order;
  102068. unsigned qlp_coeff_precision;
  102069. FLAC__bool do_qlp_coeff_prec_search;
  102070. FLAC__bool do_exhaustive_model_search;
  102071. FLAC__bool do_escape_coding;
  102072. unsigned min_residual_partition_order;
  102073. unsigned max_residual_partition_order;
  102074. unsigned rice_parameter_search_dist;
  102075. FLAC__uint64 total_samples_estimate;
  102076. FLAC__StreamMetadata **metadata;
  102077. unsigned num_metadata_blocks;
  102078. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102079. #if FLAC__HAS_OGG
  102080. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102081. #endif
  102082. } FLAC__StreamEncoderProtected;
  102083. #endif
  102084. /*** End of inlined file: stream_encoder.h ***/
  102085. #if FLAC__HAS_OGG
  102086. #include "include/private/ogg_helper.h"
  102087. #include "include/private/ogg_mapping.h"
  102088. #endif
  102089. /*** Start of inlined file: stream_encoder_framing.h ***/
  102090. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102091. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102092. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102093. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102094. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102095. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102096. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102097. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102098. #endif
  102099. /*** End of inlined file: stream_encoder_framing.h ***/
  102100. /*** Start of inlined file: window.h ***/
  102101. #ifndef FLAC__PRIVATE__WINDOW_H
  102102. #define FLAC__PRIVATE__WINDOW_H
  102103. #ifdef HAVE_CONFIG_H
  102104. #include <config.h>
  102105. #endif
  102106. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102107. /*
  102108. * FLAC__window_*()
  102109. * --------------------------------------------------------------------
  102110. * Calculates window coefficients according to different apodization
  102111. * functions.
  102112. *
  102113. * OUT window[0,L-1]
  102114. * IN L (number of points in window)
  102115. */
  102116. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102117. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102118. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102119. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102120. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102121. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102122. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102123. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102124. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102125. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102126. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102127. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102128. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102129. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102130. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102131. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102132. #endif
  102133. /*** End of inlined file: window.h ***/
  102134. #ifndef FLaC__INLINE
  102135. #define FLaC__INLINE
  102136. #endif
  102137. #ifdef min
  102138. #undef min
  102139. #endif
  102140. #define min(x,y) ((x)<(y)?(x):(y))
  102141. #ifdef max
  102142. #undef max
  102143. #endif
  102144. #define max(x,y) ((x)>(y)?(x):(y))
  102145. /* Exact Rice codeword length calculation is off by default. The simple
  102146. * (and fast) estimation (of how many bits a residual value will be
  102147. * encoded with) in this encoder is very good, almost always yielding
  102148. * compression within 0.1% of exact calculation.
  102149. */
  102150. #undef EXACT_RICE_BITS_CALCULATION
  102151. /* Rice parameter searching is off by default. The simple (and fast)
  102152. * parameter estimation in this encoder is very good, almost always
  102153. * yielding compression within 0.1% of the optimal parameters.
  102154. */
  102155. #undef ENABLE_RICE_PARAMETER_SEARCH
  102156. typedef struct {
  102157. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102158. unsigned size; /* of each data[] in samples */
  102159. unsigned tail;
  102160. } verify_input_fifo;
  102161. typedef struct {
  102162. const FLAC__byte *data;
  102163. unsigned capacity;
  102164. unsigned bytes;
  102165. } verify_output;
  102166. typedef enum {
  102167. ENCODER_IN_MAGIC = 0,
  102168. ENCODER_IN_METADATA = 1,
  102169. ENCODER_IN_AUDIO = 2
  102170. } EncoderStateHint;
  102171. static struct CompressionLevels {
  102172. FLAC__bool do_mid_side_stereo;
  102173. FLAC__bool loose_mid_side_stereo;
  102174. unsigned max_lpc_order;
  102175. unsigned qlp_coeff_precision;
  102176. FLAC__bool do_qlp_coeff_prec_search;
  102177. FLAC__bool do_escape_coding;
  102178. FLAC__bool do_exhaustive_model_search;
  102179. unsigned min_residual_partition_order;
  102180. unsigned max_residual_partition_order;
  102181. unsigned rice_parameter_search_dist;
  102182. } compression_levels_[] = {
  102183. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102184. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102185. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102186. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102187. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102188. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102189. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102190. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102191. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102192. };
  102193. /***********************************************************************
  102194. *
  102195. * Private class method prototypes
  102196. *
  102197. ***********************************************************************/
  102198. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102199. static void free_(FLAC__StreamEncoder *encoder);
  102200. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102201. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102202. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102203. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102204. #if FLAC__HAS_OGG
  102205. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102206. #endif
  102207. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102208. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102209. static FLAC__bool process_subframe_(
  102210. FLAC__StreamEncoder *encoder,
  102211. unsigned min_partition_order,
  102212. unsigned max_partition_order,
  102213. const FLAC__FrameHeader *frame_header,
  102214. unsigned subframe_bps,
  102215. const FLAC__int32 integer_signal[],
  102216. FLAC__Subframe *subframe[2],
  102217. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102218. FLAC__int32 *residual[2],
  102219. unsigned *best_subframe,
  102220. unsigned *best_bits
  102221. );
  102222. static FLAC__bool add_subframe_(
  102223. FLAC__StreamEncoder *encoder,
  102224. unsigned blocksize,
  102225. unsigned subframe_bps,
  102226. const FLAC__Subframe *subframe,
  102227. FLAC__BitWriter *frame
  102228. );
  102229. static unsigned evaluate_constant_subframe_(
  102230. FLAC__StreamEncoder *encoder,
  102231. const FLAC__int32 signal,
  102232. unsigned blocksize,
  102233. unsigned subframe_bps,
  102234. FLAC__Subframe *subframe
  102235. );
  102236. static unsigned evaluate_fixed_subframe_(
  102237. FLAC__StreamEncoder *encoder,
  102238. const FLAC__int32 signal[],
  102239. FLAC__int32 residual[],
  102240. FLAC__uint64 abs_residual_partition_sums[],
  102241. unsigned raw_bits_per_partition[],
  102242. unsigned blocksize,
  102243. unsigned subframe_bps,
  102244. unsigned order,
  102245. unsigned rice_parameter,
  102246. unsigned rice_parameter_limit,
  102247. unsigned min_partition_order,
  102248. unsigned max_partition_order,
  102249. FLAC__bool do_escape_coding,
  102250. unsigned rice_parameter_search_dist,
  102251. FLAC__Subframe *subframe,
  102252. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102253. );
  102254. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102255. static unsigned evaluate_lpc_subframe_(
  102256. FLAC__StreamEncoder *encoder,
  102257. const FLAC__int32 signal[],
  102258. FLAC__int32 residual[],
  102259. FLAC__uint64 abs_residual_partition_sums[],
  102260. unsigned raw_bits_per_partition[],
  102261. const FLAC__real lp_coeff[],
  102262. unsigned blocksize,
  102263. unsigned subframe_bps,
  102264. unsigned order,
  102265. unsigned qlp_coeff_precision,
  102266. unsigned rice_parameter,
  102267. unsigned rice_parameter_limit,
  102268. unsigned min_partition_order,
  102269. unsigned max_partition_order,
  102270. FLAC__bool do_escape_coding,
  102271. unsigned rice_parameter_search_dist,
  102272. FLAC__Subframe *subframe,
  102273. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102274. );
  102275. #endif
  102276. static unsigned evaluate_verbatim_subframe_(
  102277. FLAC__StreamEncoder *encoder,
  102278. const FLAC__int32 signal[],
  102279. unsigned blocksize,
  102280. unsigned subframe_bps,
  102281. FLAC__Subframe *subframe
  102282. );
  102283. static unsigned find_best_partition_order_(
  102284. struct FLAC__StreamEncoderPrivate *private_,
  102285. const FLAC__int32 residual[],
  102286. FLAC__uint64 abs_residual_partition_sums[],
  102287. unsigned raw_bits_per_partition[],
  102288. unsigned residual_samples,
  102289. unsigned predictor_order,
  102290. unsigned rice_parameter,
  102291. unsigned rice_parameter_limit,
  102292. unsigned min_partition_order,
  102293. unsigned max_partition_order,
  102294. unsigned bps,
  102295. FLAC__bool do_escape_coding,
  102296. unsigned rice_parameter_search_dist,
  102297. FLAC__EntropyCodingMethod *best_ecm
  102298. );
  102299. static void precompute_partition_info_sums_(
  102300. const FLAC__int32 residual[],
  102301. FLAC__uint64 abs_residual_partition_sums[],
  102302. unsigned residual_samples,
  102303. unsigned predictor_order,
  102304. unsigned min_partition_order,
  102305. unsigned max_partition_order,
  102306. unsigned bps
  102307. );
  102308. static void precompute_partition_info_escapes_(
  102309. const FLAC__int32 residual[],
  102310. unsigned raw_bits_per_partition[],
  102311. unsigned residual_samples,
  102312. unsigned predictor_order,
  102313. unsigned min_partition_order,
  102314. unsigned max_partition_order
  102315. );
  102316. static FLAC__bool set_partitioned_rice_(
  102317. #ifdef EXACT_RICE_BITS_CALCULATION
  102318. const FLAC__int32 residual[],
  102319. #endif
  102320. const FLAC__uint64 abs_residual_partition_sums[],
  102321. const unsigned raw_bits_per_partition[],
  102322. const unsigned residual_samples,
  102323. const unsigned predictor_order,
  102324. const unsigned suggested_rice_parameter,
  102325. const unsigned rice_parameter_limit,
  102326. const unsigned rice_parameter_search_dist,
  102327. const unsigned partition_order,
  102328. const FLAC__bool search_for_escapes,
  102329. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102330. unsigned *bits
  102331. );
  102332. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102333. /* verify-related routines: */
  102334. static void append_to_verify_fifo_(
  102335. verify_input_fifo *fifo,
  102336. const FLAC__int32 * const input[],
  102337. unsigned input_offset,
  102338. unsigned channels,
  102339. unsigned wide_samples
  102340. );
  102341. static void append_to_verify_fifo_interleaved_(
  102342. verify_input_fifo *fifo,
  102343. const FLAC__int32 input[],
  102344. unsigned input_offset,
  102345. unsigned channels,
  102346. unsigned wide_samples
  102347. );
  102348. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102349. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102350. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102351. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102352. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102353. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102354. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102355. 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);
  102356. static FILE *get_binary_stdout_(void);
  102357. /***********************************************************************
  102358. *
  102359. * Private class data
  102360. *
  102361. ***********************************************************************/
  102362. typedef struct FLAC__StreamEncoderPrivate {
  102363. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102364. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102365. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102366. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102367. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102368. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102369. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102370. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102371. #endif
  102372. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102373. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102374. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102375. FLAC__int32 *residual_workspace_mid_side[2][2];
  102376. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102377. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102378. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102379. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102380. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102381. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102382. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102383. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102384. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102385. unsigned best_subframe_mid_side[2];
  102386. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102387. unsigned best_subframe_bits_mid_side[2];
  102388. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102389. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102390. FLAC__BitWriter *frame; /* the current frame being worked on */
  102391. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102392. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102393. FLAC__ChannelAssignment last_channel_assignment;
  102394. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102395. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102396. unsigned current_sample_number;
  102397. unsigned current_frame_number;
  102398. FLAC__MD5Context md5context;
  102399. FLAC__CPUInfo cpuinfo;
  102400. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102401. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102402. #else
  102403. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102404. #endif
  102405. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102406. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102407. 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[]);
  102408. 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[]);
  102409. 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[]);
  102410. #endif
  102411. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102412. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102413. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102414. FLAC__bool disable_constant_subframes;
  102415. FLAC__bool disable_fixed_subframes;
  102416. FLAC__bool disable_verbatim_subframes;
  102417. #if FLAC__HAS_OGG
  102418. FLAC__bool is_ogg;
  102419. #endif
  102420. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102421. FLAC__StreamEncoderSeekCallback seek_callback;
  102422. FLAC__StreamEncoderTellCallback tell_callback;
  102423. FLAC__StreamEncoderWriteCallback write_callback;
  102424. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102425. FLAC__StreamEncoderProgressCallback progress_callback;
  102426. void *client_data;
  102427. unsigned first_seekpoint_to_check;
  102428. FILE *file; /* only used when encoding to a file */
  102429. FLAC__uint64 bytes_written;
  102430. FLAC__uint64 samples_written;
  102431. unsigned frames_written;
  102432. unsigned total_frames_estimate;
  102433. /* unaligned (original) pointers to allocated data */
  102434. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102435. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102436. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102437. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102438. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102439. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102440. FLAC__real *windowed_signal_unaligned;
  102441. #endif
  102442. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102443. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102444. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102445. unsigned *raw_bits_per_partition_unaligned;
  102446. /*
  102447. * These fields have been moved here from private function local
  102448. * declarations merely to save stack space during encoding.
  102449. */
  102450. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102451. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102452. #endif
  102453. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102454. /*
  102455. * The data for the verify section
  102456. */
  102457. struct {
  102458. FLAC__StreamDecoder *decoder;
  102459. EncoderStateHint state_hint;
  102460. FLAC__bool needs_magic_hack;
  102461. verify_input_fifo input_fifo;
  102462. verify_output output;
  102463. struct {
  102464. FLAC__uint64 absolute_sample;
  102465. unsigned frame_number;
  102466. unsigned channel;
  102467. unsigned sample;
  102468. FLAC__int32 expected;
  102469. FLAC__int32 got;
  102470. } error_stats;
  102471. } verify;
  102472. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102473. } FLAC__StreamEncoderPrivate;
  102474. /***********************************************************************
  102475. *
  102476. * Public static class data
  102477. *
  102478. ***********************************************************************/
  102479. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102480. "FLAC__STREAM_ENCODER_OK",
  102481. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102482. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102483. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102484. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102485. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102486. "FLAC__STREAM_ENCODER_IO_ERROR",
  102487. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102488. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102489. };
  102490. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102491. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102492. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102493. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102494. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102495. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102496. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102497. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102498. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102499. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102500. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102501. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102502. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102503. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102504. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102505. };
  102506. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102507. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102508. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102509. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102510. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102511. };
  102512. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102513. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102514. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102515. };
  102516. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102517. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102518. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102519. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102520. };
  102521. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102522. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102523. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102524. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102525. };
  102526. /* Number of samples that will be overread to watch for end of stream. By
  102527. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102528. * always try to read blocksize+1 samples before encoding a block, so that
  102529. * even if the stream has a total sample count that is an integral multiple
  102530. * of the blocksize, we will still notice when we are encoding the last
  102531. * block. This is needed, for example, to correctly set the end-of-stream
  102532. * marker in Ogg FLAC.
  102533. *
  102534. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102535. * not really any reason to change it.
  102536. */
  102537. static const unsigned OVERREAD_ = 1;
  102538. /***********************************************************************
  102539. *
  102540. * Class constructor/destructor
  102541. *
  102542. */
  102543. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102544. {
  102545. FLAC__StreamEncoder *encoder;
  102546. unsigned i;
  102547. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102548. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102549. if(encoder == 0) {
  102550. return 0;
  102551. }
  102552. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102553. if(encoder->protected_ == 0) {
  102554. free(encoder);
  102555. return 0;
  102556. }
  102557. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102558. if(encoder->private_ == 0) {
  102559. free(encoder->protected_);
  102560. free(encoder);
  102561. return 0;
  102562. }
  102563. encoder->private_->frame = FLAC__bitwriter_new();
  102564. if(encoder->private_->frame == 0) {
  102565. free(encoder->private_);
  102566. free(encoder->protected_);
  102567. free(encoder);
  102568. return 0;
  102569. }
  102570. encoder->private_->file = 0;
  102571. set_defaults_enc(encoder);
  102572. encoder->private_->is_being_deleted = false;
  102573. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102574. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102575. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102576. }
  102577. for(i = 0; i < 2; i++) {
  102578. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102579. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102580. }
  102581. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102582. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102583. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102584. }
  102585. for(i = 0; i < 2; i++) {
  102586. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102587. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102588. }
  102589. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102590. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102591. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102592. }
  102593. for(i = 0; i < 2; i++) {
  102594. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102595. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102596. }
  102597. for(i = 0; i < 2; i++)
  102598. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102599. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102600. return encoder;
  102601. }
  102602. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102603. {
  102604. unsigned i;
  102605. FLAC__ASSERT(0 != encoder);
  102606. FLAC__ASSERT(0 != encoder->protected_);
  102607. FLAC__ASSERT(0 != encoder->private_);
  102608. FLAC__ASSERT(0 != encoder->private_->frame);
  102609. encoder->private_->is_being_deleted = true;
  102610. (void)FLAC__stream_encoder_finish(encoder);
  102611. if(0 != encoder->private_->verify.decoder)
  102612. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102613. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102614. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102615. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102616. }
  102617. for(i = 0; i < 2; i++) {
  102618. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102619. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102620. }
  102621. for(i = 0; i < 2; i++)
  102622. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102623. FLAC__bitwriter_delete(encoder->private_->frame);
  102624. free(encoder->private_);
  102625. free(encoder->protected_);
  102626. free(encoder);
  102627. }
  102628. /***********************************************************************
  102629. *
  102630. * Public class methods
  102631. *
  102632. ***********************************************************************/
  102633. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102634. FLAC__StreamEncoder *encoder,
  102635. FLAC__StreamEncoderReadCallback read_callback,
  102636. FLAC__StreamEncoderWriteCallback write_callback,
  102637. FLAC__StreamEncoderSeekCallback seek_callback,
  102638. FLAC__StreamEncoderTellCallback tell_callback,
  102639. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102640. void *client_data,
  102641. FLAC__bool is_ogg
  102642. )
  102643. {
  102644. unsigned i;
  102645. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102646. FLAC__ASSERT(0 != encoder);
  102647. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102648. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102649. #if !FLAC__HAS_OGG
  102650. if(is_ogg)
  102651. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102652. #endif
  102653. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102654. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102655. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102656. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102657. if(encoder->protected_->channels != 2) {
  102658. encoder->protected_->do_mid_side_stereo = false;
  102659. encoder->protected_->loose_mid_side_stereo = false;
  102660. }
  102661. else if(!encoder->protected_->do_mid_side_stereo)
  102662. encoder->protected_->loose_mid_side_stereo = false;
  102663. if(encoder->protected_->bits_per_sample >= 32)
  102664. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102665. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102666. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102667. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102668. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102669. if(encoder->protected_->blocksize == 0) {
  102670. if(encoder->protected_->max_lpc_order == 0)
  102671. encoder->protected_->blocksize = 1152;
  102672. else
  102673. encoder->protected_->blocksize = 4096;
  102674. }
  102675. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102676. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102677. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102678. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102679. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102680. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102681. if(encoder->protected_->qlp_coeff_precision == 0) {
  102682. if(encoder->protected_->bits_per_sample < 16) {
  102683. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102684. /* @@@ until then we'll make a guess */
  102685. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102686. }
  102687. else if(encoder->protected_->bits_per_sample == 16) {
  102688. if(encoder->protected_->blocksize <= 192)
  102689. encoder->protected_->qlp_coeff_precision = 7;
  102690. else if(encoder->protected_->blocksize <= 384)
  102691. encoder->protected_->qlp_coeff_precision = 8;
  102692. else if(encoder->protected_->blocksize <= 576)
  102693. encoder->protected_->qlp_coeff_precision = 9;
  102694. else if(encoder->protected_->blocksize <= 1152)
  102695. encoder->protected_->qlp_coeff_precision = 10;
  102696. else if(encoder->protected_->blocksize <= 2304)
  102697. encoder->protected_->qlp_coeff_precision = 11;
  102698. else if(encoder->protected_->blocksize <= 4608)
  102699. encoder->protected_->qlp_coeff_precision = 12;
  102700. else
  102701. encoder->protected_->qlp_coeff_precision = 13;
  102702. }
  102703. else {
  102704. if(encoder->protected_->blocksize <= 384)
  102705. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102706. else if(encoder->protected_->blocksize <= 1152)
  102707. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102708. else
  102709. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102710. }
  102711. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102712. }
  102713. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102714. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102715. if(encoder->protected_->streamable_subset) {
  102716. if(
  102717. encoder->protected_->blocksize != 192 &&
  102718. encoder->protected_->blocksize != 576 &&
  102719. encoder->protected_->blocksize != 1152 &&
  102720. encoder->protected_->blocksize != 2304 &&
  102721. encoder->protected_->blocksize != 4608 &&
  102722. encoder->protected_->blocksize != 256 &&
  102723. encoder->protected_->blocksize != 512 &&
  102724. encoder->protected_->blocksize != 1024 &&
  102725. encoder->protected_->blocksize != 2048 &&
  102726. encoder->protected_->blocksize != 4096 &&
  102727. encoder->protected_->blocksize != 8192 &&
  102728. encoder->protected_->blocksize != 16384
  102729. )
  102730. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102731. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102732. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102733. if(
  102734. encoder->protected_->bits_per_sample != 8 &&
  102735. encoder->protected_->bits_per_sample != 12 &&
  102736. encoder->protected_->bits_per_sample != 16 &&
  102737. encoder->protected_->bits_per_sample != 20 &&
  102738. encoder->protected_->bits_per_sample != 24
  102739. )
  102740. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102741. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102742. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102743. if(
  102744. encoder->protected_->sample_rate <= 48000 &&
  102745. (
  102746. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102747. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102748. )
  102749. ) {
  102750. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102751. }
  102752. }
  102753. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102754. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102755. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102756. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102757. #if FLAC__HAS_OGG
  102758. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102759. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102760. unsigned i;
  102761. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102762. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102763. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102764. for( ; i > 0; i--)
  102765. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102766. encoder->protected_->metadata[0] = vc;
  102767. break;
  102768. }
  102769. }
  102770. }
  102771. #endif
  102772. /* keep track of any SEEKTABLE block */
  102773. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102774. unsigned i;
  102775. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102776. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102777. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102778. break; /* take only the first one */
  102779. }
  102780. }
  102781. }
  102782. /* validate metadata */
  102783. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102784. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102785. metadata_has_seektable = false;
  102786. metadata_has_vorbis_comment = false;
  102787. metadata_picture_has_type1 = false;
  102788. metadata_picture_has_type2 = false;
  102789. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102790. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102791. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102792. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102793. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102794. if(metadata_has_seektable) /* only one is allowed */
  102795. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102796. metadata_has_seektable = true;
  102797. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102798. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102799. }
  102800. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102801. if(metadata_has_vorbis_comment) /* only one is allowed */
  102802. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102803. metadata_has_vorbis_comment = true;
  102804. }
  102805. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102806. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102807. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102808. }
  102809. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102810. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102811. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102812. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102813. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102814. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102815. metadata_picture_has_type1 = true;
  102816. /* standard icon must be 32x32 pixel PNG */
  102817. if(
  102818. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102819. (
  102820. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102821. m->data.picture.width != 32 ||
  102822. m->data.picture.height != 32
  102823. )
  102824. )
  102825. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102826. }
  102827. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102828. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102829. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102830. metadata_picture_has_type2 = true;
  102831. }
  102832. }
  102833. }
  102834. encoder->private_->input_capacity = 0;
  102835. for(i = 0; i < encoder->protected_->channels; i++) {
  102836. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102837. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102838. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102839. #endif
  102840. }
  102841. for(i = 0; i < 2; i++) {
  102842. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102843. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102844. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102845. #endif
  102846. }
  102847. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102848. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102849. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102850. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102851. #endif
  102852. for(i = 0; i < encoder->protected_->channels; i++) {
  102853. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102854. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102855. encoder->private_->best_subframe[i] = 0;
  102856. }
  102857. for(i = 0; i < 2; i++) {
  102858. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102859. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102860. encoder->private_->best_subframe_mid_side[i] = 0;
  102861. }
  102862. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102863. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102864. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102865. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102866. #else
  102867. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102868. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102869. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102870. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102871. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102872. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102873. 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);
  102874. #endif
  102875. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102876. encoder->private_->loose_mid_side_stereo_frames = 1;
  102877. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102878. encoder->private_->current_sample_number = 0;
  102879. encoder->private_->current_frame_number = 0;
  102880. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102881. 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? */
  102882. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102883. /*
  102884. * get the CPU info and set the function pointers
  102885. */
  102886. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102887. /* first default to the non-asm routines */
  102888. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102889. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102890. #endif
  102891. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102892. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102893. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102894. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102895. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102896. #endif
  102897. /* now override with asm where appropriate */
  102898. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102899. # ifndef FLAC__NO_ASM
  102900. if(encoder->private_->cpuinfo.use_asm) {
  102901. # ifdef FLAC__CPU_IA32
  102902. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102903. # ifdef FLAC__HAS_NASM
  102904. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102905. if(encoder->protected_->max_lpc_order < 4)
  102906. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102907. else if(encoder->protected_->max_lpc_order < 8)
  102908. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102909. else if(encoder->protected_->max_lpc_order < 12)
  102910. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102911. else
  102912. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102913. }
  102914. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102915. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102916. else
  102917. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102918. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102919. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102920. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102921. }
  102922. else {
  102923. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102924. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102925. }
  102926. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102927. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102928. # endif /* FLAC__HAS_NASM */
  102929. # endif /* FLAC__CPU_IA32 */
  102930. }
  102931. # endif /* !FLAC__NO_ASM */
  102932. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102933. /* finally override based on wide-ness if necessary */
  102934. if(encoder->private_->use_wide_by_block) {
  102935. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102936. }
  102937. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102938. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102939. #if FLAC__HAS_OGG
  102940. encoder->private_->is_ogg = is_ogg;
  102941. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102942. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102943. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102944. }
  102945. #endif
  102946. encoder->private_->read_callback = read_callback;
  102947. encoder->private_->write_callback = write_callback;
  102948. encoder->private_->seek_callback = seek_callback;
  102949. encoder->private_->tell_callback = tell_callback;
  102950. encoder->private_->metadata_callback = metadata_callback;
  102951. encoder->private_->client_data = client_data;
  102952. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102953. /* the above function sets the state for us in case of an error */
  102954. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102955. }
  102956. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102957. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102958. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102959. }
  102960. /*
  102961. * Set up the verify stuff if necessary
  102962. */
  102963. if(encoder->protected_->verify) {
  102964. /*
  102965. * First, set up the fifo which will hold the
  102966. * original signal to compare against
  102967. */
  102968. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102969. for(i = 0; i < encoder->protected_->channels; i++) {
  102970. 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))) {
  102971. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102972. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102973. }
  102974. }
  102975. encoder->private_->verify.input_fifo.tail = 0;
  102976. /*
  102977. * Now set up a stream decoder for verification
  102978. */
  102979. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102980. if(0 == encoder->private_->verify.decoder) {
  102981. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102982. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102983. }
  102984. 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) {
  102985. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102986. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102987. }
  102988. }
  102989. encoder->private_->verify.error_stats.absolute_sample = 0;
  102990. encoder->private_->verify.error_stats.frame_number = 0;
  102991. encoder->private_->verify.error_stats.channel = 0;
  102992. encoder->private_->verify.error_stats.sample = 0;
  102993. encoder->private_->verify.error_stats.expected = 0;
  102994. encoder->private_->verify.error_stats.got = 0;
  102995. /*
  102996. * These must be done before we write any metadata, because that
  102997. * calls the write_callback, which uses these values.
  102998. */
  102999. encoder->private_->first_seekpoint_to_check = 0;
  103000. encoder->private_->samples_written = 0;
  103001. encoder->protected_->streaminfo_offset = 0;
  103002. encoder->protected_->seektable_offset = 0;
  103003. encoder->protected_->audio_offset = 0;
  103004. /*
  103005. * write the stream header
  103006. */
  103007. if(encoder->protected_->verify)
  103008. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103009. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103010. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103011. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103012. }
  103013. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103014. /* the above function sets the state for us in case of an error */
  103015. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103016. }
  103017. /*
  103018. * write the STREAMINFO metadata block
  103019. */
  103020. if(encoder->protected_->verify)
  103021. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103022. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103023. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103024. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103025. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103026. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103027. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103028. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103029. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103030. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103031. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103032. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103033. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103034. if(encoder->protected_->do_md5)
  103035. FLAC__MD5Init(&encoder->private_->md5context);
  103036. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103037. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103038. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103039. }
  103040. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103041. /* the above function sets the state for us in case of an error */
  103042. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103043. }
  103044. /*
  103045. * Now that the STREAMINFO block is written, we can init this to an
  103046. * absurdly-high value...
  103047. */
  103048. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103049. /* ... and clear this to 0 */
  103050. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103051. /*
  103052. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103053. * if not, we will write an empty one (FLAC__add_metadata_block()
  103054. * automatically supplies the vendor string).
  103055. *
  103056. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103057. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103058. * true it will have already insured that the metadata list is properly
  103059. * ordered.)
  103060. */
  103061. if(!metadata_has_vorbis_comment) {
  103062. FLAC__StreamMetadata vorbis_comment;
  103063. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103064. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103065. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103066. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103067. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103068. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103069. vorbis_comment.data.vorbis_comment.comments = 0;
  103070. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103071. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103072. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103073. }
  103074. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103075. /* the above function sets the state for us in case of an error */
  103076. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103077. }
  103078. }
  103079. /*
  103080. * write the user's metadata blocks
  103081. */
  103082. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103083. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103084. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103085. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103086. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103087. }
  103088. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103089. /* the above function sets the state for us in case of an error */
  103090. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103091. }
  103092. }
  103093. /* now that all the metadata is written, we save the stream offset */
  103094. 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 */
  103095. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103096. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103097. }
  103098. if(encoder->protected_->verify)
  103099. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103100. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103101. }
  103102. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103103. FLAC__StreamEncoder *encoder,
  103104. FLAC__StreamEncoderWriteCallback write_callback,
  103105. FLAC__StreamEncoderSeekCallback seek_callback,
  103106. FLAC__StreamEncoderTellCallback tell_callback,
  103107. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103108. void *client_data
  103109. )
  103110. {
  103111. return init_stream_internal_enc(
  103112. encoder,
  103113. /*read_callback=*/0,
  103114. write_callback,
  103115. seek_callback,
  103116. tell_callback,
  103117. metadata_callback,
  103118. client_data,
  103119. /*is_ogg=*/false
  103120. );
  103121. }
  103122. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103123. FLAC__StreamEncoder *encoder,
  103124. FLAC__StreamEncoderReadCallback read_callback,
  103125. FLAC__StreamEncoderWriteCallback write_callback,
  103126. FLAC__StreamEncoderSeekCallback seek_callback,
  103127. FLAC__StreamEncoderTellCallback tell_callback,
  103128. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103129. void *client_data
  103130. )
  103131. {
  103132. return init_stream_internal_enc(
  103133. encoder,
  103134. read_callback,
  103135. write_callback,
  103136. seek_callback,
  103137. tell_callback,
  103138. metadata_callback,
  103139. client_data,
  103140. /*is_ogg=*/true
  103141. );
  103142. }
  103143. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103144. FLAC__StreamEncoder *encoder,
  103145. FILE *file,
  103146. FLAC__StreamEncoderProgressCallback progress_callback,
  103147. void *client_data,
  103148. FLAC__bool is_ogg
  103149. )
  103150. {
  103151. FLAC__StreamEncoderInitStatus init_status;
  103152. FLAC__ASSERT(0 != encoder);
  103153. FLAC__ASSERT(0 != file);
  103154. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103155. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103156. /* double protection */
  103157. if(file == 0) {
  103158. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103159. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103160. }
  103161. /*
  103162. * To make sure that our file does not go unclosed after an error, we
  103163. * must assign the FILE pointer before any further error can occur in
  103164. * this routine.
  103165. */
  103166. if(file == stdout)
  103167. file = get_binary_stdout_(); /* just to be safe */
  103168. encoder->private_->file = file;
  103169. encoder->private_->progress_callback = progress_callback;
  103170. encoder->private_->bytes_written = 0;
  103171. encoder->private_->samples_written = 0;
  103172. encoder->private_->frames_written = 0;
  103173. init_status = init_stream_internal_enc(
  103174. encoder,
  103175. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103176. file_write_callback_,
  103177. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103178. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103179. /*metadata_callback=*/0,
  103180. client_data,
  103181. is_ogg
  103182. );
  103183. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103184. /* the above function sets the state for us in case of an error */
  103185. return init_status;
  103186. }
  103187. {
  103188. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103189. FLAC__ASSERT(blocksize != 0);
  103190. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103191. }
  103192. return init_status;
  103193. }
  103194. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103195. FLAC__StreamEncoder *encoder,
  103196. FILE *file,
  103197. FLAC__StreamEncoderProgressCallback progress_callback,
  103198. void *client_data
  103199. )
  103200. {
  103201. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103202. }
  103203. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103204. FLAC__StreamEncoder *encoder,
  103205. FILE *file,
  103206. FLAC__StreamEncoderProgressCallback progress_callback,
  103207. void *client_data
  103208. )
  103209. {
  103210. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103211. }
  103212. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103213. FLAC__StreamEncoder *encoder,
  103214. const char *filename,
  103215. FLAC__StreamEncoderProgressCallback progress_callback,
  103216. void *client_data,
  103217. FLAC__bool is_ogg
  103218. )
  103219. {
  103220. FILE *file;
  103221. FLAC__ASSERT(0 != encoder);
  103222. /*
  103223. * To make sure that our file does not go unclosed after an error, we
  103224. * have to do the same entrance checks here that are later performed
  103225. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103226. */
  103227. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103228. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103229. file = filename? fopen(filename, "w+b") : stdout;
  103230. if(file == 0) {
  103231. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103232. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103233. }
  103234. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103235. }
  103236. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103237. FLAC__StreamEncoder *encoder,
  103238. const char *filename,
  103239. FLAC__StreamEncoderProgressCallback progress_callback,
  103240. void *client_data
  103241. )
  103242. {
  103243. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103244. }
  103245. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103246. FLAC__StreamEncoder *encoder,
  103247. const char *filename,
  103248. FLAC__StreamEncoderProgressCallback progress_callback,
  103249. void *client_data
  103250. )
  103251. {
  103252. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103253. }
  103254. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103255. {
  103256. FLAC__bool error = false;
  103257. FLAC__ASSERT(0 != encoder);
  103258. FLAC__ASSERT(0 != encoder->private_);
  103259. FLAC__ASSERT(0 != encoder->protected_);
  103260. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103261. return true;
  103262. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103263. if(encoder->private_->current_sample_number != 0) {
  103264. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103265. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103266. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103267. error = true;
  103268. }
  103269. }
  103270. if(encoder->protected_->do_md5)
  103271. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103272. if(!encoder->private_->is_being_deleted) {
  103273. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103274. if(encoder->private_->seek_callback) {
  103275. #if FLAC__HAS_OGG
  103276. if(encoder->private_->is_ogg)
  103277. update_ogg_metadata_(encoder);
  103278. else
  103279. #endif
  103280. update_metadata_(encoder);
  103281. /* check if an error occurred while updating metadata */
  103282. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103283. error = true;
  103284. }
  103285. if(encoder->private_->metadata_callback)
  103286. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103287. }
  103288. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103289. if(!error)
  103290. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103291. error = true;
  103292. }
  103293. }
  103294. if(0 != encoder->private_->file) {
  103295. if(encoder->private_->file != stdout)
  103296. fclose(encoder->private_->file);
  103297. encoder->private_->file = 0;
  103298. }
  103299. #if FLAC__HAS_OGG
  103300. if(encoder->private_->is_ogg)
  103301. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103302. #endif
  103303. free_(encoder);
  103304. set_defaults_enc(encoder);
  103305. if(!error)
  103306. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103307. return !error;
  103308. }
  103309. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103310. {
  103311. FLAC__ASSERT(0 != encoder);
  103312. FLAC__ASSERT(0 != encoder->private_);
  103313. FLAC__ASSERT(0 != encoder->protected_);
  103314. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103315. return false;
  103316. #if FLAC__HAS_OGG
  103317. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103318. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103319. return true;
  103320. #else
  103321. (void)value;
  103322. return false;
  103323. #endif
  103324. }
  103325. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103326. {
  103327. FLAC__ASSERT(0 != encoder);
  103328. FLAC__ASSERT(0 != encoder->private_);
  103329. FLAC__ASSERT(0 != encoder->protected_);
  103330. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103331. return false;
  103332. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103333. encoder->protected_->verify = value;
  103334. #endif
  103335. return true;
  103336. }
  103337. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103338. {
  103339. FLAC__ASSERT(0 != encoder);
  103340. FLAC__ASSERT(0 != encoder->private_);
  103341. FLAC__ASSERT(0 != encoder->protected_);
  103342. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103343. return false;
  103344. encoder->protected_->streamable_subset = value;
  103345. return true;
  103346. }
  103347. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103348. {
  103349. FLAC__ASSERT(0 != encoder);
  103350. FLAC__ASSERT(0 != encoder->private_);
  103351. FLAC__ASSERT(0 != encoder->protected_);
  103352. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103353. return false;
  103354. encoder->protected_->do_md5 = value;
  103355. return true;
  103356. }
  103357. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103358. {
  103359. FLAC__ASSERT(0 != encoder);
  103360. FLAC__ASSERT(0 != encoder->private_);
  103361. FLAC__ASSERT(0 != encoder->protected_);
  103362. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103363. return false;
  103364. encoder->protected_->channels = value;
  103365. return true;
  103366. }
  103367. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103368. {
  103369. FLAC__ASSERT(0 != encoder);
  103370. FLAC__ASSERT(0 != encoder->private_);
  103371. FLAC__ASSERT(0 != encoder->protected_);
  103372. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103373. return false;
  103374. encoder->protected_->bits_per_sample = value;
  103375. return true;
  103376. }
  103377. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103378. {
  103379. FLAC__ASSERT(0 != encoder);
  103380. FLAC__ASSERT(0 != encoder->private_);
  103381. FLAC__ASSERT(0 != encoder->protected_);
  103382. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103383. return false;
  103384. encoder->protected_->sample_rate = value;
  103385. return true;
  103386. }
  103387. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103388. {
  103389. FLAC__bool ok = true;
  103390. FLAC__ASSERT(0 != encoder);
  103391. FLAC__ASSERT(0 != encoder->private_);
  103392. FLAC__ASSERT(0 != encoder->protected_);
  103393. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103394. return false;
  103395. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103396. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103397. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103398. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103399. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103400. #if 0
  103401. /* was: */
  103402. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103403. /* but it's too hard to specify the string in a locale-specific way */
  103404. #else
  103405. encoder->protected_->num_apodizations = 1;
  103406. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103407. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103408. #endif
  103409. #endif
  103410. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103411. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103412. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103413. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103414. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103415. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103416. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103417. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103418. return ok;
  103419. }
  103420. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103421. {
  103422. FLAC__ASSERT(0 != encoder);
  103423. FLAC__ASSERT(0 != encoder->private_);
  103424. FLAC__ASSERT(0 != encoder->protected_);
  103425. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103426. return false;
  103427. encoder->protected_->blocksize = value;
  103428. return true;
  103429. }
  103430. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103431. {
  103432. FLAC__ASSERT(0 != encoder);
  103433. FLAC__ASSERT(0 != encoder->private_);
  103434. FLAC__ASSERT(0 != encoder->protected_);
  103435. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103436. return false;
  103437. encoder->protected_->do_mid_side_stereo = value;
  103438. return true;
  103439. }
  103440. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103441. {
  103442. FLAC__ASSERT(0 != encoder);
  103443. FLAC__ASSERT(0 != encoder->private_);
  103444. FLAC__ASSERT(0 != encoder->protected_);
  103445. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103446. return false;
  103447. encoder->protected_->loose_mid_side_stereo = value;
  103448. return true;
  103449. }
  103450. /*@@@@add to tests*/
  103451. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103452. {
  103453. FLAC__ASSERT(0 != encoder);
  103454. FLAC__ASSERT(0 != encoder->private_);
  103455. FLAC__ASSERT(0 != encoder->protected_);
  103456. FLAC__ASSERT(0 != specification);
  103457. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103458. return false;
  103459. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103460. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103461. #else
  103462. encoder->protected_->num_apodizations = 0;
  103463. while(1) {
  103464. const char *s = strchr(specification, ';');
  103465. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103466. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103467. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103468. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103469. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103470. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103471. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103472. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103473. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103474. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103475. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103476. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103477. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103478. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103479. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103480. if (stddev > 0.0 && stddev <= 0.5) {
  103481. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103482. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103483. }
  103484. }
  103485. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103486. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103487. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103488. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103489. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103490. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103491. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103492. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103493. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103494. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103495. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103496. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103497. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103498. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103499. if (p >= 0.0 && p <= 1.0) {
  103500. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103501. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103502. }
  103503. }
  103504. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103505. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103506. if (encoder->protected_->num_apodizations == 32)
  103507. break;
  103508. if (s)
  103509. specification = s+1;
  103510. else
  103511. break;
  103512. }
  103513. if(encoder->protected_->num_apodizations == 0) {
  103514. encoder->protected_->num_apodizations = 1;
  103515. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103516. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103517. }
  103518. #endif
  103519. return true;
  103520. }
  103521. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103522. {
  103523. FLAC__ASSERT(0 != encoder);
  103524. FLAC__ASSERT(0 != encoder->private_);
  103525. FLAC__ASSERT(0 != encoder->protected_);
  103526. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103527. return false;
  103528. encoder->protected_->max_lpc_order = value;
  103529. return true;
  103530. }
  103531. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103532. {
  103533. FLAC__ASSERT(0 != encoder);
  103534. FLAC__ASSERT(0 != encoder->private_);
  103535. FLAC__ASSERT(0 != encoder->protected_);
  103536. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103537. return false;
  103538. encoder->protected_->qlp_coeff_precision = value;
  103539. return true;
  103540. }
  103541. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103542. {
  103543. FLAC__ASSERT(0 != encoder);
  103544. FLAC__ASSERT(0 != encoder->private_);
  103545. FLAC__ASSERT(0 != encoder->protected_);
  103546. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103547. return false;
  103548. encoder->protected_->do_qlp_coeff_prec_search = value;
  103549. return true;
  103550. }
  103551. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103552. {
  103553. FLAC__ASSERT(0 != encoder);
  103554. FLAC__ASSERT(0 != encoder->private_);
  103555. FLAC__ASSERT(0 != encoder->protected_);
  103556. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103557. return false;
  103558. #if 0
  103559. /*@@@ deprecated: */
  103560. encoder->protected_->do_escape_coding = value;
  103561. #else
  103562. (void)value;
  103563. #endif
  103564. return true;
  103565. }
  103566. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103567. {
  103568. FLAC__ASSERT(0 != encoder);
  103569. FLAC__ASSERT(0 != encoder->private_);
  103570. FLAC__ASSERT(0 != encoder->protected_);
  103571. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103572. return false;
  103573. encoder->protected_->do_exhaustive_model_search = value;
  103574. return true;
  103575. }
  103576. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103577. {
  103578. FLAC__ASSERT(0 != encoder);
  103579. FLAC__ASSERT(0 != encoder->private_);
  103580. FLAC__ASSERT(0 != encoder->protected_);
  103581. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103582. return false;
  103583. encoder->protected_->min_residual_partition_order = value;
  103584. return true;
  103585. }
  103586. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103587. {
  103588. FLAC__ASSERT(0 != encoder);
  103589. FLAC__ASSERT(0 != encoder->private_);
  103590. FLAC__ASSERT(0 != encoder->protected_);
  103591. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103592. return false;
  103593. encoder->protected_->max_residual_partition_order = value;
  103594. return true;
  103595. }
  103596. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103597. {
  103598. FLAC__ASSERT(0 != encoder);
  103599. FLAC__ASSERT(0 != encoder->private_);
  103600. FLAC__ASSERT(0 != encoder->protected_);
  103601. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103602. return false;
  103603. #if 0
  103604. /*@@@ deprecated: */
  103605. encoder->protected_->rice_parameter_search_dist = value;
  103606. #else
  103607. (void)value;
  103608. #endif
  103609. return true;
  103610. }
  103611. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103612. {
  103613. FLAC__ASSERT(0 != encoder);
  103614. FLAC__ASSERT(0 != encoder->private_);
  103615. FLAC__ASSERT(0 != encoder->protected_);
  103616. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103617. return false;
  103618. encoder->protected_->total_samples_estimate = value;
  103619. return true;
  103620. }
  103621. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103622. {
  103623. FLAC__ASSERT(0 != encoder);
  103624. FLAC__ASSERT(0 != encoder->private_);
  103625. FLAC__ASSERT(0 != encoder->protected_);
  103626. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103627. return false;
  103628. if(0 == metadata)
  103629. num_blocks = 0;
  103630. if(0 == num_blocks)
  103631. metadata = 0;
  103632. /* realloc() does not do exactly what we want so... */
  103633. if(encoder->protected_->metadata) {
  103634. free(encoder->protected_->metadata);
  103635. encoder->protected_->metadata = 0;
  103636. encoder->protected_->num_metadata_blocks = 0;
  103637. }
  103638. if(num_blocks) {
  103639. FLAC__StreamMetadata **m;
  103640. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103641. return false;
  103642. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103643. encoder->protected_->metadata = m;
  103644. encoder->protected_->num_metadata_blocks = num_blocks;
  103645. }
  103646. #if FLAC__HAS_OGG
  103647. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103648. return false;
  103649. #endif
  103650. return true;
  103651. }
  103652. /*
  103653. * These three functions are not static, but not publically exposed in
  103654. * include/FLAC/ either. They are used by the test suite.
  103655. */
  103656. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103657. {
  103658. FLAC__ASSERT(0 != encoder);
  103659. FLAC__ASSERT(0 != encoder->private_);
  103660. FLAC__ASSERT(0 != encoder->protected_);
  103661. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103662. return false;
  103663. encoder->private_->disable_constant_subframes = value;
  103664. return true;
  103665. }
  103666. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103667. {
  103668. FLAC__ASSERT(0 != encoder);
  103669. FLAC__ASSERT(0 != encoder->private_);
  103670. FLAC__ASSERT(0 != encoder->protected_);
  103671. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103672. return false;
  103673. encoder->private_->disable_fixed_subframes = value;
  103674. return true;
  103675. }
  103676. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103677. {
  103678. FLAC__ASSERT(0 != encoder);
  103679. FLAC__ASSERT(0 != encoder->private_);
  103680. FLAC__ASSERT(0 != encoder->protected_);
  103681. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103682. return false;
  103683. encoder->private_->disable_verbatim_subframes = value;
  103684. return true;
  103685. }
  103686. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103687. {
  103688. FLAC__ASSERT(0 != encoder);
  103689. FLAC__ASSERT(0 != encoder->private_);
  103690. FLAC__ASSERT(0 != encoder->protected_);
  103691. return encoder->protected_->state;
  103692. }
  103693. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103694. {
  103695. FLAC__ASSERT(0 != encoder);
  103696. FLAC__ASSERT(0 != encoder->private_);
  103697. FLAC__ASSERT(0 != encoder->protected_);
  103698. if(encoder->protected_->verify)
  103699. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103700. else
  103701. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103702. }
  103703. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103704. {
  103705. FLAC__ASSERT(0 != encoder);
  103706. FLAC__ASSERT(0 != encoder->private_);
  103707. FLAC__ASSERT(0 != encoder->protected_);
  103708. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103709. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103710. else
  103711. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103712. }
  103713. 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)
  103714. {
  103715. FLAC__ASSERT(0 != encoder);
  103716. FLAC__ASSERT(0 != encoder->private_);
  103717. FLAC__ASSERT(0 != encoder->protected_);
  103718. if(0 != absolute_sample)
  103719. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103720. if(0 != frame_number)
  103721. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103722. if(0 != channel)
  103723. *channel = encoder->private_->verify.error_stats.channel;
  103724. if(0 != sample)
  103725. *sample = encoder->private_->verify.error_stats.sample;
  103726. if(0 != expected)
  103727. *expected = encoder->private_->verify.error_stats.expected;
  103728. if(0 != got)
  103729. *got = encoder->private_->verify.error_stats.got;
  103730. }
  103731. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103732. {
  103733. FLAC__ASSERT(0 != encoder);
  103734. FLAC__ASSERT(0 != encoder->private_);
  103735. FLAC__ASSERT(0 != encoder->protected_);
  103736. return encoder->protected_->verify;
  103737. }
  103738. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103739. {
  103740. FLAC__ASSERT(0 != encoder);
  103741. FLAC__ASSERT(0 != encoder->private_);
  103742. FLAC__ASSERT(0 != encoder->protected_);
  103743. return encoder->protected_->streamable_subset;
  103744. }
  103745. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103746. {
  103747. FLAC__ASSERT(0 != encoder);
  103748. FLAC__ASSERT(0 != encoder->private_);
  103749. FLAC__ASSERT(0 != encoder->protected_);
  103750. return encoder->protected_->do_md5;
  103751. }
  103752. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103753. {
  103754. FLAC__ASSERT(0 != encoder);
  103755. FLAC__ASSERT(0 != encoder->private_);
  103756. FLAC__ASSERT(0 != encoder->protected_);
  103757. return encoder->protected_->channels;
  103758. }
  103759. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103760. {
  103761. FLAC__ASSERT(0 != encoder);
  103762. FLAC__ASSERT(0 != encoder->private_);
  103763. FLAC__ASSERT(0 != encoder->protected_);
  103764. return encoder->protected_->bits_per_sample;
  103765. }
  103766. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103767. {
  103768. FLAC__ASSERT(0 != encoder);
  103769. FLAC__ASSERT(0 != encoder->private_);
  103770. FLAC__ASSERT(0 != encoder->protected_);
  103771. return encoder->protected_->sample_rate;
  103772. }
  103773. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103774. {
  103775. FLAC__ASSERT(0 != encoder);
  103776. FLAC__ASSERT(0 != encoder->private_);
  103777. FLAC__ASSERT(0 != encoder->protected_);
  103778. return encoder->protected_->blocksize;
  103779. }
  103780. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103781. {
  103782. FLAC__ASSERT(0 != encoder);
  103783. FLAC__ASSERT(0 != encoder->private_);
  103784. FLAC__ASSERT(0 != encoder->protected_);
  103785. return encoder->protected_->do_mid_side_stereo;
  103786. }
  103787. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103788. {
  103789. FLAC__ASSERT(0 != encoder);
  103790. FLAC__ASSERT(0 != encoder->private_);
  103791. FLAC__ASSERT(0 != encoder->protected_);
  103792. return encoder->protected_->loose_mid_side_stereo;
  103793. }
  103794. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103795. {
  103796. FLAC__ASSERT(0 != encoder);
  103797. FLAC__ASSERT(0 != encoder->private_);
  103798. FLAC__ASSERT(0 != encoder->protected_);
  103799. return encoder->protected_->max_lpc_order;
  103800. }
  103801. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103802. {
  103803. FLAC__ASSERT(0 != encoder);
  103804. FLAC__ASSERT(0 != encoder->private_);
  103805. FLAC__ASSERT(0 != encoder->protected_);
  103806. return encoder->protected_->qlp_coeff_precision;
  103807. }
  103808. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103809. {
  103810. FLAC__ASSERT(0 != encoder);
  103811. FLAC__ASSERT(0 != encoder->private_);
  103812. FLAC__ASSERT(0 != encoder->protected_);
  103813. return encoder->protected_->do_qlp_coeff_prec_search;
  103814. }
  103815. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103816. {
  103817. FLAC__ASSERT(0 != encoder);
  103818. FLAC__ASSERT(0 != encoder->private_);
  103819. FLAC__ASSERT(0 != encoder->protected_);
  103820. return encoder->protected_->do_escape_coding;
  103821. }
  103822. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103823. {
  103824. FLAC__ASSERT(0 != encoder);
  103825. FLAC__ASSERT(0 != encoder->private_);
  103826. FLAC__ASSERT(0 != encoder->protected_);
  103827. return encoder->protected_->do_exhaustive_model_search;
  103828. }
  103829. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103830. {
  103831. FLAC__ASSERT(0 != encoder);
  103832. FLAC__ASSERT(0 != encoder->private_);
  103833. FLAC__ASSERT(0 != encoder->protected_);
  103834. return encoder->protected_->min_residual_partition_order;
  103835. }
  103836. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103837. {
  103838. FLAC__ASSERT(0 != encoder);
  103839. FLAC__ASSERT(0 != encoder->private_);
  103840. FLAC__ASSERT(0 != encoder->protected_);
  103841. return encoder->protected_->max_residual_partition_order;
  103842. }
  103843. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103844. {
  103845. FLAC__ASSERT(0 != encoder);
  103846. FLAC__ASSERT(0 != encoder->private_);
  103847. FLAC__ASSERT(0 != encoder->protected_);
  103848. return encoder->protected_->rice_parameter_search_dist;
  103849. }
  103850. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103851. {
  103852. FLAC__ASSERT(0 != encoder);
  103853. FLAC__ASSERT(0 != encoder->private_);
  103854. FLAC__ASSERT(0 != encoder->protected_);
  103855. return encoder->protected_->total_samples_estimate;
  103856. }
  103857. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103858. {
  103859. unsigned i, j = 0, channel;
  103860. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103861. FLAC__ASSERT(0 != encoder);
  103862. FLAC__ASSERT(0 != encoder->private_);
  103863. FLAC__ASSERT(0 != encoder->protected_);
  103864. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103865. do {
  103866. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103867. if(encoder->protected_->verify)
  103868. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103869. for(channel = 0; channel < channels; channel++)
  103870. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103871. if(encoder->protected_->do_mid_side_stereo) {
  103872. FLAC__ASSERT(channels == 2);
  103873. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103874. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103875. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103876. 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' ! */
  103877. }
  103878. }
  103879. else
  103880. j += n;
  103881. encoder->private_->current_sample_number += n;
  103882. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103883. if(encoder->private_->current_sample_number > blocksize) {
  103884. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103885. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103886. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103887. return false;
  103888. /* move unprocessed overread samples to beginnings of arrays */
  103889. for(channel = 0; channel < channels; channel++)
  103890. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103891. if(encoder->protected_->do_mid_side_stereo) {
  103892. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103893. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103894. }
  103895. encoder->private_->current_sample_number = 1;
  103896. }
  103897. } while(j < samples);
  103898. return true;
  103899. }
  103900. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103901. {
  103902. unsigned i, j, k, channel;
  103903. FLAC__int32 x, mid, side;
  103904. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103905. FLAC__ASSERT(0 != encoder);
  103906. FLAC__ASSERT(0 != encoder->private_);
  103907. FLAC__ASSERT(0 != encoder->protected_);
  103908. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103909. j = k = 0;
  103910. /*
  103911. * we have several flavors of the same basic loop, optimized for
  103912. * different conditions:
  103913. */
  103914. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103915. /*
  103916. * stereo coding: unroll channel loop
  103917. */
  103918. do {
  103919. if(encoder->protected_->verify)
  103920. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103921. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103922. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103923. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103924. x = buffer[k++];
  103925. encoder->private_->integer_signal[1][i] = x;
  103926. mid += x;
  103927. side -= x;
  103928. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103929. encoder->private_->integer_signal_mid_side[1][i] = side;
  103930. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103931. }
  103932. encoder->private_->current_sample_number = i;
  103933. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103934. if(i > blocksize) {
  103935. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103936. return false;
  103937. /* move unprocessed overread samples to beginnings of arrays */
  103938. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103939. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103940. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103941. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103942. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103943. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103944. encoder->private_->current_sample_number = 1;
  103945. }
  103946. } while(j < samples);
  103947. }
  103948. else {
  103949. /*
  103950. * independent channel coding: buffer each channel in inner loop
  103951. */
  103952. do {
  103953. if(encoder->protected_->verify)
  103954. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103955. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103956. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103957. for(channel = 0; channel < channels; channel++)
  103958. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103959. }
  103960. encoder->private_->current_sample_number = i;
  103961. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103962. if(i > blocksize) {
  103963. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103964. return false;
  103965. /* move unprocessed overread samples to beginnings of arrays */
  103966. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103967. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103968. for(channel = 0; channel < channels; channel++)
  103969. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103970. encoder->private_->current_sample_number = 1;
  103971. }
  103972. } while(j < samples);
  103973. }
  103974. return true;
  103975. }
  103976. /***********************************************************************
  103977. *
  103978. * Private class methods
  103979. *
  103980. ***********************************************************************/
  103981. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103982. {
  103983. FLAC__ASSERT(0 != encoder);
  103984. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103985. encoder->protected_->verify = true;
  103986. #else
  103987. encoder->protected_->verify = false;
  103988. #endif
  103989. encoder->protected_->streamable_subset = true;
  103990. encoder->protected_->do_md5 = true;
  103991. encoder->protected_->do_mid_side_stereo = false;
  103992. encoder->protected_->loose_mid_side_stereo = false;
  103993. encoder->protected_->channels = 2;
  103994. encoder->protected_->bits_per_sample = 16;
  103995. encoder->protected_->sample_rate = 44100;
  103996. encoder->protected_->blocksize = 0;
  103997. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103998. encoder->protected_->num_apodizations = 1;
  103999. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104000. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104001. #endif
  104002. encoder->protected_->max_lpc_order = 0;
  104003. encoder->protected_->qlp_coeff_precision = 0;
  104004. encoder->protected_->do_qlp_coeff_prec_search = false;
  104005. encoder->protected_->do_exhaustive_model_search = false;
  104006. encoder->protected_->do_escape_coding = false;
  104007. encoder->protected_->min_residual_partition_order = 0;
  104008. encoder->protected_->max_residual_partition_order = 0;
  104009. encoder->protected_->rice_parameter_search_dist = 0;
  104010. encoder->protected_->total_samples_estimate = 0;
  104011. encoder->protected_->metadata = 0;
  104012. encoder->protected_->num_metadata_blocks = 0;
  104013. encoder->private_->seek_table = 0;
  104014. encoder->private_->disable_constant_subframes = false;
  104015. encoder->private_->disable_fixed_subframes = false;
  104016. encoder->private_->disable_verbatim_subframes = false;
  104017. #if FLAC__HAS_OGG
  104018. encoder->private_->is_ogg = false;
  104019. #endif
  104020. encoder->private_->read_callback = 0;
  104021. encoder->private_->write_callback = 0;
  104022. encoder->private_->seek_callback = 0;
  104023. encoder->private_->tell_callback = 0;
  104024. encoder->private_->metadata_callback = 0;
  104025. encoder->private_->progress_callback = 0;
  104026. encoder->private_->client_data = 0;
  104027. #if FLAC__HAS_OGG
  104028. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104029. #endif
  104030. }
  104031. void free_(FLAC__StreamEncoder *encoder)
  104032. {
  104033. unsigned i, channel;
  104034. FLAC__ASSERT(0 != encoder);
  104035. if(encoder->protected_->metadata) {
  104036. free(encoder->protected_->metadata);
  104037. encoder->protected_->metadata = 0;
  104038. encoder->protected_->num_metadata_blocks = 0;
  104039. }
  104040. for(i = 0; i < encoder->protected_->channels; i++) {
  104041. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104042. free(encoder->private_->integer_signal_unaligned[i]);
  104043. encoder->private_->integer_signal_unaligned[i] = 0;
  104044. }
  104045. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104046. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104047. free(encoder->private_->real_signal_unaligned[i]);
  104048. encoder->private_->real_signal_unaligned[i] = 0;
  104049. }
  104050. #endif
  104051. }
  104052. for(i = 0; i < 2; i++) {
  104053. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104054. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104055. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104056. }
  104057. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104058. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104059. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104060. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104061. }
  104062. #endif
  104063. }
  104064. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104065. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104066. if(0 != encoder->private_->window_unaligned[i]) {
  104067. free(encoder->private_->window_unaligned[i]);
  104068. encoder->private_->window_unaligned[i] = 0;
  104069. }
  104070. }
  104071. if(0 != encoder->private_->windowed_signal_unaligned) {
  104072. free(encoder->private_->windowed_signal_unaligned);
  104073. encoder->private_->windowed_signal_unaligned = 0;
  104074. }
  104075. #endif
  104076. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104077. for(i = 0; i < 2; i++) {
  104078. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104079. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104080. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104081. }
  104082. }
  104083. }
  104084. for(channel = 0; channel < 2; channel++) {
  104085. for(i = 0; i < 2; i++) {
  104086. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104087. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104088. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104089. }
  104090. }
  104091. }
  104092. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104093. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104094. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104095. }
  104096. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104097. free(encoder->private_->raw_bits_per_partition_unaligned);
  104098. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104099. }
  104100. if(encoder->protected_->verify) {
  104101. for(i = 0; i < encoder->protected_->channels; i++) {
  104102. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104103. free(encoder->private_->verify.input_fifo.data[i]);
  104104. encoder->private_->verify.input_fifo.data[i] = 0;
  104105. }
  104106. }
  104107. }
  104108. FLAC__bitwriter_free(encoder->private_->frame);
  104109. }
  104110. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104111. {
  104112. FLAC__bool ok;
  104113. unsigned i, channel;
  104114. FLAC__ASSERT(new_blocksize > 0);
  104115. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104116. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104117. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104118. if(new_blocksize <= encoder->private_->input_capacity)
  104119. return true;
  104120. ok = true;
  104121. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104122. * requires that the input arrays (in our case the integer signals)
  104123. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104124. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104125. */
  104126. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104127. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104128. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104129. encoder->private_->integer_signal[i] += 4;
  104130. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104131. #if 0 /* @@@ currently unused */
  104132. if(encoder->protected_->max_lpc_order > 0)
  104133. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104134. #endif
  104135. #endif
  104136. }
  104137. for(i = 0; ok && i < 2; i++) {
  104138. 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]);
  104139. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104140. encoder->private_->integer_signal_mid_side[i] += 4;
  104141. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104142. #if 0 /* @@@ currently unused */
  104143. if(encoder->protected_->max_lpc_order > 0)
  104144. 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]);
  104145. #endif
  104146. #endif
  104147. }
  104148. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104149. if(ok && encoder->protected_->max_lpc_order > 0) {
  104150. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104151. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104152. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104153. }
  104154. #endif
  104155. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104156. for(i = 0; ok && i < 2; i++) {
  104157. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104158. }
  104159. }
  104160. for(channel = 0; ok && channel < 2; channel++) {
  104161. for(i = 0; ok && i < 2; i++) {
  104162. 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]);
  104163. }
  104164. }
  104165. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104166. /*@@@ 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) */
  104167. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104168. if(encoder->protected_->do_escape_coding)
  104169. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104170. /* now adjust the windows if the blocksize has changed */
  104171. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104172. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104173. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104174. switch(encoder->protected_->apodizations[i].type) {
  104175. case FLAC__APODIZATION_BARTLETT:
  104176. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104177. break;
  104178. case FLAC__APODIZATION_BARTLETT_HANN:
  104179. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104180. break;
  104181. case FLAC__APODIZATION_BLACKMAN:
  104182. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104183. break;
  104184. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104185. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104186. break;
  104187. case FLAC__APODIZATION_CONNES:
  104188. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104189. break;
  104190. case FLAC__APODIZATION_FLATTOP:
  104191. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104192. break;
  104193. case FLAC__APODIZATION_GAUSS:
  104194. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104195. break;
  104196. case FLAC__APODIZATION_HAMMING:
  104197. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104198. break;
  104199. case FLAC__APODIZATION_HANN:
  104200. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104201. break;
  104202. case FLAC__APODIZATION_KAISER_BESSEL:
  104203. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104204. break;
  104205. case FLAC__APODIZATION_NUTTALL:
  104206. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104207. break;
  104208. case FLAC__APODIZATION_RECTANGLE:
  104209. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104210. break;
  104211. case FLAC__APODIZATION_TRIANGLE:
  104212. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104213. break;
  104214. case FLAC__APODIZATION_TUKEY:
  104215. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104216. break;
  104217. case FLAC__APODIZATION_WELCH:
  104218. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104219. break;
  104220. default:
  104221. FLAC__ASSERT(0);
  104222. /* double protection */
  104223. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104224. break;
  104225. }
  104226. }
  104227. }
  104228. #endif
  104229. if(ok)
  104230. encoder->private_->input_capacity = new_blocksize;
  104231. else
  104232. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104233. return ok;
  104234. }
  104235. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104236. {
  104237. const FLAC__byte *buffer;
  104238. size_t bytes;
  104239. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104240. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104241. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104242. return false;
  104243. }
  104244. if(encoder->protected_->verify) {
  104245. encoder->private_->verify.output.data = buffer;
  104246. encoder->private_->verify.output.bytes = bytes;
  104247. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104248. encoder->private_->verify.needs_magic_hack = true;
  104249. }
  104250. else {
  104251. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104252. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104253. FLAC__bitwriter_clear(encoder->private_->frame);
  104254. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104255. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104256. return false;
  104257. }
  104258. }
  104259. }
  104260. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104261. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104262. FLAC__bitwriter_clear(encoder->private_->frame);
  104263. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104264. return false;
  104265. }
  104266. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104267. FLAC__bitwriter_clear(encoder->private_->frame);
  104268. if(samples > 0) {
  104269. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104270. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104271. }
  104272. return true;
  104273. }
  104274. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104275. {
  104276. FLAC__StreamEncoderWriteStatus status;
  104277. FLAC__uint64 output_position = 0;
  104278. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104279. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104280. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104281. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104282. }
  104283. /*
  104284. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104285. */
  104286. if(samples == 0) {
  104287. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104288. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104289. encoder->protected_->streaminfo_offset = output_position;
  104290. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104291. encoder->protected_->seektable_offset = output_position;
  104292. }
  104293. /*
  104294. * Mark the current seek point if hit (if audio_offset == 0 that
  104295. * means we're still writing metadata and haven't hit the first
  104296. * frame yet)
  104297. */
  104298. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104299. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104300. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104301. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104302. FLAC__uint64 test_sample;
  104303. unsigned i;
  104304. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104305. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104306. if(test_sample > frame_last_sample) {
  104307. break;
  104308. }
  104309. else if(test_sample >= frame_first_sample) {
  104310. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104311. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104312. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104313. encoder->private_->first_seekpoint_to_check++;
  104314. /* DO NOT: "break;" and here's why:
  104315. * The seektable template may contain more than one target
  104316. * sample for any given frame; we will keep looping, generating
  104317. * duplicate seekpoints for them, and we'll clean it up later,
  104318. * just before writing the seektable back to the metadata.
  104319. */
  104320. }
  104321. else {
  104322. encoder->private_->first_seekpoint_to_check++;
  104323. }
  104324. }
  104325. }
  104326. #if FLAC__HAS_OGG
  104327. if(encoder->private_->is_ogg) {
  104328. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104329. &encoder->protected_->ogg_encoder_aspect,
  104330. buffer,
  104331. bytes,
  104332. samples,
  104333. encoder->private_->current_frame_number,
  104334. is_last_block,
  104335. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104336. encoder,
  104337. encoder->private_->client_data
  104338. );
  104339. }
  104340. else
  104341. #endif
  104342. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104343. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104344. encoder->private_->bytes_written += bytes;
  104345. encoder->private_->samples_written += samples;
  104346. /* we keep a high watermark on the number of frames written because
  104347. * when the encoder goes back to write metadata, 'current_frame'
  104348. * will drop back to 0.
  104349. */
  104350. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104351. }
  104352. else
  104353. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104354. return status;
  104355. }
  104356. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104357. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104358. {
  104359. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104360. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104361. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104362. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104363. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104364. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104365. FLAC__StreamEncoderSeekStatus seek_status;
  104366. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104367. /* All this is based on intimate knowledge of the stream header
  104368. * layout, but a change to the header format that would break this
  104369. * would also break all streams encoded in the previous format.
  104370. */
  104371. /*
  104372. * Write MD5 signature
  104373. */
  104374. {
  104375. const unsigned md5_offset =
  104376. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104377. (
  104378. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104379. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104380. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104381. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104382. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104383. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104384. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104385. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104386. ) / 8;
  104387. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104388. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104389. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104390. return;
  104391. }
  104392. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104393. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104394. return;
  104395. }
  104396. }
  104397. /*
  104398. * Write total samples
  104399. */
  104400. {
  104401. const unsigned total_samples_byte_offset =
  104402. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104403. (
  104404. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104405. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104406. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104407. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104408. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104409. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104410. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104411. - 4
  104412. ) / 8;
  104413. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104414. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104415. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104416. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104417. b[4] = (FLAC__byte)(samples & 0xFF);
  104418. 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) {
  104419. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104420. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104421. return;
  104422. }
  104423. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104424. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104425. return;
  104426. }
  104427. }
  104428. /*
  104429. * Write min/max framesize
  104430. */
  104431. {
  104432. const unsigned min_framesize_offset =
  104433. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104434. (
  104435. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104436. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104437. ) / 8;
  104438. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104439. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104440. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104441. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104442. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104443. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104444. 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) {
  104445. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104446. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104447. return;
  104448. }
  104449. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104450. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104451. return;
  104452. }
  104453. }
  104454. /*
  104455. * Write seektable
  104456. */
  104457. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104458. unsigned i;
  104459. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104460. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104461. 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) {
  104462. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104463. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104464. return;
  104465. }
  104466. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104467. FLAC__uint64 xx;
  104468. unsigned x;
  104469. xx = encoder->private_->seek_table->points[i].sample_number;
  104470. b[7] = (FLAC__byte)xx; xx >>= 8;
  104471. b[6] = (FLAC__byte)xx; xx >>= 8;
  104472. b[5] = (FLAC__byte)xx; xx >>= 8;
  104473. b[4] = (FLAC__byte)xx; xx >>= 8;
  104474. b[3] = (FLAC__byte)xx; xx >>= 8;
  104475. b[2] = (FLAC__byte)xx; xx >>= 8;
  104476. b[1] = (FLAC__byte)xx; xx >>= 8;
  104477. b[0] = (FLAC__byte)xx; xx >>= 8;
  104478. xx = encoder->private_->seek_table->points[i].stream_offset;
  104479. b[15] = (FLAC__byte)xx; xx >>= 8;
  104480. b[14] = (FLAC__byte)xx; xx >>= 8;
  104481. b[13] = (FLAC__byte)xx; xx >>= 8;
  104482. b[12] = (FLAC__byte)xx; xx >>= 8;
  104483. b[11] = (FLAC__byte)xx; xx >>= 8;
  104484. b[10] = (FLAC__byte)xx; xx >>= 8;
  104485. b[9] = (FLAC__byte)xx; xx >>= 8;
  104486. b[8] = (FLAC__byte)xx; xx >>= 8;
  104487. x = encoder->private_->seek_table->points[i].frame_samples;
  104488. b[17] = (FLAC__byte)x; x >>= 8;
  104489. b[16] = (FLAC__byte)x; x >>= 8;
  104490. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104491. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104492. return;
  104493. }
  104494. }
  104495. }
  104496. }
  104497. #if FLAC__HAS_OGG
  104498. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104499. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104500. {
  104501. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104502. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104503. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104504. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104505. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104506. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104507. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104508. FLAC__STREAM_SYNC_LENGTH
  104509. ;
  104510. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104511. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104512. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104513. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104514. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104515. ogg_page page;
  104516. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104517. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104518. /* Pre-check that client supports seeking, since we don't want the
  104519. * ogg_helper code to ever have to deal with this condition.
  104520. */
  104521. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104522. return;
  104523. /* All this is based on intimate knowledge of the stream header
  104524. * layout, but a change to the header format that would break this
  104525. * would also break all streams encoded in the previous format.
  104526. */
  104527. /**
  104528. ** Write STREAMINFO stats
  104529. **/
  104530. simple_ogg_page__init(&page);
  104531. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104532. simple_ogg_page__clear(&page);
  104533. return; /* state already set */
  104534. }
  104535. /*
  104536. * Write MD5 signature
  104537. */
  104538. {
  104539. const unsigned md5_offset =
  104540. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104541. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104542. (
  104543. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104544. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104545. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104546. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104547. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104548. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104549. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104550. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104551. ) / 8;
  104552. if(md5_offset + 16 > (unsigned)page.body_len) {
  104553. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104554. simple_ogg_page__clear(&page);
  104555. return;
  104556. }
  104557. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104558. }
  104559. /*
  104560. * Write total samples
  104561. */
  104562. {
  104563. const unsigned total_samples_byte_offset =
  104564. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104565. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104566. (
  104567. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104568. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104569. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104570. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104571. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104572. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104573. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104574. - 4
  104575. ) / 8;
  104576. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104577. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104578. simple_ogg_page__clear(&page);
  104579. return;
  104580. }
  104581. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104582. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104583. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104584. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104585. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104586. b[4] = (FLAC__byte)(samples & 0xFF);
  104587. memcpy(page.body + total_samples_byte_offset, b, 5);
  104588. }
  104589. /*
  104590. * Write min/max framesize
  104591. */
  104592. {
  104593. const unsigned min_framesize_offset =
  104594. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104595. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104596. (
  104597. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104598. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104599. ) / 8;
  104600. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104601. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104602. simple_ogg_page__clear(&page);
  104603. return;
  104604. }
  104605. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104606. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104607. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104608. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104609. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104610. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104611. memcpy(page.body + min_framesize_offset, b, 6);
  104612. }
  104613. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104614. simple_ogg_page__clear(&page);
  104615. return; /* state already set */
  104616. }
  104617. simple_ogg_page__clear(&page);
  104618. /*
  104619. * Write seektable
  104620. */
  104621. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104622. unsigned i;
  104623. FLAC__byte *p;
  104624. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104625. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104626. simple_ogg_page__init(&page);
  104627. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104628. simple_ogg_page__clear(&page);
  104629. return; /* state already set */
  104630. }
  104631. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104632. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104633. simple_ogg_page__clear(&page);
  104634. return;
  104635. }
  104636. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104637. FLAC__uint64 xx;
  104638. unsigned x;
  104639. xx = encoder->private_->seek_table->points[i].sample_number;
  104640. b[7] = (FLAC__byte)xx; xx >>= 8;
  104641. b[6] = (FLAC__byte)xx; xx >>= 8;
  104642. b[5] = (FLAC__byte)xx; xx >>= 8;
  104643. b[4] = (FLAC__byte)xx; xx >>= 8;
  104644. b[3] = (FLAC__byte)xx; xx >>= 8;
  104645. b[2] = (FLAC__byte)xx; xx >>= 8;
  104646. b[1] = (FLAC__byte)xx; xx >>= 8;
  104647. b[0] = (FLAC__byte)xx; xx >>= 8;
  104648. xx = encoder->private_->seek_table->points[i].stream_offset;
  104649. b[15] = (FLAC__byte)xx; xx >>= 8;
  104650. b[14] = (FLAC__byte)xx; xx >>= 8;
  104651. b[13] = (FLAC__byte)xx; xx >>= 8;
  104652. b[12] = (FLAC__byte)xx; xx >>= 8;
  104653. b[11] = (FLAC__byte)xx; xx >>= 8;
  104654. b[10] = (FLAC__byte)xx; xx >>= 8;
  104655. b[9] = (FLAC__byte)xx; xx >>= 8;
  104656. b[8] = (FLAC__byte)xx; xx >>= 8;
  104657. x = encoder->private_->seek_table->points[i].frame_samples;
  104658. b[17] = (FLAC__byte)x; x >>= 8;
  104659. b[16] = (FLAC__byte)x; x >>= 8;
  104660. memcpy(p, b, 18);
  104661. }
  104662. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104663. simple_ogg_page__clear(&page);
  104664. return; /* state already set */
  104665. }
  104666. simple_ogg_page__clear(&page);
  104667. }
  104668. }
  104669. #endif
  104670. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104671. {
  104672. FLAC__uint16 crc;
  104673. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104674. /*
  104675. * Accumulate raw signal to the MD5 signature
  104676. */
  104677. 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)) {
  104678. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104679. return false;
  104680. }
  104681. /*
  104682. * Process the frame header and subframes into the frame bitbuffer
  104683. */
  104684. if(!process_subframes_(encoder, is_fractional_block)) {
  104685. /* the above function sets the state for us in case of an error */
  104686. return false;
  104687. }
  104688. /*
  104689. * Zero-pad the frame to a byte_boundary
  104690. */
  104691. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104692. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104693. return false;
  104694. }
  104695. /*
  104696. * CRC-16 the whole thing
  104697. */
  104698. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104699. if(
  104700. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104701. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104702. ) {
  104703. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104704. return false;
  104705. }
  104706. /*
  104707. * Write it
  104708. */
  104709. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104710. /* the above function sets the state for us in case of an error */
  104711. return false;
  104712. }
  104713. /*
  104714. * Get ready for the next frame
  104715. */
  104716. encoder->private_->current_sample_number = 0;
  104717. encoder->private_->current_frame_number++;
  104718. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104719. return true;
  104720. }
  104721. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104722. {
  104723. FLAC__FrameHeader frame_header;
  104724. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104725. FLAC__bool do_independent, do_mid_side;
  104726. /*
  104727. * Calculate the min,max Rice partition orders
  104728. */
  104729. if(is_fractional_block) {
  104730. max_partition_order = 0;
  104731. }
  104732. else {
  104733. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104734. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104735. }
  104736. min_partition_order = min(min_partition_order, max_partition_order);
  104737. /*
  104738. * Setup the frame
  104739. */
  104740. frame_header.blocksize = encoder->protected_->blocksize;
  104741. frame_header.sample_rate = encoder->protected_->sample_rate;
  104742. frame_header.channels = encoder->protected_->channels;
  104743. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104744. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104745. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104746. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104747. /*
  104748. * Figure out what channel assignments to try
  104749. */
  104750. if(encoder->protected_->do_mid_side_stereo) {
  104751. if(encoder->protected_->loose_mid_side_stereo) {
  104752. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104753. do_independent = true;
  104754. do_mid_side = true;
  104755. }
  104756. else {
  104757. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104758. do_mid_side = !do_independent;
  104759. }
  104760. }
  104761. else {
  104762. do_independent = true;
  104763. do_mid_side = true;
  104764. }
  104765. }
  104766. else {
  104767. do_independent = true;
  104768. do_mid_side = false;
  104769. }
  104770. FLAC__ASSERT(do_independent || do_mid_side);
  104771. /*
  104772. * Check for wasted bits; set effective bps for each subframe
  104773. */
  104774. if(do_independent) {
  104775. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104776. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104777. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104778. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104779. }
  104780. }
  104781. if(do_mid_side) {
  104782. FLAC__ASSERT(encoder->protected_->channels == 2);
  104783. for(channel = 0; channel < 2; channel++) {
  104784. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104785. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104786. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104787. }
  104788. }
  104789. /*
  104790. * First do a normal encoding pass of each independent channel
  104791. */
  104792. if(do_independent) {
  104793. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104794. if(!
  104795. process_subframe_(
  104796. encoder,
  104797. min_partition_order,
  104798. max_partition_order,
  104799. &frame_header,
  104800. encoder->private_->subframe_bps[channel],
  104801. encoder->private_->integer_signal[channel],
  104802. encoder->private_->subframe_workspace_ptr[channel],
  104803. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104804. encoder->private_->residual_workspace[channel],
  104805. encoder->private_->best_subframe+channel,
  104806. encoder->private_->best_subframe_bits+channel
  104807. )
  104808. )
  104809. return false;
  104810. }
  104811. }
  104812. /*
  104813. * Now do mid and side channels if requested
  104814. */
  104815. if(do_mid_side) {
  104816. FLAC__ASSERT(encoder->protected_->channels == 2);
  104817. for(channel = 0; channel < 2; channel++) {
  104818. if(!
  104819. process_subframe_(
  104820. encoder,
  104821. min_partition_order,
  104822. max_partition_order,
  104823. &frame_header,
  104824. encoder->private_->subframe_bps_mid_side[channel],
  104825. encoder->private_->integer_signal_mid_side[channel],
  104826. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104827. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104828. encoder->private_->residual_workspace_mid_side[channel],
  104829. encoder->private_->best_subframe_mid_side+channel,
  104830. encoder->private_->best_subframe_bits_mid_side+channel
  104831. )
  104832. )
  104833. return false;
  104834. }
  104835. }
  104836. /*
  104837. * Compose the frame bitbuffer
  104838. */
  104839. if(do_mid_side) {
  104840. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104841. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104842. FLAC__ChannelAssignment channel_assignment;
  104843. FLAC__ASSERT(encoder->protected_->channels == 2);
  104844. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104845. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104846. }
  104847. else {
  104848. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104849. unsigned min_bits;
  104850. int ca;
  104851. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104852. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104853. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104854. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104855. FLAC__ASSERT(do_independent && do_mid_side);
  104856. /* We have to figure out which channel assignent results in the smallest frame */
  104857. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104858. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104859. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104860. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104861. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104862. min_bits = bits[channel_assignment];
  104863. for(ca = 1; ca <= 3; ca++) {
  104864. if(bits[ca] < min_bits) {
  104865. min_bits = bits[ca];
  104866. channel_assignment = (FLAC__ChannelAssignment)ca;
  104867. }
  104868. }
  104869. }
  104870. frame_header.channel_assignment = channel_assignment;
  104871. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104872. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104873. return false;
  104874. }
  104875. switch(channel_assignment) {
  104876. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104877. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104878. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104879. break;
  104880. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104881. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104882. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104883. break;
  104884. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104885. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104886. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104887. break;
  104888. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104889. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104890. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104891. break;
  104892. default:
  104893. FLAC__ASSERT(0);
  104894. }
  104895. switch(channel_assignment) {
  104896. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104897. left_bps = encoder->private_->subframe_bps [0];
  104898. right_bps = encoder->private_->subframe_bps [1];
  104899. break;
  104900. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104901. left_bps = encoder->private_->subframe_bps [0];
  104902. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104903. break;
  104904. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104905. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104906. right_bps = encoder->private_->subframe_bps [1];
  104907. break;
  104908. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104909. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104910. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104911. break;
  104912. default:
  104913. FLAC__ASSERT(0);
  104914. }
  104915. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104916. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104917. return false;
  104918. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104919. return false;
  104920. }
  104921. else {
  104922. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104923. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104924. return false;
  104925. }
  104926. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104927. 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)) {
  104928. /* the above function sets the state for us in case of an error */
  104929. return false;
  104930. }
  104931. }
  104932. }
  104933. if(encoder->protected_->loose_mid_side_stereo) {
  104934. encoder->private_->loose_mid_side_stereo_frame_count++;
  104935. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104936. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104937. }
  104938. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104939. return true;
  104940. }
  104941. FLAC__bool process_subframe_(
  104942. FLAC__StreamEncoder *encoder,
  104943. unsigned min_partition_order,
  104944. unsigned max_partition_order,
  104945. const FLAC__FrameHeader *frame_header,
  104946. unsigned subframe_bps,
  104947. const FLAC__int32 integer_signal[],
  104948. FLAC__Subframe *subframe[2],
  104949. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104950. FLAC__int32 *residual[2],
  104951. unsigned *best_subframe,
  104952. unsigned *best_bits
  104953. )
  104954. {
  104955. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104956. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104957. #else
  104958. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104959. #endif
  104960. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104961. FLAC__double lpc_residual_bits_per_sample;
  104962. 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 */
  104963. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104964. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104965. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104966. #endif
  104967. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104968. unsigned rice_parameter;
  104969. unsigned _candidate_bits, _best_bits;
  104970. unsigned _best_subframe;
  104971. /* only use RICE2 partitions if stream bps > 16 */
  104972. 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;
  104973. FLAC__ASSERT(frame_header->blocksize > 0);
  104974. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104975. _best_subframe = 0;
  104976. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104977. _best_bits = UINT_MAX;
  104978. else
  104979. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104980. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104981. unsigned signal_is_constant = false;
  104982. 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);
  104983. /* check for constant subframe */
  104984. if(
  104985. !encoder->private_->disable_constant_subframes &&
  104986. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104987. fixed_residual_bits_per_sample[1] == 0.0
  104988. #else
  104989. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104990. #endif
  104991. ) {
  104992. /* the above means it's possible all samples are the same value; now double-check it: */
  104993. unsigned i;
  104994. signal_is_constant = true;
  104995. for(i = 1; i < frame_header->blocksize; i++) {
  104996. if(integer_signal[0] != integer_signal[i]) {
  104997. signal_is_constant = false;
  104998. break;
  104999. }
  105000. }
  105001. }
  105002. if(signal_is_constant) {
  105003. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105004. if(_candidate_bits < _best_bits) {
  105005. _best_subframe = !_best_subframe;
  105006. _best_bits = _candidate_bits;
  105007. }
  105008. }
  105009. else {
  105010. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105011. /* encode fixed */
  105012. if(encoder->protected_->do_exhaustive_model_search) {
  105013. min_fixed_order = 0;
  105014. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105015. }
  105016. else {
  105017. min_fixed_order = max_fixed_order = guess_fixed_order;
  105018. }
  105019. if(max_fixed_order >= frame_header->blocksize)
  105020. max_fixed_order = frame_header->blocksize - 1;
  105021. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105022. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105023. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105024. continue; /* don't even try */
  105025. 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 */
  105026. #else
  105027. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105028. continue; /* don't even try */
  105029. 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 */
  105030. #endif
  105031. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105032. if(rice_parameter >= rice_parameter_limit) {
  105033. #ifdef DEBUG_VERBOSE
  105034. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105035. #endif
  105036. rice_parameter = rice_parameter_limit - 1;
  105037. }
  105038. _candidate_bits =
  105039. evaluate_fixed_subframe_(
  105040. encoder,
  105041. integer_signal,
  105042. residual[!_best_subframe],
  105043. encoder->private_->abs_residual_partition_sums,
  105044. encoder->private_->raw_bits_per_partition,
  105045. frame_header->blocksize,
  105046. subframe_bps,
  105047. fixed_order,
  105048. rice_parameter,
  105049. rice_parameter_limit,
  105050. min_partition_order,
  105051. max_partition_order,
  105052. encoder->protected_->do_escape_coding,
  105053. encoder->protected_->rice_parameter_search_dist,
  105054. subframe[!_best_subframe],
  105055. partitioned_rice_contents[!_best_subframe]
  105056. );
  105057. if(_candidate_bits < _best_bits) {
  105058. _best_subframe = !_best_subframe;
  105059. _best_bits = _candidate_bits;
  105060. }
  105061. }
  105062. }
  105063. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105064. /* encode lpc */
  105065. if(encoder->protected_->max_lpc_order > 0) {
  105066. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105067. max_lpc_order = frame_header->blocksize-1;
  105068. else
  105069. max_lpc_order = encoder->protected_->max_lpc_order;
  105070. if(max_lpc_order > 0) {
  105071. unsigned a;
  105072. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105073. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105074. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105075. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105076. if(autoc[0] != 0.0) {
  105077. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105078. if(encoder->protected_->do_exhaustive_model_search) {
  105079. min_lpc_order = 1;
  105080. }
  105081. else {
  105082. const unsigned guess_lpc_order =
  105083. FLAC__lpc_compute_best_order(
  105084. lpc_error,
  105085. max_lpc_order,
  105086. frame_header->blocksize,
  105087. subframe_bps + (
  105088. encoder->protected_->do_qlp_coeff_prec_search?
  105089. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105090. encoder->protected_->qlp_coeff_precision
  105091. )
  105092. );
  105093. min_lpc_order = max_lpc_order = guess_lpc_order;
  105094. }
  105095. if(max_lpc_order >= frame_header->blocksize)
  105096. max_lpc_order = frame_header->blocksize - 1;
  105097. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105098. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105099. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105100. continue; /* don't even try */
  105101. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105102. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105103. if(rice_parameter >= rice_parameter_limit) {
  105104. #ifdef DEBUG_VERBOSE
  105105. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105106. #endif
  105107. rice_parameter = rice_parameter_limit - 1;
  105108. }
  105109. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105110. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105111. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105112. if(subframe_bps <= 17) {
  105113. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105114. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105115. }
  105116. else
  105117. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105118. }
  105119. else {
  105120. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105121. }
  105122. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105123. _candidate_bits =
  105124. evaluate_lpc_subframe_(
  105125. encoder,
  105126. integer_signal,
  105127. residual[!_best_subframe],
  105128. encoder->private_->abs_residual_partition_sums,
  105129. encoder->private_->raw_bits_per_partition,
  105130. encoder->private_->lp_coeff[lpc_order-1],
  105131. frame_header->blocksize,
  105132. subframe_bps,
  105133. lpc_order,
  105134. qlp_coeff_precision,
  105135. rice_parameter,
  105136. rice_parameter_limit,
  105137. min_partition_order,
  105138. max_partition_order,
  105139. encoder->protected_->do_escape_coding,
  105140. encoder->protected_->rice_parameter_search_dist,
  105141. subframe[!_best_subframe],
  105142. partitioned_rice_contents[!_best_subframe]
  105143. );
  105144. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105145. if(_candidate_bits < _best_bits) {
  105146. _best_subframe = !_best_subframe;
  105147. _best_bits = _candidate_bits;
  105148. }
  105149. }
  105150. }
  105151. }
  105152. }
  105153. }
  105154. }
  105155. }
  105156. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105157. }
  105158. }
  105159. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105160. if(_best_bits == UINT_MAX) {
  105161. FLAC__ASSERT(_best_subframe == 0);
  105162. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105163. }
  105164. *best_subframe = _best_subframe;
  105165. *best_bits = _best_bits;
  105166. return true;
  105167. }
  105168. FLAC__bool add_subframe_(
  105169. FLAC__StreamEncoder *encoder,
  105170. unsigned blocksize,
  105171. unsigned subframe_bps,
  105172. const FLAC__Subframe *subframe,
  105173. FLAC__BitWriter *frame
  105174. )
  105175. {
  105176. switch(subframe->type) {
  105177. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105178. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105179. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105180. return false;
  105181. }
  105182. break;
  105183. case FLAC__SUBFRAME_TYPE_FIXED:
  105184. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105185. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105186. return false;
  105187. }
  105188. break;
  105189. case FLAC__SUBFRAME_TYPE_LPC:
  105190. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105191. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105192. return false;
  105193. }
  105194. break;
  105195. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105196. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105197. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105198. return false;
  105199. }
  105200. break;
  105201. default:
  105202. FLAC__ASSERT(0);
  105203. }
  105204. return true;
  105205. }
  105206. #define SPOTCHECK_ESTIMATE 0
  105207. #if SPOTCHECK_ESTIMATE
  105208. static void spotcheck_subframe_estimate_(
  105209. FLAC__StreamEncoder *encoder,
  105210. unsigned blocksize,
  105211. unsigned subframe_bps,
  105212. const FLAC__Subframe *subframe,
  105213. unsigned estimate
  105214. )
  105215. {
  105216. FLAC__bool ret;
  105217. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105218. if(frame == 0) {
  105219. fprintf(stderr, "EST: can't allocate frame\n");
  105220. return;
  105221. }
  105222. if(!FLAC__bitwriter_init(frame)) {
  105223. fprintf(stderr, "EST: can't init frame\n");
  105224. return;
  105225. }
  105226. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105227. FLAC__ASSERT(ret);
  105228. {
  105229. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105230. if(estimate != actual)
  105231. 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);
  105232. }
  105233. FLAC__bitwriter_delete(frame);
  105234. }
  105235. #endif
  105236. unsigned evaluate_constant_subframe_(
  105237. FLAC__StreamEncoder *encoder,
  105238. const FLAC__int32 signal,
  105239. unsigned blocksize,
  105240. unsigned subframe_bps,
  105241. FLAC__Subframe *subframe
  105242. )
  105243. {
  105244. unsigned estimate;
  105245. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105246. subframe->data.constant.value = signal;
  105247. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105248. #if SPOTCHECK_ESTIMATE
  105249. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105250. #else
  105251. (void)encoder, (void)blocksize;
  105252. #endif
  105253. return estimate;
  105254. }
  105255. unsigned evaluate_fixed_subframe_(
  105256. FLAC__StreamEncoder *encoder,
  105257. const FLAC__int32 signal[],
  105258. FLAC__int32 residual[],
  105259. FLAC__uint64 abs_residual_partition_sums[],
  105260. unsigned raw_bits_per_partition[],
  105261. unsigned blocksize,
  105262. unsigned subframe_bps,
  105263. unsigned order,
  105264. unsigned rice_parameter,
  105265. unsigned rice_parameter_limit,
  105266. unsigned min_partition_order,
  105267. unsigned max_partition_order,
  105268. FLAC__bool do_escape_coding,
  105269. unsigned rice_parameter_search_dist,
  105270. FLAC__Subframe *subframe,
  105271. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105272. )
  105273. {
  105274. unsigned i, residual_bits, estimate;
  105275. const unsigned residual_samples = blocksize - order;
  105276. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105277. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105278. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105279. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105280. subframe->data.fixed.residual = residual;
  105281. residual_bits =
  105282. find_best_partition_order_(
  105283. encoder->private_,
  105284. residual,
  105285. abs_residual_partition_sums,
  105286. raw_bits_per_partition,
  105287. residual_samples,
  105288. order,
  105289. rice_parameter,
  105290. rice_parameter_limit,
  105291. min_partition_order,
  105292. max_partition_order,
  105293. subframe_bps,
  105294. do_escape_coding,
  105295. rice_parameter_search_dist,
  105296. &subframe->data.fixed.entropy_coding_method
  105297. );
  105298. subframe->data.fixed.order = order;
  105299. for(i = 0; i < order; i++)
  105300. subframe->data.fixed.warmup[i] = signal[i];
  105301. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105302. #if SPOTCHECK_ESTIMATE
  105303. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105304. #endif
  105305. return estimate;
  105306. }
  105307. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105308. unsigned evaluate_lpc_subframe_(
  105309. FLAC__StreamEncoder *encoder,
  105310. const FLAC__int32 signal[],
  105311. FLAC__int32 residual[],
  105312. FLAC__uint64 abs_residual_partition_sums[],
  105313. unsigned raw_bits_per_partition[],
  105314. const FLAC__real lp_coeff[],
  105315. unsigned blocksize,
  105316. unsigned subframe_bps,
  105317. unsigned order,
  105318. unsigned qlp_coeff_precision,
  105319. unsigned rice_parameter,
  105320. unsigned rice_parameter_limit,
  105321. unsigned min_partition_order,
  105322. unsigned max_partition_order,
  105323. FLAC__bool do_escape_coding,
  105324. unsigned rice_parameter_search_dist,
  105325. FLAC__Subframe *subframe,
  105326. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105327. )
  105328. {
  105329. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105330. unsigned i, residual_bits, estimate;
  105331. int quantization, ret;
  105332. const unsigned residual_samples = blocksize - order;
  105333. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105334. if(subframe_bps <= 16) {
  105335. FLAC__ASSERT(order > 0);
  105336. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105337. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105338. }
  105339. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105340. if(ret != 0)
  105341. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105342. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105343. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105344. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105345. else
  105346. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105347. else
  105348. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105349. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105350. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105351. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105352. subframe->data.lpc.residual = residual;
  105353. residual_bits =
  105354. find_best_partition_order_(
  105355. encoder->private_,
  105356. residual,
  105357. abs_residual_partition_sums,
  105358. raw_bits_per_partition,
  105359. residual_samples,
  105360. order,
  105361. rice_parameter,
  105362. rice_parameter_limit,
  105363. min_partition_order,
  105364. max_partition_order,
  105365. subframe_bps,
  105366. do_escape_coding,
  105367. rice_parameter_search_dist,
  105368. &subframe->data.lpc.entropy_coding_method
  105369. );
  105370. subframe->data.lpc.order = order;
  105371. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105372. subframe->data.lpc.quantization_level = quantization;
  105373. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105374. for(i = 0; i < order; i++)
  105375. subframe->data.lpc.warmup[i] = signal[i];
  105376. 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;
  105377. #if SPOTCHECK_ESTIMATE
  105378. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105379. #endif
  105380. return estimate;
  105381. }
  105382. #endif
  105383. unsigned evaluate_verbatim_subframe_(
  105384. FLAC__StreamEncoder *encoder,
  105385. const FLAC__int32 signal[],
  105386. unsigned blocksize,
  105387. unsigned subframe_bps,
  105388. FLAC__Subframe *subframe
  105389. )
  105390. {
  105391. unsigned estimate;
  105392. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105393. subframe->data.verbatim.data = signal;
  105394. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105395. #if SPOTCHECK_ESTIMATE
  105396. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105397. #else
  105398. (void)encoder;
  105399. #endif
  105400. return estimate;
  105401. }
  105402. unsigned find_best_partition_order_(
  105403. FLAC__StreamEncoderPrivate *private_,
  105404. const FLAC__int32 residual[],
  105405. FLAC__uint64 abs_residual_partition_sums[],
  105406. unsigned raw_bits_per_partition[],
  105407. unsigned residual_samples,
  105408. unsigned predictor_order,
  105409. unsigned rice_parameter,
  105410. unsigned rice_parameter_limit,
  105411. unsigned min_partition_order,
  105412. unsigned max_partition_order,
  105413. unsigned bps,
  105414. FLAC__bool do_escape_coding,
  105415. unsigned rice_parameter_search_dist,
  105416. FLAC__EntropyCodingMethod *best_ecm
  105417. )
  105418. {
  105419. unsigned residual_bits, best_residual_bits = 0;
  105420. unsigned best_parameters_index = 0;
  105421. unsigned best_partition_order = 0;
  105422. const unsigned blocksize = residual_samples + predictor_order;
  105423. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105424. min_partition_order = min(min_partition_order, max_partition_order);
  105425. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105426. if(do_escape_coding)
  105427. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105428. {
  105429. int partition_order;
  105430. unsigned sum;
  105431. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105432. if(!
  105433. set_partitioned_rice_(
  105434. #ifdef EXACT_RICE_BITS_CALCULATION
  105435. residual,
  105436. #endif
  105437. abs_residual_partition_sums+sum,
  105438. raw_bits_per_partition+sum,
  105439. residual_samples,
  105440. predictor_order,
  105441. rice_parameter,
  105442. rice_parameter_limit,
  105443. rice_parameter_search_dist,
  105444. (unsigned)partition_order,
  105445. do_escape_coding,
  105446. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105447. &residual_bits
  105448. )
  105449. )
  105450. {
  105451. FLAC__ASSERT(best_residual_bits != 0);
  105452. break;
  105453. }
  105454. sum += 1u << partition_order;
  105455. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105456. best_residual_bits = residual_bits;
  105457. best_parameters_index = !best_parameters_index;
  105458. best_partition_order = partition_order;
  105459. }
  105460. }
  105461. }
  105462. best_ecm->data.partitioned_rice.order = best_partition_order;
  105463. {
  105464. /*
  105465. * We are allowed to de-const the pointer based on our special
  105466. * knowledge; it is const to the outside world.
  105467. */
  105468. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105469. unsigned partition;
  105470. /* save best parameters and raw_bits */
  105471. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105472. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105473. if(do_escape_coding)
  105474. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105475. /*
  105476. * Now need to check if the type should be changed to
  105477. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105478. * size of the rice parameters.
  105479. */
  105480. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105481. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105482. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105483. break;
  105484. }
  105485. }
  105486. }
  105487. return best_residual_bits;
  105488. }
  105489. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105490. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105491. const FLAC__int32 residual[],
  105492. FLAC__uint64 abs_residual_partition_sums[],
  105493. unsigned blocksize,
  105494. unsigned predictor_order,
  105495. unsigned min_partition_order,
  105496. unsigned max_partition_order
  105497. );
  105498. #endif
  105499. void precompute_partition_info_sums_(
  105500. const FLAC__int32 residual[],
  105501. FLAC__uint64 abs_residual_partition_sums[],
  105502. unsigned residual_samples,
  105503. unsigned predictor_order,
  105504. unsigned min_partition_order,
  105505. unsigned max_partition_order,
  105506. unsigned bps
  105507. )
  105508. {
  105509. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105510. unsigned partitions = 1u << max_partition_order;
  105511. FLAC__ASSERT(default_partition_samples > predictor_order);
  105512. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105513. /* slightly pessimistic but still catches all common cases */
  105514. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105515. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105516. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105517. return;
  105518. }
  105519. #endif
  105520. /* first do max_partition_order */
  105521. {
  105522. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105523. /* slightly pessimistic but still catches all common cases */
  105524. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105525. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105526. FLAC__uint32 abs_residual_partition_sum;
  105527. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105528. end += default_partition_samples;
  105529. abs_residual_partition_sum = 0;
  105530. for( ; residual_sample < end; residual_sample++)
  105531. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105532. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105533. }
  105534. }
  105535. else { /* have to pessimistically use 64 bits for accumulator */
  105536. FLAC__uint64 abs_residual_partition_sum;
  105537. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105538. end += default_partition_samples;
  105539. abs_residual_partition_sum = 0;
  105540. for( ; residual_sample < end; residual_sample++)
  105541. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105542. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105543. }
  105544. }
  105545. }
  105546. /* now merge partitions for lower orders */
  105547. {
  105548. unsigned from_partition = 0, to_partition = partitions;
  105549. int partition_order;
  105550. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105551. unsigned i;
  105552. partitions >>= 1;
  105553. for(i = 0; i < partitions; i++) {
  105554. abs_residual_partition_sums[to_partition++] =
  105555. abs_residual_partition_sums[from_partition ] +
  105556. abs_residual_partition_sums[from_partition+1];
  105557. from_partition += 2;
  105558. }
  105559. }
  105560. }
  105561. }
  105562. void precompute_partition_info_escapes_(
  105563. const FLAC__int32 residual[],
  105564. unsigned raw_bits_per_partition[],
  105565. unsigned residual_samples,
  105566. unsigned predictor_order,
  105567. unsigned min_partition_order,
  105568. unsigned max_partition_order
  105569. )
  105570. {
  105571. int partition_order;
  105572. unsigned from_partition, to_partition = 0;
  105573. const unsigned blocksize = residual_samples + predictor_order;
  105574. /* first do max_partition_order */
  105575. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105576. FLAC__int32 r;
  105577. FLAC__uint32 rmax;
  105578. unsigned partition, partition_sample, partition_samples, residual_sample;
  105579. const unsigned partitions = 1u << partition_order;
  105580. const unsigned default_partition_samples = blocksize >> partition_order;
  105581. FLAC__ASSERT(default_partition_samples > predictor_order);
  105582. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105583. partition_samples = default_partition_samples;
  105584. if(partition == 0)
  105585. partition_samples -= predictor_order;
  105586. rmax = 0;
  105587. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105588. r = residual[residual_sample++];
  105589. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105590. if(r < 0)
  105591. rmax |= ~r;
  105592. else
  105593. rmax |= r;
  105594. }
  105595. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105596. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105597. }
  105598. to_partition = partitions;
  105599. break; /*@@@ yuck, should remove the 'for' loop instead */
  105600. }
  105601. /* now merge partitions for lower orders */
  105602. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105603. unsigned m;
  105604. unsigned i;
  105605. const unsigned partitions = 1u << partition_order;
  105606. for(i = 0; i < partitions; i++) {
  105607. m = raw_bits_per_partition[from_partition];
  105608. from_partition++;
  105609. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105610. from_partition++;
  105611. to_partition++;
  105612. }
  105613. }
  105614. }
  105615. #ifdef EXACT_RICE_BITS_CALCULATION
  105616. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105617. const unsigned rice_parameter,
  105618. const unsigned partition_samples,
  105619. const FLAC__int32 *residual
  105620. )
  105621. {
  105622. unsigned i, partition_bits =
  105623. 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 */
  105624. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105625. ;
  105626. for(i = 0; i < partition_samples; i++)
  105627. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105628. return partition_bits;
  105629. }
  105630. #else
  105631. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105632. const unsigned rice_parameter,
  105633. const unsigned partition_samples,
  105634. const FLAC__uint64 abs_residual_partition_sum
  105635. )
  105636. {
  105637. return
  105638. 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 */
  105639. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105640. (
  105641. rice_parameter?
  105642. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105643. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105644. )
  105645. - (partition_samples >> 1)
  105646. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105647. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105648. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105649. * So the subtraction term tries to guess how many extra bits were contributed.
  105650. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105651. */
  105652. ;
  105653. }
  105654. #endif
  105655. FLAC__bool set_partitioned_rice_(
  105656. #ifdef EXACT_RICE_BITS_CALCULATION
  105657. const FLAC__int32 residual[],
  105658. #endif
  105659. const FLAC__uint64 abs_residual_partition_sums[],
  105660. const unsigned raw_bits_per_partition[],
  105661. const unsigned residual_samples,
  105662. const unsigned predictor_order,
  105663. const unsigned suggested_rice_parameter,
  105664. const unsigned rice_parameter_limit,
  105665. const unsigned rice_parameter_search_dist,
  105666. const unsigned partition_order,
  105667. const FLAC__bool search_for_escapes,
  105668. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105669. unsigned *bits
  105670. )
  105671. {
  105672. unsigned rice_parameter, partition_bits;
  105673. unsigned best_partition_bits, best_rice_parameter = 0;
  105674. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105675. unsigned *parameters, *raw_bits;
  105676. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105677. unsigned min_rice_parameter, max_rice_parameter;
  105678. #else
  105679. (void)rice_parameter_search_dist;
  105680. #endif
  105681. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105682. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105683. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105684. parameters = partitioned_rice_contents->parameters;
  105685. raw_bits = partitioned_rice_contents->raw_bits;
  105686. if(partition_order == 0) {
  105687. best_partition_bits = (unsigned)(-1);
  105688. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105689. if(rice_parameter_search_dist) {
  105690. if(suggested_rice_parameter < rice_parameter_search_dist)
  105691. min_rice_parameter = 0;
  105692. else
  105693. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105694. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105695. if(max_rice_parameter >= rice_parameter_limit) {
  105696. #ifdef DEBUG_VERBOSE
  105697. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105698. #endif
  105699. max_rice_parameter = rice_parameter_limit - 1;
  105700. }
  105701. }
  105702. else
  105703. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105704. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105705. #else
  105706. rice_parameter = suggested_rice_parameter;
  105707. #endif
  105708. #ifdef EXACT_RICE_BITS_CALCULATION
  105709. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105710. #else
  105711. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105712. #endif
  105713. if(partition_bits < best_partition_bits) {
  105714. best_rice_parameter = rice_parameter;
  105715. best_partition_bits = partition_bits;
  105716. }
  105717. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105718. }
  105719. #endif
  105720. if(search_for_escapes) {
  105721. 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;
  105722. if(partition_bits <= best_partition_bits) {
  105723. raw_bits[0] = raw_bits_per_partition[0];
  105724. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105725. best_partition_bits = partition_bits;
  105726. }
  105727. else
  105728. raw_bits[0] = 0;
  105729. }
  105730. parameters[0] = best_rice_parameter;
  105731. bits_ += best_partition_bits;
  105732. }
  105733. else {
  105734. unsigned partition, residual_sample;
  105735. unsigned partition_samples;
  105736. FLAC__uint64 mean, k;
  105737. const unsigned partitions = 1u << partition_order;
  105738. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105739. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105740. if(partition == 0) {
  105741. if(partition_samples <= predictor_order)
  105742. return false;
  105743. else
  105744. partition_samples -= predictor_order;
  105745. }
  105746. mean = abs_residual_partition_sums[partition];
  105747. /* we are basically calculating the size in bits of the
  105748. * average residual magnitude in the partition:
  105749. * rice_parameter = floor(log2(mean/partition_samples))
  105750. * 'mean' is not a good name for the variable, it is
  105751. * actually the sum of magnitudes of all residual values
  105752. * in the partition, so the actual mean is
  105753. * mean/partition_samples
  105754. */
  105755. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105756. ;
  105757. if(rice_parameter >= rice_parameter_limit) {
  105758. #ifdef DEBUG_VERBOSE
  105759. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105760. #endif
  105761. rice_parameter = rice_parameter_limit - 1;
  105762. }
  105763. best_partition_bits = (unsigned)(-1);
  105764. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105765. if(rice_parameter_search_dist) {
  105766. if(rice_parameter < rice_parameter_search_dist)
  105767. min_rice_parameter = 0;
  105768. else
  105769. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105770. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105771. if(max_rice_parameter >= rice_parameter_limit) {
  105772. #ifdef DEBUG_VERBOSE
  105773. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105774. #endif
  105775. max_rice_parameter = rice_parameter_limit - 1;
  105776. }
  105777. }
  105778. else
  105779. min_rice_parameter = max_rice_parameter = rice_parameter;
  105780. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105781. #endif
  105782. #ifdef EXACT_RICE_BITS_CALCULATION
  105783. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105784. #else
  105785. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105786. #endif
  105787. if(partition_bits < best_partition_bits) {
  105788. best_rice_parameter = rice_parameter;
  105789. best_partition_bits = partition_bits;
  105790. }
  105791. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105792. }
  105793. #endif
  105794. if(search_for_escapes) {
  105795. 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;
  105796. if(partition_bits <= best_partition_bits) {
  105797. raw_bits[partition] = raw_bits_per_partition[partition];
  105798. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105799. best_partition_bits = partition_bits;
  105800. }
  105801. else
  105802. raw_bits[partition] = 0;
  105803. }
  105804. parameters[partition] = best_rice_parameter;
  105805. bits_ += best_partition_bits;
  105806. residual_sample += partition_samples;
  105807. }
  105808. }
  105809. *bits = bits_;
  105810. return true;
  105811. }
  105812. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105813. {
  105814. unsigned i, shift;
  105815. FLAC__int32 x = 0;
  105816. for(i = 0; i < samples && !(x&1); i++)
  105817. x |= signal[i];
  105818. if(x == 0) {
  105819. shift = 0;
  105820. }
  105821. else {
  105822. for(shift = 0; !(x&1); shift++)
  105823. x >>= 1;
  105824. }
  105825. if(shift > 0) {
  105826. for(i = 0; i < samples; i++)
  105827. signal[i] >>= shift;
  105828. }
  105829. return shift;
  105830. }
  105831. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105832. {
  105833. unsigned channel;
  105834. for(channel = 0; channel < channels; channel++)
  105835. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105836. fifo->tail += wide_samples;
  105837. FLAC__ASSERT(fifo->tail <= fifo->size);
  105838. }
  105839. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105840. {
  105841. unsigned channel;
  105842. unsigned sample, wide_sample;
  105843. unsigned tail = fifo->tail;
  105844. sample = input_offset * channels;
  105845. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105846. for(channel = 0; channel < channels; channel++)
  105847. fifo->data[channel][tail] = input[sample++];
  105848. tail++;
  105849. }
  105850. fifo->tail = tail;
  105851. FLAC__ASSERT(fifo->tail <= fifo->size);
  105852. }
  105853. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105854. {
  105855. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105856. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105857. (void)decoder;
  105858. if(encoder->private_->verify.needs_magic_hack) {
  105859. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105860. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105861. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105862. encoder->private_->verify.needs_magic_hack = false;
  105863. }
  105864. else {
  105865. if(encoded_bytes == 0) {
  105866. /*
  105867. * If we get here, a FIFO underflow has occurred,
  105868. * which means there is a bug somewhere.
  105869. */
  105870. FLAC__ASSERT(0);
  105871. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105872. }
  105873. else if(encoded_bytes < *bytes)
  105874. *bytes = encoded_bytes;
  105875. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105876. encoder->private_->verify.output.data += *bytes;
  105877. encoder->private_->verify.output.bytes -= *bytes;
  105878. }
  105879. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105880. }
  105881. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105882. {
  105883. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105884. unsigned channel;
  105885. const unsigned channels = frame->header.channels;
  105886. const unsigned blocksize = frame->header.blocksize;
  105887. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105888. (void)decoder;
  105889. for(channel = 0; channel < channels; channel++) {
  105890. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105891. unsigned i, sample = 0;
  105892. FLAC__int32 expect = 0, got = 0;
  105893. for(i = 0; i < blocksize; i++) {
  105894. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105895. sample = i;
  105896. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105897. got = (FLAC__int32)buffer[channel][i];
  105898. break;
  105899. }
  105900. }
  105901. FLAC__ASSERT(i < blocksize);
  105902. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105903. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105904. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105905. encoder->private_->verify.error_stats.channel = channel;
  105906. encoder->private_->verify.error_stats.sample = sample;
  105907. encoder->private_->verify.error_stats.expected = expect;
  105908. encoder->private_->verify.error_stats.got = got;
  105909. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105910. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105911. }
  105912. }
  105913. /* dequeue the frame from the fifo */
  105914. encoder->private_->verify.input_fifo.tail -= blocksize;
  105915. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105916. for(channel = 0; channel < channels; channel++)
  105917. 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]));
  105918. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105919. }
  105920. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105921. {
  105922. (void)decoder, (void)metadata, (void)client_data;
  105923. }
  105924. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105925. {
  105926. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105927. (void)decoder, (void)status;
  105928. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105929. }
  105930. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105931. {
  105932. (void)client_data;
  105933. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105934. if (*bytes == 0) {
  105935. if (feof(encoder->private_->file))
  105936. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105937. else if (ferror(encoder->private_->file))
  105938. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105939. }
  105940. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105941. }
  105942. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105943. {
  105944. (void)client_data;
  105945. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105946. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105947. else
  105948. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105949. }
  105950. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105951. {
  105952. off_t offset;
  105953. (void)client_data;
  105954. offset = ftello(encoder->private_->file);
  105955. if(offset < 0) {
  105956. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105957. }
  105958. else {
  105959. *absolute_byte_offset = (FLAC__uint64)offset;
  105960. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105961. }
  105962. }
  105963. #ifdef FLAC__VALGRIND_TESTING
  105964. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105965. {
  105966. size_t ret = fwrite(ptr, size, nmemb, stream);
  105967. if(!ferror(stream))
  105968. fflush(stream);
  105969. return ret;
  105970. }
  105971. #else
  105972. #define local__fwrite fwrite
  105973. #endif
  105974. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105975. {
  105976. (void)client_data, (void)current_frame;
  105977. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105978. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105979. #if FLAC__HAS_OGG
  105980. /* We would like to be able to use 'samples > 0' in the
  105981. * clause here but currently because of the nature of our
  105982. * Ogg writing implementation, 'samples' is always 0 (see
  105983. * ogg_encoder_aspect.c). The downside is extra progress
  105984. * callbacks.
  105985. */
  105986. encoder->private_->is_ogg? true :
  105987. #endif
  105988. samples > 0
  105989. );
  105990. if(call_it) {
  105991. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105992. * because at this point in the callback chain, the stats
  105993. * have not been updated. Only after we return and control
  105994. * gets back to write_frame_() are the stats updated
  105995. */
  105996. 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);
  105997. }
  105998. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105999. }
  106000. else
  106001. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106002. }
  106003. /*
  106004. * This will forcibly set stdout to binary mode (for OSes that require it)
  106005. */
  106006. FILE *get_binary_stdout_(void)
  106007. {
  106008. /* if something breaks here it is probably due to the presence or
  106009. * absence of an underscore before the identifiers 'setmode',
  106010. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106011. */
  106012. #if defined _MSC_VER || defined __MINGW32__
  106013. _setmode(_fileno(stdout), _O_BINARY);
  106014. #elif defined __CYGWIN__
  106015. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106016. setmode(_fileno(stdout), _O_BINARY);
  106017. #elif defined __EMX__
  106018. setmode(fileno(stdout), O_BINARY);
  106019. #endif
  106020. return stdout;
  106021. }
  106022. #endif
  106023. /*** End of inlined file: stream_encoder.c ***/
  106024. /*** Start of inlined file: stream_encoder_framing.c ***/
  106025. /*** Start of inlined file: juce_FlacHeader.h ***/
  106026. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106027. // tasks..
  106028. #define VERSION "1.2.1"
  106029. #define FLAC__NO_DLL 1
  106030. #if JUCE_MSVC
  106031. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106032. #endif
  106033. #if JUCE_MAC
  106034. #define FLAC__SYS_DARWIN 1
  106035. #endif
  106036. /*** End of inlined file: juce_FlacHeader.h ***/
  106037. #if JUCE_USE_FLAC
  106038. #if HAVE_CONFIG_H
  106039. # include <config.h>
  106040. #endif
  106041. #include <stdio.h>
  106042. #include <string.h> /* for strlen() */
  106043. #ifdef max
  106044. #undef max
  106045. #endif
  106046. #define max(x,y) ((x)>(y)?(x):(y))
  106047. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106048. 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);
  106049. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106050. {
  106051. unsigned i, j;
  106052. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106053. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106054. return false;
  106055. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106056. return false;
  106057. /*
  106058. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106059. */
  106060. i = metadata->length;
  106061. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106062. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106063. i -= metadata->data.vorbis_comment.vendor_string.length;
  106064. i += vendor_string_length;
  106065. }
  106066. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106067. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106068. return false;
  106069. switch(metadata->type) {
  106070. case FLAC__METADATA_TYPE_STREAMINFO:
  106071. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106072. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106073. return false;
  106074. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106075. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106076. return false;
  106077. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106078. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106079. return false;
  106080. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106081. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106082. return false;
  106083. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106084. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106085. return false;
  106086. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106087. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106088. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106089. return false;
  106090. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106091. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106092. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106093. return false;
  106094. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106095. return false;
  106096. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106097. return false;
  106098. break;
  106099. case FLAC__METADATA_TYPE_PADDING:
  106100. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106101. return false;
  106102. break;
  106103. case FLAC__METADATA_TYPE_APPLICATION:
  106104. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106105. return false;
  106106. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106107. return false;
  106108. break;
  106109. case FLAC__METADATA_TYPE_SEEKTABLE:
  106110. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106111. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106112. return false;
  106113. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106114. return false;
  106115. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106116. return false;
  106117. }
  106118. break;
  106119. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106120. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106121. return false;
  106122. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106123. return false;
  106124. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106125. return false;
  106126. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106127. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106128. return false;
  106129. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106130. return false;
  106131. }
  106132. break;
  106133. case FLAC__METADATA_TYPE_CUESHEET:
  106134. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106135. 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))
  106136. return false;
  106137. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106138. return false;
  106139. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106140. return false;
  106141. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106142. return false;
  106143. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106144. return false;
  106145. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106146. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106147. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106148. return false;
  106149. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106150. return false;
  106151. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106152. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106153. return false;
  106154. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106155. return false;
  106156. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106157. return false;
  106158. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106159. return false;
  106160. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106161. return false;
  106162. for(j = 0; j < track->num_indices; j++) {
  106163. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106164. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106165. return false;
  106166. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106167. return false;
  106168. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106169. return false;
  106170. }
  106171. }
  106172. break;
  106173. case FLAC__METADATA_TYPE_PICTURE:
  106174. {
  106175. size_t len;
  106176. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106177. return false;
  106178. len = strlen(metadata->data.picture.mime_type);
  106179. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106180. return false;
  106181. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106182. return false;
  106183. len = strlen((const char *)metadata->data.picture.description);
  106184. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106185. return false;
  106186. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106187. return false;
  106188. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106189. return false;
  106190. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106191. return false;
  106192. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106193. return false;
  106194. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106195. return false;
  106196. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106197. return false;
  106198. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106199. return false;
  106200. }
  106201. break;
  106202. default:
  106203. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106204. return false;
  106205. break;
  106206. }
  106207. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106208. return true;
  106209. }
  106210. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106211. {
  106212. unsigned u, blocksize_hint, sample_rate_hint;
  106213. FLAC__byte crc;
  106214. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106215. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106216. return false;
  106217. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106218. return false;
  106219. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106220. return false;
  106221. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106222. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106223. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106224. blocksize_hint = 0;
  106225. switch(header->blocksize) {
  106226. case 192: u = 1; break;
  106227. case 576: u = 2; break;
  106228. case 1152: u = 3; break;
  106229. case 2304: u = 4; break;
  106230. case 4608: u = 5; break;
  106231. case 256: u = 8; break;
  106232. case 512: u = 9; break;
  106233. case 1024: u = 10; break;
  106234. case 2048: u = 11; break;
  106235. case 4096: u = 12; break;
  106236. case 8192: u = 13; break;
  106237. case 16384: u = 14; break;
  106238. case 32768: u = 15; break;
  106239. default:
  106240. if(header->blocksize <= 0x100)
  106241. blocksize_hint = u = 6;
  106242. else
  106243. blocksize_hint = u = 7;
  106244. break;
  106245. }
  106246. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106247. return false;
  106248. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106249. sample_rate_hint = 0;
  106250. switch(header->sample_rate) {
  106251. case 88200: u = 1; break;
  106252. case 176400: u = 2; break;
  106253. case 192000: u = 3; break;
  106254. case 8000: u = 4; break;
  106255. case 16000: u = 5; break;
  106256. case 22050: u = 6; break;
  106257. case 24000: u = 7; break;
  106258. case 32000: u = 8; break;
  106259. case 44100: u = 9; break;
  106260. case 48000: u = 10; break;
  106261. case 96000: u = 11; break;
  106262. default:
  106263. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106264. sample_rate_hint = u = 12;
  106265. else if(header->sample_rate % 10 == 0)
  106266. sample_rate_hint = u = 14;
  106267. else if(header->sample_rate <= 0xffff)
  106268. sample_rate_hint = u = 13;
  106269. else
  106270. u = 0;
  106271. break;
  106272. }
  106273. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106274. return false;
  106275. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106276. switch(header->channel_assignment) {
  106277. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106278. u = header->channels - 1;
  106279. break;
  106280. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106281. FLAC__ASSERT(header->channels == 2);
  106282. u = 8;
  106283. break;
  106284. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106285. FLAC__ASSERT(header->channels == 2);
  106286. u = 9;
  106287. break;
  106288. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106289. FLAC__ASSERT(header->channels == 2);
  106290. u = 10;
  106291. break;
  106292. default:
  106293. FLAC__ASSERT(0);
  106294. }
  106295. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106296. return false;
  106297. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106298. switch(header->bits_per_sample) {
  106299. case 8 : u = 1; break;
  106300. case 12: u = 2; break;
  106301. case 16: u = 4; break;
  106302. case 20: u = 5; break;
  106303. case 24: u = 6; break;
  106304. default: u = 0; break;
  106305. }
  106306. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106307. return false;
  106308. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106309. return false;
  106310. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106311. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106312. return false;
  106313. }
  106314. else {
  106315. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106316. return false;
  106317. }
  106318. if(blocksize_hint)
  106319. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106320. return false;
  106321. switch(sample_rate_hint) {
  106322. case 12:
  106323. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106324. return false;
  106325. break;
  106326. case 13:
  106327. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106328. return false;
  106329. break;
  106330. case 14:
  106331. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106332. return false;
  106333. break;
  106334. }
  106335. /* write the CRC */
  106336. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106337. return false;
  106338. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106339. return false;
  106340. return true;
  106341. }
  106342. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106343. {
  106344. FLAC__bool ok;
  106345. ok =
  106346. 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) &&
  106347. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106348. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106349. ;
  106350. return ok;
  106351. }
  106352. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106353. {
  106354. unsigned i;
  106355. 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))
  106356. return false;
  106357. if(wasted_bits)
  106358. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106359. return false;
  106360. for(i = 0; i < subframe->order; i++)
  106361. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106362. return false;
  106363. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106364. return false;
  106365. switch(subframe->entropy_coding_method.type) {
  106366. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106367. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106368. if(!add_residual_partitioned_rice_(
  106369. bw,
  106370. subframe->residual,
  106371. residual_samples,
  106372. subframe->order,
  106373. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106374. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106375. subframe->entropy_coding_method.data.partitioned_rice.order,
  106376. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106377. ))
  106378. return false;
  106379. break;
  106380. default:
  106381. FLAC__ASSERT(0);
  106382. }
  106383. return true;
  106384. }
  106385. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106386. {
  106387. unsigned i;
  106388. 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))
  106389. return false;
  106390. if(wasted_bits)
  106391. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106392. return false;
  106393. for(i = 0; i < subframe->order; i++)
  106394. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106395. return false;
  106396. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106397. return false;
  106398. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106399. return false;
  106400. for(i = 0; i < subframe->order; i++)
  106401. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106402. return false;
  106403. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106404. return false;
  106405. switch(subframe->entropy_coding_method.type) {
  106406. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106407. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106408. if(!add_residual_partitioned_rice_(
  106409. bw,
  106410. subframe->residual,
  106411. residual_samples,
  106412. subframe->order,
  106413. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106414. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106415. subframe->entropy_coding_method.data.partitioned_rice.order,
  106416. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106417. ))
  106418. return false;
  106419. break;
  106420. default:
  106421. FLAC__ASSERT(0);
  106422. }
  106423. return true;
  106424. }
  106425. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106426. {
  106427. unsigned i;
  106428. const FLAC__int32 *signal = subframe->data;
  106429. 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))
  106430. return false;
  106431. if(wasted_bits)
  106432. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106433. return false;
  106434. for(i = 0; i < samples; i++)
  106435. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106436. return false;
  106437. return true;
  106438. }
  106439. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106440. {
  106441. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106442. return false;
  106443. switch(method->type) {
  106444. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106445. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106446. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106447. return false;
  106448. break;
  106449. default:
  106450. FLAC__ASSERT(0);
  106451. }
  106452. return true;
  106453. }
  106454. 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)
  106455. {
  106456. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106457. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106458. if(partition_order == 0) {
  106459. unsigned i;
  106460. if(raw_bits[0] == 0) {
  106461. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106462. return false;
  106463. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106464. return false;
  106465. }
  106466. else {
  106467. FLAC__ASSERT(rice_parameters[0] == 0);
  106468. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106469. return false;
  106470. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106471. return false;
  106472. for(i = 0; i < residual_samples; i++) {
  106473. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106474. return false;
  106475. }
  106476. }
  106477. return true;
  106478. }
  106479. else {
  106480. unsigned i, j, k = 0, k_last = 0;
  106481. unsigned partition_samples;
  106482. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106483. for(i = 0; i < (1u<<partition_order); i++) {
  106484. partition_samples = default_partition_samples;
  106485. if(i == 0)
  106486. partition_samples -= predictor_order;
  106487. k += partition_samples;
  106488. if(raw_bits[i] == 0) {
  106489. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106490. return false;
  106491. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106492. return false;
  106493. }
  106494. else {
  106495. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106496. return false;
  106497. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106498. return false;
  106499. for(j = k_last; j < k; j++) {
  106500. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106501. return false;
  106502. }
  106503. }
  106504. k_last = k;
  106505. }
  106506. return true;
  106507. }
  106508. }
  106509. #endif
  106510. /*** End of inlined file: stream_encoder_framing.c ***/
  106511. /*** Start of inlined file: window_flac.c ***/
  106512. /*** Start of inlined file: juce_FlacHeader.h ***/
  106513. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106514. // tasks..
  106515. #define VERSION "1.2.1"
  106516. #define FLAC__NO_DLL 1
  106517. #if JUCE_MSVC
  106518. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106519. #endif
  106520. #if JUCE_MAC
  106521. #define FLAC__SYS_DARWIN 1
  106522. #endif
  106523. /*** End of inlined file: juce_FlacHeader.h ***/
  106524. #if JUCE_USE_FLAC
  106525. #if HAVE_CONFIG_H
  106526. # include <config.h>
  106527. #endif
  106528. #include <math.h>
  106529. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106530. #ifndef M_PI
  106531. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106532. #define M_PI 3.14159265358979323846
  106533. #endif
  106534. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106535. {
  106536. const FLAC__int32 N = L - 1;
  106537. FLAC__int32 n;
  106538. if (L & 1) {
  106539. for (n = 0; n <= N/2; n++)
  106540. window[n] = 2.0f * n / (float)N;
  106541. for (; n <= N; n++)
  106542. window[n] = 2.0f - 2.0f * n / (float)N;
  106543. }
  106544. else {
  106545. for (n = 0; n <= L/2-1; n++)
  106546. window[n] = 2.0f * n / (float)N;
  106547. for (; n <= N; n++)
  106548. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106549. }
  106550. }
  106551. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106552. {
  106553. const FLAC__int32 N = L - 1;
  106554. FLAC__int32 n;
  106555. for (n = 0; n < L; n++)
  106556. 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)));
  106557. }
  106558. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106559. {
  106560. const FLAC__int32 N = L - 1;
  106561. FLAC__int32 n;
  106562. for (n = 0; n < L; n++)
  106563. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106564. }
  106565. /* 4-term -92dB side-lobe */
  106566. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106567. {
  106568. const FLAC__int32 N = L - 1;
  106569. FLAC__int32 n;
  106570. for (n = 0; n <= N; n++)
  106571. 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));
  106572. }
  106573. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106574. {
  106575. const FLAC__int32 N = L - 1;
  106576. const double N2 = (double)N / 2.;
  106577. FLAC__int32 n;
  106578. for (n = 0; n <= N; n++) {
  106579. double k = ((double)n - N2) / N2;
  106580. k = 1.0f - k * k;
  106581. window[n] = (FLAC__real)(k * k);
  106582. }
  106583. }
  106584. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106585. {
  106586. const FLAC__int32 N = L - 1;
  106587. FLAC__int32 n;
  106588. for (n = 0; n < L; n++)
  106589. 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));
  106590. }
  106591. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106592. {
  106593. const FLAC__int32 N = L - 1;
  106594. const double N2 = (double)N / 2.;
  106595. FLAC__int32 n;
  106596. for (n = 0; n <= N; n++) {
  106597. const double k = ((double)n - N2) / (stddev * N2);
  106598. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106599. }
  106600. }
  106601. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106602. {
  106603. const FLAC__int32 N = L - 1;
  106604. FLAC__int32 n;
  106605. for (n = 0; n < L; n++)
  106606. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106607. }
  106608. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106609. {
  106610. const FLAC__int32 N = L - 1;
  106611. FLAC__int32 n;
  106612. for (n = 0; n < L; n++)
  106613. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106614. }
  106615. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106616. {
  106617. const FLAC__int32 N = L - 1;
  106618. FLAC__int32 n;
  106619. for (n = 0; n < L; n++)
  106620. 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));
  106621. }
  106622. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106623. {
  106624. const FLAC__int32 N = L - 1;
  106625. FLAC__int32 n;
  106626. for (n = 0; n < L; n++)
  106627. 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));
  106628. }
  106629. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106630. {
  106631. FLAC__int32 n;
  106632. for (n = 0; n < L; n++)
  106633. window[n] = 1.0f;
  106634. }
  106635. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106636. {
  106637. FLAC__int32 n;
  106638. if (L & 1) {
  106639. for (n = 1; n <= L+1/2; n++)
  106640. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106641. for (; n <= L; n++)
  106642. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106643. }
  106644. else {
  106645. for (n = 1; n <= L/2; n++)
  106646. window[n-1] = 2.0f * n / (float)L;
  106647. for (; n <= L; n++)
  106648. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106649. }
  106650. }
  106651. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106652. {
  106653. if (p <= 0.0)
  106654. FLAC__window_rectangle(window, L);
  106655. else if (p >= 1.0)
  106656. FLAC__window_hann(window, L);
  106657. else {
  106658. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106659. FLAC__int32 n;
  106660. /* start with rectangle... */
  106661. FLAC__window_rectangle(window, L);
  106662. /* ...replace ends with hann */
  106663. if (Np > 0) {
  106664. for (n = 0; n <= Np; n++) {
  106665. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106666. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106667. }
  106668. }
  106669. }
  106670. }
  106671. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106672. {
  106673. const FLAC__int32 N = L - 1;
  106674. const double N2 = (double)N / 2.;
  106675. FLAC__int32 n;
  106676. for (n = 0; n <= N; n++) {
  106677. const double k = ((double)n - N2) / N2;
  106678. window[n] = (FLAC__real)(1.0f - k * k);
  106679. }
  106680. }
  106681. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106682. #endif
  106683. /*** End of inlined file: window_flac.c ***/
  106684. #else
  106685. #include <FLAC/all.h>
  106686. #endif
  106687. }
  106688. #undef max
  106689. #undef min
  106690. BEGIN_JUCE_NAMESPACE
  106691. static const char* const flacFormatName = "FLAC file";
  106692. static const char* const flacExtensions[] = { ".flac", 0 };
  106693. class FlacReader : public AudioFormatReader
  106694. {
  106695. public:
  106696. FlacReader (InputStream* const in)
  106697. : AudioFormatReader (in, TRANS (flacFormatName)),
  106698. reservoir (2, 0),
  106699. reservoirStart (0),
  106700. samplesInReservoir (0),
  106701. scanningForLength (false)
  106702. {
  106703. using namespace FlacNamespace;
  106704. lengthInSamples = 0;
  106705. decoder = FLAC__stream_decoder_new();
  106706. ok = FLAC__stream_decoder_init_stream (decoder,
  106707. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106708. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106709. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106710. if (ok)
  106711. {
  106712. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106713. if (lengthInSamples == 0 && sampleRate > 0)
  106714. {
  106715. // the length hasn't been stored in the metadata, so we'll need to
  106716. // work it out the length the hard way, by scanning the whole file..
  106717. scanningForLength = true;
  106718. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106719. scanningForLength = false;
  106720. const int64 tempLength = lengthInSamples;
  106721. FLAC__stream_decoder_reset (decoder);
  106722. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106723. lengthInSamples = tempLength;
  106724. }
  106725. }
  106726. }
  106727. ~FlacReader()
  106728. {
  106729. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106730. }
  106731. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106732. {
  106733. sampleRate = info.sample_rate;
  106734. bitsPerSample = info.bits_per_sample;
  106735. lengthInSamples = (unsigned int) info.total_samples;
  106736. numChannels = info.channels;
  106737. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106738. }
  106739. // returns the number of samples read
  106740. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106741. int64 startSampleInFile, int numSamples)
  106742. {
  106743. using namespace FlacNamespace;
  106744. if (! ok)
  106745. return false;
  106746. while (numSamples > 0)
  106747. {
  106748. if (startSampleInFile >= reservoirStart
  106749. && startSampleInFile < reservoirStart + samplesInReservoir)
  106750. {
  106751. const int num = (int) jmin ((int64) numSamples,
  106752. reservoirStart + samplesInReservoir - startSampleInFile);
  106753. jassert (num > 0);
  106754. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106755. if (destSamples[i] != 0)
  106756. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106757. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106758. sizeof (int) * num);
  106759. startOffsetInDestBuffer += num;
  106760. startSampleInFile += num;
  106761. numSamples -= num;
  106762. }
  106763. else
  106764. {
  106765. if (startSampleInFile >= (int) lengthInSamples)
  106766. {
  106767. samplesInReservoir = 0;
  106768. }
  106769. else if (startSampleInFile < reservoirStart
  106770. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106771. {
  106772. // had some problems with flac crashing if the read pos is aligned more
  106773. // accurately than this. Probably fixed in newer versions of the library, though.
  106774. reservoirStart = (int) (startSampleInFile & ~511);
  106775. samplesInReservoir = 0;
  106776. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106777. }
  106778. else
  106779. {
  106780. reservoirStart += samplesInReservoir;
  106781. samplesInReservoir = 0;
  106782. FLAC__stream_decoder_process_single (decoder);
  106783. }
  106784. if (samplesInReservoir == 0)
  106785. break;
  106786. }
  106787. }
  106788. if (numSamples > 0)
  106789. {
  106790. for (int i = numDestChannels; --i >= 0;)
  106791. if (destSamples[i] != 0)
  106792. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106793. sizeof (int) * numSamples);
  106794. }
  106795. return true;
  106796. }
  106797. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106798. {
  106799. if (scanningForLength)
  106800. {
  106801. lengthInSamples += numSamples;
  106802. }
  106803. else
  106804. {
  106805. if (numSamples > reservoir.getNumSamples())
  106806. reservoir.setSize (numChannels, numSamples, false, false, true);
  106807. const int bitsToShift = 32 - bitsPerSample;
  106808. for (int i = 0; i < (int) numChannels; ++i)
  106809. {
  106810. const FlacNamespace::FLAC__int32* src = buffer[i];
  106811. int n = i;
  106812. while (src == 0 && n > 0)
  106813. src = buffer [--n];
  106814. if (src != 0)
  106815. {
  106816. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106817. for (int j = 0; j < numSamples; ++j)
  106818. dest[j] = src[j] << bitsToShift;
  106819. }
  106820. }
  106821. samplesInReservoir = numSamples;
  106822. }
  106823. }
  106824. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106825. {
  106826. using namespace FlacNamespace;
  106827. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106828. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106829. }
  106830. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106831. {
  106832. using namespace FlacNamespace;
  106833. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106834. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106835. }
  106836. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106837. {
  106838. using namespace FlacNamespace;
  106839. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106840. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106841. }
  106842. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106843. {
  106844. using namespace FlacNamespace;
  106845. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106846. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106847. }
  106848. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106849. {
  106850. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106851. }
  106852. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106853. const FlacNamespace::FLAC__Frame* frame,
  106854. const FlacNamespace::FLAC__int32* const buffer[],
  106855. void* client_data)
  106856. {
  106857. using namespace FlacNamespace;
  106858. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106859. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106860. }
  106861. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106862. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106863. void* client_data)
  106864. {
  106865. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106866. }
  106867. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106868. {
  106869. }
  106870. private:
  106871. FlacNamespace::FLAC__StreamDecoder* decoder;
  106872. AudioSampleBuffer reservoir;
  106873. int reservoirStart, samplesInReservoir;
  106874. bool ok, scanningForLength;
  106875. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  106876. };
  106877. class FlacWriter : public AudioFormatWriter
  106878. {
  106879. public:
  106880. FlacWriter (OutputStream* const out, double sampleRate_,
  106881. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106882. : AudioFormatWriter (out, TRANS (flacFormatName),
  106883. sampleRate_, numChannels_, bitsPerSample_)
  106884. {
  106885. using namespace FlacNamespace;
  106886. encoder = FLAC__stream_encoder_new();
  106887. if (qualityOptionIndex > 0)
  106888. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106889. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106890. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106891. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106892. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106893. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106894. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106895. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106896. ok = FLAC__stream_encoder_init_stream (encoder,
  106897. encodeWriteCallback, encodeSeekCallback,
  106898. encodeTellCallback, encodeMetadataCallback,
  106899. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106900. }
  106901. ~FlacWriter()
  106902. {
  106903. if (ok)
  106904. {
  106905. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106906. output->flush();
  106907. }
  106908. else
  106909. {
  106910. output = 0; // to stop the base class deleting this, as it needs to be returned
  106911. // to the caller of createWriter()
  106912. }
  106913. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106914. }
  106915. bool write (const int** samplesToWrite, int numSamples)
  106916. {
  106917. using namespace FlacNamespace;
  106918. if (! ok)
  106919. return false;
  106920. int* buf[3];
  106921. HeapBlock<int> temp;
  106922. const int bitsToShift = 32 - bitsPerSample;
  106923. if (bitsToShift > 0)
  106924. {
  106925. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106926. temp.malloc (numSamples * numChannelsToWrite);
  106927. buf[0] = temp.getData();
  106928. buf[1] = temp.getData() + numSamples;
  106929. buf[2] = 0;
  106930. for (int i = numChannelsToWrite; --i >= 0;)
  106931. if (samplesToWrite[i] != 0)
  106932. for (int j = 0; j < numSamples; ++j)
  106933. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106934. samplesToWrite = const_cast<const int**> (buf);
  106935. }
  106936. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  106937. }
  106938. bool writeData (const void* const data, const int size) const
  106939. {
  106940. return output->write (data, size);
  106941. }
  106942. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106943. {
  106944. using namespace FlacNamespace;
  106945. b += bytes;
  106946. for (int i = 0; i < bytes; ++i)
  106947. {
  106948. *(--b) = (FLAC__byte) (val & 0xff);
  106949. val >>= 8;
  106950. }
  106951. }
  106952. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106953. {
  106954. using namespace FlacNamespace;
  106955. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106956. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106957. const unsigned int channelsMinus1 = info.channels - 1;
  106958. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106959. packUint32 (info.min_blocksize, buffer, 2);
  106960. packUint32 (info.max_blocksize, buffer + 2, 2);
  106961. packUint32 (info.min_framesize, buffer + 4, 3);
  106962. packUint32 (info.max_framesize, buffer + 7, 3);
  106963. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106964. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106965. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106966. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106967. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106968. memcpy (buffer + 18, info.md5sum, 16);
  106969. const bool seekOk = output->setPosition (4);
  106970. (void) seekOk;
  106971. // if this fails, you've given it an output stream that can't seek! It needs
  106972. // to be able to seek back to write the header
  106973. jassert (seekOk);
  106974. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106975. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106976. }
  106977. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106978. const FlacNamespace::FLAC__byte buffer[],
  106979. size_t bytes,
  106980. unsigned int /*samples*/,
  106981. unsigned int /*current_frame*/,
  106982. void* client_data)
  106983. {
  106984. using namespace FlacNamespace;
  106985. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106986. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106987. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106988. }
  106989. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106990. {
  106991. using namespace FlacNamespace;
  106992. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106993. }
  106994. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106995. {
  106996. using namespace FlacNamespace;
  106997. if (client_data == 0)
  106998. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106999. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107000. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107001. }
  107002. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107003. {
  107004. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107005. }
  107006. bool ok;
  107007. private:
  107008. FlacNamespace::FLAC__StreamEncoder* encoder;
  107009. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  107010. };
  107011. FlacAudioFormat::FlacAudioFormat()
  107012. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107013. {
  107014. }
  107015. FlacAudioFormat::~FlacAudioFormat()
  107016. {
  107017. }
  107018. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107019. {
  107020. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107021. return Array <int> (rates);
  107022. }
  107023. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107024. {
  107025. const int depths[] = { 16, 24, 0 };
  107026. return Array <int> (depths);
  107027. }
  107028. bool FlacAudioFormat::canDoStereo() { return true; }
  107029. bool FlacAudioFormat::canDoMono() { return true; }
  107030. bool FlacAudioFormat::isCompressed() { return true; }
  107031. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107032. const bool deleteStreamIfOpeningFails)
  107033. {
  107034. ScopedPointer<FlacReader> r (new FlacReader (in));
  107035. if (r->sampleRate != 0)
  107036. return r.release();
  107037. if (! deleteStreamIfOpeningFails)
  107038. r->input = 0;
  107039. return 0;
  107040. }
  107041. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107042. double sampleRate,
  107043. unsigned int numberOfChannels,
  107044. int bitsPerSample,
  107045. const StringPairArray& /*metadataValues*/,
  107046. int qualityOptionIndex)
  107047. {
  107048. if (getPossibleBitDepths().contains (bitsPerSample))
  107049. {
  107050. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107051. if (w->ok)
  107052. return w.release();
  107053. }
  107054. return 0;
  107055. }
  107056. END_JUCE_NAMESPACE
  107057. #endif
  107058. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107059. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107060. #if JUCE_USE_OGGVORBIS
  107061. #if JUCE_MAC
  107062. #define __MACOSX__ 1
  107063. #endif
  107064. namespace OggVorbisNamespace
  107065. {
  107066. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107067. /*** Start of inlined file: vorbisenc.h ***/
  107068. #ifndef _OV_ENC_H_
  107069. #define _OV_ENC_H_
  107070. #ifdef __cplusplus
  107071. extern "C"
  107072. {
  107073. #endif /* __cplusplus */
  107074. /*** Start of inlined file: codec.h ***/
  107075. #ifndef _vorbis_codec_h_
  107076. #define _vorbis_codec_h_
  107077. #ifdef __cplusplus
  107078. extern "C"
  107079. {
  107080. #endif /* __cplusplus */
  107081. /*** Start of inlined file: ogg.h ***/
  107082. #ifndef _OGG_H
  107083. #define _OGG_H
  107084. #ifdef __cplusplus
  107085. extern "C" {
  107086. #endif
  107087. /*** Start of inlined file: os_types.h ***/
  107088. #ifndef _OS_TYPES_H
  107089. #define _OS_TYPES_H
  107090. /* make it easy on the folks that want to compile the libs with a
  107091. different malloc than stdlib */
  107092. #define _ogg_malloc malloc
  107093. #define _ogg_calloc calloc
  107094. #define _ogg_realloc realloc
  107095. #define _ogg_free free
  107096. #if defined(_WIN32)
  107097. # if defined(__CYGWIN__)
  107098. # include <_G_config.h>
  107099. typedef _G_int64_t ogg_int64_t;
  107100. typedef _G_int32_t ogg_int32_t;
  107101. typedef _G_uint32_t ogg_uint32_t;
  107102. typedef _G_int16_t ogg_int16_t;
  107103. typedef _G_uint16_t ogg_uint16_t;
  107104. # elif defined(__MINGW32__)
  107105. typedef short ogg_int16_t;
  107106. typedef unsigned short ogg_uint16_t;
  107107. typedef int ogg_int32_t;
  107108. typedef unsigned int ogg_uint32_t;
  107109. typedef long long ogg_int64_t;
  107110. typedef unsigned long long ogg_uint64_t;
  107111. # elif defined(__MWERKS__)
  107112. typedef long long ogg_int64_t;
  107113. typedef int ogg_int32_t;
  107114. typedef unsigned int ogg_uint32_t;
  107115. typedef short ogg_int16_t;
  107116. typedef unsigned short ogg_uint16_t;
  107117. # else
  107118. /* MSVC/Borland */
  107119. typedef __int64 ogg_int64_t;
  107120. typedef __int32 ogg_int32_t;
  107121. typedef unsigned __int32 ogg_uint32_t;
  107122. typedef __int16 ogg_int16_t;
  107123. typedef unsigned __int16 ogg_uint16_t;
  107124. # endif
  107125. #elif defined(__MACOS__)
  107126. # include <sys/types.h>
  107127. typedef SInt16 ogg_int16_t;
  107128. typedef UInt16 ogg_uint16_t;
  107129. typedef SInt32 ogg_int32_t;
  107130. typedef UInt32 ogg_uint32_t;
  107131. typedef SInt64 ogg_int64_t;
  107132. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107133. # include <sys/types.h>
  107134. typedef int16_t ogg_int16_t;
  107135. typedef u_int16_t ogg_uint16_t;
  107136. typedef int32_t ogg_int32_t;
  107137. typedef u_int32_t ogg_uint32_t;
  107138. typedef int64_t ogg_int64_t;
  107139. #elif defined(__BEOS__)
  107140. /* Be */
  107141. # include <inttypes.h>
  107142. typedef int16_t ogg_int16_t;
  107143. typedef u_int16_t ogg_uint16_t;
  107144. typedef int32_t ogg_int32_t;
  107145. typedef u_int32_t ogg_uint32_t;
  107146. typedef int64_t ogg_int64_t;
  107147. #elif defined (__EMX__)
  107148. /* OS/2 GCC */
  107149. typedef short ogg_int16_t;
  107150. typedef unsigned short ogg_uint16_t;
  107151. typedef int ogg_int32_t;
  107152. typedef unsigned int ogg_uint32_t;
  107153. typedef long long ogg_int64_t;
  107154. #elif defined (DJGPP)
  107155. /* DJGPP */
  107156. typedef short ogg_int16_t;
  107157. typedef int ogg_int32_t;
  107158. typedef unsigned int ogg_uint32_t;
  107159. typedef long long ogg_int64_t;
  107160. #elif defined(R5900)
  107161. /* PS2 EE */
  107162. typedef long ogg_int64_t;
  107163. typedef int ogg_int32_t;
  107164. typedef unsigned ogg_uint32_t;
  107165. typedef short ogg_int16_t;
  107166. #elif defined(__SYMBIAN32__)
  107167. /* Symbian GCC */
  107168. typedef signed short ogg_int16_t;
  107169. typedef unsigned short ogg_uint16_t;
  107170. typedef signed int ogg_int32_t;
  107171. typedef unsigned int ogg_uint32_t;
  107172. typedef long long int ogg_int64_t;
  107173. #else
  107174. # include <sys/types.h>
  107175. /*** Start of inlined file: config_types.h ***/
  107176. #ifndef __CONFIG_TYPES_H__
  107177. #define __CONFIG_TYPES_H__
  107178. typedef int16_t ogg_int16_t;
  107179. typedef unsigned short ogg_uint16_t;
  107180. typedef int32_t ogg_int32_t;
  107181. typedef unsigned int ogg_uint32_t;
  107182. typedef int64_t ogg_int64_t;
  107183. #endif
  107184. /*** End of inlined file: config_types.h ***/
  107185. #endif
  107186. #endif /* _OS_TYPES_H */
  107187. /*** End of inlined file: os_types.h ***/
  107188. typedef struct {
  107189. long endbyte;
  107190. int endbit;
  107191. unsigned char *buffer;
  107192. unsigned char *ptr;
  107193. long storage;
  107194. } oggpack_buffer;
  107195. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107196. typedef struct {
  107197. unsigned char *header;
  107198. long header_len;
  107199. unsigned char *body;
  107200. long body_len;
  107201. } ogg_page;
  107202. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107203. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107204. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107205. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107206. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107207. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107208. }
  107209. /* ogg_stream_state contains the current encode/decode state of a logical
  107210. Ogg bitstream **********************************************************/
  107211. typedef struct {
  107212. unsigned char *body_data; /* bytes from packet bodies */
  107213. long body_storage; /* storage elements allocated */
  107214. long body_fill; /* elements stored; fill mark */
  107215. long body_returned; /* elements of fill returned */
  107216. int *lacing_vals; /* The values that will go to the segment table */
  107217. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107218. this way, but it is simple coupled to the
  107219. lacing fifo */
  107220. long lacing_storage;
  107221. long lacing_fill;
  107222. long lacing_packet;
  107223. long lacing_returned;
  107224. unsigned char header[282]; /* working space for header encode */
  107225. int header_fill;
  107226. int e_o_s; /* set when we have buffered the last packet in the
  107227. logical bitstream */
  107228. int b_o_s; /* set after we've written the initial page
  107229. of a logical bitstream */
  107230. long serialno;
  107231. long pageno;
  107232. ogg_int64_t packetno; /* sequence number for decode; the framing
  107233. knows where there's a hole in the data,
  107234. but we need coupling so that the codec
  107235. (which is in a seperate abstraction
  107236. layer) also knows about the gap */
  107237. ogg_int64_t granulepos;
  107238. } ogg_stream_state;
  107239. /* ogg_packet is used to encapsulate the data and metadata belonging
  107240. to a single raw Ogg/Vorbis packet *************************************/
  107241. typedef struct {
  107242. unsigned char *packet;
  107243. long bytes;
  107244. long b_o_s;
  107245. long e_o_s;
  107246. ogg_int64_t granulepos;
  107247. ogg_int64_t packetno; /* sequence number for decode; the framing
  107248. knows where there's a hole in the data,
  107249. but we need coupling so that the codec
  107250. (which is in a seperate abstraction
  107251. layer) also knows about the gap */
  107252. } ogg_packet;
  107253. typedef struct {
  107254. unsigned char *data;
  107255. int storage;
  107256. int fill;
  107257. int returned;
  107258. int unsynced;
  107259. int headerbytes;
  107260. int bodybytes;
  107261. } ogg_sync_state;
  107262. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107263. extern void oggpack_writeinit(oggpack_buffer *b);
  107264. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107265. extern void oggpack_writealign(oggpack_buffer *b);
  107266. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107267. extern void oggpack_reset(oggpack_buffer *b);
  107268. extern void oggpack_writeclear(oggpack_buffer *b);
  107269. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107270. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107271. extern long oggpack_look(oggpack_buffer *b,int bits);
  107272. extern long oggpack_look1(oggpack_buffer *b);
  107273. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107274. extern void oggpack_adv1(oggpack_buffer *b);
  107275. extern long oggpack_read(oggpack_buffer *b,int bits);
  107276. extern long oggpack_read1(oggpack_buffer *b);
  107277. extern long oggpack_bytes(oggpack_buffer *b);
  107278. extern long oggpack_bits(oggpack_buffer *b);
  107279. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107280. extern void oggpackB_writeinit(oggpack_buffer *b);
  107281. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107282. extern void oggpackB_writealign(oggpack_buffer *b);
  107283. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107284. extern void oggpackB_reset(oggpack_buffer *b);
  107285. extern void oggpackB_writeclear(oggpack_buffer *b);
  107286. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107287. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107288. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107289. extern long oggpackB_look1(oggpack_buffer *b);
  107290. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107291. extern void oggpackB_adv1(oggpack_buffer *b);
  107292. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107293. extern long oggpackB_read1(oggpack_buffer *b);
  107294. extern long oggpackB_bytes(oggpack_buffer *b);
  107295. extern long oggpackB_bits(oggpack_buffer *b);
  107296. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107297. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107298. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107299. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107300. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107301. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107302. extern int ogg_sync_init(ogg_sync_state *oy);
  107303. extern int ogg_sync_clear(ogg_sync_state *oy);
  107304. extern int ogg_sync_reset(ogg_sync_state *oy);
  107305. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107306. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107307. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107308. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107309. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107310. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107311. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107312. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107313. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107314. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107315. extern int ogg_stream_clear(ogg_stream_state *os);
  107316. extern int ogg_stream_reset(ogg_stream_state *os);
  107317. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107318. extern int ogg_stream_destroy(ogg_stream_state *os);
  107319. extern int ogg_stream_eos(ogg_stream_state *os);
  107320. extern void ogg_page_checksum_set(ogg_page *og);
  107321. extern int ogg_page_version(ogg_page *og);
  107322. extern int ogg_page_continued(ogg_page *og);
  107323. extern int ogg_page_bos(ogg_page *og);
  107324. extern int ogg_page_eos(ogg_page *og);
  107325. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107326. extern int ogg_page_serialno(ogg_page *og);
  107327. extern long ogg_page_pageno(ogg_page *og);
  107328. extern int ogg_page_packets(ogg_page *og);
  107329. extern void ogg_packet_clear(ogg_packet *op);
  107330. #ifdef __cplusplus
  107331. }
  107332. #endif
  107333. #endif /* _OGG_H */
  107334. /*** End of inlined file: ogg.h ***/
  107335. typedef struct vorbis_info{
  107336. int version;
  107337. int channels;
  107338. long rate;
  107339. /* The below bitrate declarations are *hints*.
  107340. Combinations of the three values carry the following implications:
  107341. all three set to the same value:
  107342. implies a fixed rate bitstream
  107343. only nominal set:
  107344. implies a VBR stream that averages the nominal bitrate. No hard
  107345. upper/lower limit
  107346. upper and or lower set:
  107347. implies a VBR bitstream that obeys the bitrate limits. nominal
  107348. may also be set to give a nominal rate.
  107349. none set:
  107350. the coder does not care to speculate.
  107351. */
  107352. long bitrate_upper;
  107353. long bitrate_nominal;
  107354. long bitrate_lower;
  107355. long bitrate_window;
  107356. void *codec_setup;
  107357. } vorbis_info;
  107358. /* vorbis_dsp_state buffers the current vorbis audio
  107359. analysis/synthesis state. The DSP state belongs to a specific
  107360. logical bitstream ****************************************************/
  107361. typedef struct vorbis_dsp_state{
  107362. int analysisp;
  107363. vorbis_info *vi;
  107364. float **pcm;
  107365. float **pcmret;
  107366. int pcm_storage;
  107367. int pcm_current;
  107368. int pcm_returned;
  107369. int preextrapolate;
  107370. int eofflag;
  107371. long lW;
  107372. long W;
  107373. long nW;
  107374. long centerW;
  107375. ogg_int64_t granulepos;
  107376. ogg_int64_t sequence;
  107377. ogg_int64_t glue_bits;
  107378. ogg_int64_t time_bits;
  107379. ogg_int64_t floor_bits;
  107380. ogg_int64_t res_bits;
  107381. void *backend_state;
  107382. } vorbis_dsp_state;
  107383. typedef struct vorbis_block{
  107384. /* necessary stream state for linking to the framing abstraction */
  107385. float **pcm; /* this is a pointer into local storage */
  107386. oggpack_buffer opb;
  107387. long lW;
  107388. long W;
  107389. long nW;
  107390. int pcmend;
  107391. int mode;
  107392. int eofflag;
  107393. ogg_int64_t granulepos;
  107394. ogg_int64_t sequence;
  107395. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107396. /* local storage to avoid remallocing; it's up to the mapping to
  107397. structure it */
  107398. void *localstore;
  107399. long localtop;
  107400. long localalloc;
  107401. long totaluse;
  107402. struct alloc_chain *reap;
  107403. /* bitmetrics for the frame */
  107404. long glue_bits;
  107405. long time_bits;
  107406. long floor_bits;
  107407. long res_bits;
  107408. void *internal;
  107409. } vorbis_block;
  107410. /* vorbis_block is a single block of data to be processed as part of
  107411. the analysis/synthesis stream; it belongs to a specific logical
  107412. bitstream, but is independant from other vorbis_blocks belonging to
  107413. that logical bitstream. *************************************************/
  107414. struct alloc_chain{
  107415. void *ptr;
  107416. struct alloc_chain *next;
  107417. };
  107418. /* vorbis_info contains all the setup information specific to the
  107419. specific compression/decompression mode in progress (eg,
  107420. psychoacoustic settings, channel setup, options, codebook
  107421. etc). vorbis_info and substructures are in backends.h.
  107422. *********************************************************************/
  107423. /* the comments are not part of vorbis_info so that vorbis_info can be
  107424. static storage */
  107425. typedef struct vorbis_comment{
  107426. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107427. whatever vendor is set to in encode */
  107428. char **user_comments;
  107429. int *comment_lengths;
  107430. int comments;
  107431. char *vendor;
  107432. } vorbis_comment;
  107433. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107434. and produce a packet (see docs/analysis.txt). The packet is then
  107435. coded into a framed OggSquish bitstream by the second layer (see
  107436. docs/framing.txt). Decode is the reverse process; we sync/frame
  107437. the bitstream and extract individual packets, then decode the
  107438. packet back into PCM audio.
  107439. The extra framing/packetizing is used in streaming formats, such as
  107440. files. Over the net (such as with UDP), the framing and
  107441. packetization aren't necessary as they're provided by the transport
  107442. and the streaming layer is not used */
  107443. /* Vorbis PRIMITIVES: general ***************************************/
  107444. extern void vorbis_info_init(vorbis_info *vi);
  107445. extern void vorbis_info_clear(vorbis_info *vi);
  107446. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107447. extern void vorbis_comment_init(vorbis_comment *vc);
  107448. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107449. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107450. const char *tag, char *contents);
  107451. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107452. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107453. extern void vorbis_comment_clear(vorbis_comment *vc);
  107454. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107455. extern int vorbis_block_clear(vorbis_block *vb);
  107456. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107457. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107458. ogg_int64_t granulepos);
  107459. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107460. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107461. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107462. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107463. vorbis_comment *vc,
  107464. ogg_packet *op,
  107465. ogg_packet *op_comm,
  107466. ogg_packet *op_code);
  107467. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107468. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107469. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107470. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107471. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107472. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107473. ogg_packet *op);
  107474. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107475. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107476. ogg_packet *op);
  107477. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107478. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107479. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107480. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107481. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107482. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107483. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107484. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107485. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107486. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107487. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107488. /* Vorbis ERRORS and return codes ***********************************/
  107489. #define OV_FALSE -1
  107490. #define OV_EOF -2
  107491. #define OV_HOLE -3
  107492. #define OV_EREAD -128
  107493. #define OV_EFAULT -129
  107494. #define OV_EIMPL -130
  107495. #define OV_EINVAL -131
  107496. #define OV_ENOTVORBIS -132
  107497. #define OV_EBADHEADER -133
  107498. #define OV_EVERSION -134
  107499. #define OV_ENOTAUDIO -135
  107500. #define OV_EBADPACKET -136
  107501. #define OV_EBADLINK -137
  107502. #define OV_ENOSEEK -138
  107503. #ifdef __cplusplus
  107504. }
  107505. #endif /* __cplusplus */
  107506. #endif
  107507. /*** End of inlined file: codec.h ***/
  107508. extern int vorbis_encode_init(vorbis_info *vi,
  107509. long channels,
  107510. long rate,
  107511. long max_bitrate,
  107512. long nominal_bitrate,
  107513. long min_bitrate);
  107514. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107515. long channels,
  107516. long rate,
  107517. long max_bitrate,
  107518. long nominal_bitrate,
  107519. long min_bitrate);
  107520. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107521. long channels,
  107522. long rate,
  107523. float quality /* quality level from 0. (lo) to 1. (hi) */
  107524. );
  107525. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107526. long channels,
  107527. long rate,
  107528. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107529. );
  107530. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107531. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107532. /* deprecated rate management supported only for compatability */
  107533. #define OV_ECTL_RATEMANAGE_GET 0x10
  107534. #define OV_ECTL_RATEMANAGE_SET 0x11
  107535. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107536. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107537. struct ovectl_ratemanage_arg {
  107538. int management_active;
  107539. long bitrate_hard_min;
  107540. long bitrate_hard_max;
  107541. double bitrate_hard_window;
  107542. long bitrate_av_lo;
  107543. long bitrate_av_hi;
  107544. double bitrate_av_window;
  107545. double bitrate_av_window_center;
  107546. };
  107547. /* new rate setup */
  107548. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107549. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107550. struct ovectl_ratemanage2_arg {
  107551. int management_active;
  107552. long bitrate_limit_min_kbps;
  107553. long bitrate_limit_max_kbps;
  107554. long bitrate_limit_reservoir_bits;
  107555. double bitrate_limit_reservoir_bias;
  107556. long bitrate_average_kbps;
  107557. double bitrate_average_damping;
  107558. };
  107559. #define OV_ECTL_LOWPASS_GET 0x20
  107560. #define OV_ECTL_LOWPASS_SET 0x21
  107561. #define OV_ECTL_IBLOCK_GET 0x30
  107562. #define OV_ECTL_IBLOCK_SET 0x31
  107563. #ifdef __cplusplus
  107564. }
  107565. #endif /* __cplusplus */
  107566. #endif
  107567. /*** End of inlined file: vorbisenc.h ***/
  107568. /*** Start of inlined file: vorbisfile.h ***/
  107569. #ifndef _OV_FILE_H_
  107570. #define _OV_FILE_H_
  107571. #ifdef __cplusplus
  107572. extern "C"
  107573. {
  107574. #endif /* __cplusplus */
  107575. #include <stdio.h>
  107576. /* The function prototypes for the callbacks are basically the same as for
  107577. * the stdio functions fread, fseek, fclose, ftell.
  107578. * The one difference is that the FILE * arguments have been replaced with
  107579. * a void * - this is to be used as a pointer to whatever internal data these
  107580. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107581. *
  107582. * If you use other functions, check the docs for these functions and return
  107583. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107584. * unseekable
  107585. */
  107586. typedef struct {
  107587. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107588. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107589. int (*close_func) (void *datasource);
  107590. long (*tell_func) (void *datasource);
  107591. } ov_callbacks;
  107592. #define NOTOPEN 0
  107593. #define PARTOPEN 1
  107594. #define OPENED 2
  107595. #define STREAMSET 3
  107596. #define INITSET 4
  107597. typedef struct OggVorbis_File {
  107598. void *datasource; /* Pointer to a FILE *, etc. */
  107599. int seekable;
  107600. ogg_int64_t offset;
  107601. ogg_int64_t end;
  107602. ogg_sync_state oy;
  107603. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107604. stream appears */
  107605. int links;
  107606. ogg_int64_t *offsets;
  107607. ogg_int64_t *dataoffsets;
  107608. long *serialnos;
  107609. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107610. compatability; x2 size, stores both
  107611. beginning and end values */
  107612. vorbis_info *vi;
  107613. vorbis_comment *vc;
  107614. /* Decoding working state local storage */
  107615. ogg_int64_t pcm_offset;
  107616. int ready_state;
  107617. long current_serialno;
  107618. int current_link;
  107619. double bittrack;
  107620. double samptrack;
  107621. ogg_stream_state os; /* take physical pages, weld into a logical
  107622. stream of packets */
  107623. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107624. vorbis_block vb; /* local working space for packet->PCM decode */
  107625. ov_callbacks callbacks;
  107626. } OggVorbis_File;
  107627. extern int ov_clear(OggVorbis_File *vf);
  107628. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107629. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107630. char *initial, long ibytes, ov_callbacks callbacks);
  107631. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107632. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107633. char *initial, long ibytes, ov_callbacks callbacks);
  107634. extern int ov_test_open(OggVorbis_File *vf);
  107635. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107636. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107637. extern long ov_streams(OggVorbis_File *vf);
  107638. extern long ov_seekable(OggVorbis_File *vf);
  107639. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107640. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107641. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107642. extern double ov_time_total(OggVorbis_File *vf,int i);
  107643. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107644. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107645. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107646. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107647. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107648. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107649. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107650. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107651. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107652. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107653. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107654. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107655. extern double ov_time_tell(OggVorbis_File *vf);
  107656. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107657. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107658. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107659. int *bitstream);
  107660. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107661. int bigendianp,int word,int sgned,int *bitstream);
  107662. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107663. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107664. extern int ov_halfrate_p(OggVorbis_File *vf);
  107665. #ifdef __cplusplus
  107666. }
  107667. #endif /* __cplusplus */
  107668. #endif
  107669. /*** End of inlined file: vorbisfile.h ***/
  107670. /*** Start of inlined file: bitwise.c ***/
  107671. /* We're 'LSb' endian; if we write a word but read individual bits,
  107672. then we'll read the lsb first */
  107673. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107674. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107675. // tasks..
  107676. #if JUCE_MSVC
  107677. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107678. #endif
  107679. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107680. #if JUCE_USE_OGGVORBIS
  107681. #include <string.h>
  107682. #include <stdlib.h>
  107683. #define BUFFER_INCREMENT 256
  107684. static const unsigned long mask[]=
  107685. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107686. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107687. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107688. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107689. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107690. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107691. 0x3fffffff,0x7fffffff,0xffffffff };
  107692. static const unsigned int mask8B[]=
  107693. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107694. void oggpack_writeinit(oggpack_buffer *b){
  107695. memset(b,0,sizeof(*b));
  107696. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107697. b->buffer[0]='\0';
  107698. b->storage=BUFFER_INCREMENT;
  107699. }
  107700. void oggpackB_writeinit(oggpack_buffer *b){
  107701. oggpack_writeinit(b);
  107702. }
  107703. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107704. long bytes=bits>>3;
  107705. bits-=bytes*8;
  107706. b->ptr=b->buffer+bytes;
  107707. b->endbit=bits;
  107708. b->endbyte=bytes;
  107709. *b->ptr&=mask[bits];
  107710. }
  107711. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107712. long bytes=bits>>3;
  107713. bits-=bytes*8;
  107714. b->ptr=b->buffer+bytes;
  107715. b->endbit=bits;
  107716. b->endbyte=bytes;
  107717. *b->ptr&=mask8B[bits];
  107718. }
  107719. /* Takes only up to 32 bits. */
  107720. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107721. if(b->endbyte+4>=b->storage){
  107722. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107723. b->storage+=BUFFER_INCREMENT;
  107724. b->ptr=b->buffer+b->endbyte;
  107725. }
  107726. value&=mask[bits];
  107727. bits+=b->endbit;
  107728. b->ptr[0]|=value<<b->endbit;
  107729. if(bits>=8){
  107730. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107731. if(bits>=16){
  107732. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107733. if(bits>=24){
  107734. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107735. if(bits>=32){
  107736. if(b->endbit)
  107737. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107738. else
  107739. b->ptr[4]=0;
  107740. }
  107741. }
  107742. }
  107743. }
  107744. b->endbyte+=bits/8;
  107745. b->ptr+=bits/8;
  107746. b->endbit=bits&7;
  107747. }
  107748. /* Takes only up to 32 bits. */
  107749. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107750. if(b->endbyte+4>=b->storage){
  107751. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107752. b->storage+=BUFFER_INCREMENT;
  107753. b->ptr=b->buffer+b->endbyte;
  107754. }
  107755. value=(value&mask[bits])<<(32-bits);
  107756. bits+=b->endbit;
  107757. b->ptr[0]|=value>>(24+b->endbit);
  107758. if(bits>=8){
  107759. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107760. if(bits>=16){
  107761. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107762. if(bits>=24){
  107763. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107764. if(bits>=32){
  107765. if(b->endbit)
  107766. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107767. else
  107768. b->ptr[4]=0;
  107769. }
  107770. }
  107771. }
  107772. }
  107773. b->endbyte+=bits/8;
  107774. b->ptr+=bits/8;
  107775. b->endbit=bits&7;
  107776. }
  107777. void oggpack_writealign(oggpack_buffer *b){
  107778. int bits=8-b->endbit;
  107779. if(bits<8)
  107780. oggpack_write(b,0,bits);
  107781. }
  107782. void oggpackB_writealign(oggpack_buffer *b){
  107783. int bits=8-b->endbit;
  107784. if(bits<8)
  107785. oggpackB_write(b,0,bits);
  107786. }
  107787. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107788. void *source,
  107789. long bits,
  107790. void (*w)(oggpack_buffer *,
  107791. unsigned long,
  107792. int),
  107793. int msb){
  107794. unsigned char *ptr=(unsigned char *)source;
  107795. long bytes=bits/8;
  107796. bits-=bytes*8;
  107797. if(b->endbit){
  107798. int i;
  107799. /* unaligned copy. Do it the hard way. */
  107800. for(i=0;i<bytes;i++)
  107801. w(b,(unsigned long)(ptr[i]),8);
  107802. }else{
  107803. /* aligned block copy */
  107804. if(b->endbyte+bytes+1>=b->storage){
  107805. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107806. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107807. b->ptr=b->buffer+b->endbyte;
  107808. }
  107809. memmove(b->ptr,source,bytes);
  107810. b->ptr+=bytes;
  107811. b->endbyte+=bytes;
  107812. *b->ptr=0;
  107813. }
  107814. if(bits){
  107815. if(msb)
  107816. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107817. else
  107818. w(b,(unsigned long)(ptr[bytes]),bits);
  107819. }
  107820. }
  107821. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107822. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107823. }
  107824. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107825. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107826. }
  107827. void oggpack_reset(oggpack_buffer *b){
  107828. b->ptr=b->buffer;
  107829. b->buffer[0]=0;
  107830. b->endbit=b->endbyte=0;
  107831. }
  107832. void oggpackB_reset(oggpack_buffer *b){
  107833. oggpack_reset(b);
  107834. }
  107835. void oggpack_writeclear(oggpack_buffer *b){
  107836. _ogg_free(b->buffer);
  107837. memset(b,0,sizeof(*b));
  107838. }
  107839. void oggpackB_writeclear(oggpack_buffer *b){
  107840. oggpack_writeclear(b);
  107841. }
  107842. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107843. memset(b,0,sizeof(*b));
  107844. b->buffer=b->ptr=buf;
  107845. b->storage=bytes;
  107846. }
  107847. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107848. oggpack_readinit(b,buf,bytes);
  107849. }
  107850. /* Read in bits without advancing the bitptr; bits <= 32 */
  107851. long oggpack_look(oggpack_buffer *b,int bits){
  107852. unsigned long ret;
  107853. unsigned long m=mask[bits];
  107854. bits+=b->endbit;
  107855. if(b->endbyte+4>=b->storage){
  107856. /* not the main path */
  107857. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107858. }
  107859. ret=b->ptr[0]>>b->endbit;
  107860. if(bits>8){
  107861. ret|=b->ptr[1]<<(8-b->endbit);
  107862. if(bits>16){
  107863. ret|=b->ptr[2]<<(16-b->endbit);
  107864. if(bits>24){
  107865. ret|=b->ptr[3]<<(24-b->endbit);
  107866. if(bits>32 && b->endbit)
  107867. ret|=b->ptr[4]<<(32-b->endbit);
  107868. }
  107869. }
  107870. }
  107871. return(m&ret);
  107872. }
  107873. /* Read in bits without advancing the bitptr; bits <= 32 */
  107874. long oggpackB_look(oggpack_buffer *b,int bits){
  107875. unsigned long ret;
  107876. int m=32-bits;
  107877. bits+=b->endbit;
  107878. if(b->endbyte+4>=b->storage){
  107879. /* not the main path */
  107880. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107881. }
  107882. ret=b->ptr[0]<<(24+b->endbit);
  107883. if(bits>8){
  107884. ret|=b->ptr[1]<<(16+b->endbit);
  107885. if(bits>16){
  107886. ret|=b->ptr[2]<<(8+b->endbit);
  107887. if(bits>24){
  107888. ret|=b->ptr[3]<<(b->endbit);
  107889. if(bits>32 && b->endbit)
  107890. ret|=b->ptr[4]>>(8-b->endbit);
  107891. }
  107892. }
  107893. }
  107894. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107895. }
  107896. long oggpack_look1(oggpack_buffer *b){
  107897. if(b->endbyte>=b->storage)return(-1);
  107898. return((b->ptr[0]>>b->endbit)&1);
  107899. }
  107900. long oggpackB_look1(oggpack_buffer *b){
  107901. if(b->endbyte>=b->storage)return(-1);
  107902. return((b->ptr[0]>>(7-b->endbit))&1);
  107903. }
  107904. void oggpack_adv(oggpack_buffer *b,int bits){
  107905. bits+=b->endbit;
  107906. b->ptr+=bits/8;
  107907. b->endbyte+=bits/8;
  107908. b->endbit=bits&7;
  107909. }
  107910. void oggpackB_adv(oggpack_buffer *b,int bits){
  107911. oggpack_adv(b,bits);
  107912. }
  107913. void oggpack_adv1(oggpack_buffer *b){
  107914. if(++(b->endbit)>7){
  107915. b->endbit=0;
  107916. b->ptr++;
  107917. b->endbyte++;
  107918. }
  107919. }
  107920. void oggpackB_adv1(oggpack_buffer *b){
  107921. oggpack_adv1(b);
  107922. }
  107923. /* bits <= 32 */
  107924. long oggpack_read(oggpack_buffer *b,int bits){
  107925. long ret;
  107926. unsigned long m=mask[bits];
  107927. bits+=b->endbit;
  107928. if(b->endbyte+4>=b->storage){
  107929. /* not the main path */
  107930. ret=-1L;
  107931. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107932. }
  107933. ret=b->ptr[0]>>b->endbit;
  107934. if(bits>8){
  107935. ret|=b->ptr[1]<<(8-b->endbit);
  107936. if(bits>16){
  107937. ret|=b->ptr[2]<<(16-b->endbit);
  107938. if(bits>24){
  107939. ret|=b->ptr[3]<<(24-b->endbit);
  107940. if(bits>32 && b->endbit){
  107941. ret|=b->ptr[4]<<(32-b->endbit);
  107942. }
  107943. }
  107944. }
  107945. }
  107946. ret&=m;
  107947. overflow:
  107948. b->ptr+=bits/8;
  107949. b->endbyte+=bits/8;
  107950. b->endbit=bits&7;
  107951. return(ret);
  107952. }
  107953. /* bits <= 32 */
  107954. long oggpackB_read(oggpack_buffer *b,int bits){
  107955. long ret;
  107956. long m=32-bits;
  107957. bits+=b->endbit;
  107958. if(b->endbyte+4>=b->storage){
  107959. /* not the main path */
  107960. ret=-1L;
  107961. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107962. }
  107963. ret=b->ptr[0]<<(24+b->endbit);
  107964. if(bits>8){
  107965. ret|=b->ptr[1]<<(16+b->endbit);
  107966. if(bits>16){
  107967. ret|=b->ptr[2]<<(8+b->endbit);
  107968. if(bits>24){
  107969. ret|=b->ptr[3]<<(b->endbit);
  107970. if(bits>32 && b->endbit)
  107971. ret|=b->ptr[4]>>(8-b->endbit);
  107972. }
  107973. }
  107974. }
  107975. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107976. overflow:
  107977. b->ptr+=bits/8;
  107978. b->endbyte+=bits/8;
  107979. b->endbit=bits&7;
  107980. return(ret);
  107981. }
  107982. long oggpack_read1(oggpack_buffer *b){
  107983. long ret;
  107984. if(b->endbyte>=b->storage){
  107985. /* not the main path */
  107986. ret=-1L;
  107987. goto overflow;
  107988. }
  107989. ret=(b->ptr[0]>>b->endbit)&1;
  107990. overflow:
  107991. b->endbit++;
  107992. if(b->endbit>7){
  107993. b->endbit=0;
  107994. b->ptr++;
  107995. b->endbyte++;
  107996. }
  107997. return(ret);
  107998. }
  107999. long oggpackB_read1(oggpack_buffer *b){
  108000. long ret;
  108001. if(b->endbyte>=b->storage){
  108002. /* not the main path */
  108003. ret=-1L;
  108004. goto overflow;
  108005. }
  108006. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108007. overflow:
  108008. b->endbit++;
  108009. if(b->endbit>7){
  108010. b->endbit=0;
  108011. b->ptr++;
  108012. b->endbyte++;
  108013. }
  108014. return(ret);
  108015. }
  108016. long oggpack_bytes(oggpack_buffer *b){
  108017. return(b->endbyte+(b->endbit+7)/8);
  108018. }
  108019. long oggpack_bits(oggpack_buffer *b){
  108020. return(b->endbyte*8+b->endbit);
  108021. }
  108022. long oggpackB_bytes(oggpack_buffer *b){
  108023. return oggpack_bytes(b);
  108024. }
  108025. long oggpackB_bits(oggpack_buffer *b){
  108026. return oggpack_bits(b);
  108027. }
  108028. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108029. return(b->buffer);
  108030. }
  108031. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108032. return oggpack_get_buffer(b);
  108033. }
  108034. /* Self test of the bitwise routines; everything else is based on
  108035. them, so they damned well better be solid. */
  108036. #ifdef _V_SELFTEST
  108037. #include <stdio.h>
  108038. static int ilog(unsigned int v){
  108039. int ret=0;
  108040. while(v){
  108041. ret++;
  108042. v>>=1;
  108043. }
  108044. return(ret);
  108045. }
  108046. oggpack_buffer o;
  108047. oggpack_buffer r;
  108048. void report(char *in){
  108049. fprintf(stderr,"%s",in);
  108050. exit(1);
  108051. }
  108052. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108053. long bytes,i;
  108054. unsigned char *buffer;
  108055. oggpack_reset(&o);
  108056. for(i=0;i<vals;i++)
  108057. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108058. buffer=oggpack_get_buffer(&o);
  108059. bytes=oggpack_bytes(&o);
  108060. if(bytes!=compsize)report("wrong number of bytes!\n");
  108061. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108062. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108063. report("wrote incorrect value!\n");
  108064. }
  108065. oggpack_readinit(&r,buffer,bytes);
  108066. for(i=0;i<vals;i++){
  108067. int tbit=bits?bits:ilog(b[i]);
  108068. if(oggpack_look(&r,tbit)==-1)
  108069. report("out of data!\n");
  108070. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108071. report("looked at incorrect value!\n");
  108072. if(tbit==1)
  108073. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108074. report("looked at single bit incorrect value!\n");
  108075. if(tbit==1){
  108076. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108077. report("read incorrect single bit value!\n");
  108078. }else{
  108079. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108080. report("read incorrect value!\n");
  108081. }
  108082. }
  108083. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108084. }
  108085. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108086. long bytes,i;
  108087. unsigned char *buffer;
  108088. oggpackB_reset(&o);
  108089. for(i=0;i<vals;i++)
  108090. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108091. buffer=oggpackB_get_buffer(&o);
  108092. bytes=oggpackB_bytes(&o);
  108093. if(bytes!=compsize)report("wrong number of bytes!\n");
  108094. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108095. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108096. report("wrote incorrect value!\n");
  108097. }
  108098. oggpackB_readinit(&r,buffer,bytes);
  108099. for(i=0;i<vals;i++){
  108100. int tbit=bits?bits:ilog(b[i]);
  108101. if(oggpackB_look(&r,tbit)==-1)
  108102. report("out of data!\n");
  108103. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108104. report("looked at incorrect value!\n");
  108105. if(tbit==1)
  108106. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108107. report("looked at single bit incorrect value!\n");
  108108. if(tbit==1){
  108109. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108110. report("read incorrect single bit value!\n");
  108111. }else{
  108112. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108113. report("read incorrect value!\n");
  108114. }
  108115. }
  108116. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108117. }
  108118. int main(void){
  108119. unsigned char *buffer;
  108120. long bytes,i;
  108121. static unsigned long testbuffer1[]=
  108122. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108123. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108124. int test1size=43;
  108125. static unsigned long testbuffer2[]=
  108126. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108127. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108128. 85525151,0,12321,1,349528352};
  108129. int test2size=21;
  108130. static unsigned long testbuffer3[]=
  108131. {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,
  108132. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108133. int test3size=56;
  108134. static unsigned long large[]=
  108135. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108136. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108137. 85525151,0,12321,1,2146528352};
  108138. int onesize=33;
  108139. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108140. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108141. 223,4};
  108142. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108143. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108144. 245,251,128};
  108145. int twosize=6;
  108146. static int two[6]={61,255,255,251,231,29};
  108147. static int twoB[6]={247,63,255,253,249,120};
  108148. int threesize=54;
  108149. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108150. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108151. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108152. 100,52,4,14,18,86,77,1};
  108153. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108154. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108155. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108156. 200,20,254,4,58,106,176,144,0};
  108157. int foursize=38;
  108158. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108159. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108160. 28,2,133,0,1};
  108161. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108162. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108163. 129,10,4,32};
  108164. int fivesize=45;
  108165. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108166. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108167. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108168. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108169. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108170. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108171. int sixsize=7;
  108172. static int six[7]={17,177,170,242,169,19,148};
  108173. static int sixB[7]={136,141,85,79,149,200,41};
  108174. /* Test read/write together */
  108175. /* Later we test against pregenerated bitstreams */
  108176. oggpack_writeinit(&o);
  108177. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108178. cliptest(testbuffer1,test1size,0,one,onesize);
  108179. fprintf(stderr,"ok.");
  108180. fprintf(stderr,"\nNull bit call (LSb): ");
  108181. cliptest(testbuffer3,test3size,0,two,twosize);
  108182. fprintf(stderr,"ok.");
  108183. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108184. cliptest(testbuffer2,test2size,0,three,threesize);
  108185. fprintf(stderr,"ok.");
  108186. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108187. oggpack_reset(&o);
  108188. for(i=0;i<test2size;i++)
  108189. oggpack_write(&o,large[i],32);
  108190. buffer=oggpack_get_buffer(&o);
  108191. bytes=oggpack_bytes(&o);
  108192. oggpack_readinit(&r,buffer,bytes);
  108193. for(i=0;i<test2size;i++){
  108194. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108195. if(oggpack_look(&r,32)!=large[i]){
  108196. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108197. oggpack_look(&r,32),large[i]);
  108198. report("read incorrect value!\n");
  108199. }
  108200. oggpack_adv(&r,32);
  108201. }
  108202. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108203. fprintf(stderr,"ok.");
  108204. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108205. cliptest(testbuffer1,test1size,7,four,foursize);
  108206. fprintf(stderr,"ok.");
  108207. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108208. cliptest(testbuffer2,test2size,17,five,fivesize);
  108209. fprintf(stderr,"ok.");
  108210. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108211. cliptest(testbuffer3,test3size,1,six,sixsize);
  108212. fprintf(stderr,"ok.");
  108213. fprintf(stderr,"\nTesting read past end (LSb): ");
  108214. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108215. for(i=0;i<64;i++){
  108216. if(oggpack_read(&r,1)!=0){
  108217. fprintf(stderr,"failed; got -1 prematurely.\n");
  108218. exit(1);
  108219. }
  108220. }
  108221. if(oggpack_look(&r,1)!=-1 ||
  108222. oggpack_read(&r,1)!=-1){
  108223. fprintf(stderr,"failed; read past end without -1.\n");
  108224. exit(1);
  108225. }
  108226. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108227. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108228. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108229. exit(1);
  108230. }
  108231. if(oggpack_look(&r,18)!=0 ||
  108232. oggpack_look(&r,18)!=0){
  108233. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108234. exit(1);
  108235. }
  108236. if(oggpack_look(&r,19)!=-1 ||
  108237. oggpack_look(&r,19)!=-1){
  108238. fprintf(stderr,"failed; read past end without -1.\n");
  108239. exit(1);
  108240. }
  108241. if(oggpack_look(&r,32)!=-1 ||
  108242. oggpack_look(&r,32)!=-1){
  108243. fprintf(stderr,"failed; read past end without -1.\n");
  108244. exit(1);
  108245. }
  108246. oggpack_writeclear(&o);
  108247. fprintf(stderr,"ok.\n");
  108248. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108249. /* Test read/write together */
  108250. /* Later we test against pregenerated bitstreams */
  108251. oggpackB_writeinit(&o);
  108252. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108253. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108254. fprintf(stderr,"ok.");
  108255. fprintf(stderr,"\nNull bit call (MSb): ");
  108256. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108257. fprintf(stderr,"ok.");
  108258. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108259. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108260. fprintf(stderr,"ok.");
  108261. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108262. oggpackB_reset(&o);
  108263. for(i=0;i<test2size;i++)
  108264. oggpackB_write(&o,large[i],32);
  108265. buffer=oggpackB_get_buffer(&o);
  108266. bytes=oggpackB_bytes(&o);
  108267. oggpackB_readinit(&r,buffer,bytes);
  108268. for(i=0;i<test2size;i++){
  108269. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108270. if(oggpackB_look(&r,32)!=large[i]){
  108271. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108272. oggpackB_look(&r,32),large[i]);
  108273. report("read incorrect value!\n");
  108274. }
  108275. oggpackB_adv(&r,32);
  108276. }
  108277. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108278. fprintf(stderr,"ok.");
  108279. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108280. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108281. fprintf(stderr,"ok.");
  108282. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108283. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108284. fprintf(stderr,"ok.");
  108285. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108286. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108287. fprintf(stderr,"ok.");
  108288. fprintf(stderr,"\nTesting read past end (MSb): ");
  108289. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108290. for(i=0;i<64;i++){
  108291. if(oggpackB_read(&r,1)!=0){
  108292. fprintf(stderr,"failed; got -1 prematurely.\n");
  108293. exit(1);
  108294. }
  108295. }
  108296. if(oggpackB_look(&r,1)!=-1 ||
  108297. oggpackB_read(&r,1)!=-1){
  108298. fprintf(stderr,"failed; read past end without -1.\n");
  108299. exit(1);
  108300. }
  108301. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108302. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108303. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108304. exit(1);
  108305. }
  108306. if(oggpackB_look(&r,18)!=0 ||
  108307. oggpackB_look(&r,18)!=0){
  108308. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108309. exit(1);
  108310. }
  108311. if(oggpackB_look(&r,19)!=-1 ||
  108312. oggpackB_look(&r,19)!=-1){
  108313. fprintf(stderr,"failed; read past end without -1.\n");
  108314. exit(1);
  108315. }
  108316. if(oggpackB_look(&r,32)!=-1 ||
  108317. oggpackB_look(&r,32)!=-1){
  108318. fprintf(stderr,"failed; read past end without -1.\n");
  108319. exit(1);
  108320. }
  108321. oggpackB_writeclear(&o);
  108322. fprintf(stderr,"ok.\n\n");
  108323. return(0);
  108324. }
  108325. #endif /* _V_SELFTEST */
  108326. #undef BUFFER_INCREMENT
  108327. #endif
  108328. /*** End of inlined file: bitwise.c ***/
  108329. /*** Start of inlined file: framing.c ***/
  108330. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108331. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108332. // tasks..
  108333. #if JUCE_MSVC
  108334. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108335. #endif
  108336. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108337. #if JUCE_USE_OGGVORBIS
  108338. #include <stdlib.h>
  108339. #include <string.h>
  108340. /* A complete description of Ogg framing exists in docs/framing.html */
  108341. int ogg_page_version(ogg_page *og){
  108342. return((int)(og->header[4]));
  108343. }
  108344. int ogg_page_continued(ogg_page *og){
  108345. return((int)(og->header[5]&0x01));
  108346. }
  108347. int ogg_page_bos(ogg_page *og){
  108348. return((int)(og->header[5]&0x02));
  108349. }
  108350. int ogg_page_eos(ogg_page *og){
  108351. return((int)(og->header[5]&0x04));
  108352. }
  108353. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108354. unsigned char *page=og->header;
  108355. ogg_int64_t granulepos=page[13]&(0xff);
  108356. granulepos= (granulepos<<8)|(page[12]&0xff);
  108357. granulepos= (granulepos<<8)|(page[11]&0xff);
  108358. granulepos= (granulepos<<8)|(page[10]&0xff);
  108359. granulepos= (granulepos<<8)|(page[9]&0xff);
  108360. granulepos= (granulepos<<8)|(page[8]&0xff);
  108361. granulepos= (granulepos<<8)|(page[7]&0xff);
  108362. granulepos= (granulepos<<8)|(page[6]&0xff);
  108363. return(granulepos);
  108364. }
  108365. int ogg_page_serialno(ogg_page *og){
  108366. return(og->header[14] |
  108367. (og->header[15]<<8) |
  108368. (og->header[16]<<16) |
  108369. (og->header[17]<<24));
  108370. }
  108371. long ogg_page_pageno(ogg_page *og){
  108372. return(og->header[18] |
  108373. (og->header[19]<<8) |
  108374. (og->header[20]<<16) |
  108375. (og->header[21]<<24));
  108376. }
  108377. /* returns the number of packets that are completed on this page (if
  108378. the leading packet is begun on a previous page, but ends on this
  108379. page, it's counted */
  108380. /* NOTE:
  108381. If a page consists of a packet begun on a previous page, and a new
  108382. packet begun (but not completed) on this page, the return will be:
  108383. ogg_page_packets(page) ==1,
  108384. ogg_page_continued(page) !=0
  108385. If a page happens to be a single packet that was begun on a
  108386. previous page, and spans to the next page (in the case of a three or
  108387. more page packet), the return will be:
  108388. ogg_page_packets(page) ==0,
  108389. ogg_page_continued(page) !=0
  108390. */
  108391. int ogg_page_packets(ogg_page *og){
  108392. int i,n=og->header[26],count=0;
  108393. for(i=0;i<n;i++)
  108394. if(og->header[27+i]<255)count++;
  108395. return(count);
  108396. }
  108397. #if 0
  108398. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108399. use the static init below) */
  108400. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108401. int i;
  108402. unsigned long r;
  108403. r = index << 24;
  108404. for (i=0; i<8; i++)
  108405. if (r & 0x80000000UL)
  108406. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108407. polynomial, although we use an
  108408. unreflected alg and an init/final
  108409. of 0, not 0xffffffff */
  108410. else
  108411. r<<=1;
  108412. return (r & 0xffffffffUL);
  108413. }
  108414. #endif
  108415. static const ogg_uint32_t crc_lookup[256]={
  108416. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108417. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108418. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108419. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108420. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108421. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108422. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108423. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108424. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108425. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108426. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108427. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108428. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108429. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108430. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108431. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108432. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108433. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108434. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108435. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108436. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108437. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108438. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108439. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108440. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108441. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108442. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108443. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108444. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108445. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108446. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108447. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108448. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108449. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108450. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108451. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108452. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108453. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108454. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108455. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108456. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108457. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108458. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108459. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108460. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108461. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108462. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108463. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108464. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108465. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108466. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108467. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108468. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108469. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108470. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108471. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108472. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108473. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108474. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108475. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108476. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108477. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108478. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108479. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108480. /* init the encode/decode logical stream state */
  108481. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108482. if(os){
  108483. memset(os,0,sizeof(*os));
  108484. os->body_storage=16*1024;
  108485. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108486. os->lacing_storage=1024;
  108487. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108488. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108489. os->serialno=serialno;
  108490. return(0);
  108491. }
  108492. return(-1);
  108493. }
  108494. /* _clear does not free os, only the non-flat storage within */
  108495. int ogg_stream_clear(ogg_stream_state *os){
  108496. if(os){
  108497. if(os->body_data)_ogg_free(os->body_data);
  108498. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108499. if(os->granule_vals)_ogg_free(os->granule_vals);
  108500. memset(os,0,sizeof(*os));
  108501. }
  108502. return(0);
  108503. }
  108504. int ogg_stream_destroy(ogg_stream_state *os){
  108505. if(os){
  108506. ogg_stream_clear(os);
  108507. _ogg_free(os);
  108508. }
  108509. return(0);
  108510. }
  108511. /* Helpers for ogg_stream_encode; this keeps the structure and
  108512. what's happening fairly clear */
  108513. static void _os_body_expand(ogg_stream_state *os,int needed){
  108514. if(os->body_storage<=os->body_fill+needed){
  108515. os->body_storage+=(needed+1024);
  108516. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108517. }
  108518. }
  108519. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108520. if(os->lacing_storage<=os->lacing_fill+needed){
  108521. os->lacing_storage+=(needed+32);
  108522. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108523. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108524. }
  108525. }
  108526. /* checksum the page */
  108527. /* Direct table CRC; note that this will be faster in the future if we
  108528. perform the checksum silmultaneously with other copies */
  108529. void ogg_page_checksum_set(ogg_page *og){
  108530. if(og){
  108531. ogg_uint32_t crc_reg=0;
  108532. int i;
  108533. /* safety; needed for API behavior, but not framing code */
  108534. og->header[22]=0;
  108535. og->header[23]=0;
  108536. og->header[24]=0;
  108537. og->header[25]=0;
  108538. for(i=0;i<og->header_len;i++)
  108539. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108540. for(i=0;i<og->body_len;i++)
  108541. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108542. og->header[22]=(unsigned char)(crc_reg&0xff);
  108543. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108544. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108545. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108546. }
  108547. }
  108548. /* submit data to the internal buffer of the framing engine */
  108549. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108550. int lacing_vals=op->bytes/255+1,i;
  108551. if(os->body_returned){
  108552. /* advance packet data according to the body_returned pointer. We
  108553. had to keep it around to return a pointer into the buffer last
  108554. call */
  108555. os->body_fill-=os->body_returned;
  108556. if(os->body_fill)
  108557. memmove(os->body_data,os->body_data+os->body_returned,
  108558. os->body_fill);
  108559. os->body_returned=0;
  108560. }
  108561. /* make sure we have the buffer storage */
  108562. _os_body_expand(os,op->bytes);
  108563. _os_lacing_expand(os,lacing_vals);
  108564. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108565. the liability of overly clean abstraction for the time being. It
  108566. will actually be fairly easy to eliminate the extra copy in the
  108567. future */
  108568. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108569. os->body_fill+=op->bytes;
  108570. /* Store lacing vals for this packet */
  108571. for(i=0;i<lacing_vals-1;i++){
  108572. os->lacing_vals[os->lacing_fill+i]=255;
  108573. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108574. }
  108575. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108576. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108577. /* flag the first segment as the beginning of the packet */
  108578. os->lacing_vals[os->lacing_fill]|= 0x100;
  108579. os->lacing_fill+=lacing_vals;
  108580. /* for the sake of completeness */
  108581. os->packetno++;
  108582. if(op->e_o_s)os->e_o_s=1;
  108583. return(0);
  108584. }
  108585. /* This will flush remaining packets into a page (returning nonzero),
  108586. even if there is not enough data to trigger a flush normally
  108587. (undersized page). If there are no packets or partial packets to
  108588. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108589. try to flush a normal sized page like ogg_stream_pageout; a call to
  108590. ogg_stream_flush does not guarantee that all packets have flushed.
  108591. Only a return value of 0 from ogg_stream_flush indicates all packet
  108592. data is flushed into pages.
  108593. since ogg_stream_flush will flush the last page in a stream even if
  108594. it's undersized, you almost certainly want to use ogg_stream_pageout
  108595. (and *not* ogg_stream_flush) unless you specifically need to flush
  108596. an page regardless of size in the middle of a stream. */
  108597. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108598. int i;
  108599. int vals=0;
  108600. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108601. int bytes=0;
  108602. long acc=0;
  108603. ogg_int64_t granule_pos=-1;
  108604. if(maxvals==0)return(0);
  108605. /* construct a page */
  108606. /* decide how many segments to include */
  108607. /* If this is the initial header case, the first page must only include
  108608. the initial header packet */
  108609. if(os->b_o_s==0){ /* 'initial header page' case */
  108610. granule_pos=0;
  108611. for(vals=0;vals<maxvals;vals++){
  108612. if((os->lacing_vals[vals]&0x0ff)<255){
  108613. vals++;
  108614. break;
  108615. }
  108616. }
  108617. }else{
  108618. for(vals=0;vals<maxvals;vals++){
  108619. if(acc>4096)break;
  108620. acc+=os->lacing_vals[vals]&0x0ff;
  108621. if((os->lacing_vals[vals]&0xff)<255)
  108622. granule_pos=os->granule_vals[vals];
  108623. }
  108624. }
  108625. /* construct the header in temp storage */
  108626. memcpy(os->header,"OggS",4);
  108627. /* stream structure version */
  108628. os->header[4]=0x00;
  108629. /* continued packet flag? */
  108630. os->header[5]=0x00;
  108631. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108632. /* first page flag? */
  108633. if(os->b_o_s==0)os->header[5]|=0x02;
  108634. /* last page flag? */
  108635. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108636. os->b_o_s=1;
  108637. /* 64 bits of PCM position */
  108638. for(i=6;i<14;i++){
  108639. os->header[i]=(unsigned char)(granule_pos&0xff);
  108640. granule_pos>>=8;
  108641. }
  108642. /* 32 bits of stream serial number */
  108643. {
  108644. long serialno=os->serialno;
  108645. for(i=14;i<18;i++){
  108646. os->header[i]=(unsigned char)(serialno&0xff);
  108647. serialno>>=8;
  108648. }
  108649. }
  108650. /* 32 bits of page counter (we have both counter and page header
  108651. because this val can roll over) */
  108652. if(os->pageno==-1)os->pageno=0; /* because someone called
  108653. stream_reset; this would be a
  108654. strange thing to do in an
  108655. encode stream, but it has
  108656. plausible uses */
  108657. {
  108658. long pageno=os->pageno++;
  108659. for(i=18;i<22;i++){
  108660. os->header[i]=(unsigned char)(pageno&0xff);
  108661. pageno>>=8;
  108662. }
  108663. }
  108664. /* zero for computation; filled in later */
  108665. os->header[22]=0;
  108666. os->header[23]=0;
  108667. os->header[24]=0;
  108668. os->header[25]=0;
  108669. /* segment table */
  108670. os->header[26]=(unsigned char)(vals&0xff);
  108671. for(i=0;i<vals;i++)
  108672. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108673. /* set pointers in the ogg_page struct */
  108674. og->header=os->header;
  108675. og->header_len=os->header_fill=vals+27;
  108676. og->body=os->body_data+os->body_returned;
  108677. og->body_len=bytes;
  108678. /* advance the lacing data and set the body_returned pointer */
  108679. os->lacing_fill-=vals;
  108680. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108681. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108682. os->body_returned+=bytes;
  108683. /* calculate the checksum */
  108684. ogg_page_checksum_set(og);
  108685. /* done */
  108686. return(1);
  108687. }
  108688. /* This constructs pages from buffered packet segments. The pointers
  108689. returned are to static buffers; do not free. The returned buffers are
  108690. good only until the next call (using the same ogg_stream_state) */
  108691. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108692. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108693. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108694. os->lacing_fill>=255 || /* 'segment table full' case */
  108695. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108696. return(ogg_stream_flush(os,og));
  108697. }
  108698. /* not enough data to construct a page and not end of stream */
  108699. return(0);
  108700. }
  108701. int ogg_stream_eos(ogg_stream_state *os){
  108702. return os->e_o_s;
  108703. }
  108704. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108705. /* This has two layers to place more of the multi-serialno and paging
  108706. control in the application's hands. First, we expose a data buffer
  108707. using ogg_sync_buffer(). The app either copies into the
  108708. buffer, or passes it directly to read(), etc. We then call
  108709. ogg_sync_wrote() to tell how many bytes we just added.
  108710. Pages are returned (pointers into the buffer in ogg_sync_state)
  108711. by ogg_sync_pageout(). The page is then submitted to
  108712. ogg_stream_pagein() along with the appropriate
  108713. ogg_stream_state* (ie, matching serialno). We then get raw
  108714. packets out calling ogg_stream_packetout() with a
  108715. ogg_stream_state. */
  108716. /* initialize the struct to a known state */
  108717. int ogg_sync_init(ogg_sync_state *oy){
  108718. if(oy){
  108719. memset(oy,0,sizeof(*oy));
  108720. }
  108721. return(0);
  108722. }
  108723. /* clear non-flat storage within */
  108724. int ogg_sync_clear(ogg_sync_state *oy){
  108725. if(oy){
  108726. if(oy->data)_ogg_free(oy->data);
  108727. ogg_sync_init(oy);
  108728. }
  108729. return(0);
  108730. }
  108731. int ogg_sync_destroy(ogg_sync_state *oy){
  108732. if(oy){
  108733. ogg_sync_clear(oy);
  108734. _ogg_free(oy);
  108735. }
  108736. return(0);
  108737. }
  108738. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108739. /* first, clear out any space that has been previously returned */
  108740. if(oy->returned){
  108741. oy->fill-=oy->returned;
  108742. if(oy->fill>0)
  108743. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108744. oy->returned=0;
  108745. }
  108746. if(size>oy->storage-oy->fill){
  108747. /* We need to extend the internal buffer */
  108748. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108749. if(oy->data)
  108750. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108751. else
  108752. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108753. oy->storage=newsize;
  108754. }
  108755. /* expose a segment at least as large as requested at the fill mark */
  108756. return((char *)oy->data+oy->fill);
  108757. }
  108758. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108759. if(oy->fill+bytes>oy->storage)return(-1);
  108760. oy->fill+=bytes;
  108761. return(0);
  108762. }
  108763. /* sync the stream. This is meant to be useful for finding page
  108764. boundaries.
  108765. return values for this:
  108766. -n) skipped n bytes
  108767. 0) page not ready; more data (no bytes skipped)
  108768. n) page synced at current location; page length n bytes
  108769. */
  108770. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108771. unsigned char *page=oy->data+oy->returned;
  108772. unsigned char *next;
  108773. long bytes=oy->fill-oy->returned;
  108774. if(oy->headerbytes==0){
  108775. int headerbytes,i;
  108776. if(bytes<27)return(0); /* not enough for a header */
  108777. /* verify capture pattern */
  108778. if(memcmp(page,"OggS",4))goto sync_fail;
  108779. headerbytes=page[26]+27;
  108780. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108781. /* count up body length in the segment table */
  108782. for(i=0;i<page[26];i++)
  108783. oy->bodybytes+=page[27+i];
  108784. oy->headerbytes=headerbytes;
  108785. }
  108786. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108787. /* The whole test page is buffered. Verify the checksum */
  108788. {
  108789. /* Grab the checksum bytes, set the header field to zero */
  108790. char chksum[4];
  108791. ogg_page log;
  108792. memcpy(chksum,page+22,4);
  108793. memset(page+22,0,4);
  108794. /* set up a temp page struct and recompute the checksum */
  108795. log.header=page;
  108796. log.header_len=oy->headerbytes;
  108797. log.body=page+oy->headerbytes;
  108798. log.body_len=oy->bodybytes;
  108799. ogg_page_checksum_set(&log);
  108800. /* Compare */
  108801. if(memcmp(chksum,page+22,4)){
  108802. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108803. at all) */
  108804. /* replace the computed checksum with the one actually read in */
  108805. memcpy(page+22,chksum,4);
  108806. /* Bad checksum. Lose sync */
  108807. goto sync_fail;
  108808. }
  108809. }
  108810. /* yes, have a whole page all ready to go */
  108811. {
  108812. unsigned char *page=oy->data+oy->returned;
  108813. long bytes;
  108814. if(og){
  108815. og->header=page;
  108816. og->header_len=oy->headerbytes;
  108817. og->body=page+oy->headerbytes;
  108818. og->body_len=oy->bodybytes;
  108819. }
  108820. oy->unsynced=0;
  108821. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108822. oy->headerbytes=0;
  108823. oy->bodybytes=0;
  108824. return(bytes);
  108825. }
  108826. sync_fail:
  108827. oy->headerbytes=0;
  108828. oy->bodybytes=0;
  108829. /* search for possible capture */
  108830. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108831. if(!next)
  108832. next=oy->data+oy->fill;
  108833. oy->returned=next-oy->data;
  108834. return(-(next-page));
  108835. }
  108836. /* sync the stream and get a page. Keep trying until we find a page.
  108837. Supress 'sync errors' after reporting the first.
  108838. return values:
  108839. -1) recapture (hole in data)
  108840. 0) need more data
  108841. 1) page returned
  108842. Returns pointers into buffered data; invalidated by next call to
  108843. _stream, _clear, _init, or _buffer */
  108844. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108845. /* all we need to do is verify a page at the head of the stream
  108846. buffer. If it doesn't verify, we look for the next potential
  108847. frame */
  108848. for(;;){
  108849. long ret=ogg_sync_pageseek(oy,og);
  108850. if(ret>0){
  108851. /* have a page */
  108852. return(1);
  108853. }
  108854. if(ret==0){
  108855. /* need more data */
  108856. return(0);
  108857. }
  108858. /* head did not start a synced page... skipped some bytes */
  108859. if(!oy->unsynced){
  108860. oy->unsynced=1;
  108861. return(-1);
  108862. }
  108863. /* loop. keep looking */
  108864. }
  108865. }
  108866. /* add the incoming page to the stream state; we decompose the page
  108867. into packet segments here as well. */
  108868. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108869. unsigned char *header=og->header;
  108870. unsigned char *body=og->body;
  108871. long bodysize=og->body_len;
  108872. int segptr=0;
  108873. int version=ogg_page_version(og);
  108874. int continued=ogg_page_continued(og);
  108875. int bos=ogg_page_bos(og);
  108876. int eos=ogg_page_eos(og);
  108877. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108878. int serialno=ogg_page_serialno(og);
  108879. long pageno=ogg_page_pageno(og);
  108880. int segments=header[26];
  108881. /* clean up 'returned data' */
  108882. {
  108883. long lr=os->lacing_returned;
  108884. long br=os->body_returned;
  108885. /* body data */
  108886. if(br){
  108887. os->body_fill-=br;
  108888. if(os->body_fill)
  108889. memmove(os->body_data,os->body_data+br,os->body_fill);
  108890. os->body_returned=0;
  108891. }
  108892. if(lr){
  108893. /* segment table */
  108894. if(os->lacing_fill-lr){
  108895. memmove(os->lacing_vals,os->lacing_vals+lr,
  108896. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108897. memmove(os->granule_vals,os->granule_vals+lr,
  108898. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108899. }
  108900. os->lacing_fill-=lr;
  108901. os->lacing_packet-=lr;
  108902. os->lacing_returned=0;
  108903. }
  108904. }
  108905. /* check the serial number */
  108906. if(serialno!=os->serialno)return(-1);
  108907. if(version>0)return(-1);
  108908. _os_lacing_expand(os,segments+1);
  108909. /* are we in sequence? */
  108910. if(pageno!=os->pageno){
  108911. int i;
  108912. /* unroll previous partial packet (if any) */
  108913. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108914. os->body_fill-=os->lacing_vals[i]&0xff;
  108915. os->lacing_fill=os->lacing_packet;
  108916. /* make a note of dropped data in segment table */
  108917. if(os->pageno!=-1){
  108918. os->lacing_vals[os->lacing_fill++]=0x400;
  108919. os->lacing_packet++;
  108920. }
  108921. }
  108922. /* are we a 'continued packet' page? If so, we may need to skip
  108923. some segments */
  108924. if(continued){
  108925. if(os->lacing_fill<1 ||
  108926. os->lacing_vals[os->lacing_fill-1]==0x400){
  108927. bos=0;
  108928. for(;segptr<segments;segptr++){
  108929. int val=header[27+segptr];
  108930. body+=val;
  108931. bodysize-=val;
  108932. if(val<255){
  108933. segptr++;
  108934. break;
  108935. }
  108936. }
  108937. }
  108938. }
  108939. if(bodysize){
  108940. _os_body_expand(os,bodysize);
  108941. memcpy(os->body_data+os->body_fill,body,bodysize);
  108942. os->body_fill+=bodysize;
  108943. }
  108944. {
  108945. int saved=-1;
  108946. while(segptr<segments){
  108947. int val=header[27+segptr];
  108948. os->lacing_vals[os->lacing_fill]=val;
  108949. os->granule_vals[os->lacing_fill]=-1;
  108950. if(bos){
  108951. os->lacing_vals[os->lacing_fill]|=0x100;
  108952. bos=0;
  108953. }
  108954. if(val<255)saved=os->lacing_fill;
  108955. os->lacing_fill++;
  108956. segptr++;
  108957. if(val<255)os->lacing_packet=os->lacing_fill;
  108958. }
  108959. /* set the granulepos on the last granuleval of the last full packet */
  108960. if(saved!=-1){
  108961. os->granule_vals[saved]=granulepos;
  108962. }
  108963. }
  108964. if(eos){
  108965. os->e_o_s=1;
  108966. if(os->lacing_fill>0)
  108967. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108968. }
  108969. os->pageno=pageno+1;
  108970. return(0);
  108971. }
  108972. /* clear things to an initial state. Good to call, eg, before seeking */
  108973. int ogg_sync_reset(ogg_sync_state *oy){
  108974. oy->fill=0;
  108975. oy->returned=0;
  108976. oy->unsynced=0;
  108977. oy->headerbytes=0;
  108978. oy->bodybytes=0;
  108979. return(0);
  108980. }
  108981. int ogg_stream_reset(ogg_stream_state *os){
  108982. os->body_fill=0;
  108983. os->body_returned=0;
  108984. os->lacing_fill=0;
  108985. os->lacing_packet=0;
  108986. os->lacing_returned=0;
  108987. os->header_fill=0;
  108988. os->e_o_s=0;
  108989. os->b_o_s=0;
  108990. os->pageno=-1;
  108991. os->packetno=0;
  108992. os->granulepos=0;
  108993. return(0);
  108994. }
  108995. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108996. ogg_stream_reset(os);
  108997. os->serialno=serialno;
  108998. return(0);
  108999. }
  109000. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109001. /* The last part of decode. We have the stream broken into packet
  109002. segments. Now we need to group them into packets (or return the
  109003. out of sync markers) */
  109004. int ptr=os->lacing_returned;
  109005. if(os->lacing_packet<=ptr)return(0);
  109006. if(os->lacing_vals[ptr]&0x400){
  109007. /* we need to tell the codec there's a gap; it might need to
  109008. handle previous packet dependencies. */
  109009. os->lacing_returned++;
  109010. os->packetno++;
  109011. return(-1);
  109012. }
  109013. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109014. to ask if there's a whole packet
  109015. waiting */
  109016. /* Gather the whole packet. We'll have no holes or a partial packet */
  109017. {
  109018. int size=os->lacing_vals[ptr]&0xff;
  109019. int bytes=size;
  109020. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109021. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109022. while(size==255){
  109023. int val=os->lacing_vals[++ptr];
  109024. size=val&0xff;
  109025. if(val&0x200)eos=0x200;
  109026. bytes+=size;
  109027. }
  109028. if(op){
  109029. op->e_o_s=eos;
  109030. op->b_o_s=bos;
  109031. op->packet=os->body_data+os->body_returned;
  109032. op->packetno=os->packetno;
  109033. op->granulepos=os->granule_vals[ptr];
  109034. op->bytes=bytes;
  109035. }
  109036. if(adv){
  109037. os->body_returned+=bytes;
  109038. os->lacing_returned=ptr+1;
  109039. os->packetno++;
  109040. }
  109041. }
  109042. return(1);
  109043. }
  109044. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109045. return _packetout(os,op,1);
  109046. }
  109047. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109048. return _packetout(os,op,0);
  109049. }
  109050. void ogg_packet_clear(ogg_packet *op) {
  109051. _ogg_free(op->packet);
  109052. memset(op, 0, sizeof(*op));
  109053. }
  109054. #ifdef _V_SELFTEST
  109055. #include <stdio.h>
  109056. ogg_stream_state os_en, os_de;
  109057. ogg_sync_state oy;
  109058. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109059. long j;
  109060. static int sequence=0;
  109061. static int lastno=0;
  109062. if(op->bytes!=len){
  109063. fprintf(stderr,"incorrect packet length!\n");
  109064. exit(1);
  109065. }
  109066. if(op->granulepos!=pos){
  109067. fprintf(stderr,"incorrect packet position!\n");
  109068. exit(1);
  109069. }
  109070. /* packet number just follows sequence/gap; adjust the input number
  109071. for that */
  109072. if(no==0){
  109073. sequence=0;
  109074. }else{
  109075. sequence++;
  109076. if(no>lastno+1)
  109077. sequence++;
  109078. }
  109079. lastno=no;
  109080. if(op->packetno!=sequence){
  109081. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109082. (long)(op->packetno),sequence);
  109083. exit(1);
  109084. }
  109085. /* Test data */
  109086. for(j=0;j<op->bytes;j++)
  109087. if(op->packet[j]!=((j+no)&0xff)){
  109088. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109089. j,op->packet[j],(j+no)&0xff);
  109090. exit(1);
  109091. }
  109092. }
  109093. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109094. long j;
  109095. /* Test data */
  109096. for(j=0;j<og->body_len;j++)
  109097. if(og->body[j]!=data[j]){
  109098. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109099. j,data[j],og->body[j]);
  109100. exit(1);
  109101. }
  109102. /* Test header */
  109103. for(j=0;j<og->header_len;j++){
  109104. if(og->header[j]!=header[j]){
  109105. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109106. for(j=0;j<header[26]+27;j++)
  109107. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109108. fprintf(stderr,"\n");
  109109. exit(1);
  109110. }
  109111. }
  109112. if(og->header_len!=header[26]+27){
  109113. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109114. og->header_len,header[26]+27);
  109115. exit(1);
  109116. }
  109117. }
  109118. void print_header(ogg_page *og){
  109119. int j;
  109120. fprintf(stderr,"\nHEADER:\n");
  109121. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109122. og->header[0],og->header[1],og->header[2],og->header[3],
  109123. (int)og->header[4],(int)og->header[5]);
  109124. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109125. (og->header[9]<<24)|(og->header[8]<<16)|
  109126. (og->header[7]<<8)|og->header[6],
  109127. (og->header[17]<<24)|(og->header[16]<<16)|
  109128. (og->header[15]<<8)|og->header[14],
  109129. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109130. (og->header[19]<<8)|og->header[18]);
  109131. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109132. (int)og->header[22],(int)og->header[23],
  109133. (int)og->header[24],(int)og->header[25],
  109134. (int)og->header[26]);
  109135. for(j=27;j<og->header_len;j++)
  109136. fprintf(stderr,"%d ",(int)og->header[j]);
  109137. fprintf(stderr,")\n\n");
  109138. }
  109139. void copy_page(ogg_page *og){
  109140. unsigned char *temp=_ogg_malloc(og->header_len);
  109141. memcpy(temp,og->header,og->header_len);
  109142. og->header=temp;
  109143. temp=_ogg_malloc(og->body_len);
  109144. memcpy(temp,og->body,og->body_len);
  109145. og->body=temp;
  109146. }
  109147. void free_page(ogg_page *og){
  109148. _ogg_free (og->header);
  109149. _ogg_free (og->body);
  109150. }
  109151. void error(void){
  109152. fprintf(stderr,"error!\n");
  109153. exit(1);
  109154. }
  109155. /* 17 only */
  109156. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109157. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109158. 0x01,0x02,0x03,0x04,0,0,0,0,
  109159. 0x15,0xed,0xec,0x91,
  109160. 1,
  109161. 17};
  109162. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109163. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109164. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109165. 0x01,0x02,0x03,0x04,0,0,0,0,
  109166. 0x59,0x10,0x6c,0x2c,
  109167. 1,
  109168. 17};
  109169. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109170. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109171. 0x01,0x02,0x03,0x04,1,0,0,0,
  109172. 0x89,0x33,0x85,0xce,
  109173. 13,
  109174. 254,255,0,255,1,255,245,255,255,0,
  109175. 255,255,90};
  109176. /* nil packets; beginning,middle,end */
  109177. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109178. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109179. 0x01,0x02,0x03,0x04,0,0,0,0,
  109180. 0xff,0x7b,0x23,0x17,
  109181. 1,
  109182. 0};
  109183. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109184. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109185. 0x01,0x02,0x03,0x04,1,0,0,0,
  109186. 0x5c,0x3f,0x66,0xcb,
  109187. 17,
  109188. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109189. 255,255,90,0};
  109190. /* large initial packet */
  109191. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109192. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109193. 0x01,0x02,0x03,0x04,0,0,0,0,
  109194. 0x01,0x27,0x31,0xaa,
  109195. 18,
  109196. 255,255,255,255,255,255,255,255,
  109197. 255,255,255,255,255,255,255,255,255,10};
  109198. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109199. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109200. 0x01,0x02,0x03,0x04,1,0,0,0,
  109201. 0x7f,0x4e,0x8a,0xd2,
  109202. 4,
  109203. 255,4,255,0};
  109204. /* continuing packet test */
  109205. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109206. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109207. 0x01,0x02,0x03,0x04,0,0,0,0,
  109208. 0xff,0x7b,0x23,0x17,
  109209. 1,
  109210. 0};
  109211. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109212. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109213. 0x01,0x02,0x03,0x04,1,0,0,0,
  109214. 0x54,0x05,0x51,0xc8,
  109215. 17,
  109216. 255,255,255,255,255,255,255,255,
  109217. 255,255,255,255,255,255,255,255,255};
  109218. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109219. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109220. 0x01,0x02,0x03,0x04,2,0,0,0,
  109221. 0xc8,0xc3,0xcb,0xed,
  109222. 5,
  109223. 10,255,4,255,0};
  109224. /* page with the 255 segment limit */
  109225. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109226. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109227. 0x01,0x02,0x03,0x04,0,0,0,0,
  109228. 0xff,0x7b,0x23,0x17,
  109229. 1,
  109230. 0};
  109231. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109232. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109233. 0x01,0x02,0x03,0x04,1,0,0,0,
  109234. 0xed,0x2a,0x2e,0xa7,
  109235. 255,
  109236. 10,10,10,10,10,10,10,10,
  109237. 10,10,10,10,10,10,10,10,
  109238. 10,10,10,10,10,10,10,10,
  109239. 10,10,10,10,10,10,10,10,
  109240. 10,10,10,10,10,10,10,10,
  109241. 10,10,10,10,10,10,10,10,
  109242. 10,10,10,10,10,10,10,10,
  109243. 10,10,10,10,10,10,10,10,
  109244. 10,10,10,10,10,10,10,10,
  109245. 10,10,10,10,10,10,10,10,
  109246. 10,10,10,10,10,10,10,10,
  109247. 10,10,10,10,10,10,10,10,
  109248. 10,10,10,10,10,10,10,10,
  109249. 10,10,10,10,10,10,10,10,
  109250. 10,10,10,10,10,10,10,10,
  109251. 10,10,10,10,10,10,10,10,
  109252. 10,10,10,10,10,10,10,10,
  109253. 10,10,10,10,10,10,10,10,
  109254. 10,10,10,10,10,10,10,10,
  109255. 10,10,10,10,10,10,10,10,
  109256. 10,10,10,10,10,10,10,10,
  109257. 10,10,10,10,10,10,10,10,
  109258. 10,10,10,10,10,10,10,10,
  109259. 10,10,10,10,10,10,10,10,
  109260. 10,10,10,10,10,10,10,10,
  109261. 10,10,10,10,10,10,10,10,
  109262. 10,10,10,10,10,10,10,10,
  109263. 10,10,10,10,10,10,10,10,
  109264. 10,10,10,10,10,10,10,10,
  109265. 10,10,10,10,10,10,10,10,
  109266. 10,10,10,10,10,10,10,10,
  109267. 10,10,10,10,10,10,10};
  109268. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109269. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109270. 0x01,0x02,0x03,0x04,2,0,0,0,
  109271. 0x6c,0x3b,0x82,0x3d,
  109272. 1,
  109273. 50};
  109274. /* packet that overspans over an entire page */
  109275. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109276. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109277. 0x01,0x02,0x03,0x04,0,0,0,0,
  109278. 0xff,0x7b,0x23,0x17,
  109279. 1,
  109280. 0};
  109281. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109282. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109283. 0x01,0x02,0x03,0x04,1,0,0,0,
  109284. 0x3c,0xd9,0x4d,0x3f,
  109285. 17,
  109286. 100,255,255,255,255,255,255,255,255,
  109287. 255,255,255,255,255,255,255,255};
  109288. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109289. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109290. 0x01,0x02,0x03,0x04,2,0,0,0,
  109291. 0x01,0xd2,0xe5,0xe5,
  109292. 17,
  109293. 255,255,255,255,255,255,255,255,
  109294. 255,255,255,255,255,255,255,255,255};
  109295. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109296. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109297. 0x01,0x02,0x03,0x04,3,0,0,0,
  109298. 0xef,0xdd,0x88,0xde,
  109299. 7,
  109300. 255,255,75,255,4,255,0};
  109301. /* packet that overspans over an entire page */
  109302. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109303. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109304. 0x01,0x02,0x03,0x04,0,0,0,0,
  109305. 0xff,0x7b,0x23,0x17,
  109306. 1,
  109307. 0};
  109308. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109309. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109310. 0x01,0x02,0x03,0x04,1,0,0,0,
  109311. 0x3c,0xd9,0x4d,0x3f,
  109312. 17,
  109313. 100,255,255,255,255,255,255,255,255,
  109314. 255,255,255,255,255,255,255,255};
  109315. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109316. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109317. 0x01,0x02,0x03,0x04,2,0,0,0,
  109318. 0xd4,0xe0,0x60,0xe5,
  109319. 1,0};
  109320. void test_pack(const int *pl, const int **headers, int byteskip,
  109321. int pageskip, int packetskip){
  109322. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109323. long inptr=0;
  109324. long outptr=0;
  109325. long deptr=0;
  109326. long depacket=0;
  109327. long granule_pos=7,pageno=0;
  109328. int i,j,packets,pageout=pageskip;
  109329. int eosflag=0;
  109330. int bosflag=0;
  109331. int byteskipcount=0;
  109332. ogg_stream_reset(&os_en);
  109333. ogg_stream_reset(&os_de);
  109334. ogg_sync_reset(&oy);
  109335. for(packets=0;packets<packetskip;packets++)
  109336. depacket+=pl[packets];
  109337. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109338. for(i=0;i<packets;i++){
  109339. /* construct a test packet */
  109340. ogg_packet op;
  109341. int len=pl[i];
  109342. op.packet=data+inptr;
  109343. op.bytes=len;
  109344. op.e_o_s=(pl[i+1]<0?1:0);
  109345. op.granulepos=granule_pos;
  109346. granule_pos+=1024;
  109347. for(j=0;j<len;j++)data[inptr++]=i+j;
  109348. /* submit the test packet */
  109349. ogg_stream_packetin(&os_en,&op);
  109350. /* retrieve any finished pages */
  109351. {
  109352. ogg_page og;
  109353. while(ogg_stream_pageout(&os_en,&og)){
  109354. /* We have a page. Check it carefully */
  109355. fprintf(stderr,"%ld, ",pageno);
  109356. if(headers[pageno]==NULL){
  109357. fprintf(stderr,"coded too many pages!\n");
  109358. exit(1);
  109359. }
  109360. check_page(data+outptr,headers[pageno],&og);
  109361. outptr+=og.body_len;
  109362. pageno++;
  109363. if(pageskip){
  109364. bosflag=1;
  109365. pageskip--;
  109366. deptr+=og.body_len;
  109367. }
  109368. /* have a complete page; submit it to sync/decode */
  109369. {
  109370. ogg_page og_de;
  109371. ogg_packet op_de,op_de2;
  109372. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109373. char *next=buf;
  109374. byteskipcount+=og.header_len;
  109375. if(byteskipcount>byteskip){
  109376. memcpy(next,og.header,byteskipcount-byteskip);
  109377. next+=byteskipcount-byteskip;
  109378. byteskipcount=byteskip;
  109379. }
  109380. byteskipcount+=og.body_len;
  109381. if(byteskipcount>byteskip){
  109382. memcpy(next,og.body,byteskipcount-byteskip);
  109383. next+=byteskipcount-byteskip;
  109384. byteskipcount=byteskip;
  109385. }
  109386. ogg_sync_wrote(&oy,next-buf);
  109387. while(1){
  109388. int ret=ogg_sync_pageout(&oy,&og_de);
  109389. if(ret==0)break;
  109390. if(ret<0)continue;
  109391. /* got a page. Happy happy. Verify that it's good. */
  109392. fprintf(stderr,"(%ld), ",pageout);
  109393. check_page(data+deptr,headers[pageout],&og_de);
  109394. deptr+=og_de.body_len;
  109395. pageout++;
  109396. /* submit it to deconstitution */
  109397. ogg_stream_pagein(&os_de,&og_de);
  109398. /* packets out? */
  109399. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109400. ogg_stream_packetpeek(&os_de,NULL);
  109401. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109402. /* verify peek and out match */
  109403. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109404. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109405. depacket);
  109406. exit(1);
  109407. }
  109408. /* verify the packet! */
  109409. /* check data */
  109410. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109411. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109412. depacket);
  109413. exit(1);
  109414. }
  109415. /* check bos flag */
  109416. if(bosflag==0 && op_de.b_o_s==0){
  109417. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109418. exit(1);
  109419. }
  109420. if(bosflag && op_de.b_o_s){
  109421. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109422. exit(1);
  109423. }
  109424. bosflag=1;
  109425. depacket+=op_de.bytes;
  109426. /* check eos flag */
  109427. if(eosflag){
  109428. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109429. exit(1);
  109430. }
  109431. if(op_de.e_o_s)eosflag=1;
  109432. /* check granulepos flag */
  109433. if(op_de.granulepos!=-1){
  109434. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109435. }
  109436. }
  109437. }
  109438. }
  109439. }
  109440. }
  109441. }
  109442. _ogg_free(data);
  109443. if(headers[pageno]!=NULL){
  109444. fprintf(stderr,"did not write last page!\n");
  109445. exit(1);
  109446. }
  109447. if(headers[pageout]!=NULL){
  109448. fprintf(stderr,"did not decode last page!\n");
  109449. exit(1);
  109450. }
  109451. if(inptr!=outptr){
  109452. fprintf(stderr,"encoded page data incomplete!\n");
  109453. exit(1);
  109454. }
  109455. if(inptr!=deptr){
  109456. fprintf(stderr,"decoded page data incomplete!\n");
  109457. exit(1);
  109458. }
  109459. if(inptr!=depacket){
  109460. fprintf(stderr,"decoded packet data incomplete!\n");
  109461. exit(1);
  109462. }
  109463. if(!eosflag){
  109464. fprintf(stderr,"Never got a packet with EOS set!\n");
  109465. exit(1);
  109466. }
  109467. fprintf(stderr,"ok.\n");
  109468. }
  109469. int main(void){
  109470. ogg_stream_init(&os_en,0x04030201);
  109471. ogg_stream_init(&os_de,0x04030201);
  109472. ogg_sync_init(&oy);
  109473. /* Exercise each code path in the framing code. Also verify that
  109474. the checksums are working. */
  109475. {
  109476. /* 17 only */
  109477. const int packets[]={17, -1};
  109478. const int *headret[]={head1_0,NULL};
  109479. fprintf(stderr,"testing single page encoding... ");
  109480. test_pack(packets,headret,0,0,0);
  109481. }
  109482. {
  109483. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109484. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109485. const int *headret[]={head1_1,head2_1,NULL};
  109486. fprintf(stderr,"testing basic page encoding... ");
  109487. test_pack(packets,headret,0,0,0);
  109488. }
  109489. {
  109490. /* nil packets; beginning,middle,end */
  109491. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109492. const int *headret[]={head1_2,head2_2,NULL};
  109493. fprintf(stderr,"testing basic nil packets... ");
  109494. test_pack(packets,headret,0,0,0);
  109495. }
  109496. {
  109497. /* large initial packet */
  109498. const int packets[]={4345,259,255,-1};
  109499. const int *headret[]={head1_3,head2_3,NULL};
  109500. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109501. test_pack(packets,headret,0,0,0);
  109502. }
  109503. {
  109504. /* continuing packet test */
  109505. const int packets[]={0,4345,259,255,-1};
  109506. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109507. fprintf(stderr,"testing single packet page span... ");
  109508. test_pack(packets,headret,0,0,0);
  109509. }
  109510. /* page with the 255 segment limit */
  109511. {
  109512. const int packets[]={0,10,10,10,10,10,10,10,10,
  109513. 10,10,10,10,10,10,10,10,
  109514. 10,10,10,10,10,10,10,10,
  109515. 10,10,10,10,10,10,10,10,
  109516. 10,10,10,10,10,10,10,10,
  109517. 10,10,10,10,10,10,10,10,
  109518. 10,10,10,10,10,10,10,10,
  109519. 10,10,10,10,10,10,10,10,
  109520. 10,10,10,10,10,10,10,10,
  109521. 10,10,10,10,10,10,10,10,
  109522. 10,10,10,10,10,10,10,10,
  109523. 10,10,10,10,10,10,10,10,
  109524. 10,10,10,10,10,10,10,10,
  109525. 10,10,10,10,10,10,10,10,
  109526. 10,10,10,10,10,10,10,10,
  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,50,-1};
  109544. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109545. fprintf(stderr,"testing max packet segments... ");
  109546. test_pack(packets,headret,0,0,0);
  109547. }
  109548. {
  109549. /* packet that overspans over an entire page */
  109550. const int packets[]={0,100,9000,259,255,-1};
  109551. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109552. fprintf(stderr,"testing very large packets... ");
  109553. test_pack(packets,headret,0,0,0);
  109554. }
  109555. {
  109556. /* test for the libogg 1.1.1 resync in large continuation bug
  109557. found by Josh Coalson) */
  109558. const int packets[]={0,100,9000,259,255,-1};
  109559. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109560. fprintf(stderr,"testing continuation resync in very large packets... ");
  109561. test_pack(packets,headret,100,2,3);
  109562. }
  109563. {
  109564. /* term only page. why not? */
  109565. const int packets[]={0,100,4080,-1};
  109566. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109567. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109568. test_pack(packets,headret,0,0,0);
  109569. }
  109570. {
  109571. /* build a bunch of pages for testing */
  109572. unsigned char *data=_ogg_malloc(1024*1024);
  109573. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109574. int inptr=0,i,j;
  109575. ogg_page og[5];
  109576. ogg_stream_reset(&os_en);
  109577. for(i=0;pl[i]!=-1;i++){
  109578. ogg_packet op;
  109579. int len=pl[i];
  109580. op.packet=data+inptr;
  109581. op.bytes=len;
  109582. op.e_o_s=(pl[i+1]<0?1:0);
  109583. op.granulepos=(i+1)*1000;
  109584. for(j=0;j<len;j++)data[inptr++]=i+j;
  109585. ogg_stream_packetin(&os_en,&op);
  109586. }
  109587. _ogg_free(data);
  109588. /* retrieve finished pages */
  109589. for(i=0;i<5;i++){
  109590. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109591. fprintf(stderr,"Too few pages output building sync tests!\n");
  109592. exit(1);
  109593. }
  109594. copy_page(&og[i]);
  109595. }
  109596. /* Test lost pages on pagein/packetout: no rollback */
  109597. {
  109598. ogg_page temp;
  109599. ogg_packet test;
  109600. fprintf(stderr,"Testing loss of pages... ");
  109601. ogg_sync_reset(&oy);
  109602. ogg_stream_reset(&os_de);
  109603. for(i=0;i<5;i++){
  109604. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109605. og[i].header_len);
  109606. ogg_sync_wrote(&oy,og[i].header_len);
  109607. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109608. ogg_sync_wrote(&oy,og[i].body_len);
  109609. }
  109610. ogg_sync_pageout(&oy,&temp);
  109611. ogg_stream_pagein(&os_de,&temp);
  109612. ogg_sync_pageout(&oy,&temp);
  109613. ogg_stream_pagein(&os_de,&temp);
  109614. ogg_sync_pageout(&oy,&temp);
  109615. /* skip */
  109616. ogg_sync_pageout(&oy,&temp);
  109617. ogg_stream_pagein(&os_de,&temp);
  109618. /* do we get the expected results/packets? */
  109619. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109620. checkpacket(&test,0,0,0);
  109621. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109622. checkpacket(&test,100,1,-1);
  109623. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109624. checkpacket(&test,4079,2,3000);
  109625. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109626. fprintf(stderr,"Error: loss of page did not return error\n");
  109627. exit(1);
  109628. }
  109629. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109630. checkpacket(&test,76,5,-1);
  109631. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109632. checkpacket(&test,34,6,-1);
  109633. fprintf(stderr,"ok.\n");
  109634. }
  109635. /* Test lost pages on pagein/packetout: rollback with continuation */
  109636. {
  109637. ogg_page temp;
  109638. ogg_packet test;
  109639. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109640. ogg_sync_reset(&oy);
  109641. ogg_stream_reset(&os_de);
  109642. for(i=0;i<5;i++){
  109643. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109644. og[i].header_len);
  109645. ogg_sync_wrote(&oy,og[i].header_len);
  109646. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109647. ogg_sync_wrote(&oy,og[i].body_len);
  109648. }
  109649. ogg_sync_pageout(&oy,&temp);
  109650. ogg_stream_pagein(&os_de,&temp);
  109651. ogg_sync_pageout(&oy,&temp);
  109652. ogg_stream_pagein(&os_de,&temp);
  109653. ogg_sync_pageout(&oy,&temp);
  109654. ogg_stream_pagein(&os_de,&temp);
  109655. ogg_sync_pageout(&oy,&temp);
  109656. /* skip */
  109657. ogg_sync_pageout(&oy,&temp);
  109658. ogg_stream_pagein(&os_de,&temp);
  109659. /* do we get the expected results/packets? */
  109660. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109661. checkpacket(&test,0,0,0);
  109662. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109663. checkpacket(&test,100,1,-1);
  109664. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109665. checkpacket(&test,4079,2,3000);
  109666. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109667. checkpacket(&test,2956,3,4000);
  109668. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109669. fprintf(stderr,"Error: loss of page did not return error\n");
  109670. exit(1);
  109671. }
  109672. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109673. checkpacket(&test,300,13,14000);
  109674. fprintf(stderr,"ok.\n");
  109675. }
  109676. /* the rest only test sync */
  109677. {
  109678. ogg_page og_de;
  109679. /* Test fractional page inputs: incomplete capture */
  109680. fprintf(stderr,"Testing sync on partial inputs... ");
  109681. ogg_sync_reset(&oy);
  109682. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109683. 3);
  109684. ogg_sync_wrote(&oy,3);
  109685. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109686. /* Test fractional page inputs: incomplete fixed header */
  109687. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109688. 20);
  109689. ogg_sync_wrote(&oy,20);
  109690. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109691. /* Test fractional page inputs: incomplete header */
  109692. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109693. 5);
  109694. ogg_sync_wrote(&oy,5);
  109695. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109696. /* Test fractional page inputs: incomplete body */
  109697. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109698. og[1].header_len-28);
  109699. ogg_sync_wrote(&oy,og[1].header_len-28);
  109700. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109701. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109702. ogg_sync_wrote(&oy,1000);
  109703. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109704. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109705. og[1].body_len-1000);
  109706. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109707. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109708. fprintf(stderr,"ok.\n");
  109709. }
  109710. /* Test fractional page inputs: page + incomplete capture */
  109711. {
  109712. ogg_page og_de;
  109713. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109714. ogg_sync_reset(&oy);
  109715. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109716. og[1].header_len);
  109717. ogg_sync_wrote(&oy,og[1].header_len);
  109718. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109719. og[1].body_len);
  109720. ogg_sync_wrote(&oy,og[1].body_len);
  109721. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109722. 20);
  109723. ogg_sync_wrote(&oy,20);
  109724. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109725. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109726. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109727. og[1].header_len-20);
  109728. ogg_sync_wrote(&oy,og[1].header_len-20);
  109729. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109730. og[1].body_len);
  109731. ogg_sync_wrote(&oy,og[1].body_len);
  109732. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109733. fprintf(stderr,"ok.\n");
  109734. }
  109735. /* Test recapture: garbage + page */
  109736. {
  109737. ogg_page og_de;
  109738. fprintf(stderr,"Testing search for capture... ");
  109739. ogg_sync_reset(&oy);
  109740. /* 'garbage' */
  109741. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109742. og[1].body_len);
  109743. ogg_sync_wrote(&oy,og[1].body_len);
  109744. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109745. og[1].header_len);
  109746. ogg_sync_wrote(&oy,og[1].header_len);
  109747. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109748. og[1].body_len);
  109749. ogg_sync_wrote(&oy,og[1].body_len);
  109750. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109751. 20);
  109752. ogg_sync_wrote(&oy,20);
  109753. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109754. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109755. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109756. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109757. og[2].header_len-20);
  109758. ogg_sync_wrote(&oy,og[2].header_len-20);
  109759. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109760. og[2].body_len);
  109761. ogg_sync_wrote(&oy,og[2].body_len);
  109762. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109763. fprintf(stderr,"ok.\n");
  109764. }
  109765. /* Test recapture: page + garbage + page */
  109766. {
  109767. ogg_page og_de;
  109768. fprintf(stderr,"Testing recapture... ");
  109769. ogg_sync_reset(&oy);
  109770. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109771. og[1].header_len);
  109772. ogg_sync_wrote(&oy,og[1].header_len);
  109773. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109774. og[1].body_len);
  109775. ogg_sync_wrote(&oy,og[1].body_len);
  109776. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109777. og[2].header_len);
  109778. ogg_sync_wrote(&oy,og[2].header_len);
  109779. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109780. og[2].header_len);
  109781. ogg_sync_wrote(&oy,og[2].header_len);
  109782. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109783. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109784. og[2].body_len-5);
  109785. ogg_sync_wrote(&oy,og[2].body_len-5);
  109786. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109787. og[3].header_len);
  109788. ogg_sync_wrote(&oy,og[3].header_len);
  109789. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109790. og[3].body_len);
  109791. ogg_sync_wrote(&oy,og[3].body_len);
  109792. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109793. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109794. fprintf(stderr,"ok.\n");
  109795. }
  109796. /* Free page data that was previously copied */
  109797. {
  109798. for(i=0;i<5;i++){
  109799. free_page(&og[i]);
  109800. }
  109801. }
  109802. }
  109803. return(0);
  109804. }
  109805. #endif
  109806. #endif
  109807. /*** End of inlined file: framing.c ***/
  109808. /*** Start of inlined file: analysis.c ***/
  109809. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109810. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109811. // tasks..
  109812. #if JUCE_MSVC
  109813. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109814. #endif
  109815. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109816. #if JUCE_USE_OGGVORBIS
  109817. #include <stdio.h>
  109818. #include <string.h>
  109819. #include <math.h>
  109820. /*** Start of inlined file: codec_internal.h ***/
  109821. #ifndef _V_CODECI_H_
  109822. #define _V_CODECI_H_
  109823. /*** Start of inlined file: envelope.h ***/
  109824. #ifndef _V_ENVELOPE_
  109825. #define _V_ENVELOPE_
  109826. /*** Start of inlined file: mdct.h ***/
  109827. #ifndef _OGG_mdct_H_
  109828. #define _OGG_mdct_H_
  109829. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109830. #ifdef MDCT_INTEGERIZED
  109831. #define DATA_TYPE int
  109832. #define REG_TYPE register int
  109833. #define TRIGBITS 14
  109834. #define cPI3_8 6270
  109835. #define cPI2_8 11585
  109836. #define cPI1_8 15137
  109837. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109838. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109839. #define HALVE(x) ((x)>>1)
  109840. #else
  109841. #define DATA_TYPE float
  109842. #define REG_TYPE float
  109843. #define cPI3_8 .38268343236508977175F
  109844. #define cPI2_8 .70710678118654752441F
  109845. #define cPI1_8 .92387953251128675613F
  109846. #define FLOAT_CONV(x) (x)
  109847. #define MULT_NORM(x) (x)
  109848. #define HALVE(x) ((x)*.5f)
  109849. #endif
  109850. typedef struct {
  109851. int n;
  109852. int log2n;
  109853. DATA_TYPE *trig;
  109854. int *bitrev;
  109855. DATA_TYPE scale;
  109856. } mdct_lookup;
  109857. extern void mdct_init(mdct_lookup *lookup,int n);
  109858. extern void mdct_clear(mdct_lookup *l);
  109859. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109860. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109861. #endif
  109862. /*** End of inlined file: mdct.h ***/
  109863. #define VE_PRE 16
  109864. #define VE_WIN 4
  109865. #define VE_POST 2
  109866. #define VE_AMP (VE_PRE+VE_POST-1)
  109867. #define VE_BANDS 7
  109868. #define VE_NEARDC 15
  109869. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109870. #define VE_MAXSTRETCH 12 /* one-third full block */
  109871. typedef struct {
  109872. float ampbuf[VE_AMP];
  109873. int ampptr;
  109874. float nearDC[VE_NEARDC];
  109875. float nearDC_acc;
  109876. float nearDC_partialacc;
  109877. int nearptr;
  109878. } envelope_filter_state;
  109879. typedef struct {
  109880. int begin;
  109881. int end;
  109882. float *window;
  109883. float total;
  109884. } envelope_band;
  109885. typedef struct {
  109886. int ch;
  109887. int winlength;
  109888. int searchstep;
  109889. float minenergy;
  109890. mdct_lookup mdct;
  109891. float *mdct_win;
  109892. envelope_band band[VE_BANDS];
  109893. envelope_filter_state *filter;
  109894. int stretch;
  109895. int *mark;
  109896. long storage;
  109897. long current;
  109898. long curmark;
  109899. long cursor;
  109900. } envelope_lookup;
  109901. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109902. extern void _ve_envelope_clear(envelope_lookup *e);
  109903. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109904. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109905. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109906. #endif
  109907. /*** End of inlined file: envelope.h ***/
  109908. /*** Start of inlined file: codebook.h ***/
  109909. #ifndef _V_CODEBOOK_H_
  109910. #define _V_CODEBOOK_H_
  109911. /* This structure encapsulates huffman and VQ style encoding books; it
  109912. doesn't do anything specific to either.
  109913. valuelist/quantlist are nonNULL (and q_* significant) only if
  109914. there's entry->value mapping to be done.
  109915. If encode-side mapping must be done (and thus the entry needs to be
  109916. hunted), the auxiliary encode pointer will point to a decision
  109917. tree. This is true of both VQ and huffman, but is mostly useful
  109918. with VQ.
  109919. */
  109920. typedef struct static_codebook{
  109921. long dim; /* codebook dimensions (elements per vector) */
  109922. long entries; /* codebook entries */
  109923. long *lengthlist; /* codeword lengths in bits */
  109924. /* mapping ***************************************************************/
  109925. int maptype; /* 0=none
  109926. 1=implicitly populated values from map column
  109927. 2=listed arbitrary values */
  109928. /* The below does a linear, single monotonic sequence mapping. */
  109929. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109930. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109931. int q_quant; /* bits: 0 < quant <= 16 */
  109932. int q_sequencep; /* bitflag */
  109933. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109934. map == 2: list of dim*entries quantized entry vals
  109935. */
  109936. /* encode helpers ********************************************************/
  109937. struct encode_aux_nearestmatch *nearest_tree;
  109938. struct encode_aux_threshmatch *thresh_tree;
  109939. struct encode_aux_pigeonhole *pigeon_tree;
  109940. int allocedp;
  109941. } static_codebook;
  109942. /* this structures an arbitrary trained book to quickly find the
  109943. nearest cell match */
  109944. typedef struct encode_aux_nearestmatch{
  109945. /* pre-calculated partitioning tree */
  109946. long *ptr0;
  109947. long *ptr1;
  109948. long *p; /* decision points (each is an entry) */
  109949. long *q; /* decision points (each is an entry) */
  109950. long aux; /* number of tree entries */
  109951. long alloc;
  109952. } encode_aux_nearestmatch;
  109953. /* assumes a maptype of 1; encode side only, so that's OK */
  109954. typedef struct encode_aux_threshmatch{
  109955. float *quantthresh;
  109956. long *quantmap;
  109957. int quantvals;
  109958. int threshvals;
  109959. } encode_aux_threshmatch;
  109960. typedef struct encode_aux_pigeonhole{
  109961. float min;
  109962. float del;
  109963. int mapentries;
  109964. int quantvals;
  109965. long *pigeonmap;
  109966. long fittotal;
  109967. long *fitlist;
  109968. long *fitmap;
  109969. long *fitlength;
  109970. } encode_aux_pigeonhole;
  109971. typedef struct codebook{
  109972. long dim; /* codebook dimensions (elements per vector) */
  109973. long entries; /* codebook entries */
  109974. long used_entries; /* populated codebook entries */
  109975. const static_codebook *c;
  109976. /* for encode, the below are entry-ordered, fully populated */
  109977. /* for decode, the below are ordered by bitreversed codeword and only
  109978. used entries are populated */
  109979. float *valuelist; /* list of dim*entries actual entry values */
  109980. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109981. int *dec_index; /* only used if sparseness collapsed */
  109982. char *dec_codelengths;
  109983. ogg_uint32_t *dec_firsttable;
  109984. int dec_firsttablen;
  109985. int dec_maxlength;
  109986. } codebook;
  109987. extern void vorbis_staticbook_clear(static_codebook *b);
  109988. extern void vorbis_staticbook_destroy(static_codebook *b);
  109989. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109990. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109991. extern void vorbis_book_clear(codebook *b);
  109992. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109993. extern float *_book_logdist(const static_codebook *b,float *vals);
  109994. extern float _float32_unpack(long val);
  109995. extern long _float32_pack(float val);
  109996. extern int _best(codebook *book, float *a, int step);
  109997. extern int _ilog(unsigned int v);
  109998. extern long _book_maptype1_quantvals(const static_codebook *b);
  109999. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110000. extern long vorbis_book_codeword(codebook *book,int entry);
  110001. extern long vorbis_book_codelen(codebook *book,int entry);
  110002. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110003. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110004. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110005. extern int vorbis_book_errorv(codebook *book, float *a);
  110006. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110007. oggpack_buffer *b);
  110008. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110009. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110010. oggpack_buffer *b,int n);
  110011. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110012. oggpack_buffer *b,int n);
  110013. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110014. oggpack_buffer *b,int n);
  110015. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110016. long off,int ch,
  110017. oggpack_buffer *b,int n);
  110018. #endif
  110019. /*** End of inlined file: codebook.h ***/
  110020. #define BLOCKTYPE_IMPULSE 0
  110021. #define BLOCKTYPE_PADDING 1
  110022. #define BLOCKTYPE_TRANSITION 0
  110023. #define BLOCKTYPE_LONG 1
  110024. #define PACKETBLOBS 15
  110025. typedef struct vorbis_block_internal{
  110026. float **pcmdelay; /* this is a pointer into local storage */
  110027. float ampmax;
  110028. int blocktype;
  110029. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110030. blob [PACKETBLOBS/2] points to
  110031. the oggpack_buffer in the
  110032. main vorbis_block */
  110033. } vorbis_block_internal;
  110034. typedef void vorbis_look_floor;
  110035. typedef void vorbis_look_residue;
  110036. typedef void vorbis_look_transform;
  110037. /* mode ************************************************************/
  110038. typedef struct {
  110039. int blockflag;
  110040. int windowtype;
  110041. int transformtype;
  110042. int mapping;
  110043. } vorbis_info_mode;
  110044. typedef void vorbis_info_floor;
  110045. typedef void vorbis_info_residue;
  110046. typedef void vorbis_info_mapping;
  110047. /*** Start of inlined file: psy.h ***/
  110048. #ifndef _V_PSY_H_
  110049. #define _V_PSY_H_
  110050. /*** Start of inlined file: smallft.h ***/
  110051. #ifndef _V_SMFT_H_
  110052. #define _V_SMFT_H_
  110053. typedef struct {
  110054. int n;
  110055. float *trigcache;
  110056. int *splitcache;
  110057. } drft_lookup;
  110058. extern void drft_forward(drft_lookup *l,float *data);
  110059. extern void drft_backward(drft_lookup *l,float *data);
  110060. extern void drft_init(drft_lookup *l,int n);
  110061. extern void drft_clear(drft_lookup *l);
  110062. #endif
  110063. /*** End of inlined file: smallft.h ***/
  110064. /*** Start of inlined file: backends.h ***/
  110065. /* this is exposed up here because we need it for static modes.
  110066. Lookups for each backend aren't exposed because there's no reason
  110067. to do so */
  110068. #ifndef _vorbis_backend_h_
  110069. #define _vorbis_backend_h_
  110070. /* this would all be simpler/shorter with templates, but.... */
  110071. /* Floor backend generic *****************************************/
  110072. typedef struct{
  110073. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110074. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110075. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110076. void (*free_info) (vorbis_info_floor *);
  110077. void (*free_look) (vorbis_look_floor *);
  110078. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110079. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110080. void *buffer,float *);
  110081. } vorbis_func_floor;
  110082. typedef struct{
  110083. int order;
  110084. long rate;
  110085. long barkmap;
  110086. int ampbits;
  110087. int ampdB;
  110088. int numbooks; /* <= 16 */
  110089. int books[16];
  110090. float lessthan; /* encode-only config setting hacks for libvorbis */
  110091. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110092. } vorbis_info_floor0;
  110093. #define VIF_POSIT 63
  110094. #define VIF_CLASS 16
  110095. #define VIF_PARTS 31
  110096. typedef struct{
  110097. int partitions; /* 0 to 31 */
  110098. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110099. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110100. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110101. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110102. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110103. int mult; /* 1 2 3 or 4 */
  110104. int postlist[VIF_POSIT+2]; /* first two implicit */
  110105. /* encode side analysis parameters */
  110106. float maxover;
  110107. float maxunder;
  110108. float maxerr;
  110109. float twofitweight;
  110110. float twofitatten;
  110111. int n;
  110112. } vorbis_info_floor1;
  110113. /* Residue backend generic *****************************************/
  110114. typedef struct{
  110115. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110116. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110117. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110118. vorbis_info_residue *);
  110119. void (*free_info) (vorbis_info_residue *);
  110120. void (*free_look) (vorbis_look_residue *);
  110121. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110122. float **,int *,int);
  110123. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110124. vorbis_look_residue *,
  110125. float **,float **,int *,int,long **);
  110126. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110127. float **,int *,int);
  110128. } vorbis_func_residue;
  110129. typedef struct vorbis_info_residue0{
  110130. /* block-partitioned VQ coded straight residue */
  110131. long begin;
  110132. long end;
  110133. /* first stage (lossless partitioning) */
  110134. int grouping; /* group n vectors per partition */
  110135. int partitions; /* possible codebooks for a partition */
  110136. int groupbook; /* huffbook for partitioning */
  110137. int secondstages[64]; /* expanded out to pointers in lookup */
  110138. int booklist[256]; /* list of second stage books */
  110139. float classmetric1[64];
  110140. float classmetric2[64];
  110141. } vorbis_info_residue0;
  110142. /* Mapping backend generic *****************************************/
  110143. typedef struct{
  110144. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110145. oggpack_buffer *);
  110146. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110147. void (*free_info) (vorbis_info_mapping *);
  110148. int (*forward) (struct vorbis_block *vb);
  110149. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110150. } vorbis_func_mapping;
  110151. typedef struct vorbis_info_mapping0{
  110152. int submaps; /* <= 16 */
  110153. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110154. int floorsubmap[16]; /* [mux] submap to floors */
  110155. int residuesubmap[16]; /* [mux] submap to residue */
  110156. int coupling_steps;
  110157. int coupling_mag[256];
  110158. int coupling_ang[256];
  110159. } vorbis_info_mapping0;
  110160. #endif
  110161. /*** End of inlined file: backends.h ***/
  110162. #ifndef EHMER_MAX
  110163. #define EHMER_MAX 56
  110164. #endif
  110165. /* psychoacoustic setup ********************************************/
  110166. #define P_BANDS 17 /* 62Hz to 16kHz */
  110167. #define P_LEVELS 8 /* 30dB to 100dB */
  110168. #define P_LEVEL_0 30. /* 30 dB */
  110169. #define P_NOISECURVES 3
  110170. #define NOISE_COMPAND_LEVELS 40
  110171. typedef struct vorbis_info_psy{
  110172. int blockflag;
  110173. float ath_adjatt;
  110174. float ath_maxatt;
  110175. float tone_masteratt[P_NOISECURVES];
  110176. float tone_centerboost;
  110177. float tone_decay;
  110178. float tone_abs_limit;
  110179. float toneatt[P_BANDS];
  110180. int noisemaskp;
  110181. float noisemaxsupp;
  110182. float noisewindowlo;
  110183. float noisewindowhi;
  110184. int noisewindowlomin;
  110185. int noisewindowhimin;
  110186. int noisewindowfixed;
  110187. float noiseoff[P_NOISECURVES][P_BANDS];
  110188. float noisecompand[NOISE_COMPAND_LEVELS];
  110189. float max_curve_dB;
  110190. int normal_channel_p;
  110191. int normal_point_p;
  110192. int normal_start;
  110193. int normal_partition;
  110194. double normal_thresh;
  110195. } vorbis_info_psy;
  110196. typedef struct{
  110197. int eighth_octave_lines;
  110198. /* for block long/short tuning; encode only */
  110199. float preecho_thresh[VE_BANDS];
  110200. float postecho_thresh[VE_BANDS];
  110201. float stretch_penalty;
  110202. float preecho_minenergy;
  110203. float ampmax_att_per_sec;
  110204. /* channel coupling config */
  110205. int coupling_pkHz[PACKETBLOBS];
  110206. int coupling_pointlimit[2][PACKETBLOBS];
  110207. int coupling_prepointamp[PACKETBLOBS];
  110208. int coupling_postpointamp[PACKETBLOBS];
  110209. int sliding_lowpass[2][PACKETBLOBS];
  110210. } vorbis_info_psy_global;
  110211. typedef struct {
  110212. float ampmax;
  110213. int channels;
  110214. vorbis_info_psy_global *gi;
  110215. int coupling_pointlimit[2][P_NOISECURVES];
  110216. } vorbis_look_psy_global;
  110217. typedef struct {
  110218. int n;
  110219. struct vorbis_info_psy *vi;
  110220. float ***tonecurves;
  110221. float **noiseoffset;
  110222. float *ath;
  110223. long *octave; /* in n.ocshift format */
  110224. long *bark;
  110225. long firstoc;
  110226. long shiftoc;
  110227. int eighth_octave_lines; /* power of two, please */
  110228. int total_octave_lines;
  110229. long rate; /* cache it */
  110230. float m_val; /* Masking compensation value */
  110231. } vorbis_look_psy;
  110232. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110233. vorbis_info_psy_global *gi,int n,long rate);
  110234. extern void _vp_psy_clear(vorbis_look_psy *p);
  110235. extern void *_vi_psy_dup(void *source);
  110236. extern void _vi_psy_free(vorbis_info_psy *i);
  110237. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110238. extern void _vp_remove_floor(vorbis_look_psy *p,
  110239. float *mdct,
  110240. int *icodedflr,
  110241. float *residue,
  110242. int sliding_lowpass);
  110243. extern void _vp_noisemask(vorbis_look_psy *p,
  110244. float *logmdct,
  110245. float *logmask);
  110246. extern void _vp_tonemask(vorbis_look_psy *p,
  110247. float *logfft,
  110248. float *logmask,
  110249. float global_specmax,
  110250. float local_specmax);
  110251. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110252. float *noise,
  110253. float *tone,
  110254. int offset_select,
  110255. float *logmask,
  110256. float *mdct,
  110257. float *logmdct);
  110258. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110259. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110260. vorbis_info_psy_global *g,
  110261. vorbis_look_psy *p,
  110262. vorbis_info_mapping0 *vi,
  110263. float **mdct);
  110264. extern void _vp_couple(int blobno,
  110265. vorbis_info_psy_global *g,
  110266. vorbis_look_psy *p,
  110267. vorbis_info_mapping0 *vi,
  110268. float **res,
  110269. float **mag_memo,
  110270. int **mag_sort,
  110271. int **ifloor,
  110272. int *nonzero,
  110273. int sliding_lowpass);
  110274. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110275. float *in,float *out,int *sortedindex);
  110276. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110277. float *magnitudes,int *sortedindex);
  110278. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110279. vorbis_look_psy *p,
  110280. vorbis_info_mapping0 *vi,
  110281. float **mags);
  110282. extern void hf_reduction(vorbis_info_psy_global *g,
  110283. vorbis_look_psy *p,
  110284. vorbis_info_mapping0 *vi,
  110285. float **mdct);
  110286. #endif
  110287. /*** End of inlined file: psy.h ***/
  110288. /*** Start of inlined file: bitrate.h ***/
  110289. #ifndef _V_BITRATE_H_
  110290. #define _V_BITRATE_H_
  110291. /*** Start of inlined file: os.h ***/
  110292. #ifndef _OS_H
  110293. #define _OS_H
  110294. /********************************************************************
  110295. * *
  110296. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110297. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110298. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110299. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110300. * *
  110301. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110302. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110303. * *
  110304. ********************************************************************
  110305. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110306. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110307. ********************************************************************/
  110308. #ifdef HAVE_CONFIG_H
  110309. #include "config.h"
  110310. #endif
  110311. #include <math.h>
  110312. /*** Start of inlined file: misc.h ***/
  110313. #ifndef _V_RANDOM_H_
  110314. #define _V_RANDOM_H_
  110315. extern int analysis_noisy;
  110316. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110317. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110318. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110319. ogg_int64_t off);
  110320. #ifdef DEBUG_MALLOC
  110321. #define _VDBG_GRAPHFILE "malloc.m"
  110322. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110323. extern void _VDBG_free(void *ptr,char *file,long line);
  110324. #ifndef MISC_C
  110325. #undef _ogg_malloc
  110326. #undef _ogg_calloc
  110327. #undef _ogg_realloc
  110328. #undef _ogg_free
  110329. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110330. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110331. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110332. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110333. #endif
  110334. #endif
  110335. #endif
  110336. /*** End of inlined file: misc.h ***/
  110337. #ifndef _V_IFDEFJAIL_H_
  110338. # define _V_IFDEFJAIL_H_
  110339. # ifdef __GNUC__
  110340. # define STIN static __inline__
  110341. # elif _WIN32
  110342. # define STIN static __inline
  110343. # else
  110344. # define STIN static
  110345. # endif
  110346. #ifdef DJGPP
  110347. # define rint(x) (floor((x)+0.5f))
  110348. #endif
  110349. #ifndef M_PI
  110350. # define M_PI (3.1415926536f)
  110351. #endif
  110352. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110353. # include <malloc.h>
  110354. # define rint(x) (floor((x)+0.5f))
  110355. # define NO_FLOAT_MATH_LIB
  110356. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110357. #endif
  110358. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110359. void *_alloca(size_t size);
  110360. # define alloca _alloca
  110361. #endif
  110362. #ifndef FAST_HYPOT
  110363. # define FAST_HYPOT hypot
  110364. #endif
  110365. #endif
  110366. #ifdef HAVE_ALLOCA_H
  110367. # include <alloca.h>
  110368. #endif
  110369. #ifdef USE_MEMORY_H
  110370. # include <memory.h>
  110371. #endif
  110372. #ifndef min
  110373. # define min(x,y) ((x)>(y)?(y):(x))
  110374. #endif
  110375. #ifndef max
  110376. # define max(x,y) ((x)<(y)?(y):(x))
  110377. #endif
  110378. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110379. # define VORBIS_FPU_CONTROL
  110380. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110381. Because of encapsulation constraints (GCC can't see inside the asm
  110382. block and so we end up doing stupid things like a store/load that
  110383. is collectively a noop), we do it this way */
  110384. /* we must set up the fpu before this works!! */
  110385. typedef ogg_int16_t vorbis_fpu_control;
  110386. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110387. ogg_int16_t ret;
  110388. ogg_int16_t temp;
  110389. __asm__ __volatile__("fnstcw %0\n\t"
  110390. "movw %0,%%dx\n\t"
  110391. "orw $62463,%%dx\n\t"
  110392. "movw %%dx,%1\n\t"
  110393. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110394. *fpu=ret;
  110395. }
  110396. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110397. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110398. }
  110399. /* assumes the FPU is in round mode! */
  110400. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110401. we get extra fst/fld to
  110402. truncate precision */
  110403. int i;
  110404. __asm__("fistl %0": "=m"(i) : "t"(f));
  110405. return(i);
  110406. }
  110407. #endif
  110408. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110409. # define VORBIS_FPU_CONTROL
  110410. typedef ogg_int16_t vorbis_fpu_control;
  110411. static __inline int vorbis_ftoi(double f){
  110412. int i;
  110413. __asm{
  110414. fld f
  110415. fistp i
  110416. }
  110417. return i;
  110418. }
  110419. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110420. }
  110421. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110422. }
  110423. #endif
  110424. #ifndef VORBIS_FPU_CONTROL
  110425. typedef int vorbis_fpu_control;
  110426. static int vorbis_ftoi(double f){
  110427. return (int)(f+.5);
  110428. }
  110429. /* We don't have special code for this compiler/arch, so do it the slow way */
  110430. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110431. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110432. #endif
  110433. #endif /* _OS_H */
  110434. /*** End of inlined file: os.h ***/
  110435. /* encode side bitrate tracking */
  110436. typedef struct bitrate_manager_state {
  110437. int managed;
  110438. long avg_reservoir;
  110439. long minmax_reservoir;
  110440. long avg_bitsper;
  110441. long min_bitsper;
  110442. long max_bitsper;
  110443. long short_per_long;
  110444. double avgfloat;
  110445. vorbis_block *vb;
  110446. int choice;
  110447. } bitrate_manager_state;
  110448. typedef struct bitrate_manager_info{
  110449. long avg_rate;
  110450. long min_rate;
  110451. long max_rate;
  110452. long reservoir_bits;
  110453. double reservoir_bias;
  110454. double slew_damp;
  110455. } bitrate_manager_info;
  110456. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110457. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110458. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110459. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110460. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110461. #endif
  110462. /*** End of inlined file: bitrate.h ***/
  110463. static int ilog(unsigned int v){
  110464. int ret=0;
  110465. while(v){
  110466. ret++;
  110467. v>>=1;
  110468. }
  110469. return(ret);
  110470. }
  110471. static int ilog2(unsigned int v){
  110472. int ret=0;
  110473. if(v)--v;
  110474. while(v){
  110475. ret++;
  110476. v>>=1;
  110477. }
  110478. return(ret);
  110479. }
  110480. typedef struct private_state {
  110481. /* local lookup storage */
  110482. envelope_lookup *ve; /* envelope lookup */
  110483. int window[2];
  110484. vorbis_look_transform **transform[2]; /* block, type */
  110485. drft_lookup fft_look[2];
  110486. int modebits;
  110487. vorbis_look_floor **flr;
  110488. vorbis_look_residue **residue;
  110489. vorbis_look_psy *psy;
  110490. vorbis_look_psy_global *psy_g_look;
  110491. /* local storage, only used on the encoding side. This way the
  110492. application does not need to worry about freeing some packets'
  110493. memory and not others'; packet storage is always tracked.
  110494. Cleared next call to a _dsp_ function */
  110495. unsigned char *header;
  110496. unsigned char *header1;
  110497. unsigned char *header2;
  110498. bitrate_manager_state bms;
  110499. ogg_int64_t sample_count;
  110500. } private_state;
  110501. /* codec_setup_info contains all the setup information specific to the
  110502. specific compression/decompression mode in progress (eg,
  110503. psychoacoustic settings, channel setup, options, codebook
  110504. etc).
  110505. *********************************************************************/
  110506. /*** Start of inlined file: highlevel.h ***/
  110507. typedef struct highlevel_byblocktype {
  110508. double tone_mask_setting;
  110509. double tone_peaklimit_setting;
  110510. double noise_bias_setting;
  110511. double noise_compand_setting;
  110512. } highlevel_byblocktype;
  110513. typedef struct highlevel_encode_setup {
  110514. void *setup;
  110515. int set_in_stone;
  110516. double base_setting;
  110517. double long_setting;
  110518. double short_setting;
  110519. double impulse_noisetune;
  110520. int managed;
  110521. long bitrate_min;
  110522. long bitrate_av;
  110523. double bitrate_av_damp;
  110524. long bitrate_max;
  110525. long bitrate_reservoir;
  110526. double bitrate_reservoir_bias;
  110527. int impulse_block_p;
  110528. int noise_normalize_p;
  110529. double stereo_point_setting;
  110530. double lowpass_kHz;
  110531. double ath_floating_dB;
  110532. double ath_absolute_dB;
  110533. double amplitude_track_dBpersec;
  110534. double trigger_setting;
  110535. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110536. } highlevel_encode_setup;
  110537. /*** End of inlined file: highlevel.h ***/
  110538. typedef struct codec_setup_info {
  110539. /* Vorbis supports only short and long blocks, but allows the
  110540. encoder to choose the sizes */
  110541. long blocksizes[2];
  110542. /* modes are the primary means of supporting on-the-fly different
  110543. blocksizes, different channel mappings (LR or M/A),
  110544. different residue backends, etc. Each mode consists of a
  110545. blocksize flag and a mapping (along with the mapping setup */
  110546. int modes;
  110547. int maps;
  110548. int floors;
  110549. int residues;
  110550. int books;
  110551. int psys; /* encode only */
  110552. vorbis_info_mode *mode_param[64];
  110553. int map_type[64];
  110554. vorbis_info_mapping *map_param[64];
  110555. int floor_type[64];
  110556. vorbis_info_floor *floor_param[64];
  110557. int residue_type[64];
  110558. vorbis_info_residue *residue_param[64];
  110559. static_codebook *book_param[256];
  110560. codebook *fullbooks;
  110561. vorbis_info_psy *psy_param[4]; /* encode only */
  110562. vorbis_info_psy_global psy_g_param;
  110563. bitrate_manager_info bi;
  110564. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110565. highly redundant structure, but
  110566. improves clarity of program flow. */
  110567. int halfrate_flag; /* painless downsample for decode */
  110568. } codec_setup_info;
  110569. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110570. extern void _vp_global_free(vorbis_look_psy_global *look);
  110571. #endif
  110572. /*** End of inlined file: codec_internal.h ***/
  110573. /*** Start of inlined file: registry.h ***/
  110574. #ifndef _V_REG_H_
  110575. #define _V_REG_H_
  110576. #define VI_TRANSFORMB 1
  110577. #define VI_WINDOWB 1
  110578. #define VI_TIMEB 1
  110579. #define VI_FLOORB 2
  110580. #define VI_RESB 3
  110581. #define VI_MAPB 1
  110582. extern vorbis_func_floor *_floor_P[];
  110583. extern vorbis_func_residue *_residue_P[];
  110584. extern vorbis_func_mapping *_mapping_P[];
  110585. #endif
  110586. /*** End of inlined file: registry.h ***/
  110587. /*** Start of inlined file: scales.h ***/
  110588. #ifndef _V_SCALES_H_
  110589. #define _V_SCALES_H_
  110590. #include <math.h>
  110591. /* 20log10(x) */
  110592. #define VORBIS_IEEE_FLOAT32 1
  110593. #ifdef VORBIS_IEEE_FLOAT32
  110594. static float unitnorm(float x){
  110595. union {
  110596. ogg_uint32_t i;
  110597. float f;
  110598. } ix;
  110599. ix.f = x;
  110600. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110601. return ix.f;
  110602. }
  110603. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110604. static float todB(const float *x){
  110605. union {
  110606. ogg_uint32_t i;
  110607. float f;
  110608. } ix;
  110609. ix.f = *x;
  110610. ix.i = ix.i&0x7fffffff;
  110611. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110612. }
  110613. #define todB_nn(x) todB(x)
  110614. #else
  110615. static float unitnorm(float x){
  110616. if(x<0)return(-1.f);
  110617. return(1.f);
  110618. }
  110619. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110620. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110621. #endif
  110622. #define fromdB(x) (exp((x)*.11512925f))
  110623. /* The bark scale equations are approximations, since the original
  110624. table was somewhat hand rolled. The below are chosen to have the
  110625. best possible fit to the rolled tables, thus their somewhat odd
  110626. appearance (these are more accurate and over a longer range than
  110627. the oft-quoted bark equations found in the texts I have). The
  110628. approximations are valid from 0 - 30kHz (nyquist) or so.
  110629. all f in Hz, z in Bark */
  110630. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110631. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110632. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110633. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110634. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110635. 0.0 */
  110636. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110637. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110638. #endif
  110639. /*** End of inlined file: scales.h ***/
  110640. int analysis_noisy=1;
  110641. /* decides between modes, dispatches to the appropriate mapping. */
  110642. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110643. int ret,i;
  110644. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110645. vb->glue_bits=0;
  110646. vb->time_bits=0;
  110647. vb->floor_bits=0;
  110648. vb->res_bits=0;
  110649. /* first things first. Make sure encode is ready */
  110650. for(i=0;i<PACKETBLOBS;i++)
  110651. oggpack_reset(vbi->packetblob[i]);
  110652. /* we only have one mapping type (0), and we let the mapping code
  110653. itself figure out what soft mode to use. This allows easier
  110654. bitrate management */
  110655. if((ret=_mapping_P[0]->forward(vb)))
  110656. return(ret);
  110657. if(op){
  110658. if(vorbis_bitrate_managed(vb))
  110659. /* The app is using a bitmanaged mode... but not using the
  110660. bitrate management interface. */
  110661. return(OV_EINVAL);
  110662. op->packet=oggpack_get_buffer(&vb->opb);
  110663. op->bytes=oggpack_bytes(&vb->opb);
  110664. op->b_o_s=0;
  110665. op->e_o_s=vb->eofflag;
  110666. op->granulepos=vb->granulepos;
  110667. op->packetno=vb->sequence; /* for sake of completeness */
  110668. }
  110669. return(0);
  110670. }
  110671. /* there was no great place to put this.... */
  110672. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110673. int j;
  110674. FILE *of;
  110675. char buffer[80];
  110676. /* if(i==5870){*/
  110677. sprintf(buffer,"%s_%d.m",base,i);
  110678. of=fopen(buffer,"w");
  110679. if(!of)perror("failed to open data dump file");
  110680. for(j=0;j<n;j++){
  110681. if(bark){
  110682. float b=toBARK((4000.f*j/n)+.25);
  110683. fprintf(of,"%f ",b);
  110684. }else
  110685. if(off!=0)
  110686. fprintf(of,"%f ",(double)(j+off)/8000.);
  110687. else
  110688. fprintf(of,"%f ",(double)j);
  110689. if(dB){
  110690. float val;
  110691. if(v[j]==0.)
  110692. val=-140.;
  110693. else
  110694. val=todB(v+j);
  110695. fprintf(of,"%f\n",val);
  110696. }else{
  110697. fprintf(of,"%f\n",v[j]);
  110698. }
  110699. }
  110700. fclose(of);
  110701. /* } */
  110702. }
  110703. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110704. ogg_int64_t off){
  110705. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110706. }
  110707. #endif
  110708. /*** End of inlined file: analysis.c ***/
  110709. /*** Start of inlined file: bitrate.c ***/
  110710. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110711. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110712. // tasks..
  110713. #if JUCE_MSVC
  110714. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110715. #endif
  110716. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110717. #if JUCE_USE_OGGVORBIS
  110718. #include <stdlib.h>
  110719. #include <string.h>
  110720. #include <math.h>
  110721. /* compute bitrate tracking setup */
  110722. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110723. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110724. bitrate_manager_info *bi=&ci->bi;
  110725. memset(bm,0,sizeof(*bm));
  110726. if(bi && (bi->reservoir_bits>0)){
  110727. long ratesamples=vi->rate;
  110728. int halfsamples=ci->blocksizes[0]>>1;
  110729. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110730. bm->managed=1;
  110731. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110732. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110733. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110734. bm->avgfloat=PACKETBLOBS/2;
  110735. /* not a necessary fix, but one that leads to a more balanced
  110736. typical initialization */
  110737. {
  110738. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110739. bm->minmax_reservoir=desired_fill;
  110740. bm->avg_reservoir=desired_fill;
  110741. }
  110742. }
  110743. }
  110744. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110745. memset(bm,0,sizeof(*bm));
  110746. return;
  110747. }
  110748. int vorbis_bitrate_managed(vorbis_block *vb){
  110749. vorbis_dsp_state *vd=vb->vd;
  110750. private_state *b=(private_state*)vd->backend_state;
  110751. bitrate_manager_state *bm=&b->bms;
  110752. if(bm && bm->managed)return(1);
  110753. return(0);
  110754. }
  110755. /* finish taking in the block we just processed */
  110756. int vorbis_bitrate_addblock(vorbis_block *vb){
  110757. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110758. vorbis_dsp_state *vd=vb->vd;
  110759. private_state *b=(private_state*)vd->backend_state;
  110760. bitrate_manager_state *bm=&b->bms;
  110761. vorbis_info *vi=vd->vi;
  110762. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110763. bitrate_manager_info *bi=&ci->bi;
  110764. int choice=rint(bm->avgfloat);
  110765. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110766. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110767. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110768. int samples=ci->blocksizes[vb->W]>>1;
  110769. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110770. if(!bm->managed){
  110771. /* not a bitrate managed stream, but for API simplicity, we'll
  110772. buffer the packet to keep the code path clean */
  110773. if(bm->vb)return(-1); /* one has been submitted without
  110774. being claimed */
  110775. bm->vb=vb;
  110776. return(0);
  110777. }
  110778. bm->vb=vb;
  110779. /* look ahead for avg floater */
  110780. if(bm->avg_bitsper>0){
  110781. double slew=0.;
  110782. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110783. double slewlimit= 15./bi->slew_damp;
  110784. /* choosing a new floater:
  110785. if we're over target, we slew down
  110786. if we're under target, we slew up
  110787. choose slew as follows: look through packetblobs of this frame
  110788. and set slew as the first in the appropriate direction that
  110789. gives us the slew we want. This may mean no slew if delta is
  110790. already favorable.
  110791. Then limit slew to slew max */
  110792. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110793. while(choice>0 && this_bits>avg_target_bits &&
  110794. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110795. choice--;
  110796. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110797. }
  110798. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110799. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110800. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110801. choice++;
  110802. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110803. }
  110804. }
  110805. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110806. if(slew<-slewlimit)slew=-slewlimit;
  110807. if(slew>slewlimit)slew=slewlimit;
  110808. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110809. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110810. }
  110811. /* enforce min(if used) on the current floater (if used) */
  110812. if(bm->min_bitsper>0){
  110813. /* do we need to force the bitrate up? */
  110814. if(this_bits<min_target_bits){
  110815. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110816. choice++;
  110817. if(choice>=PACKETBLOBS)break;
  110818. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110819. }
  110820. }
  110821. }
  110822. /* enforce max (if used) on the current floater (if used) */
  110823. if(bm->max_bitsper>0){
  110824. /* do we need to force the bitrate down? */
  110825. if(this_bits>max_target_bits){
  110826. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110827. choice--;
  110828. if(choice<0)break;
  110829. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110830. }
  110831. }
  110832. }
  110833. /* Choice of packetblobs now made based on floater, and min/max
  110834. requirements. Now boundary check extreme choices */
  110835. if(choice<0){
  110836. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110837. frame will need to be truncated */
  110838. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110839. bm->choice=choice=0;
  110840. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110841. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110842. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110843. }
  110844. }else{
  110845. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110846. if(choice>=PACKETBLOBS)
  110847. choice=PACKETBLOBS-1;
  110848. bm->choice=choice;
  110849. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110850. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110851. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110852. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110853. }
  110854. /* now we have the final packet and the final packet size. Update statistics */
  110855. /* min and max reservoir */
  110856. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110857. if(max_target_bits>0 && this_bits>max_target_bits){
  110858. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110859. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110860. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110861. }else{
  110862. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110863. if(bm->minmax_reservoir>desired_fill){
  110864. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110865. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110866. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110867. }else{
  110868. bm->minmax_reservoir=desired_fill;
  110869. }
  110870. }else{
  110871. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110872. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110873. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110874. }else{
  110875. bm->minmax_reservoir=desired_fill;
  110876. }
  110877. }
  110878. }
  110879. }
  110880. /* avg reservoir */
  110881. if(bm->avg_bitsper>0){
  110882. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110883. bm->avg_reservoir+=this_bits-avg_target_bits;
  110884. }
  110885. return(0);
  110886. }
  110887. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110888. private_state *b=(private_state*)vd->backend_state;
  110889. bitrate_manager_state *bm=&b->bms;
  110890. vorbis_block *vb=bm->vb;
  110891. int choice=PACKETBLOBS/2;
  110892. if(!vb)return 0;
  110893. if(op){
  110894. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110895. if(vorbis_bitrate_managed(vb))
  110896. choice=bm->choice;
  110897. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110898. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110899. op->b_o_s=0;
  110900. op->e_o_s=vb->eofflag;
  110901. op->granulepos=vb->granulepos;
  110902. op->packetno=vb->sequence; /* for sake of completeness */
  110903. }
  110904. bm->vb=0;
  110905. return(1);
  110906. }
  110907. #endif
  110908. /*** End of inlined file: bitrate.c ***/
  110909. /*** Start of inlined file: block.c ***/
  110910. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110911. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110912. // tasks..
  110913. #if JUCE_MSVC
  110914. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110915. #endif
  110916. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110917. #if JUCE_USE_OGGVORBIS
  110918. #include <stdio.h>
  110919. #include <stdlib.h>
  110920. #include <string.h>
  110921. /*** Start of inlined file: window.h ***/
  110922. #ifndef _V_WINDOW_
  110923. #define _V_WINDOW_
  110924. extern float *_vorbis_window_get(int n);
  110925. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110926. int lW,int W,int nW);
  110927. #endif
  110928. /*** End of inlined file: window.h ***/
  110929. /*** Start of inlined file: lpc.h ***/
  110930. #ifndef _V_LPC_H_
  110931. #define _V_LPC_H_
  110932. /* simple linear scale LPC code */
  110933. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110934. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110935. float *data,long n);
  110936. #endif
  110937. /*** End of inlined file: lpc.h ***/
  110938. /* pcm accumulator examples (not exhaustive):
  110939. <-------------- lW ---------------->
  110940. <--------------- W ---------------->
  110941. : .....|..... _______________ |
  110942. : .''' | '''_--- | |\ |
  110943. :.....''' |_____--- '''......| | \_______|
  110944. :.................|__________________|_______|__|______|
  110945. |<------ Sl ------>| > Sr < |endW
  110946. |beginSl |endSl | |endSr
  110947. |beginW |endlW |beginSr
  110948. |< lW >|
  110949. <--------------- W ---------------->
  110950. | | .. ______________ |
  110951. | | ' `/ | ---_ |
  110952. |___.'___/`. | ---_____|
  110953. |_______|__|_______|_________________|
  110954. | >|Sl|< |<------ Sr ----->|endW
  110955. | | |endSl |beginSr |endSr
  110956. |beginW | |endlW
  110957. mult[0] |beginSl mult[n]
  110958. <-------------- lW ----------------->
  110959. |<--W-->|
  110960. : .............. ___ | |
  110961. : .''' |`/ \ | |
  110962. :.....''' |/`....\|...|
  110963. :.........................|___|___|___|
  110964. |Sl |Sr |endW
  110965. | | |endSr
  110966. | |beginSr
  110967. | |endSl
  110968. |beginSl
  110969. |beginW
  110970. */
  110971. /* block abstraction setup *********************************************/
  110972. #ifndef WORD_ALIGN
  110973. #define WORD_ALIGN 8
  110974. #endif
  110975. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110976. int i;
  110977. memset(vb,0,sizeof(*vb));
  110978. vb->vd=v;
  110979. vb->localalloc=0;
  110980. vb->localstore=NULL;
  110981. if(v->analysisp){
  110982. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110983. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110984. vbi->ampmax=-9999;
  110985. for(i=0;i<PACKETBLOBS;i++){
  110986. if(i==PACKETBLOBS/2){
  110987. vbi->packetblob[i]=&vb->opb;
  110988. }else{
  110989. vbi->packetblob[i]=
  110990. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110991. }
  110992. oggpack_writeinit(vbi->packetblob[i]);
  110993. }
  110994. }
  110995. return(0);
  110996. }
  110997. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110998. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110999. if(bytes+vb->localtop>vb->localalloc){
  111000. /* can't just _ogg_realloc... there are outstanding pointers */
  111001. if(vb->localstore){
  111002. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111003. vb->totaluse+=vb->localtop;
  111004. link->next=vb->reap;
  111005. link->ptr=vb->localstore;
  111006. vb->reap=link;
  111007. }
  111008. /* highly conservative */
  111009. vb->localalloc=bytes;
  111010. vb->localstore=_ogg_malloc(vb->localalloc);
  111011. vb->localtop=0;
  111012. }
  111013. {
  111014. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111015. vb->localtop+=bytes;
  111016. return ret;
  111017. }
  111018. }
  111019. /* reap the chain, pull the ripcord */
  111020. void _vorbis_block_ripcord(vorbis_block *vb){
  111021. /* reap the chain */
  111022. struct alloc_chain *reap=vb->reap;
  111023. while(reap){
  111024. struct alloc_chain *next=reap->next;
  111025. _ogg_free(reap->ptr);
  111026. memset(reap,0,sizeof(*reap));
  111027. _ogg_free(reap);
  111028. reap=next;
  111029. }
  111030. /* consolidate storage */
  111031. if(vb->totaluse){
  111032. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111033. vb->localalloc+=vb->totaluse;
  111034. vb->totaluse=0;
  111035. }
  111036. /* pull the ripcord */
  111037. vb->localtop=0;
  111038. vb->reap=NULL;
  111039. }
  111040. int vorbis_block_clear(vorbis_block *vb){
  111041. int i;
  111042. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111043. _vorbis_block_ripcord(vb);
  111044. if(vb->localstore)_ogg_free(vb->localstore);
  111045. if(vbi){
  111046. for(i=0;i<PACKETBLOBS;i++){
  111047. oggpack_writeclear(vbi->packetblob[i]);
  111048. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111049. }
  111050. _ogg_free(vbi);
  111051. }
  111052. memset(vb,0,sizeof(*vb));
  111053. return(0);
  111054. }
  111055. /* Analysis side code, but directly related to blocking. Thus it's
  111056. here and not in analysis.c (which is for analysis transforms only).
  111057. The init is here because some of it is shared */
  111058. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111059. int i;
  111060. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111061. private_state *b=NULL;
  111062. int hs;
  111063. if(ci==NULL) return 1;
  111064. hs=ci->halfrate_flag;
  111065. memset(v,0,sizeof(*v));
  111066. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111067. v->vi=vi;
  111068. b->modebits=ilog2(ci->modes);
  111069. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111070. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111071. /* MDCT is tranform 0 */
  111072. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111073. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111074. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111075. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111076. /* Vorbis I uses only window type 0 */
  111077. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111078. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111079. if(encp){ /* encode/decode differ here */
  111080. /* analysis always needs an fft */
  111081. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111082. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111083. /* finish the codebooks */
  111084. if(!ci->fullbooks){
  111085. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111086. for(i=0;i<ci->books;i++)
  111087. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111088. }
  111089. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111090. for(i=0;i<ci->psys;i++){
  111091. _vp_psy_init(b->psy+i,
  111092. ci->psy_param[i],
  111093. &ci->psy_g_param,
  111094. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111095. vi->rate);
  111096. }
  111097. v->analysisp=1;
  111098. }else{
  111099. /* finish the codebooks */
  111100. if(!ci->fullbooks){
  111101. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111102. for(i=0;i<ci->books;i++){
  111103. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111104. /* decode codebooks are now standalone after init */
  111105. vorbis_staticbook_destroy(ci->book_param[i]);
  111106. ci->book_param[i]=NULL;
  111107. }
  111108. }
  111109. }
  111110. /* initialize the storage vectors. blocksize[1] is small for encode,
  111111. but the correct size for decode */
  111112. v->pcm_storage=ci->blocksizes[1];
  111113. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111114. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111115. {
  111116. int i;
  111117. for(i=0;i<vi->channels;i++)
  111118. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111119. }
  111120. /* all 1 (large block) or 0 (small block) */
  111121. /* explicitly set for the sake of clarity */
  111122. v->lW=0; /* previous window size */
  111123. v->W=0; /* current window size */
  111124. /* all vector indexes */
  111125. v->centerW=ci->blocksizes[1]/2;
  111126. v->pcm_current=v->centerW;
  111127. /* initialize all the backend lookups */
  111128. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111129. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111130. for(i=0;i<ci->floors;i++)
  111131. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111132. look(v,ci->floor_param[i]);
  111133. for(i=0;i<ci->residues;i++)
  111134. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111135. look(v,ci->residue_param[i]);
  111136. return 0;
  111137. }
  111138. /* arbitrary settings and spec-mandated numbers get filled in here */
  111139. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111140. private_state *b=NULL;
  111141. if(_vds_shared_init(v,vi,1))return 1;
  111142. b=(private_state*)v->backend_state;
  111143. b->psy_g_look=_vp_global_look(vi);
  111144. /* Initialize the envelope state storage */
  111145. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111146. _ve_envelope_init(b->ve,vi);
  111147. vorbis_bitrate_init(vi,&b->bms);
  111148. /* compressed audio packets start after the headers
  111149. with sequence number 3 */
  111150. v->sequence=3;
  111151. return(0);
  111152. }
  111153. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111154. int i;
  111155. if(v){
  111156. vorbis_info *vi=v->vi;
  111157. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111158. private_state *b=(private_state*)v->backend_state;
  111159. if(b){
  111160. if(b->ve){
  111161. _ve_envelope_clear(b->ve);
  111162. _ogg_free(b->ve);
  111163. }
  111164. if(b->transform[0]){
  111165. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111166. _ogg_free(b->transform[0][0]);
  111167. _ogg_free(b->transform[0]);
  111168. }
  111169. if(b->transform[1]){
  111170. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111171. _ogg_free(b->transform[1][0]);
  111172. _ogg_free(b->transform[1]);
  111173. }
  111174. if(b->flr){
  111175. for(i=0;i<ci->floors;i++)
  111176. _floor_P[ci->floor_type[i]]->
  111177. free_look(b->flr[i]);
  111178. _ogg_free(b->flr);
  111179. }
  111180. if(b->residue){
  111181. for(i=0;i<ci->residues;i++)
  111182. _residue_P[ci->residue_type[i]]->
  111183. free_look(b->residue[i]);
  111184. _ogg_free(b->residue);
  111185. }
  111186. if(b->psy){
  111187. for(i=0;i<ci->psys;i++)
  111188. _vp_psy_clear(b->psy+i);
  111189. _ogg_free(b->psy);
  111190. }
  111191. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111192. vorbis_bitrate_clear(&b->bms);
  111193. drft_clear(&b->fft_look[0]);
  111194. drft_clear(&b->fft_look[1]);
  111195. }
  111196. if(v->pcm){
  111197. for(i=0;i<vi->channels;i++)
  111198. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111199. _ogg_free(v->pcm);
  111200. if(v->pcmret)_ogg_free(v->pcmret);
  111201. }
  111202. if(b){
  111203. /* free header, header1, header2 */
  111204. if(b->header)_ogg_free(b->header);
  111205. if(b->header1)_ogg_free(b->header1);
  111206. if(b->header2)_ogg_free(b->header2);
  111207. _ogg_free(b);
  111208. }
  111209. memset(v,0,sizeof(*v));
  111210. }
  111211. }
  111212. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111213. int i;
  111214. vorbis_info *vi=v->vi;
  111215. private_state *b=(private_state*)v->backend_state;
  111216. /* free header, header1, header2 */
  111217. if(b->header)_ogg_free(b->header);b->header=NULL;
  111218. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111219. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111220. /* Do we have enough storage space for the requested buffer? If not,
  111221. expand the PCM (and envelope) storage */
  111222. if(v->pcm_current+vals>=v->pcm_storage){
  111223. v->pcm_storage=v->pcm_current+vals*2;
  111224. for(i=0;i<vi->channels;i++){
  111225. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111226. }
  111227. }
  111228. for(i=0;i<vi->channels;i++)
  111229. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111230. return(v->pcmret);
  111231. }
  111232. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111233. int i;
  111234. int order=32;
  111235. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111236. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111237. long j;
  111238. v->preextrapolate=1;
  111239. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111240. for(i=0;i<v->vi->channels;i++){
  111241. /* need to run the extrapolation in reverse! */
  111242. for(j=0;j<v->pcm_current;j++)
  111243. work[j]=v->pcm[i][v->pcm_current-j-1];
  111244. /* prime as above */
  111245. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111246. /* run the predictor filter */
  111247. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111248. order,
  111249. work+v->pcm_current-v->centerW,
  111250. v->centerW);
  111251. for(j=0;j<v->pcm_current;j++)
  111252. v->pcm[i][v->pcm_current-j-1]=work[j];
  111253. }
  111254. }
  111255. }
  111256. /* call with val<=0 to set eof */
  111257. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111258. vorbis_info *vi=v->vi;
  111259. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111260. if(vals<=0){
  111261. int order=32;
  111262. int i;
  111263. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111264. /* if it wasn't done earlier (very short sample) */
  111265. if(!v->preextrapolate)
  111266. _preextrapolate_helper(v);
  111267. /* We're encoding the end of the stream. Just make sure we have
  111268. [at least] a few full blocks of zeroes at the end. */
  111269. /* actually, we don't want zeroes; that could drop a large
  111270. amplitude off a cliff, creating spread spectrum noise that will
  111271. suck to encode. Extrapolate for the sake of cleanliness. */
  111272. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111273. v->eofflag=v->pcm_current;
  111274. v->pcm_current+=ci->blocksizes[1]*3;
  111275. for(i=0;i<vi->channels;i++){
  111276. if(v->eofflag>order*2){
  111277. /* extrapolate with LPC to fill in */
  111278. long n;
  111279. /* make a predictor filter */
  111280. n=v->eofflag;
  111281. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111282. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111283. /* run the predictor filter */
  111284. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111285. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111286. }else{
  111287. /* not enough data to extrapolate (unlikely to happen due to
  111288. guarding the overlap, but bulletproof in case that
  111289. assumtion goes away). zeroes will do. */
  111290. memset(v->pcm[i]+v->eofflag,0,
  111291. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111292. }
  111293. }
  111294. }else{
  111295. if(v->pcm_current+vals>v->pcm_storage)
  111296. return(OV_EINVAL);
  111297. v->pcm_current+=vals;
  111298. /* we may want to reverse extrapolate the beginning of a stream
  111299. too... in case we're beginning on a cliff! */
  111300. /* clumsy, but simple. It only runs once, so simple is good. */
  111301. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111302. _preextrapolate_helper(v);
  111303. }
  111304. return(0);
  111305. }
  111306. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111307. the next block on which to continue analysis */
  111308. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111309. int i;
  111310. vorbis_info *vi=v->vi;
  111311. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111312. private_state *b=(private_state*)v->backend_state;
  111313. vorbis_look_psy_global *g=b->psy_g_look;
  111314. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111315. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111316. /* check to see if we're started... */
  111317. if(!v->preextrapolate)return(0);
  111318. /* check to see if we're done... */
  111319. if(v->eofflag==-1)return(0);
  111320. /* By our invariant, we have lW, W and centerW set. Search for
  111321. the next boundary so we can determine nW (the next window size)
  111322. which lets us compute the shape of the current block's window */
  111323. /* we do an envelope search even on a single blocksize; we may still
  111324. be throwing more bits at impulses, and envelope search handles
  111325. marking impulses too. */
  111326. {
  111327. long bp=_ve_envelope_search(v);
  111328. if(bp==-1){
  111329. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111330. full long block */
  111331. v->nW=0;
  111332. }else{
  111333. if(ci->blocksizes[0]==ci->blocksizes[1])
  111334. v->nW=0;
  111335. else
  111336. v->nW=bp;
  111337. }
  111338. }
  111339. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111340. {
  111341. /* center of next block + next block maximum right side. */
  111342. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111343. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111344. although this check is
  111345. less strict that the
  111346. _ve_envelope_search,
  111347. the search is not run
  111348. if we only use one
  111349. block size */
  111350. }
  111351. /* fill in the block. Note that for a short window, lW and nW are *short*
  111352. regardless of actual settings in the stream */
  111353. _vorbis_block_ripcord(vb);
  111354. vb->lW=v->lW;
  111355. vb->W=v->W;
  111356. vb->nW=v->nW;
  111357. if(v->W){
  111358. if(!v->lW || !v->nW){
  111359. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111360. /*fprintf(stderr,"-");*/
  111361. }else{
  111362. vbi->blocktype=BLOCKTYPE_LONG;
  111363. /*fprintf(stderr,"_");*/
  111364. }
  111365. }else{
  111366. if(_ve_envelope_mark(v)){
  111367. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111368. /*fprintf(stderr,"|");*/
  111369. }else{
  111370. vbi->blocktype=BLOCKTYPE_PADDING;
  111371. /*fprintf(stderr,".");*/
  111372. }
  111373. }
  111374. vb->vd=v;
  111375. vb->sequence=v->sequence++;
  111376. vb->granulepos=v->granulepos;
  111377. vb->pcmend=ci->blocksizes[v->W];
  111378. /* copy the vectors; this uses the local storage in vb */
  111379. /* this tracks 'strongest peak' for later psychoacoustics */
  111380. /* moved to the global psy state; clean this mess up */
  111381. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111382. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111383. vbi->ampmax=g->ampmax;
  111384. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111385. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111386. for(i=0;i<vi->channels;i++){
  111387. vbi->pcmdelay[i]=
  111388. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111389. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111390. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111391. /* before we added the delay
  111392. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111393. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111394. */
  111395. }
  111396. /* handle eof detection: eof==0 means that we've not yet received EOF
  111397. eof>0 marks the last 'real' sample in pcm[]
  111398. eof<0 'no more to do'; doesn't get here */
  111399. if(v->eofflag){
  111400. if(v->centerW>=v->eofflag){
  111401. v->eofflag=-1;
  111402. vb->eofflag=1;
  111403. return(1);
  111404. }
  111405. }
  111406. /* advance storage vectors and clean up */
  111407. {
  111408. int new_centerNext=ci->blocksizes[1]/2;
  111409. int movementW=centerNext-new_centerNext;
  111410. if(movementW>0){
  111411. _ve_envelope_shift(b->ve,movementW);
  111412. v->pcm_current-=movementW;
  111413. for(i=0;i<vi->channels;i++)
  111414. memmove(v->pcm[i],v->pcm[i]+movementW,
  111415. v->pcm_current*sizeof(*v->pcm[i]));
  111416. v->lW=v->W;
  111417. v->W=v->nW;
  111418. v->centerW=new_centerNext;
  111419. if(v->eofflag){
  111420. v->eofflag-=movementW;
  111421. if(v->eofflag<=0)v->eofflag=-1;
  111422. /* do not add padding to end of stream! */
  111423. if(v->centerW>=v->eofflag){
  111424. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111425. }else{
  111426. v->granulepos+=movementW;
  111427. }
  111428. }else{
  111429. v->granulepos+=movementW;
  111430. }
  111431. }
  111432. }
  111433. /* done */
  111434. return(1);
  111435. }
  111436. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111437. vorbis_info *vi=v->vi;
  111438. codec_setup_info *ci;
  111439. int hs;
  111440. if(!v->backend_state)return -1;
  111441. if(!vi)return -1;
  111442. ci=(codec_setup_info*) vi->codec_setup;
  111443. if(!ci)return -1;
  111444. hs=ci->halfrate_flag;
  111445. v->centerW=ci->blocksizes[1]>>(hs+1);
  111446. v->pcm_current=v->centerW>>hs;
  111447. v->pcm_returned=-1;
  111448. v->granulepos=-1;
  111449. v->sequence=-1;
  111450. v->eofflag=0;
  111451. ((private_state *)(v->backend_state))->sample_count=-1;
  111452. return(0);
  111453. }
  111454. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111455. if(_vds_shared_init(v,vi,0)) return 1;
  111456. vorbis_synthesis_restart(v);
  111457. return 0;
  111458. }
  111459. /* Unlike in analysis, the window is only partially applied for each
  111460. block. The time domain envelope is not yet handled at the point of
  111461. calling (as it relies on the previous block). */
  111462. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111463. vorbis_info *vi=v->vi;
  111464. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111465. private_state *b=(private_state*)v->backend_state;
  111466. int hs=ci->halfrate_flag;
  111467. int i,j;
  111468. if(!vb)return(OV_EINVAL);
  111469. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111470. v->lW=v->W;
  111471. v->W=vb->W;
  111472. v->nW=-1;
  111473. if((v->sequence==-1)||
  111474. (v->sequence+1 != vb->sequence)){
  111475. v->granulepos=-1; /* out of sequence; lose count */
  111476. b->sample_count=-1;
  111477. }
  111478. v->sequence=vb->sequence;
  111479. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111480. was called on block */
  111481. int n=ci->blocksizes[v->W]>>(hs+1);
  111482. int n0=ci->blocksizes[0]>>(hs+1);
  111483. int n1=ci->blocksizes[1]>>(hs+1);
  111484. int thisCenter;
  111485. int prevCenter;
  111486. v->glue_bits+=vb->glue_bits;
  111487. v->time_bits+=vb->time_bits;
  111488. v->floor_bits+=vb->floor_bits;
  111489. v->res_bits+=vb->res_bits;
  111490. if(v->centerW){
  111491. thisCenter=n1;
  111492. prevCenter=0;
  111493. }else{
  111494. thisCenter=0;
  111495. prevCenter=n1;
  111496. }
  111497. /* v->pcm is now used like a two-stage double buffer. We don't want
  111498. to have to constantly shift *or* adjust memory usage. Don't
  111499. accept a new block until the old is shifted out */
  111500. for(j=0;j<vi->channels;j++){
  111501. /* the overlap/add section */
  111502. if(v->lW){
  111503. if(v->W){
  111504. /* large/large */
  111505. float *w=_vorbis_window_get(b->window[1]-hs);
  111506. float *pcm=v->pcm[j]+prevCenter;
  111507. float *p=vb->pcm[j];
  111508. for(i=0;i<n1;i++)
  111509. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111510. }else{
  111511. /* large/small */
  111512. float *w=_vorbis_window_get(b->window[0]-hs);
  111513. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111514. float *p=vb->pcm[j];
  111515. for(i=0;i<n0;i++)
  111516. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111517. }
  111518. }else{
  111519. if(v->W){
  111520. /* small/large */
  111521. float *w=_vorbis_window_get(b->window[0]-hs);
  111522. float *pcm=v->pcm[j]+prevCenter;
  111523. float *p=vb->pcm[j]+n1/2-n0/2;
  111524. for(i=0;i<n0;i++)
  111525. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111526. for(;i<n1/2+n0/2;i++)
  111527. pcm[i]=p[i];
  111528. }else{
  111529. /* small/small */
  111530. float *w=_vorbis_window_get(b->window[0]-hs);
  111531. float *pcm=v->pcm[j]+prevCenter;
  111532. float *p=vb->pcm[j];
  111533. for(i=0;i<n0;i++)
  111534. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111535. }
  111536. }
  111537. /* the copy section */
  111538. {
  111539. float *pcm=v->pcm[j]+thisCenter;
  111540. float *p=vb->pcm[j]+n;
  111541. for(i=0;i<n;i++)
  111542. pcm[i]=p[i];
  111543. }
  111544. }
  111545. if(v->centerW)
  111546. v->centerW=0;
  111547. else
  111548. v->centerW=n1;
  111549. /* deal with initial packet state; we do this using the explicit
  111550. pcm_returned==-1 flag otherwise we're sensitive to first block
  111551. being short or long */
  111552. if(v->pcm_returned==-1){
  111553. v->pcm_returned=thisCenter;
  111554. v->pcm_current=thisCenter;
  111555. }else{
  111556. v->pcm_returned=prevCenter;
  111557. v->pcm_current=prevCenter+
  111558. ((ci->blocksizes[v->lW]/4+
  111559. ci->blocksizes[v->W]/4)>>hs);
  111560. }
  111561. }
  111562. /* track the frame number... This is for convenience, but also
  111563. making sure our last packet doesn't end with added padding. If
  111564. the last packet is partial, the number of samples we'll have to
  111565. return will be past the vb->granulepos.
  111566. This is not foolproof! It will be confused if we begin
  111567. decoding at the last page after a seek or hole. In that case,
  111568. we don't have a starting point to judge where the last frame
  111569. is. For this reason, vorbisfile will always try to make sure
  111570. it reads the last two marked pages in proper sequence */
  111571. if(b->sample_count==-1){
  111572. b->sample_count=0;
  111573. }else{
  111574. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111575. }
  111576. if(v->granulepos==-1){
  111577. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111578. v->granulepos=vb->granulepos;
  111579. /* is this a short page? */
  111580. if(b->sample_count>v->granulepos){
  111581. /* corner case; if this is both the first and last audio page,
  111582. then spec says the end is cut, not beginning */
  111583. if(vb->eofflag){
  111584. /* trim the end */
  111585. /* no preceeding granulepos; assume we started at zero (we'd
  111586. have to in a short single-page stream) */
  111587. /* granulepos could be -1 due to a seek, but that would result
  111588. in a long count, not short count */
  111589. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111590. }else{
  111591. /* trim the beginning */
  111592. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111593. if(v->pcm_returned>v->pcm_current)
  111594. v->pcm_returned=v->pcm_current;
  111595. }
  111596. }
  111597. }
  111598. }else{
  111599. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111600. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111601. if(v->granulepos>vb->granulepos){
  111602. long extra=v->granulepos-vb->granulepos;
  111603. if(extra)
  111604. if(vb->eofflag){
  111605. /* partial last frame. Strip the extra samples off */
  111606. v->pcm_current-=extra>>hs;
  111607. } /* else {Shouldn't happen *unless* the bitstream is out of
  111608. spec. Either way, believe the bitstream } */
  111609. } /* else {Shouldn't happen *unless* the bitstream is out of
  111610. spec. Either way, believe the bitstream } */
  111611. v->granulepos=vb->granulepos;
  111612. }
  111613. }
  111614. /* Update, cleanup */
  111615. if(vb->eofflag)v->eofflag=1;
  111616. return(0);
  111617. }
  111618. /* pcm==NULL indicates we just want the pending samples, no more */
  111619. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111620. vorbis_info *vi=v->vi;
  111621. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111622. if(pcm){
  111623. int i;
  111624. for(i=0;i<vi->channels;i++)
  111625. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111626. *pcm=v->pcmret;
  111627. }
  111628. return(v->pcm_current-v->pcm_returned);
  111629. }
  111630. return(0);
  111631. }
  111632. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111633. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111634. v->pcm_returned+=n;
  111635. return(0);
  111636. }
  111637. /* intended for use with a specific vorbisfile feature; we want access
  111638. to the [usually synthetic/postextrapolated] buffer and lapping at
  111639. the end of a decode cycle, specifically, a half-short-block worth.
  111640. This funtion works like pcmout above, except it will also expose
  111641. this implicit buffer data not normally decoded. */
  111642. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111643. vorbis_info *vi=v->vi;
  111644. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111645. int hs=ci->halfrate_flag;
  111646. int n=ci->blocksizes[v->W]>>(hs+1);
  111647. int n0=ci->blocksizes[0]>>(hs+1);
  111648. int n1=ci->blocksizes[1]>>(hs+1);
  111649. int i,j;
  111650. if(v->pcm_returned<0)return 0;
  111651. /* our returned data ends at pcm_returned; because the synthesis pcm
  111652. buffer is a two-fragment ring, that means our data block may be
  111653. fragmented by buffering, wrapping or a short block not filling
  111654. out a buffer. To simplify things, we unfragment if it's at all
  111655. possibly needed. Otherwise, we'd need to call lapout more than
  111656. once as well as hold additional dsp state. Opt for
  111657. simplicity. */
  111658. /* centerW was advanced by blockin; it would be the center of the
  111659. *next* block */
  111660. if(v->centerW==n1){
  111661. /* the data buffer wraps; swap the halves */
  111662. /* slow, sure, small */
  111663. for(j=0;j<vi->channels;j++){
  111664. float *p=v->pcm[j];
  111665. for(i=0;i<n1;i++){
  111666. float temp=p[i];
  111667. p[i]=p[i+n1];
  111668. p[i+n1]=temp;
  111669. }
  111670. }
  111671. v->pcm_current-=n1;
  111672. v->pcm_returned-=n1;
  111673. v->centerW=0;
  111674. }
  111675. /* solidify buffer into contiguous space */
  111676. if((v->lW^v->W)==1){
  111677. /* long/short or short/long */
  111678. for(j=0;j<vi->channels;j++){
  111679. float *s=v->pcm[j];
  111680. float *d=v->pcm[j]+(n1-n0)/2;
  111681. for(i=(n1+n0)/2-1;i>=0;--i)
  111682. d[i]=s[i];
  111683. }
  111684. v->pcm_returned+=(n1-n0)/2;
  111685. v->pcm_current+=(n1-n0)/2;
  111686. }else{
  111687. if(v->lW==0){
  111688. /* short/short */
  111689. for(j=0;j<vi->channels;j++){
  111690. float *s=v->pcm[j];
  111691. float *d=v->pcm[j]+n1-n0;
  111692. for(i=n0-1;i>=0;--i)
  111693. d[i]=s[i];
  111694. }
  111695. v->pcm_returned+=n1-n0;
  111696. v->pcm_current+=n1-n0;
  111697. }
  111698. }
  111699. if(pcm){
  111700. int i;
  111701. for(i=0;i<vi->channels;i++)
  111702. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111703. *pcm=v->pcmret;
  111704. }
  111705. return(n1+n-v->pcm_returned);
  111706. }
  111707. float *vorbis_window(vorbis_dsp_state *v,int W){
  111708. vorbis_info *vi=v->vi;
  111709. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111710. int hs=ci->halfrate_flag;
  111711. private_state *b=(private_state*)v->backend_state;
  111712. if(b->window[W]-1<0)return NULL;
  111713. return _vorbis_window_get(b->window[W]-hs);
  111714. }
  111715. #endif
  111716. /*** End of inlined file: block.c ***/
  111717. /*** Start of inlined file: codebook.c ***/
  111718. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111719. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111720. // tasks..
  111721. #if JUCE_MSVC
  111722. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111723. #endif
  111724. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111725. #if JUCE_USE_OGGVORBIS
  111726. #include <stdlib.h>
  111727. #include <string.h>
  111728. #include <math.h>
  111729. /* packs the given codebook into the bitstream **************************/
  111730. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111731. long i,j;
  111732. int ordered=0;
  111733. /* first the basic parameters */
  111734. oggpack_write(opb,0x564342,24);
  111735. oggpack_write(opb,c->dim,16);
  111736. oggpack_write(opb,c->entries,24);
  111737. /* pack the codewords. There are two packings; length ordered and
  111738. length random. Decide between the two now. */
  111739. for(i=1;i<c->entries;i++)
  111740. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111741. if(i==c->entries)ordered=1;
  111742. if(ordered){
  111743. /* length ordered. We only need to say how many codewords of
  111744. each length. The actual codewords are generated
  111745. deterministically */
  111746. long count=0;
  111747. oggpack_write(opb,1,1); /* ordered */
  111748. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111749. for(i=1;i<c->entries;i++){
  111750. long thisx=c->lengthlist[i];
  111751. long last=c->lengthlist[i-1];
  111752. if(thisx>last){
  111753. for(j=last;j<thisx;j++){
  111754. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111755. count=i;
  111756. }
  111757. }
  111758. }
  111759. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111760. }else{
  111761. /* length random. Again, we don't code the codeword itself, just
  111762. the length. This time, though, we have to encode each length */
  111763. oggpack_write(opb,0,1); /* unordered */
  111764. /* algortihmic mapping has use for 'unused entries', which we tag
  111765. here. The algorithmic mapping happens as usual, but the unused
  111766. entry has no codeword. */
  111767. for(i=0;i<c->entries;i++)
  111768. if(c->lengthlist[i]==0)break;
  111769. if(i==c->entries){
  111770. oggpack_write(opb,0,1); /* no unused entries */
  111771. for(i=0;i<c->entries;i++)
  111772. oggpack_write(opb,c->lengthlist[i]-1,5);
  111773. }else{
  111774. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111775. for(i=0;i<c->entries;i++){
  111776. if(c->lengthlist[i]==0){
  111777. oggpack_write(opb,0,1);
  111778. }else{
  111779. oggpack_write(opb,1,1);
  111780. oggpack_write(opb,c->lengthlist[i]-1,5);
  111781. }
  111782. }
  111783. }
  111784. }
  111785. /* is the entry number the desired return value, or do we have a
  111786. mapping? If we have a mapping, what type? */
  111787. oggpack_write(opb,c->maptype,4);
  111788. switch(c->maptype){
  111789. case 0:
  111790. /* no mapping */
  111791. break;
  111792. case 1:case 2:
  111793. /* implicitly populated value mapping */
  111794. /* explicitly populated value mapping */
  111795. if(!c->quantlist){
  111796. /* no quantlist? error */
  111797. return(-1);
  111798. }
  111799. /* values that define the dequantization */
  111800. oggpack_write(opb,c->q_min,32);
  111801. oggpack_write(opb,c->q_delta,32);
  111802. oggpack_write(opb,c->q_quant-1,4);
  111803. oggpack_write(opb,c->q_sequencep,1);
  111804. {
  111805. int quantvals;
  111806. switch(c->maptype){
  111807. case 1:
  111808. /* a single column of (c->entries/c->dim) quantized values for
  111809. building a full value list algorithmically (square lattice) */
  111810. quantvals=_book_maptype1_quantvals(c);
  111811. break;
  111812. case 2:
  111813. /* every value (c->entries*c->dim total) specified explicitly */
  111814. quantvals=c->entries*c->dim;
  111815. break;
  111816. default: /* NOT_REACHABLE */
  111817. quantvals=-1;
  111818. }
  111819. /* quantized values */
  111820. for(i=0;i<quantvals;i++)
  111821. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111822. }
  111823. break;
  111824. default:
  111825. /* error case; we don't have any other map types now */
  111826. return(-1);
  111827. }
  111828. return(0);
  111829. }
  111830. /* unpacks a codebook from the packet buffer into the codebook struct,
  111831. readies the codebook auxiliary structures for decode *************/
  111832. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111833. long i,j;
  111834. memset(s,0,sizeof(*s));
  111835. s->allocedp=1;
  111836. /* make sure alignment is correct */
  111837. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111838. /* first the basic parameters */
  111839. s->dim=oggpack_read(opb,16);
  111840. s->entries=oggpack_read(opb,24);
  111841. if(s->entries==-1)goto _eofout;
  111842. /* codeword ordering.... length ordered or unordered? */
  111843. switch((int)oggpack_read(opb,1)){
  111844. case 0:
  111845. /* unordered */
  111846. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111847. /* allocated but unused entries? */
  111848. if(oggpack_read(opb,1)){
  111849. /* yes, unused entries */
  111850. for(i=0;i<s->entries;i++){
  111851. if(oggpack_read(opb,1)){
  111852. long num=oggpack_read(opb,5);
  111853. if(num==-1)goto _eofout;
  111854. s->lengthlist[i]=num+1;
  111855. }else
  111856. s->lengthlist[i]=0;
  111857. }
  111858. }else{
  111859. /* all entries used; no tagging */
  111860. for(i=0;i<s->entries;i++){
  111861. long num=oggpack_read(opb,5);
  111862. if(num==-1)goto _eofout;
  111863. s->lengthlist[i]=num+1;
  111864. }
  111865. }
  111866. break;
  111867. case 1:
  111868. /* ordered */
  111869. {
  111870. long length=oggpack_read(opb,5)+1;
  111871. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111872. for(i=0;i<s->entries;){
  111873. long num=oggpack_read(opb,_ilog(s->entries-i));
  111874. if(num==-1)goto _eofout;
  111875. for(j=0;j<num && i<s->entries;j++,i++)
  111876. s->lengthlist[i]=length;
  111877. length++;
  111878. }
  111879. }
  111880. break;
  111881. default:
  111882. /* EOF */
  111883. return(-1);
  111884. }
  111885. /* Do we have a mapping to unpack? */
  111886. switch((s->maptype=oggpack_read(opb,4))){
  111887. case 0:
  111888. /* no mapping */
  111889. break;
  111890. case 1: case 2:
  111891. /* implicitly populated value mapping */
  111892. /* explicitly populated value mapping */
  111893. s->q_min=oggpack_read(opb,32);
  111894. s->q_delta=oggpack_read(opb,32);
  111895. s->q_quant=oggpack_read(opb,4)+1;
  111896. s->q_sequencep=oggpack_read(opb,1);
  111897. {
  111898. int quantvals=0;
  111899. switch(s->maptype){
  111900. case 1:
  111901. quantvals=_book_maptype1_quantvals(s);
  111902. break;
  111903. case 2:
  111904. quantvals=s->entries*s->dim;
  111905. break;
  111906. }
  111907. /* quantized values */
  111908. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111909. for(i=0;i<quantvals;i++)
  111910. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111911. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111912. }
  111913. break;
  111914. default:
  111915. goto _errout;
  111916. }
  111917. /* all set */
  111918. return(0);
  111919. _errout:
  111920. _eofout:
  111921. vorbis_staticbook_clear(s);
  111922. return(-1);
  111923. }
  111924. /* returns the number of bits ************************************************/
  111925. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111926. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111927. return(book->c->lengthlist[a]);
  111928. }
  111929. /* One the encode side, our vector writers are each designed for a
  111930. specific purpose, and the encoder is not flexible without modification:
  111931. The LSP vector coder uses a single stage nearest-match with no
  111932. interleave, so no step and no error return. This is specced by floor0
  111933. and doesn't change.
  111934. Residue0 encoding interleaves, uses multiple stages, and each stage
  111935. peels of a specific amount of resolution from a lattice (thus we want
  111936. to match by threshold, not nearest match). Residue doesn't *have* to
  111937. be encoded that way, but to change it, one will need to add more
  111938. infrastructure on the encode side (decode side is specced and simpler) */
  111939. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111940. /* returns entry number and *modifies a* to the quantization value *****/
  111941. int vorbis_book_errorv(codebook *book,float *a){
  111942. int dim=book->dim,k;
  111943. int best=_best(book,a,1);
  111944. for(k=0;k<dim;k++)
  111945. a[k]=(book->valuelist+best*dim)[k];
  111946. return(best);
  111947. }
  111948. /* returns the number of bits and *modifies a* to the quantization value *****/
  111949. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111950. int k,dim=book->dim;
  111951. for(k=0;k<dim;k++)
  111952. a[k]=(book->valuelist+best*dim)[k];
  111953. return(vorbis_book_encode(book,best,b));
  111954. }
  111955. /* the 'eliminate the decode tree' optimization actually requires the
  111956. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111957. (and one of the first places where carefully thought out design
  111958. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111959. to an MSb bitpacker), but not actually the huge hit it appears to
  111960. be. The first-stage decode table catches most words so that
  111961. bitreverse is not in the main execution path. */
  111962. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111963. int read=book->dec_maxlength;
  111964. long lo,hi;
  111965. long lok = oggpack_look(b,book->dec_firsttablen);
  111966. if (lok >= 0) {
  111967. long entry = book->dec_firsttable[lok];
  111968. if(entry&0x80000000UL){
  111969. lo=(entry>>15)&0x7fff;
  111970. hi=book->used_entries-(entry&0x7fff);
  111971. }else{
  111972. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111973. return(entry-1);
  111974. }
  111975. }else{
  111976. lo=0;
  111977. hi=book->used_entries;
  111978. }
  111979. lok = oggpack_look(b, read);
  111980. while(lok<0 && read>1)
  111981. lok = oggpack_look(b, --read);
  111982. if(lok<0)return -1;
  111983. /* bisect search for the codeword in the ordered list */
  111984. {
  111985. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111986. while(hi-lo>1){
  111987. long p=(hi-lo)>>1;
  111988. long test=book->codelist[lo+p]>testword;
  111989. lo+=p&(test-1);
  111990. hi-=p&(-test);
  111991. }
  111992. if(book->dec_codelengths[lo]<=read){
  111993. oggpack_adv(b, book->dec_codelengths[lo]);
  111994. return(lo);
  111995. }
  111996. }
  111997. oggpack_adv(b, read);
  111998. return(-1);
  111999. }
  112000. /* Decode side is specced and easier, because we don't need to find
  112001. matches using different criteria; we simply read and map. There are
  112002. two things we need to do 'depending':
  112003. We may need to support interleave. We don't really, but it's
  112004. convenient to do it here rather than rebuild the vector later.
  112005. Cascades may be additive or multiplicitive; this is not inherent in
  112006. the codebook, but set in the code using the codebook. Like
  112007. interleaving, it's easiest to do it here.
  112008. addmul==0 -> declarative (set the value)
  112009. addmul==1 -> additive
  112010. addmul==2 -> multiplicitive */
  112011. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112012. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112013. long packed_entry=decode_packed_entry_number(book,b);
  112014. if(packed_entry>=0)
  112015. return(book->dec_index[packed_entry]);
  112016. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112017. return(packed_entry);
  112018. }
  112019. /* returns 0 on OK or -1 on eof *************************************/
  112020. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112021. int step=n/book->dim;
  112022. long *entry = (long*)alloca(sizeof(*entry)*step);
  112023. float **t = (float**)alloca(sizeof(*t)*step);
  112024. int i,j,o;
  112025. for (i = 0; i < step; i++) {
  112026. entry[i]=decode_packed_entry_number(book,b);
  112027. if(entry[i]==-1)return(-1);
  112028. t[i] = book->valuelist+entry[i]*book->dim;
  112029. }
  112030. for(i=0,o=0;i<book->dim;i++,o+=step)
  112031. for (j=0;j<step;j++)
  112032. a[o+j]+=t[j][i];
  112033. return(0);
  112034. }
  112035. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112036. int i,j,entry;
  112037. float *t;
  112038. if(book->dim>8){
  112039. for(i=0;i<n;){
  112040. entry = decode_packed_entry_number(book,b);
  112041. if(entry==-1)return(-1);
  112042. t = book->valuelist+entry*book->dim;
  112043. for (j=0;j<book->dim;)
  112044. a[i++]+=t[j++];
  112045. }
  112046. }else{
  112047. for(i=0;i<n;){
  112048. entry = decode_packed_entry_number(book,b);
  112049. if(entry==-1)return(-1);
  112050. t = book->valuelist+entry*book->dim;
  112051. j=0;
  112052. switch((int)book->dim){
  112053. case 8:
  112054. a[i++]+=t[j++];
  112055. case 7:
  112056. a[i++]+=t[j++];
  112057. case 6:
  112058. a[i++]+=t[j++];
  112059. case 5:
  112060. a[i++]+=t[j++];
  112061. case 4:
  112062. a[i++]+=t[j++];
  112063. case 3:
  112064. a[i++]+=t[j++];
  112065. case 2:
  112066. a[i++]+=t[j++];
  112067. case 1:
  112068. a[i++]+=t[j++];
  112069. case 0:
  112070. break;
  112071. }
  112072. }
  112073. }
  112074. return(0);
  112075. }
  112076. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112077. int i,j,entry;
  112078. float *t;
  112079. for(i=0;i<n;){
  112080. entry = decode_packed_entry_number(book,b);
  112081. if(entry==-1)return(-1);
  112082. t = book->valuelist+entry*book->dim;
  112083. for (j=0;j<book->dim;)
  112084. a[i++]=t[j++];
  112085. }
  112086. return(0);
  112087. }
  112088. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112089. oggpack_buffer *b,int n){
  112090. long i,j,entry;
  112091. int chptr=0;
  112092. for(i=offset/ch;i<(offset+n)/ch;){
  112093. entry = decode_packed_entry_number(book,b);
  112094. if(entry==-1)return(-1);
  112095. {
  112096. const float *t = book->valuelist+entry*book->dim;
  112097. for (j=0;j<book->dim;j++){
  112098. a[chptr++][i]+=t[j];
  112099. if(chptr==ch){
  112100. chptr=0;
  112101. i++;
  112102. }
  112103. }
  112104. }
  112105. }
  112106. return(0);
  112107. }
  112108. #ifdef _V_SELFTEST
  112109. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112110. number of vectors through (keeping track of the quantized values),
  112111. and decode using the unpacked book. quantized version of in should
  112112. exactly equal out */
  112113. #include <stdio.h>
  112114. #include "vorbis/book/lsp20_0.vqh"
  112115. #include "vorbis/book/res0a_13.vqh"
  112116. #define TESTSIZE 40
  112117. float test1[TESTSIZE]={
  112118. 0.105939f,
  112119. 0.215373f,
  112120. 0.429117f,
  112121. 0.587974f,
  112122. 0.181173f,
  112123. 0.296583f,
  112124. 0.515707f,
  112125. 0.715261f,
  112126. 0.162327f,
  112127. 0.263834f,
  112128. 0.342876f,
  112129. 0.406025f,
  112130. 0.103571f,
  112131. 0.223561f,
  112132. 0.368513f,
  112133. 0.540313f,
  112134. 0.136672f,
  112135. 0.395882f,
  112136. 0.587183f,
  112137. 0.652476f,
  112138. 0.114338f,
  112139. 0.417300f,
  112140. 0.525486f,
  112141. 0.698679f,
  112142. 0.147492f,
  112143. 0.324481f,
  112144. 0.643089f,
  112145. 0.757582f,
  112146. 0.139556f,
  112147. 0.215795f,
  112148. 0.324559f,
  112149. 0.399387f,
  112150. 0.120236f,
  112151. 0.267420f,
  112152. 0.446940f,
  112153. 0.608760f,
  112154. 0.115587f,
  112155. 0.287234f,
  112156. 0.571081f,
  112157. 0.708603f,
  112158. };
  112159. float test3[TESTSIZE]={
  112160. 0,1,-2,3,4,-5,6,7,8,9,
  112161. 8,-2,7,-1,4,6,8,3,1,-9,
  112162. 10,11,12,13,14,15,26,17,18,19,
  112163. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112164. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112165. &_vq_book_res0a_13,NULL};
  112166. float *testvec[]={test1,test3};
  112167. int main(){
  112168. oggpack_buffer write;
  112169. oggpack_buffer read;
  112170. long ptr=0,i;
  112171. oggpack_writeinit(&write);
  112172. fprintf(stderr,"Testing codebook abstraction...:\n");
  112173. while(testlist[ptr]){
  112174. codebook c;
  112175. static_codebook s;
  112176. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112177. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112178. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112179. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112180. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112181. /* pack the codebook, write the testvector */
  112182. oggpack_reset(&write);
  112183. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112184. we can write */
  112185. vorbis_staticbook_pack(testlist[ptr],&write);
  112186. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112187. for(i=0;i<TESTSIZE;i+=c.dim){
  112188. int best=_best(&c,qv+i,1);
  112189. vorbis_book_encodev(&c,best,qv+i,&write);
  112190. }
  112191. vorbis_book_clear(&c);
  112192. fprintf(stderr,"OK.\n");
  112193. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112194. /* transfer the write data to a read buffer and unpack/read */
  112195. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112196. if(vorbis_staticbook_unpack(&read,&s)){
  112197. fprintf(stderr,"Error unpacking codebook.\n");
  112198. exit(1);
  112199. }
  112200. if(vorbis_book_init_decode(&c,&s)){
  112201. fprintf(stderr,"Error initializing codebook.\n");
  112202. exit(1);
  112203. }
  112204. for(i=0;i<TESTSIZE;i+=c.dim)
  112205. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112206. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112207. exit(1);
  112208. }
  112209. for(i=0;i<TESTSIZE;i++)
  112210. if(fabs(qv[i]-iv[i])>.000001){
  112211. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112212. iv[i],qv[i],i);
  112213. exit(1);
  112214. }
  112215. fprintf(stderr,"OK\n");
  112216. ptr++;
  112217. }
  112218. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112219. exit(0);
  112220. }
  112221. #endif
  112222. #endif
  112223. /*** End of inlined file: codebook.c ***/
  112224. /*** Start of inlined file: envelope.c ***/
  112225. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112226. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112227. // tasks..
  112228. #if JUCE_MSVC
  112229. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112230. #endif
  112231. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112232. #if JUCE_USE_OGGVORBIS
  112233. #include <stdlib.h>
  112234. #include <string.h>
  112235. #include <stdio.h>
  112236. #include <math.h>
  112237. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112238. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112239. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112240. int ch=vi->channels;
  112241. int i,j;
  112242. int n=e->winlength=128;
  112243. e->searchstep=64; /* not random */
  112244. e->minenergy=gi->preecho_minenergy;
  112245. e->ch=ch;
  112246. e->storage=128;
  112247. e->cursor=ci->blocksizes[1]/2;
  112248. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112249. mdct_init(&e->mdct,n);
  112250. for(i=0;i<n;i++){
  112251. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112252. e->mdct_win[i]*=e->mdct_win[i];
  112253. }
  112254. /* magic follows */
  112255. e->band[0].begin=2; e->band[0].end=4;
  112256. e->band[1].begin=4; e->band[1].end=5;
  112257. e->band[2].begin=6; e->band[2].end=6;
  112258. e->band[3].begin=9; e->band[3].end=8;
  112259. e->band[4].begin=13; e->band[4].end=8;
  112260. e->band[5].begin=17; e->band[5].end=8;
  112261. e->band[6].begin=22; e->band[6].end=8;
  112262. for(j=0;j<VE_BANDS;j++){
  112263. n=e->band[j].end;
  112264. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112265. for(i=0;i<n;i++){
  112266. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112267. e->band[j].total+=e->band[j].window[i];
  112268. }
  112269. e->band[j].total=1./e->band[j].total;
  112270. }
  112271. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112272. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112273. }
  112274. void _ve_envelope_clear(envelope_lookup *e){
  112275. int i;
  112276. mdct_clear(&e->mdct);
  112277. for(i=0;i<VE_BANDS;i++)
  112278. _ogg_free(e->band[i].window);
  112279. _ogg_free(e->mdct_win);
  112280. _ogg_free(e->filter);
  112281. _ogg_free(e->mark);
  112282. memset(e,0,sizeof(*e));
  112283. }
  112284. /* fairly straight threshhold-by-band based until we find something
  112285. that works better and isn't patented. */
  112286. static int _ve_amp(envelope_lookup *ve,
  112287. vorbis_info_psy_global *gi,
  112288. float *data,
  112289. envelope_band *bands,
  112290. envelope_filter_state *filters,
  112291. long pos){
  112292. long n=ve->winlength;
  112293. int ret=0;
  112294. long i,j;
  112295. float decay;
  112296. /* we want to have a 'minimum bar' for energy, else we're just
  112297. basing blocks on quantization noise that outweighs the signal
  112298. itself (for low power signals) */
  112299. float minV=ve->minenergy;
  112300. float *vec=(float*) alloca(n*sizeof(*vec));
  112301. /* stretch is used to gradually lengthen the number of windows
  112302. considered prevoius-to-potential-trigger */
  112303. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112304. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112305. if(penalty<0.f)penalty=0.f;
  112306. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112307. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112308. totalshift+pos*ve->searchstep);*/
  112309. /* window and transform */
  112310. for(i=0;i<n;i++)
  112311. vec[i]=data[i]*ve->mdct_win[i];
  112312. mdct_forward(&ve->mdct,vec,vec);
  112313. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112314. /* near-DC spreading function; this has nothing to do with
  112315. psychoacoustics, just sidelobe leakage and window size */
  112316. {
  112317. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112318. int ptr=filters->nearptr;
  112319. /* the accumulation is regularly refreshed from scratch to avoid
  112320. floating point creep */
  112321. if(ptr==0){
  112322. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112323. filters->nearDC_partialacc=temp;
  112324. }else{
  112325. decay=filters->nearDC_acc+=temp;
  112326. filters->nearDC_partialacc+=temp;
  112327. }
  112328. filters->nearDC_acc-=filters->nearDC[ptr];
  112329. filters->nearDC[ptr]=temp;
  112330. decay*=(1./(VE_NEARDC+1));
  112331. filters->nearptr++;
  112332. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112333. decay=todB(&decay)*.5-15.f;
  112334. }
  112335. /* perform spreading and limiting, also smooth the spectrum. yes,
  112336. the MDCT results in all real coefficients, but it still *behaves*
  112337. like real/imaginary pairs */
  112338. for(i=0;i<n/2;i+=2){
  112339. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112340. val=todB(&val)*.5f;
  112341. if(val<decay)val=decay;
  112342. if(val<minV)val=minV;
  112343. vec[i>>1]=val;
  112344. decay-=8.;
  112345. }
  112346. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112347. /* perform preecho/postecho triggering by band */
  112348. for(j=0;j<VE_BANDS;j++){
  112349. float acc=0.;
  112350. float valmax,valmin;
  112351. /* accumulate amplitude */
  112352. for(i=0;i<bands[j].end;i++)
  112353. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112354. acc*=bands[j].total;
  112355. /* convert amplitude to delta */
  112356. {
  112357. int p,thisx=filters[j].ampptr;
  112358. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112359. p=thisx;
  112360. p--;
  112361. if(p<0)p+=VE_AMP;
  112362. postmax=max(acc,filters[j].ampbuf[p]);
  112363. postmin=min(acc,filters[j].ampbuf[p]);
  112364. for(i=0;i<stretch;i++){
  112365. p--;
  112366. if(p<0)p+=VE_AMP;
  112367. premax=max(premax,filters[j].ampbuf[p]);
  112368. premin=min(premin,filters[j].ampbuf[p]);
  112369. }
  112370. valmin=postmin-premin;
  112371. valmax=postmax-premax;
  112372. /*filters[j].markers[pos]=valmax;*/
  112373. filters[j].ampbuf[thisx]=acc;
  112374. filters[j].ampptr++;
  112375. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112376. }
  112377. /* look at min/max, decide trigger */
  112378. if(valmax>gi->preecho_thresh[j]+penalty){
  112379. ret|=1;
  112380. ret|=4;
  112381. }
  112382. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112383. }
  112384. return(ret);
  112385. }
  112386. #if 0
  112387. static int seq=0;
  112388. static ogg_int64_t totalshift=-1024;
  112389. #endif
  112390. long _ve_envelope_search(vorbis_dsp_state *v){
  112391. vorbis_info *vi=v->vi;
  112392. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112393. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112394. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112395. long i,j;
  112396. int first=ve->current/ve->searchstep;
  112397. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112398. if(first<0)first=0;
  112399. /* make sure we have enough storage to match the PCM */
  112400. if(last+VE_WIN+VE_POST>ve->storage){
  112401. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112402. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112403. }
  112404. for(j=first;j<last;j++){
  112405. int ret=0;
  112406. ve->stretch++;
  112407. if(ve->stretch>VE_MAXSTRETCH*2)
  112408. ve->stretch=VE_MAXSTRETCH*2;
  112409. for(i=0;i<ve->ch;i++){
  112410. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112411. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112412. }
  112413. ve->mark[j+VE_POST]=0;
  112414. if(ret&1){
  112415. ve->mark[j]=1;
  112416. ve->mark[j+1]=1;
  112417. }
  112418. if(ret&2){
  112419. ve->mark[j]=1;
  112420. if(j>0)ve->mark[j-1]=1;
  112421. }
  112422. if(ret&4)ve->stretch=-1;
  112423. }
  112424. ve->current=last*ve->searchstep;
  112425. {
  112426. long centerW=v->centerW;
  112427. long testW=
  112428. centerW+
  112429. ci->blocksizes[v->W]/4+
  112430. ci->blocksizes[1]/2+
  112431. ci->blocksizes[0]/4;
  112432. j=ve->cursor;
  112433. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112434. working back one window */
  112435. if(j>=testW)return(1);
  112436. ve->cursor=j;
  112437. if(ve->mark[j/ve->searchstep]){
  112438. if(j>centerW){
  112439. #if 0
  112440. if(j>ve->curmark){
  112441. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112442. int l,m;
  112443. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112444. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112445. seq,
  112446. (totalshift+ve->cursor)/44100.,
  112447. (totalshift+j)/44100.);
  112448. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112449. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112450. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112451. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112452. for(m=0;m<VE_BANDS;m++){
  112453. char buf[80];
  112454. sprintf(buf,"delL%d",m);
  112455. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112456. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112457. }
  112458. for(m=0;m<VE_BANDS;m++){
  112459. char buf[80];
  112460. sprintf(buf,"delR%d",m);
  112461. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112462. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112463. }
  112464. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112465. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112466. seq++;
  112467. }
  112468. #endif
  112469. ve->curmark=j;
  112470. if(j>=testW)return(1);
  112471. return(0);
  112472. }
  112473. }
  112474. j+=ve->searchstep;
  112475. }
  112476. }
  112477. return(-1);
  112478. }
  112479. int _ve_envelope_mark(vorbis_dsp_state *v){
  112480. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112481. vorbis_info *vi=v->vi;
  112482. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112483. long centerW=v->centerW;
  112484. long beginW=centerW-ci->blocksizes[v->W]/4;
  112485. long endW=centerW+ci->blocksizes[v->W]/4;
  112486. if(v->W){
  112487. beginW-=ci->blocksizes[v->lW]/4;
  112488. endW+=ci->blocksizes[v->nW]/4;
  112489. }else{
  112490. beginW-=ci->blocksizes[0]/4;
  112491. endW+=ci->blocksizes[0]/4;
  112492. }
  112493. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112494. {
  112495. long first=beginW/ve->searchstep;
  112496. long last=endW/ve->searchstep;
  112497. long i;
  112498. for(i=first;i<last;i++)
  112499. if(ve->mark[i])return(1);
  112500. }
  112501. return(0);
  112502. }
  112503. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112504. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112505. ahead of ve->current */
  112506. int smallshift=shift/e->searchstep;
  112507. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112508. #if 0
  112509. for(i=0;i<VE_BANDS*e->ch;i++)
  112510. memmove(e->filter[i].markers,
  112511. e->filter[i].markers+smallshift,
  112512. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112513. totalshift+=shift;
  112514. #endif
  112515. e->current-=shift;
  112516. if(e->curmark>=0)
  112517. e->curmark-=shift;
  112518. e->cursor-=shift;
  112519. }
  112520. #endif
  112521. /*** End of inlined file: envelope.c ***/
  112522. /*** Start of inlined file: floor0.c ***/
  112523. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112524. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112525. // tasks..
  112526. #if JUCE_MSVC
  112527. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112528. #endif
  112529. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112530. #if JUCE_USE_OGGVORBIS
  112531. #include <stdlib.h>
  112532. #include <string.h>
  112533. #include <math.h>
  112534. /*** Start of inlined file: lsp.h ***/
  112535. #ifndef _V_LSP_H_
  112536. #define _V_LSP_H_
  112537. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112538. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112539. float *lsp,int m,
  112540. float amp,float ampoffset);
  112541. #endif
  112542. /*** End of inlined file: lsp.h ***/
  112543. #include <stdio.h>
  112544. typedef struct {
  112545. int ln;
  112546. int m;
  112547. int **linearmap;
  112548. int n[2];
  112549. vorbis_info_floor0 *vi;
  112550. long bits;
  112551. long frames;
  112552. } vorbis_look_floor0;
  112553. /***********************************************/
  112554. static void floor0_free_info(vorbis_info_floor *i){
  112555. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112556. if(info){
  112557. memset(info,0,sizeof(*info));
  112558. _ogg_free(info);
  112559. }
  112560. }
  112561. static void floor0_free_look(vorbis_look_floor *i){
  112562. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112563. if(look){
  112564. if(look->linearmap){
  112565. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112566. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112567. _ogg_free(look->linearmap);
  112568. }
  112569. memset(look,0,sizeof(*look));
  112570. _ogg_free(look);
  112571. }
  112572. }
  112573. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112574. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112575. int j;
  112576. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112577. info->order=oggpack_read(opb,8);
  112578. info->rate=oggpack_read(opb,16);
  112579. info->barkmap=oggpack_read(opb,16);
  112580. info->ampbits=oggpack_read(opb,6);
  112581. info->ampdB=oggpack_read(opb,8);
  112582. info->numbooks=oggpack_read(opb,4)+1;
  112583. if(info->order<1)goto err_out;
  112584. if(info->rate<1)goto err_out;
  112585. if(info->barkmap<1)goto err_out;
  112586. if(info->numbooks<1)goto err_out;
  112587. for(j=0;j<info->numbooks;j++){
  112588. info->books[j]=oggpack_read(opb,8);
  112589. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112590. }
  112591. return(info);
  112592. err_out:
  112593. floor0_free_info(info);
  112594. return(NULL);
  112595. }
  112596. /* initialize Bark scale and normalization lookups. We could do this
  112597. with static tables, but Vorbis allows a number of possible
  112598. combinations, so it's best to do it computationally.
  112599. The below is authoritative in terms of defining scale mapping.
  112600. Note that the scale depends on the sampling rate as well as the
  112601. linear block and mapping sizes */
  112602. static void floor0_map_lazy_init(vorbis_block *vb,
  112603. vorbis_info_floor *infoX,
  112604. vorbis_look_floor0 *look){
  112605. if(!look->linearmap[vb->W]){
  112606. vorbis_dsp_state *vd=vb->vd;
  112607. vorbis_info *vi=vd->vi;
  112608. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112609. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112610. int W=vb->W;
  112611. int n=ci->blocksizes[W]/2,j;
  112612. /* we choose a scaling constant so that:
  112613. floor(bark(rate/2-1)*C)=mapped-1
  112614. floor(bark(rate/2)*C)=mapped */
  112615. float scale=look->ln/toBARK(info->rate/2.f);
  112616. /* the mapping from a linear scale to a smaller bark scale is
  112617. straightforward. We do *not* make sure that the linear mapping
  112618. does not skip bark-scale bins; the decoder simply skips them and
  112619. the encoder may do what it wishes in filling them. They're
  112620. necessary in some mapping combinations to keep the scale spacing
  112621. accurate */
  112622. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112623. for(j=0;j<n;j++){
  112624. int val=floor( toBARK((info->rate/2.f)/n*j)
  112625. *scale); /* bark numbers represent band edges */
  112626. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112627. look->linearmap[W][j]=val;
  112628. }
  112629. look->linearmap[W][j]=-1;
  112630. look->n[W]=n;
  112631. }
  112632. }
  112633. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112634. vorbis_info_floor *i){
  112635. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112636. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112637. look->m=info->order;
  112638. look->ln=info->barkmap;
  112639. look->vi=info;
  112640. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112641. return look;
  112642. }
  112643. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112644. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112645. vorbis_info_floor0 *info=look->vi;
  112646. int j,k;
  112647. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112648. if(ampraw>0){ /* also handles the -1 out of data case */
  112649. long maxval=(1<<info->ampbits)-1;
  112650. float amp=(float)ampraw/maxval*info->ampdB;
  112651. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112652. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112653. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112654. codebook *b=ci->fullbooks+info->books[booknum];
  112655. float last=0.f;
  112656. /* the additional b->dim is a guard against any possible stack
  112657. smash; b->dim is provably more than we can overflow the
  112658. vector */
  112659. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112660. for(j=0;j<look->m;j+=b->dim)
  112661. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112662. for(j=0;j<look->m;){
  112663. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112664. last=lsp[j-1];
  112665. }
  112666. lsp[look->m]=amp;
  112667. return(lsp);
  112668. }
  112669. }
  112670. eop:
  112671. return(NULL);
  112672. }
  112673. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112674. void *memo,float *out){
  112675. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112676. vorbis_info_floor0 *info=look->vi;
  112677. floor0_map_lazy_init(vb,info,look);
  112678. if(memo){
  112679. float *lsp=(float *)memo;
  112680. float amp=lsp[look->m];
  112681. /* take the coefficients back to a spectral envelope curve */
  112682. vorbis_lsp_to_curve(out,
  112683. look->linearmap[vb->W],
  112684. look->n[vb->W],
  112685. look->ln,
  112686. lsp,look->m,amp,(float)info->ampdB);
  112687. return(1);
  112688. }
  112689. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112690. return(0);
  112691. }
  112692. /* export hooks */
  112693. vorbis_func_floor floor0_exportbundle={
  112694. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112695. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112696. };
  112697. #endif
  112698. /*** End of inlined file: floor0.c ***/
  112699. /*** Start of inlined file: floor1.c ***/
  112700. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112701. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112702. // tasks..
  112703. #if JUCE_MSVC
  112704. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112705. #endif
  112706. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112707. #if JUCE_USE_OGGVORBIS
  112708. #include <stdlib.h>
  112709. #include <string.h>
  112710. #include <math.h>
  112711. #include <stdio.h>
  112712. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112713. typedef struct {
  112714. int sorted_index[VIF_POSIT+2];
  112715. int forward_index[VIF_POSIT+2];
  112716. int reverse_index[VIF_POSIT+2];
  112717. int hineighbor[VIF_POSIT];
  112718. int loneighbor[VIF_POSIT];
  112719. int posts;
  112720. int n;
  112721. int quant_q;
  112722. vorbis_info_floor1 *vi;
  112723. long phrasebits;
  112724. long postbits;
  112725. long frames;
  112726. } vorbis_look_floor1;
  112727. typedef struct lsfit_acc{
  112728. long x0;
  112729. long x1;
  112730. long xa;
  112731. long ya;
  112732. long x2a;
  112733. long y2a;
  112734. long xya;
  112735. long an;
  112736. } lsfit_acc;
  112737. /***********************************************/
  112738. static void floor1_free_info(vorbis_info_floor *i){
  112739. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112740. if(info){
  112741. memset(info,0,sizeof(*info));
  112742. _ogg_free(info);
  112743. }
  112744. }
  112745. static void floor1_free_look(vorbis_look_floor *i){
  112746. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112747. if(look){
  112748. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112749. (float)look->phrasebits/look->frames,
  112750. (float)look->postbits/look->frames,
  112751. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112752. memset(look,0,sizeof(*look));
  112753. _ogg_free(look);
  112754. }
  112755. }
  112756. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112757. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112758. int j,k;
  112759. int count=0;
  112760. int rangebits;
  112761. int maxposit=info->postlist[1];
  112762. int maxclass=-1;
  112763. /* save out partitions */
  112764. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112765. for(j=0;j<info->partitions;j++){
  112766. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112767. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112768. }
  112769. /* save out partition classes */
  112770. for(j=0;j<maxclass+1;j++){
  112771. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112772. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112773. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112774. for(k=0;k<(1<<info->class_subs[j]);k++)
  112775. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112776. }
  112777. /* save out the post list */
  112778. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112779. oggpack_write(opb,ilog2(maxposit),4);
  112780. rangebits=ilog2(maxposit);
  112781. for(j=0,k=0;j<info->partitions;j++){
  112782. count+=info->class_dim[info->partitionclass[j]];
  112783. for(;k<count;k++)
  112784. oggpack_write(opb,info->postlist[k+2],rangebits);
  112785. }
  112786. }
  112787. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112788. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112789. int j,k,count=0,maxclass=-1,rangebits;
  112790. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112791. /* read partitions */
  112792. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112793. for(j=0;j<info->partitions;j++){
  112794. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112795. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112796. }
  112797. /* read partition classes */
  112798. for(j=0;j<maxclass+1;j++){
  112799. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112800. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112801. if(info->class_subs[j]<0)
  112802. goto err_out;
  112803. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112804. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112805. goto err_out;
  112806. for(k=0;k<(1<<info->class_subs[j]);k++){
  112807. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112808. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112809. goto err_out;
  112810. }
  112811. }
  112812. /* read the post list */
  112813. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112814. rangebits=oggpack_read(opb,4);
  112815. for(j=0,k=0;j<info->partitions;j++){
  112816. count+=info->class_dim[info->partitionclass[j]];
  112817. for(;k<count;k++){
  112818. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112819. if(t<0 || t>=(1<<rangebits))
  112820. goto err_out;
  112821. }
  112822. }
  112823. info->postlist[0]=0;
  112824. info->postlist[1]=1<<rangebits;
  112825. return(info);
  112826. err_out:
  112827. floor1_free_info(info);
  112828. return(NULL);
  112829. }
  112830. static int JUCE_CDECL icomp(const void *a,const void *b){
  112831. return(**(int **)a-**(int **)b);
  112832. }
  112833. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112834. vorbis_info_floor *in){
  112835. int *sortpointer[VIF_POSIT+2];
  112836. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112837. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112838. int i,j,n=0;
  112839. look->vi=info;
  112840. look->n=info->postlist[1];
  112841. /* we drop each position value in-between already decoded values,
  112842. and use linear interpolation to predict each new value past the
  112843. edges. The positions are read in the order of the position
  112844. list... we precompute the bounding positions in the lookup. Of
  112845. course, the neighbors can change (if a position is declined), but
  112846. this is an initial mapping */
  112847. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112848. n+=2;
  112849. look->posts=n;
  112850. /* also store a sorted position index */
  112851. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112852. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112853. /* points from sort order back to range number */
  112854. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112855. /* points from range order to sorted position */
  112856. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112857. /* we actually need the post values too */
  112858. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112859. /* quantize values to multiplier spec */
  112860. switch(info->mult){
  112861. case 1: /* 1024 -> 256 */
  112862. look->quant_q=256;
  112863. break;
  112864. case 2: /* 1024 -> 128 */
  112865. look->quant_q=128;
  112866. break;
  112867. case 3: /* 1024 -> 86 */
  112868. look->quant_q=86;
  112869. break;
  112870. case 4: /* 1024 -> 64 */
  112871. look->quant_q=64;
  112872. break;
  112873. }
  112874. /* discover our neighbors for decode where we don't use fit flags
  112875. (that would push the neighbors outward) */
  112876. for(i=0;i<n-2;i++){
  112877. int lo=0;
  112878. int hi=1;
  112879. int lx=0;
  112880. int hx=look->n;
  112881. int currentx=info->postlist[i+2];
  112882. for(j=0;j<i+2;j++){
  112883. int x=info->postlist[j];
  112884. if(x>lx && x<currentx){
  112885. lo=j;
  112886. lx=x;
  112887. }
  112888. if(x<hx && x>currentx){
  112889. hi=j;
  112890. hx=x;
  112891. }
  112892. }
  112893. look->loneighbor[i]=lo;
  112894. look->hineighbor[i]=hi;
  112895. }
  112896. return(look);
  112897. }
  112898. static int render_point(int x0,int x1,int y0,int y1,int x){
  112899. y0&=0x7fff; /* mask off flag */
  112900. y1&=0x7fff;
  112901. {
  112902. int dy=y1-y0;
  112903. int adx=x1-x0;
  112904. int ady=abs(dy);
  112905. int err=ady*(x-x0);
  112906. int off=err/adx;
  112907. if(dy<0)return(y0-off);
  112908. return(y0+off);
  112909. }
  112910. }
  112911. static int vorbis_dBquant(const float *x){
  112912. int i= *x*7.3142857f+1023.5f;
  112913. if(i>1023)return(1023);
  112914. if(i<0)return(0);
  112915. return i;
  112916. }
  112917. static float FLOOR1_fromdB_LOOKUP[256]={
  112918. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112919. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112920. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112921. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112922. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112923. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112924. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112925. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112926. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112927. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112928. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112929. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112930. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112931. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112932. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112933. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112934. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112935. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112936. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112937. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112938. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112939. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112940. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112941. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112942. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112943. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112944. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112945. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112946. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112947. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112948. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112949. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112950. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112951. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112952. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112953. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112954. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112955. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112956. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112957. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112958. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112959. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112960. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112961. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112962. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112963. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112964. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112965. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112966. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112967. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112968. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112969. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112970. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112971. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112972. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112973. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112974. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112975. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112976. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112977. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112978. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112979. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112980. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112981. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112982. };
  112983. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112984. int dy=y1-y0;
  112985. int adx=x1-x0;
  112986. int ady=abs(dy);
  112987. int base=dy/adx;
  112988. int sy=(dy<0?base-1:base+1);
  112989. int x=x0;
  112990. int y=y0;
  112991. int err=0;
  112992. ady-=abs(base*adx);
  112993. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112994. while(++x<x1){
  112995. err=err+ady;
  112996. if(err>=adx){
  112997. err-=adx;
  112998. y+=sy;
  112999. }else{
  113000. y+=base;
  113001. }
  113002. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113003. }
  113004. }
  113005. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113006. int dy=y1-y0;
  113007. int adx=x1-x0;
  113008. int ady=abs(dy);
  113009. int base=dy/adx;
  113010. int sy=(dy<0?base-1:base+1);
  113011. int x=x0;
  113012. int y=y0;
  113013. int err=0;
  113014. ady-=abs(base*adx);
  113015. d[x]=y;
  113016. while(++x<x1){
  113017. err=err+ady;
  113018. if(err>=adx){
  113019. err-=adx;
  113020. y+=sy;
  113021. }else{
  113022. y+=base;
  113023. }
  113024. d[x]=y;
  113025. }
  113026. }
  113027. /* the floor has already been filtered to only include relevant sections */
  113028. static int accumulate_fit(const float *flr,const float *mdct,
  113029. int x0, int x1,lsfit_acc *a,
  113030. int n,vorbis_info_floor1 *info){
  113031. long i;
  113032. 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;
  113033. memset(a,0,sizeof(*a));
  113034. a->x0=x0;
  113035. a->x1=x1;
  113036. if(x1>=n)x1=n-1;
  113037. for(i=x0;i<=x1;i++){
  113038. int quantized=vorbis_dBquant(flr+i);
  113039. if(quantized){
  113040. if(mdct[i]+info->twofitatten>=flr[i]){
  113041. xa += i;
  113042. ya += quantized;
  113043. x2a += i*i;
  113044. y2a += quantized*quantized;
  113045. xya += i*quantized;
  113046. na++;
  113047. }else{
  113048. xb += i;
  113049. yb += quantized;
  113050. x2b += i*i;
  113051. y2b += quantized*quantized;
  113052. xyb += i*quantized;
  113053. nb++;
  113054. }
  113055. }
  113056. }
  113057. xb+=xa;
  113058. yb+=ya;
  113059. x2b+=x2a;
  113060. y2b+=y2a;
  113061. xyb+=xya;
  113062. nb+=na;
  113063. /* weight toward the actually used frequencies if we meet the threshhold */
  113064. {
  113065. int weight=nb*info->twofitweight/(na+1);
  113066. a->xa=xa*weight+xb;
  113067. a->ya=ya*weight+yb;
  113068. a->x2a=x2a*weight+x2b;
  113069. a->y2a=y2a*weight+y2b;
  113070. a->xya=xya*weight+xyb;
  113071. a->an=na*weight+nb;
  113072. }
  113073. return(na);
  113074. }
  113075. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113076. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113077. long x0=a[0].x0;
  113078. long x1=a[fits-1].x1;
  113079. for(i=0;i<fits;i++){
  113080. x+=a[i].xa;
  113081. y+=a[i].ya;
  113082. x2+=a[i].x2a;
  113083. y2+=a[i].y2a;
  113084. xy+=a[i].xya;
  113085. an+=a[i].an;
  113086. }
  113087. if(*y0>=0){
  113088. x+= x0;
  113089. y+= *y0;
  113090. x2+= x0 * x0;
  113091. y2+= *y0 * *y0;
  113092. xy+= *y0 * x0;
  113093. an++;
  113094. }
  113095. if(*y1>=0){
  113096. x+= x1;
  113097. y+= *y1;
  113098. x2+= x1 * x1;
  113099. y2+= *y1 * *y1;
  113100. xy+= *y1 * x1;
  113101. an++;
  113102. }
  113103. if(an){
  113104. /* need 64 bit multiplies, which C doesn't give portably as int */
  113105. double fx=x;
  113106. double fy=y;
  113107. double fx2=x2;
  113108. double fxy=xy;
  113109. double denom=1./(an*fx2-fx*fx);
  113110. double a=(fy*fx2-fxy*fx)*denom;
  113111. double b=(an*fxy-fx*fy)*denom;
  113112. *y0=rint(a+b*x0);
  113113. *y1=rint(a+b*x1);
  113114. /* limit to our range! */
  113115. if(*y0>1023)*y0=1023;
  113116. if(*y1>1023)*y1=1023;
  113117. if(*y0<0)*y0=0;
  113118. if(*y1<0)*y1=0;
  113119. }else{
  113120. *y0=0;
  113121. *y1=0;
  113122. }
  113123. }
  113124. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113125. long y=0;
  113126. int i;
  113127. for(i=0;i<fits && y==0;i++)
  113128. y+=a[i].ya;
  113129. *y0=*y1=y;
  113130. }*/
  113131. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113132. const float *mdct,
  113133. vorbis_info_floor1 *info){
  113134. int dy=y1-y0;
  113135. int adx=x1-x0;
  113136. int ady=abs(dy);
  113137. int base=dy/adx;
  113138. int sy=(dy<0?base-1:base+1);
  113139. int x=x0;
  113140. int y=y0;
  113141. int err=0;
  113142. int val=vorbis_dBquant(mask+x);
  113143. int mse=0;
  113144. int n=0;
  113145. ady-=abs(base*adx);
  113146. mse=(y-val);
  113147. mse*=mse;
  113148. n++;
  113149. if(mdct[x]+info->twofitatten>=mask[x]){
  113150. if(y+info->maxover<val)return(1);
  113151. if(y-info->maxunder>val)return(1);
  113152. }
  113153. while(++x<x1){
  113154. err=err+ady;
  113155. if(err>=adx){
  113156. err-=adx;
  113157. y+=sy;
  113158. }else{
  113159. y+=base;
  113160. }
  113161. val=vorbis_dBquant(mask+x);
  113162. mse+=((y-val)*(y-val));
  113163. n++;
  113164. if(mdct[x]+info->twofitatten>=mask[x]){
  113165. if(val){
  113166. if(y+info->maxover<val)return(1);
  113167. if(y-info->maxunder>val)return(1);
  113168. }
  113169. }
  113170. }
  113171. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113172. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113173. if(mse/n>info->maxerr)return(1);
  113174. return(0);
  113175. }
  113176. static int post_Y(int *A,int *B,int pos){
  113177. if(A[pos]<0)
  113178. return B[pos];
  113179. if(B[pos]<0)
  113180. return A[pos];
  113181. return (A[pos]+B[pos])>>1;
  113182. }
  113183. int *floor1_fit(vorbis_block *vb,void *look_,
  113184. const float *logmdct, /* in */
  113185. const float *logmask){
  113186. long i,j;
  113187. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113188. vorbis_info_floor1 *info=look->vi;
  113189. long n=look->n;
  113190. long posts=look->posts;
  113191. long nonzero=0;
  113192. lsfit_acc fits[VIF_POSIT+1];
  113193. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113194. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113195. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113196. int hineighbor[VIF_POSIT+2];
  113197. int *output=NULL;
  113198. int memo[VIF_POSIT+2];
  113199. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113200. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113201. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113202. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113203. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113204. /* quantize the relevant floor points and collect them into line fit
  113205. structures (one per minimal division) at the same time */
  113206. if(posts==0){
  113207. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113208. }else{
  113209. for(i=0;i<posts-1;i++)
  113210. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113211. look->sorted_index[i+1],fits+i,
  113212. n,info);
  113213. }
  113214. if(nonzero){
  113215. /* start by fitting the implicit base case.... */
  113216. int y0=-200;
  113217. int y1=-200;
  113218. fit_line(fits,posts-1,&y0,&y1);
  113219. fit_valueA[0]=y0;
  113220. fit_valueB[0]=y0;
  113221. fit_valueB[1]=y1;
  113222. fit_valueA[1]=y1;
  113223. /* Non degenerate case */
  113224. /* start progressive splitting. This is a greedy, non-optimal
  113225. algorithm, but simple and close enough to the best
  113226. answer. */
  113227. for(i=2;i<posts;i++){
  113228. int sortpos=look->reverse_index[i];
  113229. int ln=loneighbor[sortpos];
  113230. int hn=hineighbor[sortpos];
  113231. /* eliminate repeat searches of a particular range with a memo */
  113232. if(memo[ln]!=hn){
  113233. /* haven't performed this error search yet */
  113234. int lsortpos=look->reverse_index[ln];
  113235. int hsortpos=look->reverse_index[hn];
  113236. memo[ln]=hn;
  113237. {
  113238. /* A note: we want to bound/minimize *local*, not global, error */
  113239. int lx=info->postlist[ln];
  113240. int hx=info->postlist[hn];
  113241. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113242. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113243. if(ly==-1 || hy==-1){
  113244. exit(1);
  113245. }
  113246. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113247. /* outside error bounds/begin search area. Split it. */
  113248. int ly0=-200;
  113249. int ly1=-200;
  113250. int hy0=-200;
  113251. int hy1=-200;
  113252. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113253. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113254. /* store new edge values */
  113255. fit_valueB[ln]=ly0;
  113256. if(ln==0)fit_valueA[ln]=ly0;
  113257. fit_valueA[i]=ly1;
  113258. fit_valueB[i]=hy0;
  113259. fit_valueA[hn]=hy1;
  113260. if(hn==1)fit_valueB[hn]=hy1;
  113261. if(ly1>=0 || hy0>=0){
  113262. /* store new neighbor values */
  113263. for(j=sortpos-1;j>=0;j--)
  113264. if(hineighbor[j]==hn)
  113265. hineighbor[j]=i;
  113266. else
  113267. break;
  113268. for(j=sortpos+1;j<posts;j++)
  113269. if(loneighbor[j]==ln)
  113270. loneighbor[j]=i;
  113271. else
  113272. break;
  113273. }
  113274. }else{
  113275. fit_valueA[i]=-200;
  113276. fit_valueB[i]=-200;
  113277. }
  113278. }
  113279. }
  113280. }
  113281. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113282. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113283. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113284. /* fill in posts marked as not using a fit; we will zero
  113285. back out to 'unused' when encoding them so long as curve
  113286. interpolation doesn't force them into use */
  113287. for(i=2;i<posts;i++){
  113288. int ln=look->loneighbor[i-2];
  113289. int hn=look->hineighbor[i-2];
  113290. int x0=info->postlist[ln];
  113291. int x1=info->postlist[hn];
  113292. int y0=output[ln];
  113293. int y1=output[hn];
  113294. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113295. int vx=post_Y(fit_valueA,fit_valueB,i);
  113296. if(vx>=0 && predicted!=vx){
  113297. output[i]=vx;
  113298. }else{
  113299. output[i]= predicted|0x8000;
  113300. }
  113301. }
  113302. }
  113303. return(output);
  113304. }
  113305. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113306. int *A,int *B,
  113307. int del){
  113308. long i;
  113309. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113310. long posts=look->posts;
  113311. int *output=NULL;
  113312. if(A && B){
  113313. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113314. for(i=0;i<posts;i++){
  113315. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113316. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113317. }
  113318. }
  113319. return(output);
  113320. }
  113321. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113322. void*look_,
  113323. int *post,int *ilogmask){
  113324. long i,j;
  113325. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113326. vorbis_info_floor1 *info=look->vi;
  113327. long posts=look->posts;
  113328. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113329. int out[VIF_POSIT+2];
  113330. static_codebook **sbooks=ci->book_param;
  113331. codebook *books=ci->fullbooks;
  113332. static long seq=0;
  113333. /* quantize values to multiplier spec */
  113334. if(post){
  113335. for(i=0;i<posts;i++){
  113336. int val=post[i]&0x7fff;
  113337. switch(info->mult){
  113338. case 1: /* 1024 -> 256 */
  113339. val>>=2;
  113340. break;
  113341. case 2: /* 1024 -> 128 */
  113342. val>>=3;
  113343. break;
  113344. case 3: /* 1024 -> 86 */
  113345. val/=12;
  113346. break;
  113347. case 4: /* 1024 -> 64 */
  113348. val>>=4;
  113349. break;
  113350. }
  113351. post[i]=val | (post[i]&0x8000);
  113352. }
  113353. out[0]=post[0];
  113354. out[1]=post[1];
  113355. /* find prediction values for each post and subtract them */
  113356. for(i=2;i<posts;i++){
  113357. int ln=look->loneighbor[i-2];
  113358. int hn=look->hineighbor[i-2];
  113359. int x0=info->postlist[ln];
  113360. int x1=info->postlist[hn];
  113361. int y0=post[ln];
  113362. int y1=post[hn];
  113363. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113364. if((post[i]&0x8000) || (predicted==post[i])){
  113365. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113366. in interpolation */
  113367. out[i]=0;
  113368. }else{
  113369. int headroom=(look->quant_q-predicted<predicted?
  113370. look->quant_q-predicted:predicted);
  113371. int val=post[i]-predicted;
  113372. /* at this point the 'deviation' value is in the range +/- max
  113373. range, but the real, unique range can always be mapped to
  113374. only [0-maxrange). So we want to wrap the deviation into
  113375. this limited range, but do it in the way that least screws
  113376. an essentially gaussian probability distribution. */
  113377. if(val<0)
  113378. if(val<-headroom)
  113379. val=headroom-val-1;
  113380. else
  113381. val=-1-(val<<1);
  113382. else
  113383. if(val>=headroom)
  113384. val= val+headroom;
  113385. else
  113386. val<<=1;
  113387. out[i]=val;
  113388. post[ln]&=0x7fff;
  113389. post[hn]&=0x7fff;
  113390. }
  113391. }
  113392. /* we have everything we need. pack it out */
  113393. /* mark nontrivial floor */
  113394. oggpack_write(opb,1,1);
  113395. /* beginning/end post */
  113396. look->frames++;
  113397. look->postbits+=ilog(look->quant_q-1)*2;
  113398. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113399. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113400. /* partition by partition */
  113401. for(i=0,j=2;i<info->partitions;i++){
  113402. int classx=info->partitionclass[i];
  113403. int cdim=info->class_dim[classx];
  113404. int csubbits=info->class_subs[classx];
  113405. int csub=1<<csubbits;
  113406. int bookas[8]={0,0,0,0,0,0,0,0};
  113407. int cval=0;
  113408. int cshift=0;
  113409. int k,l;
  113410. /* generate the partition's first stage cascade value */
  113411. if(csubbits){
  113412. int maxval[8];
  113413. for(k=0;k<csub;k++){
  113414. int booknum=info->class_subbook[classx][k];
  113415. if(booknum<0){
  113416. maxval[k]=1;
  113417. }else{
  113418. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113419. }
  113420. }
  113421. for(k=0;k<cdim;k++){
  113422. for(l=0;l<csub;l++){
  113423. int val=out[j+k];
  113424. if(val<maxval[l]){
  113425. bookas[k]=l;
  113426. break;
  113427. }
  113428. }
  113429. cval|= bookas[k]<<cshift;
  113430. cshift+=csubbits;
  113431. }
  113432. /* write it */
  113433. look->phrasebits+=
  113434. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113435. #ifdef TRAIN_FLOOR1
  113436. {
  113437. FILE *of;
  113438. char buffer[80];
  113439. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113440. vb->pcmend/2,posts-2,class);
  113441. of=fopen(buffer,"a");
  113442. fprintf(of,"%d\n",cval);
  113443. fclose(of);
  113444. }
  113445. #endif
  113446. }
  113447. /* write post values */
  113448. for(k=0;k<cdim;k++){
  113449. int book=info->class_subbook[classx][bookas[k]];
  113450. if(book>=0){
  113451. /* hack to allow training with 'bad' books */
  113452. if(out[j+k]<(books+book)->entries)
  113453. look->postbits+=vorbis_book_encode(books+book,
  113454. out[j+k],opb);
  113455. /*else
  113456. fprintf(stderr,"+!");*/
  113457. #ifdef TRAIN_FLOOR1
  113458. {
  113459. FILE *of;
  113460. char buffer[80];
  113461. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113462. vb->pcmend/2,posts-2,class,bookas[k]);
  113463. of=fopen(buffer,"a");
  113464. fprintf(of,"%d\n",out[j+k]);
  113465. fclose(of);
  113466. }
  113467. #endif
  113468. }
  113469. }
  113470. j+=cdim;
  113471. }
  113472. {
  113473. /* generate quantized floor equivalent to what we'd unpack in decode */
  113474. /* render the lines */
  113475. int hx=0;
  113476. int lx=0;
  113477. int ly=post[0]*info->mult;
  113478. for(j=1;j<look->posts;j++){
  113479. int current=look->forward_index[j];
  113480. int hy=post[current]&0x7fff;
  113481. if(hy==post[current]){
  113482. hy*=info->mult;
  113483. hx=info->postlist[current];
  113484. render_line0(lx,hx,ly,hy,ilogmask);
  113485. lx=hx;
  113486. ly=hy;
  113487. }
  113488. }
  113489. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113490. seq++;
  113491. return(1);
  113492. }
  113493. }else{
  113494. oggpack_write(opb,0,1);
  113495. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113496. seq++;
  113497. return(0);
  113498. }
  113499. }
  113500. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113501. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113502. vorbis_info_floor1 *info=look->vi;
  113503. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113504. int i,j,k;
  113505. codebook *books=ci->fullbooks;
  113506. /* unpack wrapped/predicted values from stream */
  113507. if(oggpack_read(&vb->opb,1)==1){
  113508. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113509. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113510. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113511. /* partition by partition */
  113512. for(i=0,j=2;i<info->partitions;i++){
  113513. int classx=info->partitionclass[i];
  113514. int cdim=info->class_dim[classx];
  113515. int csubbits=info->class_subs[classx];
  113516. int csub=1<<csubbits;
  113517. int cval=0;
  113518. /* decode the partition's first stage cascade value */
  113519. if(csubbits){
  113520. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113521. if(cval==-1)goto eop;
  113522. }
  113523. for(k=0;k<cdim;k++){
  113524. int book=info->class_subbook[classx][cval&(csub-1)];
  113525. cval>>=csubbits;
  113526. if(book>=0){
  113527. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113528. goto eop;
  113529. }else{
  113530. fit_value[j+k]=0;
  113531. }
  113532. }
  113533. j+=cdim;
  113534. }
  113535. /* unwrap positive values and reconsitute via linear interpolation */
  113536. for(i=2;i<look->posts;i++){
  113537. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113538. info->postlist[look->hineighbor[i-2]],
  113539. fit_value[look->loneighbor[i-2]],
  113540. fit_value[look->hineighbor[i-2]],
  113541. info->postlist[i]);
  113542. int hiroom=look->quant_q-predicted;
  113543. int loroom=predicted;
  113544. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113545. int val=fit_value[i];
  113546. if(val){
  113547. if(val>=room){
  113548. if(hiroom>loroom){
  113549. val = val-loroom;
  113550. }else{
  113551. val = -1-(val-hiroom);
  113552. }
  113553. }else{
  113554. if(val&1){
  113555. val= -((val+1)>>1);
  113556. }else{
  113557. val>>=1;
  113558. }
  113559. }
  113560. fit_value[i]=val+predicted;
  113561. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113562. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113563. }else{
  113564. fit_value[i]=predicted|0x8000;
  113565. }
  113566. }
  113567. return(fit_value);
  113568. }
  113569. eop:
  113570. return(NULL);
  113571. }
  113572. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113573. float *out){
  113574. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113575. vorbis_info_floor1 *info=look->vi;
  113576. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113577. int n=ci->blocksizes[vb->W]/2;
  113578. int j;
  113579. if(memo){
  113580. /* render the lines */
  113581. int *fit_value=(int *)memo;
  113582. int hx=0;
  113583. int lx=0;
  113584. int ly=fit_value[0]*info->mult;
  113585. for(j=1;j<look->posts;j++){
  113586. int current=look->forward_index[j];
  113587. int hy=fit_value[current]&0x7fff;
  113588. if(hy==fit_value[current]){
  113589. hy*=info->mult;
  113590. hx=info->postlist[current];
  113591. render_line(lx,hx,ly,hy,out);
  113592. lx=hx;
  113593. ly=hy;
  113594. }
  113595. }
  113596. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113597. return(1);
  113598. }
  113599. memset(out,0,sizeof(*out)*n);
  113600. return(0);
  113601. }
  113602. /* export hooks */
  113603. vorbis_func_floor floor1_exportbundle={
  113604. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113605. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113606. };
  113607. #endif
  113608. /*** End of inlined file: floor1.c ***/
  113609. /*** Start of inlined file: info.c ***/
  113610. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113611. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113612. // tasks..
  113613. #if JUCE_MSVC
  113614. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113615. #endif
  113616. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113617. #if JUCE_USE_OGGVORBIS
  113618. /* general handling of the header and the vorbis_info structure (and
  113619. substructures) */
  113620. #include <stdlib.h>
  113621. #include <string.h>
  113622. #include <ctype.h>
  113623. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113624. while(bytes--){
  113625. oggpack_write(o,*s++,8);
  113626. }
  113627. }
  113628. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113629. while(bytes--){
  113630. *buf++=oggpack_read(o,8);
  113631. }
  113632. }
  113633. void vorbis_comment_init(vorbis_comment *vc){
  113634. memset(vc,0,sizeof(*vc));
  113635. }
  113636. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113637. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113638. (vc->comments+2)*sizeof(*vc->user_comments));
  113639. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113640. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113641. vc->comment_lengths[vc->comments]=strlen(comment);
  113642. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113643. strcpy(vc->user_comments[vc->comments], comment);
  113644. vc->comments++;
  113645. vc->user_comments[vc->comments]=NULL;
  113646. }
  113647. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113648. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113649. strcpy(comment, tag);
  113650. strcat(comment, "=");
  113651. strcat(comment, contents);
  113652. vorbis_comment_add(vc, comment);
  113653. }
  113654. /* This is more or less the same as strncasecmp - but that doesn't exist
  113655. * everywhere, and this is a fairly trivial function, so we include it */
  113656. static int tagcompare(const char *s1, const char *s2, int n){
  113657. int c=0;
  113658. while(c < n){
  113659. if(toupper(s1[c]) != toupper(s2[c]))
  113660. return !0;
  113661. c++;
  113662. }
  113663. return 0;
  113664. }
  113665. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113666. long i;
  113667. int found = 0;
  113668. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113669. char *fulltag = (char*)alloca(taglen+ 1);
  113670. strcpy(fulltag, tag);
  113671. strcat(fulltag, "=");
  113672. for(i=0;i<vc->comments;i++){
  113673. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113674. if(count == found)
  113675. /* We return a pointer to the data, not a copy */
  113676. return vc->user_comments[i] + taglen;
  113677. else
  113678. found++;
  113679. }
  113680. }
  113681. return NULL; /* didn't find anything */
  113682. }
  113683. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113684. int i,count=0;
  113685. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113686. char *fulltag = (char*)alloca(taglen+1);
  113687. strcpy(fulltag,tag);
  113688. strcat(fulltag, "=");
  113689. for(i=0;i<vc->comments;i++){
  113690. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113691. count++;
  113692. }
  113693. return count;
  113694. }
  113695. void vorbis_comment_clear(vorbis_comment *vc){
  113696. if(vc){
  113697. long i;
  113698. for(i=0;i<vc->comments;i++)
  113699. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113700. if(vc->user_comments)_ogg_free(vc->user_comments);
  113701. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113702. if(vc->vendor)_ogg_free(vc->vendor);
  113703. }
  113704. memset(vc,0,sizeof(*vc));
  113705. }
  113706. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113707. They may be equal, but short will never ge greater than long */
  113708. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113709. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113710. return ci ? ci->blocksizes[zo] : -1;
  113711. }
  113712. /* used by synthesis, which has a full, alloced vi */
  113713. void vorbis_info_init(vorbis_info *vi){
  113714. memset(vi,0,sizeof(*vi));
  113715. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113716. }
  113717. void vorbis_info_clear(vorbis_info *vi){
  113718. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113719. int i;
  113720. if(ci){
  113721. for(i=0;i<ci->modes;i++)
  113722. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113723. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113724. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113725. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113726. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113727. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113728. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113729. for(i=0;i<ci->books;i++){
  113730. if(ci->book_param[i]){
  113731. /* knows if the book was not alloced */
  113732. vorbis_staticbook_destroy(ci->book_param[i]);
  113733. }
  113734. if(ci->fullbooks)
  113735. vorbis_book_clear(ci->fullbooks+i);
  113736. }
  113737. if(ci->fullbooks)
  113738. _ogg_free(ci->fullbooks);
  113739. for(i=0;i<ci->psys;i++)
  113740. _vi_psy_free(ci->psy_param[i]);
  113741. _ogg_free(ci);
  113742. }
  113743. memset(vi,0,sizeof(*vi));
  113744. }
  113745. /* Header packing/unpacking ********************************************/
  113746. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113747. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113748. if(!ci)return(OV_EFAULT);
  113749. vi->version=oggpack_read(opb,32);
  113750. if(vi->version!=0)return(OV_EVERSION);
  113751. vi->channels=oggpack_read(opb,8);
  113752. vi->rate=oggpack_read(opb,32);
  113753. vi->bitrate_upper=oggpack_read(opb,32);
  113754. vi->bitrate_nominal=oggpack_read(opb,32);
  113755. vi->bitrate_lower=oggpack_read(opb,32);
  113756. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113757. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113758. if(vi->rate<1)goto err_out;
  113759. if(vi->channels<1)goto err_out;
  113760. if(ci->blocksizes[0]<8)goto err_out;
  113761. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113762. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113763. return(0);
  113764. err_out:
  113765. vorbis_info_clear(vi);
  113766. return(OV_EBADHEADER);
  113767. }
  113768. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113769. int i;
  113770. int vendorlen=oggpack_read(opb,32);
  113771. if(vendorlen<0)goto err_out;
  113772. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113773. _v_readstring(opb,vc->vendor,vendorlen);
  113774. vc->comments=oggpack_read(opb,32);
  113775. if(vc->comments<0)goto err_out;
  113776. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113777. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113778. for(i=0;i<vc->comments;i++){
  113779. int len=oggpack_read(opb,32);
  113780. if(len<0)goto err_out;
  113781. vc->comment_lengths[i]=len;
  113782. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113783. _v_readstring(opb,vc->user_comments[i],len);
  113784. }
  113785. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113786. return(0);
  113787. err_out:
  113788. vorbis_comment_clear(vc);
  113789. return(OV_EBADHEADER);
  113790. }
  113791. /* all of the real encoding details are here. The modes, books,
  113792. everything */
  113793. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113794. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113795. int i;
  113796. if(!ci)return(OV_EFAULT);
  113797. /* codebooks */
  113798. ci->books=oggpack_read(opb,8)+1;
  113799. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113800. for(i=0;i<ci->books;i++){
  113801. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113802. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113803. }
  113804. /* time backend settings; hooks are unused */
  113805. {
  113806. int times=oggpack_read(opb,6)+1;
  113807. for(i=0;i<times;i++){
  113808. int test=oggpack_read(opb,16);
  113809. if(test<0 || test>=VI_TIMEB)goto err_out;
  113810. }
  113811. }
  113812. /* floor backend settings */
  113813. ci->floors=oggpack_read(opb,6)+1;
  113814. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113815. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113816. for(i=0;i<ci->floors;i++){
  113817. ci->floor_type[i]=oggpack_read(opb,16);
  113818. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113819. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113820. if(!ci->floor_param[i])goto err_out;
  113821. }
  113822. /* residue backend settings */
  113823. ci->residues=oggpack_read(opb,6)+1;
  113824. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113825. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113826. for(i=0;i<ci->residues;i++){
  113827. ci->residue_type[i]=oggpack_read(opb,16);
  113828. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113829. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113830. if(!ci->residue_param[i])goto err_out;
  113831. }
  113832. /* map backend settings */
  113833. ci->maps=oggpack_read(opb,6)+1;
  113834. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113835. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113836. for(i=0;i<ci->maps;i++){
  113837. ci->map_type[i]=oggpack_read(opb,16);
  113838. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113839. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113840. if(!ci->map_param[i])goto err_out;
  113841. }
  113842. /* mode settings */
  113843. ci->modes=oggpack_read(opb,6)+1;
  113844. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113845. for(i=0;i<ci->modes;i++){
  113846. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113847. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113848. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113849. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113850. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113851. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113852. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113853. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113854. }
  113855. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113856. return(0);
  113857. err_out:
  113858. vorbis_info_clear(vi);
  113859. return(OV_EBADHEADER);
  113860. }
  113861. /* The Vorbis header is in three packets; the initial small packet in
  113862. the first page that identifies basic parameters, a second packet
  113863. with bitstream comments and a third packet that holds the
  113864. codebook. */
  113865. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113866. oggpack_buffer opb;
  113867. if(op){
  113868. oggpack_readinit(&opb,op->packet,op->bytes);
  113869. /* Which of the three types of header is this? */
  113870. /* Also verify header-ness, vorbis */
  113871. {
  113872. char buffer[6];
  113873. int packtype=oggpack_read(&opb,8);
  113874. memset(buffer,0,6);
  113875. _v_readstring(&opb,buffer,6);
  113876. if(memcmp(buffer,"vorbis",6)){
  113877. /* not a vorbis header */
  113878. return(OV_ENOTVORBIS);
  113879. }
  113880. switch(packtype){
  113881. case 0x01: /* least significant *bit* is read first */
  113882. if(!op->b_o_s){
  113883. /* Not the initial packet */
  113884. return(OV_EBADHEADER);
  113885. }
  113886. if(vi->rate!=0){
  113887. /* previously initialized info header */
  113888. return(OV_EBADHEADER);
  113889. }
  113890. return(_vorbis_unpack_info(vi,&opb));
  113891. case 0x03: /* least significant *bit* is read first */
  113892. if(vi->rate==0){
  113893. /* um... we didn't get the initial header */
  113894. return(OV_EBADHEADER);
  113895. }
  113896. return(_vorbis_unpack_comment(vc,&opb));
  113897. case 0x05: /* least significant *bit* is read first */
  113898. if(vi->rate==0 || vc->vendor==NULL){
  113899. /* um... we didn;t get the initial header or comments yet */
  113900. return(OV_EBADHEADER);
  113901. }
  113902. return(_vorbis_unpack_books(vi,&opb));
  113903. default:
  113904. /* Not a valid vorbis header type */
  113905. return(OV_EBADHEADER);
  113906. break;
  113907. }
  113908. }
  113909. }
  113910. return(OV_EBADHEADER);
  113911. }
  113912. /* pack side **********************************************************/
  113913. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113914. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113915. if(!ci)return(OV_EFAULT);
  113916. /* preamble */
  113917. oggpack_write(opb,0x01,8);
  113918. _v_writestring(opb,"vorbis", 6);
  113919. /* basic information about the stream */
  113920. oggpack_write(opb,0x00,32);
  113921. oggpack_write(opb,vi->channels,8);
  113922. oggpack_write(opb,vi->rate,32);
  113923. oggpack_write(opb,vi->bitrate_upper,32);
  113924. oggpack_write(opb,vi->bitrate_nominal,32);
  113925. oggpack_write(opb,vi->bitrate_lower,32);
  113926. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113927. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113928. oggpack_write(opb,1,1);
  113929. return(0);
  113930. }
  113931. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113932. char temp[]="Xiph.Org libVorbis I 20050304";
  113933. int bytes = strlen(temp);
  113934. /* preamble */
  113935. oggpack_write(opb,0x03,8);
  113936. _v_writestring(opb,"vorbis", 6);
  113937. /* vendor */
  113938. oggpack_write(opb,bytes,32);
  113939. _v_writestring(opb,temp, bytes);
  113940. /* comments */
  113941. oggpack_write(opb,vc->comments,32);
  113942. if(vc->comments){
  113943. int i;
  113944. for(i=0;i<vc->comments;i++){
  113945. if(vc->user_comments[i]){
  113946. oggpack_write(opb,vc->comment_lengths[i],32);
  113947. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113948. }else{
  113949. oggpack_write(opb,0,32);
  113950. }
  113951. }
  113952. }
  113953. oggpack_write(opb,1,1);
  113954. return(0);
  113955. }
  113956. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113957. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113958. int i;
  113959. if(!ci)return(OV_EFAULT);
  113960. oggpack_write(opb,0x05,8);
  113961. _v_writestring(opb,"vorbis", 6);
  113962. /* books */
  113963. oggpack_write(opb,ci->books-1,8);
  113964. for(i=0;i<ci->books;i++)
  113965. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113966. /* times; hook placeholders */
  113967. oggpack_write(opb,0,6);
  113968. oggpack_write(opb,0,16);
  113969. /* floors */
  113970. oggpack_write(opb,ci->floors-1,6);
  113971. for(i=0;i<ci->floors;i++){
  113972. oggpack_write(opb,ci->floor_type[i],16);
  113973. if(_floor_P[ci->floor_type[i]]->pack)
  113974. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113975. else
  113976. goto err_out;
  113977. }
  113978. /* residues */
  113979. oggpack_write(opb,ci->residues-1,6);
  113980. for(i=0;i<ci->residues;i++){
  113981. oggpack_write(opb,ci->residue_type[i],16);
  113982. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113983. }
  113984. /* maps */
  113985. oggpack_write(opb,ci->maps-1,6);
  113986. for(i=0;i<ci->maps;i++){
  113987. oggpack_write(opb,ci->map_type[i],16);
  113988. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113989. }
  113990. /* modes */
  113991. oggpack_write(opb,ci->modes-1,6);
  113992. for(i=0;i<ci->modes;i++){
  113993. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113994. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113995. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113996. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113997. }
  113998. oggpack_write(opb,1,1);
  113999. return(0);
  114000. err_out:
  114001. return(-1);
  114002. }
  114003. int vorbis_commentheader_out(vorbis_comment *vc,
  114004. ogg_packet *op){
  114005. oggpack_buffer opb;
  114006. oggpack_writeinit(&opb);
  114007. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114008. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114009. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114010. op->bytes=oggpack_bytes(&opb);
  114011. op->b_o_s=0;
  114012. op->e_o_s=0;
  114013. op->granulepos=0;
  114014. op->packetno=1;
  114015. return 0;
  114016. }
  114017. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114018. vorbis_comment *vc,
  114019. ogg_packet *op,
  114020. ogg_packet *op_comm,
  114021. ogg_packet *op_code){
  114022. int ret=OV_EIMPL;
  114023. vorbis_info *vi=v->vi;
  114024. oggpack_buffer opb;
  114025. private_state *b=(private_state*)v->backend_state;
  114026. if(!b){
  114027. ret=OV_EFAULT;
  114028. goto err_out;
  114029. }
  114030. /* first header packet **********************************************/
  114031. oggpack_writeinit(&opb);
  114032. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114033. /* build the packet */
  114034. if(b->header)_ogg_free(b->header);
  114035. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114036. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114037. op->packet=b->header;
  114038. op->bytes=oggpack_bytes(&opb);
  114039. op->b_o_s=1;
  114040. op->e_o_s=0;
  114041. op->granulepos=0;
  114042. op->packetno=0;
  114043. /* second header packet (comments) **********************************/
  114044. oggpack_reset(&opb);
  114045. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114046. if(b->header1)_ogg_free(b->header1);
  114047. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114048. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114049. op_comm->packet=b->header1;
  114050. op_comm->bytes=oggpack_bytes(&opb);
  114051. op_comm->b_o_s=0;
  114052. op_comm->e_o_s=0;
  114053. op_comm->granulepos=0;
  114054. op_comm->packetno=1;
  114055. /* third header packet (modes/codebooks) ****************************/
  114056. oggpack_reset(&opb);
  114057. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114058. if(b->header2)_ogg_free(b->header2);
  114059. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114060. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114061. op_code->packet=b->header2;
  114062. op_code->bytes=oggpack_bytes(&opb);
  114063. op_code->b_o_s=0;
  114064. op_code->e_o_s=0;
  114065. op_code->granulepos=0;
  114066. op_code->packetno=2;
  114067. oggpack_writeclear(&opb);
  114068. return(0);
  114069. err_out:
  114070. oggpack_writeclear(&opb);
  114071. memset(op,0,sizeof(*op));
  114072. memset(op_comm,0,sizeof(*op_comm));
  114073. memset(op_code,0,sizeof(*op_code));
  114074. if(b->header)_ogg_free(b->header);
  114075. if(b->header1)_ogg_free(b->header1);
  114076. if(b->header2)_ogg_free(b->header2);
  114077. b->header=NULL;
  114078. b->header1=NULL;
  114079. b->header2=NULL;
  114080. return(ret);
  114081. }
  114082. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114083. if(granulepos>=0)
  114084. return((double)granulepos/v->vi->rate);
  114085. return(-1);
  114086. }
  114087. #endif
  114088. /*** End of inlined file: info.c ***/
  114089. /*** Start of inlined file: lpc.c ***/
  114090. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114091. are derived from code written by Jutta Degener and Carsten Bormann;
  114092. thus we include their copyright below. The entirety of this file
  114093. is freely redistributable on the condition that both of these
  114094. copyright notices are preserved without modification. */
  114095. /* Preserved Copyright: *********************************************/
  114096. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114097. Technische Universita"t Berlin
  114098. Any use of this software is permitted provided that this notice is not
  114099. removed and that neither the authors nor the Technische Universita"t
  114100. Berlin are deemed to have made any representations as to the
  114101. suitability of this software for any purpose nor are held responsible
  114102. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114103. THIS SOFTWARE.
  114104. As a matter of courtesy, the authors request to be informed about uses
  114105. this software has found, about bugs in this software, and about any
  114106. improvements that may be of general interest.
  114107. Berlin, 28.11.1994
  114108. Jutta Degener
  114109. Carsten Bormann
  114110. *********************************************************************/
  114111. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114112. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114113. // tasks..
  114114. #if JUCE_MSVC
  114115. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114116. #endif
  114117. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114118. #if JUCE_USE_OGGVORBIS
  114119. #include <stdlib.h>
  114120. #include <string.h>
  114121. #include <math.h>
  114122. /* Autocorrelation LPC coeff generation algorithm invented by
  114123. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114124. /* Input : n elements of time doamin data
  114125. Output: m lpc coefficients, excitation energy */
  114126. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114127. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114128. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114129. double error;
  114130. int i,j;
  114131. /* autocorrelation, p+1 lag coefficients */
  114132. j=m+1;
  114133. while(j--){
  114134. double d=0; /* double needed for accumulator depth */
  114135. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114136. aut[j]=d;
  114137. }
  114138. /* Generate lpc coefficients from autocorr values */
  114139. error=aut[0];
  114140. for(i=0;i<m;i++){
  114141. double r= -aut[i+1];
  114142. if(error==0){
  114143. memset(lpci,0,m*sizeof(*lpci));
  114144. return 0;
  114145. }
  114146. /* Sum up this iteration's reflection coefficient; note that in
  114147. Vorbis we don't save it. If anyone wants to recycle this code
  114148. and needs reflection coefficients, save the results of 'r' from
  114149. each iteration. */
  114150. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114151. r/=error;
  114152. /* Update LPC coefficients and total error */
  114153. lpc[i]=r;
  114154. for(j=0;j<i/2;j++){
  114155. double tmp=lpc[j];
  114156. lpc[j]+=r*lpc[i-1-j];
  114157. lpc[i-1-j]+=r*tmp;
  114158. }
  114159. if(i%2)lpc[j]+=lpc[j]*r;
  114160. error*=1.f-r*r;
  114161. }
  114162. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114163. /* we need the error value to know how big an impulse to hit the
  114164. filter with later */
  114165. return error;
  114166. }
  114167. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114168. float *data,long n){
  114169. /* in: coeff[0...m-1] LPC coefficients
  114170. prime[0...m-1] initial values (allocated size of n+m-1)
  114171. out: data[0...n-1] data samples */
  114172. long i,j,o,p;
  114173. float y;
  114174. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114175. if(!prime)
  114176. for(i=0;i<m;i++)
  114177. work[i]=0.f;
  114178. else
  114179. for(i=0;i<m;i++)
  114180. work[i]=prime[i];
  114181. for(i=0;i<n;i++){
  114182. y=0;
  114183. o=i;
  114184. p=m;
  114185. for(j=0;j<m;j++)
  114186. y-=work[o++]*coeff[--p];
  114187. data[i]=work[o]=y;
  114188. }
  114189. }
  114190. #endif
  114191. /*** End of inlined file: lpc.c ***/
  114192. /*** Start of inlined file: lsp.c ***/
  114193. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114194. an iterative root polisher (CACM algorithm 283). It *is* possible
  114195. to confuse this algorithm into not converging; that should only
  114196. happen with absurdly closely spaced roots (very sharp peaks in the
  114197. LPC f response) which in turn should be impossible in our use of
  114198. the code. If this *does* happen anyway, it's a bug in the floor
  114199. finder; find the cause of the confusion (probably a single bin
  114200. spike or accidental near-float-limit resolution problems) and
  114201. correct it. */
  114202. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114203. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114204. // tasks..
  114205. #if JUCE_MSVC
  114206. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114207. #endif
  114208. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114209. #if JUCE_USE_OGGVORBIS
  114210. #include <math.h>
  114211. #include <string.h>
  114212. #include <stdlib.h>
  114213. /*** Start of inlined file: lookup.h ***/
  114214. #ifndef _V_LOOKUP_H_
  114215. #ifdef FLOAT_LOOKUP
  114216. extern float vorbis_coslook(float a);
  114217. extern float vorbis_invsqlook(float a);
  114218. extern float vorbis_invsq2explook(int a);
  114219. extern float vorbis_fromdBlook(float a);
  114220. #endif
  114221. #ifdef INT_LOOKUP
  114222. extern long vorbis_invsqlook_i(long a,long e);
  114223. extern long vorbis_coslook_i(long a);
  114224. extern float vorbis_fromdBlook_i(long a);
  114225. #endif
  114226. #endif
  114227. /*** End of inlined file: lookup.h ***/
  114228. /* three possible LSP to f curve functions; the exact computation
  114229. (float), a lookup based float implementation, and an integer
  114230. implementation. The float lookup is likely the optimal choice on
  114231. any machine with an FPU. The integer implementation is *not* fixed
  114232. point (due to the need for a large dynamic range and thus a
  114233. seperately tracked exponent) and thus much more complex than the
  114234. relatively simple float implementations. It's mostly for future
  114235. work on a fully fixed point implementation for processors like the
  114236. ARM family. */
  114237. /* undefine both for the 'old' but more precise implementation */
  114238. #define FLOAT_LOOKUP
  114239. #undef INT_LOOKUP
  114240. #ifdef FLOAT_LOOKUP
  114241. /*** Start of inlined file: lookup.c ***/
  114242. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114243. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114244. // tasks..
  114245. #if JUCE_MSVC
  114246. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114247. #endif
  114248. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114249. #if JUCE_USE_OGGVORBIS
  114250. #include <math.h>
  114251. /*** Start of inlined file: lookup.h ***/
  114252. #ifndef _V_LOOKUP_H_
  114253. #ifdef FLOAT_LOOKUP
  114254. extern float vorbis_coslook(float a);
  114255. extern float vorbis_invsqlook(float a);
  114256. extern float vorbis_invsq2explook(int a);
  114257. extern float vorbis_fromdBlook(float a);
  114258. #endif
  114259. #ifdef INT_LOOKUP
  114260. extern long vorbis_invsqlook_i(long a,long e);
  114261. extern long vorbis_coslook_i(long a);
  114262. extern float vorbis_fromdBlook_i(long a);
  114263. #endif
  114264. #endif
  114265. /*** End of inlined file: lookup.h ***/
  114266. /*** Start of inlined file: lookup_data.h ***/
  114267. #ifndef _V_LOOKUP_DATA_H_
  114268. #ifdef FLOAT_LOOKUP
  114269. #define COS_LOOKUP_SZ 128
  114270. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114271. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114272. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114273. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114274. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114275. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114276. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114277. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114278. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114279. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114280. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114281. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114282. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114283. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114284. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114285. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114286. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114287. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114288. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114289. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114290. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114291. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114292. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114293. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114294. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114295. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114296. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114297. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114298. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114299. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114300. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114301. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114302. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114303. -1.0000000000000f,
  114304. };
  114305. #define INVSQ_LOOKUP_SZ 32
  114306. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114307. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114308. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114309. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114310. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114311. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114312. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114313. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114314. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114315. 1.000000000000f,
  114316. };
  114317. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114318. #define INVSQ2EXP_LOOKUP_MAX 32
  114319. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114320. INVSQ2EXP_LOOKUP_MIN+1]={
  114321. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114322. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114323. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114324. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114325. 256.f, 181.019336f, 128.f, 90.50966799f,
  114326. 64.f, 45.254834f, 32.f, 22.627417f,
  114327. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114328. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114329. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114330. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114331. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114332. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114333. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114334. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114335. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114336. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114337. 1.525878906e-05f,
  114338. };
  114339. #endif
  114340. #define FROMdB_LOOKUP_SZ 35
  114341. #define FROMdB2_LOOKUP_SZ 32
  114342. #define FROMdB_SHIFT 5
  114343. #define FROMdB2_SHIFT 3
  114344. #define FROMdB2_MASK 31
  114345. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114346. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114347. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114348. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114349. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114350. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114351. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114352. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114353. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114354. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114355. };
  114356. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114357. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114358. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114359. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114360. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114361. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114362. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114363. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114364. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114365. };
  114366. #ifdef INT_LOOKUP
  114367. #define INVSQ_LOOKUP_I_SHIFT 10
  114368. #define INVSQ_LOOKUP_I_MASK 1023
  114369. static long INVSQ_LOOKUP_I[64+1]={
  114370. 92682l, 91966l, 91267l, 90583l,
  114371. 89915l, 89261l, 88621l, 87995l,
  114372. 87381l, 86781l, 86192l, 85616l,
  114373. 85051l, 84497l, 83953l, 83420l,
  114374. 82897l, 82384l, 81880l, 81385l,
  114375. 80899l, 80422l, 79953l, 79492l,
  114376. 79039l, 78594l, 78156l, 77726l,
  114377. 77302l, 76885l, 76475l, 76072l,
  114378. 75674l, 75283l, 74898l, 74519l,
  114379. 74146l, 73778l, 73415l, 73058l,
  114380. 72706l, 72359l, 72016l, 71679l,
  114381. 71347l, 71019l, 70695l, 70376l,
  114382. 70061l, 69750l, 69444l, 69141l,
  114383. 68842l, 68548l, 68256l, 67969l,
  114384. 67685l, 67405l, 67128l, 66855l,
  114385. 66585l, 66318l, 66054l, 65794l,
  114386. 65536l,
  114387. };
  114388. #define COS_LOOKUP_I_SHIFT 9
  114389. #define COS_LOOKUP_I_MASK 511
  114390. #define COS_LOOKUP_I_SZ 128
  114391. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114392. 16384l, 16379l, 16364l, 16340l,
  114393. 16305l, 16261l, 16207l, 16143l,
  114394. 16069l, 15986l, 15893l, 15791l,
  114395. 15679l, 15557l, 15426l, 15286l,
  114396. 15137l, 14978l, 14811l, 14635l,
  114397. 14449l, 14256l, 14053l, 13842l,
  114398. 13623l, 13395l, 13160l, 12916l,
  114399. 12665l, 12406l, 12140l, 11866l,
  114400. 11585l, 11297l, 11003l, 10702l,
  114401. 10394l, 10080l, 9760l, 9434l,
  114402. 9102l, 8765l, 8423l, 8076l,
  114403. 7723l, 7366l, 7005l, 6639l,
  114404. 6270l, 5897l, 5520l, 5139l,
  114405. 4756l, 4370l, 3981l, 3590l,
  114406. 3196l, 2801l, 2404l, 2006l,
  114407. 1606l, 1205l, 804l, 402l,
  114408. 0l, -401l, -803l, -1204l,
  114409. -1605l, -2005l, -2403l, -2800l,
  114410. -3195l, -3589l, -3980l, -4369l,
  114411. -4755l, -5138l, -5519l, -5896l,
  114412. -6269l, -6638l, -7004l, -7365l,
  114413. -7722l, -8075l, -8422l, -8764l,
  114414. -9101l, -9433l, -9759l, -10079l,
  114415. -10393l, -10701l, -11002l, -11296l,
  114416. -11584l, -11865l, -12139l, -12405l,
  114417. -12664l, -12915l, -13159l, -13394l,
  114418. -13622l, -13841l, -14052l, -14255l,
  114419. -14448l, -14634l, -14810l, -14977l,
  114420. -15136l, -15285l, -15425l, -15556l,
  114421. -15678l, -15790l, -15892l, -15985l,
  114422. -16068l, -16142l, -16206l, -16260l,
  114423. -16304l, -16339l, -16363l, -16378l,
  114424. -16383l,
  114425. };
  114426. #endif
  114427. #endif
  114428. /*** End of inlined file: lookup_data.h ***/
  114429. #ifdef FLOAT_LOOKUP
  114430. /* interpolated lookup based cos function, domain 0 to PI only */
  114431. float vorbis_coslook(float a){
  114432. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114433. int i=vorbis_ftoi(d-.5);
  114434. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114435. }
  114436. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114437. float vorbis_invsqlook(float a){
  114438. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114439. int i=vorbis_ftoi(d-.5f);
  114440. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114441. }
  114442. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114443. float vorbis_invsq2explook(int a){
  114444. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114445. }
  114446. #include <stdio.h>
  114447. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114448. float vorbis_fromdBlook(float a){
  114449. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114450. return (i<0)?1.f:
  114451. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114452. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114453. }
  114454. #endif
  114455. #ifdef INT_LOOKUP
  114456. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114457. 16.16 format
  114458. returns in m.8 format */
  114459. long vorbis_invsqlook_i(long a,long e){
  114460. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114461. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114462. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114463. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114464. d)>>16); /* result 1.16 */
  114465. e+=32;
  114466. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114467. e=(e>>1)-8;
  114468. return(val>>e);
  114469. }
  114470. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114471. /* a is in n.12 format */
  114472. float vorbis_fromdBlook_i(long a){
  114473. int i=(-a)>>(12-FROMdB2_SHIFT);
  114474. return (i<0)?1.f:
  114475. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114476. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114477. }
  114478. /* interpolated lookup based cos function, domain 0 to PI only */
  114479. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114480. long vorbis_coslook_i(long a){
  114481. int i=a>>COS_LOOKUP_I_SHIFT;
  114482. int d=a&COS_LOOKUP_I_MASK;
  114483. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114484. COS_LOOKUP_I_SHIFT);
  114485. }
  114486. #endif
  114487. #endif
  114488. /*** End of inlined file: lookup.c ***/
  114489. /* catch this in the build system; we #include for
  114490. compilers (like gcc) that can't inline across
  114491. modules */
  114492. /* side effect: changes *lsp to cosines of lsp */
  114493. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114494. float amp,float ampoffset){
  114495. int i;
  114496. float wdel=M_PI/ln;
  114497. vorbis_fpu_control fpu;
  114498. (void) fpu; // to avoid an unused variable warning
  114499. vorbis_fpu_setround(&fpu);
  114500. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114501. i=0;
  114502. while(i<n){
  114503. int k=map[i];
  114504. int qexp;
  114505. float p=.7071067812f;
  114506. float q=.7071067812f;
  114507. float w=vorbis_coslook(wdel*k);
  114508. float *ftmp=lsp;
  114509. int c=m>>1;
  114510. do{
  114511. q*=ftmp[0]-w;
  114512. p*=ftmp[1]-w;
  114513. ftmp+=2;
  114514. }while(--c);
  114515. if(m&1){
  114516. /* odd order filter; slightly assymetric */
  114517. /* the last coefficient */
  114518. q*=ftmp[0]-w;
  114519. q*=q;
  114520. p*=p*(1.f-w*w);
  114521. }else{
  114522. /* even order filter; still symmetric */
  114523. q*=q*(1.f+w);
  114524. p*=p*(1.f-w);
  114525. }
  114526. q=frexp(p+q,&qexp);
  114527. q=vorbis_fromdBlook(amp*
  114528. vorbis_invsqlook(q)*
  114529. vorbis_invsq2explook(qexp+m)-
  114530. ampoffset);
  114531. do{
  114532. curve[i++]*=q;
  114533. }while(map[i]==k);
  114534. }
  114535. vorbis_fpu_restore(fpu);
  114536. }
  114537. #else
  114538. #ifdef INT_LOOKUP
  114539. /*** Start of inlined file: lookup.c ***/
  114540. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114541. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114542. // tasks..
  114543. #if JUCE_MSVC
  114544. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114545. #endif
  114546. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114547. #if JUCE_USE_OGGVORBIS
  114548. #include <math.h>
  114549. /*** Start of inlined file: lookup.h ***/
  114550. #ifndef _V_LOOKUP_H_
  114551. #ifdef FLOAT_LOOKUP
  114552. extern float vorbis_coslook(float a);
  114553. extern float vorbis_invsqlook(float a);
  114554. extern float vorbis_invsq2explook(int a);
  114555. extern float vorbis_fromdBlook(float a);
  114556. #endif
  114557. #ifdef INT_LOOKUP
  114558. extern long vorbis_invsqlook_i(long a,long e);
  114559. extern long vorbis_coslook_i(long a);
  114560. extern float vorbis_fromdBlook_i(long a);
  114561. #endif
  114562. #endif
  114563. /*** End of inlined file: lookup.h ***/
  114564. /*** Start of inlined file: lookup_data.h ***/
  114565. #ifndef _V_LOOKUP_DATA_H_
  114566. #ifdef FLOAT_LOOKUP
  114567. #define COS_LOOKUP_SZ 128
  114568. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114569. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114570. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114571. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114572. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114573. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114574. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114575. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114576. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114577. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114578. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114579. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114580. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114581. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114582. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114583. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114584. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114585. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114586. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114587. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114588. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114589. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114590. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114591. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114592. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114593. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114594. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114595. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114596. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114597. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114598. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114599. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114600. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114601. -1.0000000000000f,
  114602. };
  114603. #define INVSQ_LOOKUP_SZ 32
  114604. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114605. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114606. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114607. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114608. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114609. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114610. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114611. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114612. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114613. 1.000000000000f,
  114614. };
  114615. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114616. #define INVSQ2EXP_LOOKUP_MAX 32
  114617. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114618. INVSQ2EXP_LOOKUP_MIN+1]={
  114619. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114620. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114621. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114622. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114623. 256.f, 181.019336f, 128.f, 90.50966799f,
  114624. 64.f, 45.254834f, 32.f, 22.627417f,
  114625. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114626. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114627. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114628. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114629. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114630. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114631. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114632. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114633. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114634. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114635. 1.525878906e-05f,
  114636. };
  114637. #endif
  114638. #define FROMdB_LOOKUP_SZ 35
  114639. #define FROMdB2_LOOKUP_SZ 32
  114640. #define FROMdB_SHIFT 5
  114641. #define FROMdB2_SHIFT 3
  114642. #define FROMdB2_MASK 31
  114643. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114644. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114645. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114646. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114647. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114648. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114649. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114650. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114651. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114652. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114653. };
  114654. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114655. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114656. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114657. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114658. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114659. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114660. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114661. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114662. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114663. };
  114664. #ifdef INT_LOOKUP
  114665. #define INVSQ_LOOKUP_I_SHIFT 10
  114666. #define INVSQ_LOOKUP_I_MASK 1023
  114667. static long INVSQ_LOOKUP_I[64+1]={
  114668. 92682l, 91966l, 91267l, 90583l,
  114669. 89915l, 89261l, 88621l, 87995l,
  114670. 87381l, 86781l, 86192l, 85616l,
  114671. 85051l, 84497l, 83953l, 83420l,
  114672. 82897l, 82384l, 81880l, 81385l,
  114673. 80899l, 80422l, 79953l, 79492l,
  114674. 79039l, 78594l, 78156l, 77726l,
  114675. 77302l, 76885l, 76475l, 76072l,
  114676. 75674l, 75283l, 74898l, 74519l,
  114677. 74146l, 73778l, 73415l, 73058l,
  114678. 72706l, 72359l, 72016l, 71679l,
  114679. 71347l, 71019l, 70695l, 70376l,
  114680. 70061l, 69750l, 69444l, 69141l,
  114681. 68842l, 68548l, 68256l, 67969l,
  114682. 67685l, 67405l, 67128l, 66855l,
  114683. 66585l, 66318l, 66054l, 65794l,
  114684. 65536l,
  114685. };
  114686. #define COS_LOOKUP_I_SHIFT 9
  114687. #define COS_LOOKUP_I_MASK 511
  114688. #define COS_LOOKUP_I_SZ 128
  114689. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114690. 16384l, 16379l, 16364l, 16340l,
  114691. 16305l, 16261l, 16207l, 16143l,
  114692. 16069l, 15986l, 15893l, 15791l,
  114693. 15679l, 15557l, 15426l, 15286l,
  114694. 15137l, 14978l, 14811l, 14635l,
  114695. 14449l, 14256l, 14053l, 13842l,
  114696. 13623l, 13395l, 13160l, 12916l,
  114697. 12665l, 12406l, 12140l, 11866l,
  114698. 11585l, 11297l, 11003l, 10702l,
  114699. 10394l, 10080l, 9760l, 9434l,
  114700. 9102l, 8765l, 8423l, 8076l,
  114701. 7723l, 7366l, 7005l, 6639l,
  114702. 6270l, 5897l, 5520l, 5139l,
  114703. 4756l, 4370l, 3981l, 3590l,
  114704. 3196l, 2801l, 2404l, 2006l,
  114705. 1606l, 1205l, 804l, 402l,
  114706. 0l, -401l, -803l, -1204l,
  114707. -1605l, -2005l, -2403l, -2800l,
  114708. -3195l, -3589l, -3980l, -4369l,
  114709. -4755l, -5138l, -5519l, -5896l,
  114710. -6269l, -6638l, -7004l, -7365l,
  114711. -7722l, -8075l, -8422l, -8764l,
  114712. -9101l, -9433l, -9759l, -10079l,
  114713. -10393l, -10701l, -11002l, -11296l,
  114714. -11584l, -11865l, -12139l, -12405l,
  114715. -12664l, -12915l, -13159l, -13394l,
  114716. -13622l, -13841l, -14052l, -14255l,
  114717. -14448l, -14634l, -14810l, -14977l,
  114718. -15136l, -15285l, -15425l, -15556l,
  114719. -15678l, -15790l, -15892l, -15985l,
  114720. -16068l, -16142l, -16206l, -16260l,
  114721. -16304l, -16339l, -16363l, -16378l,
  114722. -16383l,
  114723. };
  114724. #endif
  114725. #endif
  114726. /*** End of inlined file: lookup_data.h ***/
  114727. #ifdef FLOAT_LOOKUP
  114728. /* interpolated lookup based cos function, domain 0 to PI only */
  114729. float vorbis_coslook(float a){
  114730. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114731. int i=vorbis_ftoi(d-.5);
  114732. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114733. }
  114734. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114735. float vorbis_invsqlook(float a){
  114736. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114737. int i=vorbis_ftoi(d-.5f);
  114738. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114739. }
  114740. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114741. float vorbis_invsq2explook(int a){
  114742. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114743. }
  114744. #include <stdio.h>
  114745. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114746. float vorbis_fromdBlook(float a){
  114747. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114748. return (i<0)?1.f:
  114749. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114750. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114751. }
  114752. #endif
  114753. #ifdef INT_LOOKUP
  114754. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114755. 16.16 format
  114756. returns in m.8 format */
  114757. long vorbis_invsqlook_i(long a,long e){
  114758. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114759. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114760. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114761. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114762. d)>>16); /* result 1.16 */
  114763. e+=32;
  114764. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114765. e=(e>>1)-8;
  114766. return(val>>e);
  114767. }
  114768. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114769. /* a is in n.12 format */
  114770. float vorbis_fromdBlook_i(long a){
  114771. int i=(-a)>>(12-FROMdB2_SHIFT);
  114772. return (i<0)?1.f:
  114773. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114774. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114775. }
  114776. /* interpolated lookup based cos function, domain 0 to PI only */
  114777. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114778. long vorbis_coslook_i(long a){
  114779. int i=a>>COS_LOOKUP_I_SHIFT;
  114780. int d=a&COS_LOOKUP_I_MASK;
  114781. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114782. COS_LOOKUP_I_SHIFT);
  114783. }
  114784. #endif
  114785. #endif
  114786. /*** End of inlined file: lookup.c ***/
  114787. /* catch this in the build system; we #include for
  114788. compilers (like gcc) that can't inline across
  114789. modules */
  114790. static int MLOOP_1[64]={
  114791. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114792. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114793. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114794. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114795. };
  114796. static int MLOOP_2[64]={
  114797. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114798. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114799. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114800. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114801. };
  114802. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114803. /* side effect: changes *lsp to cosines of lsp */
  114804. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114805. float amp,float ampoffset){
  114806. /* 0 <= m < 256 */
  114807. /* set up for using all int later */
  114808. int i;
  114809. int ampoffseti=rint(ampoffset*4096.f);
  114810. int ampi=rint(amp*16.f);
  114811. long *ilsp=alloca(m*sizeof(*ilsp));
  114812. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114813. i=0;
  114814. while(i<n){
  114815. int j,k=map[i];
  114816. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114817. unsigned long qi=46341;
  114818. int qexp=0,shift;
  114819. long wi=vorbis_coslook_i(k*65536/ln);
  114820. qi*=labs(ilsp[0]-wi);
  114821. pi*=labs(ilsp[1]-wi);
  114822. for(j=3;j<m;j+=2){
  114823. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114824. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114825. shift=MLOOP_3[(pi|qi)>>16];
  114826. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114827. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114828. qexp+=shift;
  114829. }
  114830. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114831. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114832. shift=MLOOP_3[(pi|qi)>>16];
  114833. /* pi,qi normalized collectively, both tracked using qexp */
  114834. if(m&1){
  114835. /* odd order filter; slightly assymetric */
  114836. /* the last coefficient */
  114837. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114838. pi=(pi>>shift)<<14;
  114839. qexp+=shift;
  114840. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114841. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114842. shift=MLOOP_3[(pi|qi)>>16];
  114843. pi>>=shift;
  114844. qi>>=shift;
  114845. qexp+=shift-14*((m+1)>>1);
  114846. pi=((pi*pi)>>16);
  114847. qi=((qi*qi)>>16);
  114848. qexp=qexp*2+m;
  114849. pi*=(1<<14)-((wi*wi)>>14);
  114850. qi+=pi>>14;
  114851. }else{
  114852. /* even order filter; still symmetric */
  114853. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114854. worth tracking step by step */
  114855. pi>>=shift;
  114856. qi>>=shift;
  114857. qexp+=shift-7*m;
  114858. pi=((pi*pi)>>16);
  114859. qi=((qi*qi)>>16);
  114860. qexp=qexp*2+m;
  114861. pi*=(1<<14)-wi;
  114862. qi*=(1<<14)+wi;
  114863. qi=(qi+pi)>>14;
  114864. }
  114865. /* we've let the normalization drift because it wasn't important;
  114866. however, for the lookup, things must be normalized again. We
  114867. need at most one right shift or a number of left shifts */
  114868. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114869. qi>>=1; qexp++;
  114870. }else
  114871. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114872. qi<<=1; qexp--;
  114873. }
  114874. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114875. vorbis_invsqlook_i(qi,qexp)-
  114876. /* m.8, m+n<=8 */
  114877. ampoffseti); /* 8.12[0] */
  114878. curve[i]*=amp;
  114879. while(map[++i]==k)curve[i]*=amp;
  114880. }
  114881. }
  114882. #else
  114883. /* old, nonoptimized but simple version for any poor sap who needs to
  114884. figure out what the hell this code does, or wants the other
  114885. fraction of a dB precision */
  114886. /* side effect: changes *lsp to cosines of lsp */
  114887. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114888. float amp,float ampoffset){
  114889. int i;
  114890. float wdel=M_PI/ln;
  114891. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114892. i=0;
  114893. while(i<n){
  114894. int j,k=map[i];
  114895. float p=.5f;
  114896. float q=.5f;
  114897. float w=2.f*cos(wdel*k);
  114898. for(j=1;j<m;j+=2){
  114899. q *= w-lsp[j-1];
  114900. p *= w-lsp[j];
  114901. }
  114902. if(j==m){
  114903. /* odd order filter; slightly assymetric */
  114904. /* the last coefficient */
  114905. q*=w-lsp[j-1];
  114906. p*=p*(4.f-w*w);
  114907. q*=q;
  114908. }else{
  114909. /* even order filter; still symmetric */
  114910. p*=p*(2.f-w);
  114911. q*=q*(2.f+w);
  114912. }
  114913. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114914. curve[i]*=q;
  114915. while(map[++i]==k)curve[i]*=q;
  114916. }
  114917. }
  114918. #endif
  114919. #endif
  114920. static void cheby(float *g, int ord) {
  114921. int i, j;
  114922. g[0] *= .5f;
  114923. for(i=2; i<= ord; i++) {
  114924. for(j=ord; j >= i; j--) {
  114925. g[j-2] -= g[j];
  114926. g[j] += g[j];
  114927. }
  114928. }
  114929. }
  114930. static int JUCE_CDECL comp(const void *a,const void *b){
  114931. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114932. }
  114933. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114934. but there are root sets for which it gets into limit cycles
  114935. (exacerbated by zero suppression) and fails. We can't afford to
  114936. fail, even if the failure is 1 in 100,000,000, so we now use
  114937. Laguerre and later polish with Newton-Raphson (which can then
  114938. afford to fail) */
  114939. #define EPSILON 10e-7
  114940. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114941. int i,m;
  114942. double lastdelta=0.f;
  114943. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114944. for(i=0;i<=ord;i++)defl[i]=a[i];
  114945. for(m=ord;m>0;m--){
  114946. double newx=0.f,delta;
  114947. /* iterate a root */
  114948. while(1){
  114949. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114950. /* eval the polynomial and its first two derivatives */
  114951. for(i=m;i>0;i--){
  114952. ppp = newx*ppp + pp;
  114953. pp = newx*pp + p;
  114954. p = newx*p + defl[i-1];
  114955. }
  114956. /* Laguerre's method */
  114957. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114958. if(denom<0)
  114959. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114960. if(pp>0){
  114961. denom = pp + sqrt(denom);
  114962. if(denom<EPSILON)denom=EPSILON;
  114963. }else{
  114964. denom = pp - sqrt(denom);
  114965. if(denom>-(EPSILON))denom=-(EPSILON);
  114966. }
  114967. delta = m*p/denom;
  114968. newx -= delta;
  114969. if(delta<0.f)delta*=-1;
  114970. if(fabs(delta/newx)<10e-12)break;
  114971. lastdelta=delta;
  114972. }
  114973. r[m-1]=newx;
  114974. /* forward deflation */
  114975. for(i=m;i>0;i--)
  114976. defl[i-1]+=newx*defl[i];
  114977. defl++;
  114978. }
  114979. return(0);
  114980. }
  114981. /* for spit-and-polish only */
  114982. static int Newton_Raphson(float *a,int ord,float *r){
  114983. int i, k, count=0;
  114984. double error=1.f;
  114985. double *root=(double*)alloca(ord*sizeof(*root));
  114986. for(i=0; i<ord;i++) root[i] = r[i];
  114987. while(error>1e-20){
  114988. error=0;
  114989. for(i=0; i<ord; i++) { /* Update each point. */
  114990. double pp=0.,delta;
  114991. double rooti=root[i];
  114992. double p=a[ord];
  114993. for(k=ord-1; k>= 0; k--) {
  114994. pp= pp* rooti + p;
  114995. p = p * rooti + a[k];
  114996. }
  114997. delta = p/pp;
  114998. root[i] -= delta;
  114999. error+= delta*delta;
  115000. }
  115001. if(count>40)return(-1);
  115002. count++;
  115003. }
  115004. /* Replaced the original bubble sort with a real sort. With your
  115005. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115006. for(i=0; i<ord;i++) r[i] = root[i];
  115007. return(0);
  115008. }
  115009. /* Convert lpc coefficients to lsp coefficients */
  115010. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115011. int order2=(m+1)>>1;
  115012. int g1_order,g2_order;
  115013. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115014. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115015. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115016. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115017. int i;
  115018. /* even and odd are slightly different base cases */
  115019. g1_order=(m+1)>>1;
  115020. g2_order=(m) >>1;
  115021. /* Compute the lengths of the x polynomials. */
  115022. /* Compute the first half of K & R F1 & F2 polynomials. */
  115023. /* Compute half of the symmetric and antisymmetric polynomials. */
  115024. /* Remove the roots at +1 and -1. */
  115025. g1[g1_order] = 1.f;
  115026. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115027. g2[g2_order] = 1.f;
  115028. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115029. if(g1_order>g2_order){
  115030. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115031. }else{
  115032. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115033. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115034. }
  115035. /* Convert into polynomials in cos(alpha) */
  115036. cheby(g1,g1_order);
  115037. cheby(g2,g2_order);
  115038. /* Find the roots of the 2 even polynomials.*/
  115039. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115040. Laguerre_With_Deflation(g2,g2_order,g2r))
  115041. return(-1);
  115042. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115043. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115044. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115045. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115046. for(i=0;i<g1_order;i++)
  115047. lsp[i*2] = acos(g1r[i]);
  115048. for(i=0;i<g2_order;i++)
  115049. lsp[i*2+1] = acos(g2r[i]);
  115050. return(0);
  115051. }
  115052. #endif
  115053. /*** End of inlined file: lsp.c ***/
  115054. /*** Start of inlined file: mapping0.c ***/
  115055. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115056. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115057. // tasks..
  115058. #if JUCE_MSVC
  115059. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115060. #endif
  115061. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115062. #if JUCE_USE_OGGVORBIS
  115063. #include <stdlib.h>
  115064. #include <stdio.h>
  115065. #include <string.h>
  115066. #include <math.h>
  115067. /* simplistic, wasteful way of doing this (unique lookup for each
  115068. mode/submapping); there should be a central repository for
  115069. identical lookups. That will require minor work, so I'm putting it
  115070. off as low priority.
  115071. Why a lookup for each backend in a given mode? Because the
  115072. blocksize is set by the mode, and low backend lookups may require
  115073. parameters from other areas of the mode/mapping */
  115074. static void mapping0_free_info(vorbis_info_mapping *i){
  115075. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115076. if(info){
  115077. memset(info,0,sizeof(*info));
  115078. _ogg_free(info);
  115079. }
  115080. }
  115081. static int ilog3(unsigned int v){
  115082. int ret=0;
  115083. if(v)--v;
  115084. while(v){
  115085. ret++;
  115086. v>>=1;
  115087. }
  115088. return(ret);
  115089. }
  115090. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115091. oggpack_buffer *opb){
  115092. int i;
  115093. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115094. /* another 'we meant to do it this way' hack... up to beta 4, we
  115095. packed 4 binary zeros here to signify one submapping in use. We
  115096. now redefine that to mean four bitflags that indicate use of
  115097. deeper features; bit0:submappings, bit1:coupling,
  115098. bit2,3:reserved. This is backward compatable with all actual uses
  115099. of the beta code. */
  115100. if(info->submaps>1){
  115101. oggpack_write(opb,1,1);
  115102. oggpack_write(opb,info->submaps-1,4);
  115103. }else
  115104. oggpack_write(opb,0,1);
  115105. if(info->coupling_steps>0){
  115106. oggpack_write(opb,1,1);
  115107. oggpack_write(opb,info->coupling_steps-1,8);
  115108. for(i=0;i<info->coupling_steps;i++){
  115109. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115110. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115111. }
  115112. }else
  115113. oggpack_write(opb,0,1);
  115114. oggpack_write(opb,0,2); /* 2,3:reserved */
  115115. /* we don't write the channel submappings if we only have one... */
  115116. if(info->submaps>1){
  115117. for(i=0;i<vi->channels;i++)
  115118. oggpack_write(opb,info->chmuxlist[i],4);
  115119. }
  115120. for(i=0;i<info->submaps;i++){
  115121. oggpack_write(opb,0,8); /* time submap unused */
  115122. oggpack_write(opb,info->floorsubmap[i],8);
  115123. oggpack_write(opb,info->residuesubmap[i],8);
  115124. }
  115125. }
  115126. /* also responsible for range checking */
  115127. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115128. int i;
  115129. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115130. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115131. memset(info,0,sizeof(*info));
  115132. if(oggpack_read(opb,1))
  115133. info->submaps=oggpack_read(opb,4)+1;
  115134. else
  115135. info->submaps=1;
  115136. if(oggpack_read(opb,1)){
  115137. info->coupling_steps=oggpack_read(opb,8)+1;
  115138. for(i=0;i<info->coupling_steps;i++){
  115139. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115140. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115141. if(testM<0 ||
  115142. testA<0 ||
  115143. testM==testA ||
  115144. testM>=vi->channels ||
  115145. testA>=vi->channels) goto err_out;
  115146. }
  115147. }
  115148. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115149. if(info->submaps>1){
  115150. for(i=0;i<vi->channels;i++){
  115151. info->chmuxlist[i]=oggpack_read(opb,4);
  115152. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115153. }
  115154. }
  115155. for(i=0;i<info->submaps;i++){
  115156. oggpack_read(opb,8); /* time submap unused */
  115157. info->floorsubmap[i]=oggpack_read(opb,8);
  115158. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115159. info->residuesubmap[i]=oggpack_read(opb,8);
  115160. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115161. }
  115162. return info;
  115163. err_out:
  115164. mapping0_free_info(info);
  115165. return(NULL);
  115166. }
  115167. #if 0
  115168. static long seq=0;
  115169. static ogg_int64_t total=0;
  115170. static float FLOOR1_fromdB_LOOKUP[256]={
  115171. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115172. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115173. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115174. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115175. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115176. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115177. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115178. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115179. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115180. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115181. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115182. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115183. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115184. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115185. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115186. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115187. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115188. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115189. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115190. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115191. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115192. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115193. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115194. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115195. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115196. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115197. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115198. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115199. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115200. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115201. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115202. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115203. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115204. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115205. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115206. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115207. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115208. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115209. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115210. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115211. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115212. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115213. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115214. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115215. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115216. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115217. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115218. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115219. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115220. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115221. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115222. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115223. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115224. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115225. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115226. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115227. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115228. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115229. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115230. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115231. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115232. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115233. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115234. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115235. };
  115236. #endif
  115237. extern int *floor1_fit(vorbis_block *vb,void *look,
  115238. const float *logmdct, /* in */
  115239. const float *logmask);
  115240. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115241. int *A,int *B,
  115242. int del);
  115243. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115244. void*look,
  115245. int *post,int *ilogmask);
  115246. static int mapping0_forward(vorbis_block *vb){
  115247. vorbis_dsp_state *vd=vb->vd;
  115248. vorbis_info *vi=vd->vi;
  115249. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115250. private_state *b=(private_state*)vb->vd->backend_state;
  115251. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115252. int n=vb->pcmend;
  115253. int i,j,k;
  115254. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115255. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115256. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115257. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115258. float global_ampmax=vbi->ampmax;
  115259. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115260. int blocktype=vbi->blocktype;
  115261. int modenumber=vb->W;
  115262. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115263. vorbis_look_psy *psy_look=
  115264. b->psy+blocktype+(vb->W?2:0);
  115265. vb->mode=modenumber;
  115266. for(i=0;i<vi->channels;i++){
  115267. float scale=4.f/n;
  115268. float scale_dB;
  115269. float *pcm =vb->pcm[i];
  115270. float *logfft =pcm;
  115271. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115272. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115273. todB estimation used on IEEE 754
  115274. compliant machines had a bug that
  115275. returned dB values about a third
  115276. of a decibel too high. The bug
  115277. was harmless because tunings
  115278. implicitly took that into
  115279. account. However, fixing the bug
  115280. in the estimator requires
  115281. changing all the tunings as well.
  115282. For now, it's easier to sync
  115283. things back up here, and
  115284. recalibrate the tunings in the
  115285. next major model upgrade. */
  115286. #if 0
  115287. if(vi->channels==2)
  115288. if(i==0)
  115289. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115290. else
  115291. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115292. #endif
  115293. /* window the PCM data */
  115294. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115295. #if 0
  115296. if(vi->channels==2)
  115297. if(i==0)
  115298. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115299. else
  115300. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115301. #endif
  115302. /* transform the PCM data */
  115303. /* only MDCT right now.... */
  115304. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115305. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115306. drft_forward(&b->fft_look[vb->W],pcm);
  115307. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115308. original todB estimation used on
  115309. IEEE 754 compliant machines had a
  115310. bug that returned dB values about
  115311. a third of a decibel too high.
  115312. The bug was harmless because
  115313. tunings implicitly took that into
  115314. account. However, fixing the bug
  115315. in the estimator requires
  115316. changing all the tunings as well.
  115317. For now, it's easier to sync
  115318. things back up here, and
  115319. recalibrate the tunings in the
  115320. next major model upgrade. */
  115321. local_ampmax[i]=logfft[0];
  115322. for(j=1;j<n-1;j+=2){
  115323. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115324. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115325. .345 is a hack; the original todB
  115326. estimation used on IEEE 754
  115327. compliant machines had a bug that
  115328. returned dB values about a third
  115329. of a decibel too high. The bug
  115330. was harmless because tunings
  115331. implicitly took that into
  115332. account. However, fixing the bug
  115333. in the estimator requires
  115334. changing all the tunings as well.
  115335. For now, it's easier to sync
  115336. things back up here, and
  115337. recalibrate the tunings in the
  115338. next major model upgrade. */
  115339. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115340. }
  115341. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115342. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115343. #if 0
  115344. if(vi->channels==2){
  115345. if(i==0){
  115346. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115347. }else{
  115348. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115349. }
  115350. }
  115351. #endif
  115352. }
  115353. {
  115354. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115355. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115356. for(i=0;i<vi->channels;i++){
  115357. /* the encoder setup assumes that all the modes used by any
  115358. specific bitrate tweaking use the same floor */
  115359. int submap=info->chmuxlist[i];
  115360. /* the following makes things clearer to *me* anyway */
  115361. float *mdct =gmdct[i];
  115362. float *logfft =vb->pcm[i];
  115363. float *logmdct =logfft+n/2;
  115364. float *logmask =logfft;
  115365. vb->mode=modenumber;
  115366. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115367. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115368. for(j=0;j<n/2;j++)
  115369. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115370. todB estimation used on IEEE 754
  115371. compliant machines had a bug that
  115372. returned dB values about a third
  115373. of a decibel too high. The bug
  115374. was harmless because tunings
  115375. implicitly took that into
  115376. account. However, fixing the bug
  115377. in the estimator requires
  115378. changing all the tunings as well.
  115379. For now, it's easier to sync
  115380. things back up here, and
  115381. recalibrate the tunings in the
  115382. next major model upgrade. */
  115383. #if 0
  115384. if(vi->channels==2){
  115385. if(i==0)
  115386. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115387. else
  115388. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115389. }else{
  115390. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115391. }
  115392. #endif
  115393. /* first step; noise masking. Not only does 'noise masking'
  115394. give us curves from which we can decide how much resolution
  115395. to give noise parts of the spectrum, it also implicitly hands
  115396. us a tonality estimate (the larger the value in the
  115397. 'noise_depth' vector, the more tonal that area is) */
  115398. _vp_noisemask(psy_look,
  115399. logmdct,
  115400. noise); /* noise does not have by-frequency offset
  115401. bias applied yet */
  115402. #if 0
  115403. if(vi->channels==2){
  115404. if(i==0)
  115405. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115406. else
  115407. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115408. }
  115409. #endif
  115410. /* second step: 'all the other crap'; all the stuff that isn't
  115411. computed/fit for bitrate management goes in the second psy
  115412. vector. This includes tone masking, peak limiting and ATH */
  115413. _vp_tonemask(psy_look,
  115414. logfft,
  115415. tone,
  115416. global_ampmax,
  115417. local_ampmax[i]);
  115418. #if 0
  115419. if(vi->channels==2){
  115420. if(i==0)
  115421. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115422. else
  115423. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115424. }
  115425. #endif
  115426. /* third step; we offset the noise vectors, overlay tone
  115427. masking. We then do a floor1-specific line fit. If we're
  115428. performing bitrate management, the line fit is performed
  115429. multiple times for up/down tweakage on demand. */
  115430. #if 0
  115431. {
  115432. float aotuv[psy_look->n];
  115433. #endif
  115434. _vp_offset_and_mix(psy_look,
  115435. noise,
  115436. tone,
  115437. 1,
  115438. logmask,
  115439. mdct,
  115440. logmdct);
  115441. #if 0
  115442. if(vi->channels==2){
  115443. if(i==0)
  115444. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115445. else
  115446. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115447. }
  115448. }
  115449. #endif
  115450. #if 0
  115451. if(vi->channels==2){
  115452. if(i==0)
  115453. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115454. else
  115455. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115456. }
  115457. #endif
  115458. /* this algorithm is hardwired to floor 1 for now; abort out if
  115459. we're *not* floor1. This won't happen unless someone has
  115460. broken the encode setup lib. Guard it anyway. */
  115461. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115462. floor_posts[i][PACKETBLOBS/2]=
  115463. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115464. logmdct,
  115465. logmask);
  115466. /* are we managing bitrate? If so, perform two more fits for
  115467. later rate tweaking (fits represent hi/lo) */
  115468. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115469. /* higher rate by way of lower noise curve */
  115470. _vp_offset_and_mix(psy_look,
  115471. noise,
  115472. tone,
  115473. 2,
  115474. logmask,
  115475. mdct,
  115476. logmdct);
  115477. #if 0
  115478. if(vi->channels==2){
  115479. if(i==0)
  115480. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115481. else
  115482. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115483. }
  115484. #endif
  115485. floor_posts[i][PACKETBLOBS-1]=
  115486. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115487. logmdct,
  115488. logmask);
  115489. /* lower rate by way of higher noise curve */
  115490. _vp_offset_and_mix(psy_look,
  115491. noise,
  115492. tone,
  115493. 0,
  115494. logmask,
  115495. mdct,
  115496. logmdct);
  115497. #if 0
  115498. if(vi->channels==2)
  115499. if(i==0)
  115500. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115501. else
  115502. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115503. #endif
  115504. floor_posts[i][0]=
  115505. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115506. logmdct,
  115507. logmask);
  115508. /* we also interpolate a range of intermediate curves for
  115509. intermediate rates */
  115510. for(k=1;k<PACKETBLOBS/2;k++)
  115511. floor_posts[i][k]=
  115512. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115513. floor_posts[i][0],
  115514. floor_posts[i][PACKETBLOBS/2],
  115515. k*65536/(PACKETBLOBS/2));
  115516. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115517. floor_posts[i][k]=
  115518. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115519. floor_posts[i][PACKETBLOBS/2],
  115520. floor_posts[i][PACKETBLOBS-1],
  115521. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115522. }
  115523. }
  115524. }
  115525. vbi->ampmax=global_ampmax;
  115526. /*
  115527. the next phases are performed once for vbr-only and PACKETBLOB
  115528. times for bitrate managed modes.
  115529. 1) encode actual mode being used
  115530. 2) encode the floor for each channel, compute coded mask curve/res
  115531. 3) normalize and couple.
  115532. 4) encode residue
  115533. 5) save packet bytes to the packetblob vector
  115534. */
  115535. /* iterate over the many masking curve fits we've created */
  115536. {
  115537. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115538. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115539. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115540. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115541. float **mag_memo;
  115542. int **mag_sort;
  115543. if(info->coupling_steps){
  115544. mag_memo=_vp_quantize_couple_memo(vb,
  115545. &ci->psy_g_param,
  115546. psy_look,
  115547. info,
  115548. gmdct);
  115549. mag_sort=_vp_quantize_couple_sort(vb,
  115550. psy_look,
  115551. info,
  115552. mag_memo);
  115553. hf_reduction(&ci->psy_g_param,
  115554. psy_look,
  115555. info,
  115556. mag_memo);
  115557. }
  115558. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115559. if(psy_look->vi->normal_channel_p){
  115560. for(i=0;i<vi->channels;i++){
  115561. float *mdct =gmdct[i];
  115562. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115563. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115564. }
  115565. }
  115566. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115567. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115568. k++){
  115569. oggpack_buffer *opb=vbi->packetblob[k];
  115570. /* start out our new packet blob with packet type and mode */
  115571. /* Encode the packet type */
  115572. oggpack_write(opb,0,1);
  115573. /* Encode the modenumber */
  115574. /* Encode frame mode, pre,post windowsize, then dispatch */
  115575. oggpack_write(opb,modenumber,b->modebits);
  115576. if(vb->W){
  115577. oggpack_write(opb,vb->lW,1);
  115578. oggpack_write(opb,vb->nW,1);
  115579. }
  115580. /* encode floor, compute masking curve, sep out residue */
  115581. for(i=0;i<vi->channels;i++){
  115582. int submap=info->chmuxlist[i];
  115583. float *mdct =gmdct[i];
  115584. float *res =vb->pcm[i];
  115585. int *ilogmask=ilogmaskch[i]=
  115586. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115587. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115588. floor_posts[i][k],
  115589. ilogmask);
  115590. #if 0
  115591. {
  115592. char buf[80];
  115593. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115594. float work[n/2];
  115595. for(j=0;j<n/2;j++)
  115596. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115597. _analysis_output(buf,seq,work,n/2,1,1,0);
  115598. }
  115599. #endif
  115600. _vp_remove_floor(psy_look,
  115601. mdct,
  115602. ilogmask,
  115603. res,
  115604. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115605. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115606. #if 0
  115607. {
  115608. char buf[80];
  115609. float work[n/2];
  115610. for(j=0;j<n/2;j++)
  115611. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115612. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115613. _analysis_output(buf,seq,work,n/2,1,1,0);
  115614. }
  115615. #endif
  115616. }
  115617. /* our iteration is now based on masking curve, not prequant and
  115618. coupling. Only one prequant/coupling step */
  115619. /* quantize/couple */
  115620. /* incomplete implementation that assumes the tree is all depth
  115621. one, or no tree at all */
  115622. if(info->coupling_steps){
  115623. _vp_couple(k,
  115624. &ci->psy_g_param,
  115625. psy_look,
  115626. info,
  115627. vb->pcm,
  115628. mag_memo,
  115629. mag_sort,
  115630. ilogmaskch,
  115631. nonzero,
  115632. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115633. }
  115634. /* classify and encode by submap */
  115635. for(i=0;i<info->submaps;i++){
  115636. int ch_in_bundle=0;
  115637. long **classifications;
  115638. int resnum=info->residuesubmap[i];
  115639. for(j=0;j<vi->channels;j++){
  115640. if(info->chmuxlist[j]==i){
  115641. zerobundle[ch_in_bundle]=0;
  115642. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115643. res_bundle[ch_in_bundle]=vb->pcm[j];
  115644. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115645. }
  115646. }
  115647. classifications=_residue_P[ci->residue_type[resnum]]->
  115648. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115649. _residue_P[ci->residue_type[resnum]]->
  115650. forward(opb,vb,b->residue[resnum],
  115651. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115652. }
  115653. /* ok, done encoding. Next protopacket. */
  115654. }
  115655. }
  115656. #if 0
  115657. seq++;
  115658. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115659. #endif
  115660. return(0);
  115661. }
  115662. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115663. vorbis_dsp_state *vd=vb->vd;
  115664. vorbis_info *vi=vd->vi;
  115665. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115666. private_state *b=(private_state*)vd->backend_state;
  115667. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115668. int i,j;
  115669. long n=vb->pcmend=ci->blocksizes[vb->W];
  115670. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115671. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115672. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115673. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115674. /* recover the spectral envelope; store it in the PCM vector for now */
  115675. for(i=0;i<vi->channels;i++){
  115676. int submap=info->chmuxlist[i];
  115677. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115678. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115679. if(floormemo[i])
  115680. nonzero[i]=1;
  115681. else
  115682. nonzero[i]=0;
  115683. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115684. }
  115685. /* channel coupling can 'dirty' the nonzero listing */
  115686. for(i=0;i<info->coupling_steps;i++){
  115687. if(nonzero[info->coupling_mag[i]] ||
  115688. nonzero[info->coupling_ang[i]]){
  115689. nonzero[info->coupling_mag[i]]=1;
  115690. nonzero[info->coupling_ang[i]]=1;
  115691. }
  115692. }
  115693. /* recover the residue into our working vectors */
  115694. for(i=0;i<info->submaps;i++){
  115695. int ch_in_bundle=0;
  115696. for(j=0;j<vi->channels;j++){
  115697. if(info->chmuxlist[j]==i){
  115698. if(nonzero[j])
  115699. zerobundle[ch_in_bundle]=1;
  115700. else
  115701. zerobundle[ch_in_bundle]=0;
  115702. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115703. }
  115704. }
  115705. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115706. inverse(vb,b->residue[info->residuesubmap[i]],
  115707. pcmbundle,zerobundle,ch_in_bundle);
  115708. }
  115709. /* channel coupling */
  115710. for(i=info->coupling_steps-1;i>=0;i--){
  115711. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115712. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115713. for(j=0;j<n/2;j++){
  115714. float mag=pcmM[j];
  115715. float ang=pcmA[j];
  115716. if(mag>0)
  115717. if(ang>0){
  115718. pcmM[j]=mag;
  115719. pcmA[j]=mag-ang;
  115720. }else{
  115721. pcmA[j]=mag;
  115722. pcmM[j]=mag+ang;
  115723. }
  115724. else
  115725. if(ang>0){
  115726. pcmM[j]=mag;
  115727. pcmA[j]=mag+ang;
  115728. }else{
  115729. pcmA[j]=mag;
  115730. pcmM[j]=mag-ang;
  115731. }
  115732. }
  115733. }
  115734. /* compute and apply spectral envelope */
  115735. for(i=0;i<vi->channels;i++){
  115736. float *pcm=vb->pcm[i];
  115737. int submap=info->chmuxlist[i];
  115738. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115739. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115740. floormemo[i],pcm);
  115741. }
  115742. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115743. /* only MDCT right now.... */
  115744. for(i=0;i<vi->channels;i++){
  115745. float *pcm=vb->pcm[i];
  115746. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115747. }
  115748. /* all done! */
  115749. return(0);
  115750. }
  115751. /* export hooks */
  115752. vorbis_func_mapping mapping0_exportbundle={
  115753. &mapping0_pack,
  115754. &mapping0_unpack,
  115755. &mapping0_free_info,
  115756. &mapping0_forward,
  115757. &mapping0_inverse
  115758. };
  115759. #endif
  115760. /*** End of inlined file: mapping0.c ***/
  115761. /*** Start of inlined file: mdct.c ***/
  115762. /* this can also be run as an integer transform by uncommenting a
  115763. define in mdct.h; the integerization is a first pass and although
  115764. it's likely stable for Vorbis, the dynamic range is constrained and
  115765. roundoff isn't done (so it's noisy). Consider it functional, but
  115766. only a starting point. There's no point on a machine with an FPU */
  115767. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115768. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115769. // tasks..
  115770. #if JUCE_MSVC
  115771. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115772. #endif
  115773. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115774. #if JUCE_USE_OGGVORBIS
  115775. #include <stdio.h>
  115776. #include <stdlib.h>
  115777. #include <string.h>
  115778. #include <math.h>
  115779. /* build lookups for trig functions; also pre-figure scaling and
  115780. some window function algebra. */
  115781. void mdct_init(mdct_lookup *lookup,int n){
  115782. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115783. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115784. int i;
  115785. int n2=n>>1;
  115786. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115787. lookup->n=n;
  115788. lookup->trig=T;
  115789. lookup->bitrev=bitrev;
  115790. /* trig lookups... */
  115791. for(i=0;i<n/4;i++){
  115792. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115793. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115794. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115795. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115796. }
  115797. for(i=0;i<n/8;i++){
  115798. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115799. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115800. }
  115801. /* bitreverse lookup... */
  115802. {
  115803. int mask=(1<<(log2n-1))-1,i,j;
  115804. int msb=1<<(log2n-2);
  115805. for(i=0;i<n/8;i++){
  115806. int acc=0;
  115807. for(j=0;msb>>j;j++)
  115808. if((msb>>j)&i)acc|=1<<j;
  115809. bitrev[i*2]=((~acc)&mask)-1;
  115810. bitrev[i*2+1]=acc;
  115811. }
  115812. }
  115813. lookup->scale=FLOAT_CONV(4.f/n);
  115814. }
  115815. /* 8 point butterfly (in place, 4 register) */
  115816. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115817. REG_TYPE r0 = x[6] + x[2];
  115818. REG_TYPE r1 = x[6] - x[2];
  115819. REG_TYPE r2 = x[4] + x[0];
  115820. REG_TYPE r3 = x[4] - x[0];
  115821. x[6] = r0 + r2;
  115822. x[4] = r0 - r2;
  115823. r0 = x[5] - x[1];
  115824. r2 = x[7] - x[3];
  115825. x[0] = r1 + r0;
  115826. x[2] = r1 - r0;
  115827. r0 = x[5] + x[1];
  115828. r1 = x[7] + x[3];
  115829. x[3] = r2 + r3;
  115830. x[1] = r2 - r3;
  115831. x[7] = r1 + r0;
  115832. x[5] = r1 - r0;
  115833. }
  115834. /* 16 point butterfly (in place, 4 register) */
  115835. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115836. REG_TYPE r0 = x[1] - x[9];
  115837. REG_TYPE r1 = x[0] - x[8];
  115838. x[8] += x[0];
  115839. x[9] += x[1];
  115840. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115841. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115842. r0 = x[3] - x[11];
  115843. r1 = x[10] - x[2];
  115844. x[10] += x[2];
  115845. x[11] += x[3];
  115846. x[2] = r0;
  115847. x[3] = r1;
  115848. r0 = x[12] - x[4];
  115849. r1 = x[13] - x[5];
  115850. x[12] += x[4];
  115851. x[13] += x[5];
  115852. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115853. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115854. r0 = x[14] - x[6];
  115855. r1 = x[15] - x[7];
  115856. x[14] += x[6];
  115857. x[15] += x[7];
  115858. x[6] = r0;
  115859. x[7] = r1;
  115860. mdct_butterfly_8(x);
  115861. mdct_butterfly_8(x+8);
  115862. }
  115863. /* 32 point butterfly (in place, 4 register) */
  115864. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115865. REG_TYPE r0 = x[30] - x[14];
  115866. REG_TYPE r1 = x[31] - x[15];
  115867. x[30] += x[14];
  115868. x[31] += x[15];
  115869. x[14] = r0;
  115870. x[15] = r1;
  115871. r0 = x[28] - x[12];
  115872. r1 = x[29] - x[13];
  115873. x[28] += x[12];
  115874. x[29] += x[13];
  115875. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115876. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115877. r0 = x[26] - x[10];
  115878. r1 = x[27] - x[11];
  115879. x[26] += x[10];
  115880. x[27] += x[11];
  115881. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115882. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115883. r0 = x[24] - x[8];
  115884. r1 = x[25] - x[9];
  115885. x[24] += x[8];
  115886. x[25] += x[9];
  115887. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115888. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115889. r0 = x[22] - x[6];
  115890. r1 = x[7] - x[23];
  115891. x[22] += x[6];
  115892. x[23] += x[7];
  115893. x[6] = r1;
  115894. x[7] = r0;
  115895. r0 = x[4] - x[20];
  115896. r1 = x[5] - x[21];
  115897. x[20] += x[4];
  115898. x[21] += x[5];
  115899. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115900. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115901. r0 = x[2] - x[18];
  115902. r1 = x[3] - x[19];
  115903. x[18] += x[2];
  115904. x[19] += x[3];
  115905. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115906. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115907. r0 = x[0] - x[16];
  115908. r1 = x[1] - x[17];
  115909. x[16] += x[0];
  115910. x[17] += x[1];
  115911. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115912. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115913. mdct_butterfly_16(x);
  115914. mdct_butterfly_16(x+16);
  115915. }
  115916. /* N point first stage butterfly (in place, 2 register) */
  115917. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115918. DATA_TYPE *x,
  115919. int points){
  115920. DATA_TYPE *x1 = x + points - 8;
  115921. DATA_TYPE *x2 = x + (points>>1) - 8;
  115922. REG_TYPE r0;
  115923. REG_TYPE r1;
  115924. do{
  115925. r0 = x1[6] - x2[6];
  115926. r1 = x1[7] - x2[7];
  115927. x1[6] += x2[6];
  115928. x1[7] += x2[7];
  115929. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115930. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115931. r0 = x1[4] - x2[4];
  115932. r1 = x1[5] - x2[5];
  115933. x1[4] += x2[4];
  115934. x1[5] += x2[5];
  115935. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115936. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115937. r0 = x1[2] - x2[2];
  115938. r1 = x1[3] - x2[3];
  115939. x1[2] += x2[2];
  115940. x1[3] += x2[3];
  115941. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115942. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115943. r0 = x1[0] - x2[0];
  115944. r1 = x1[1] - x2[1];
  115945. x1[0] += x2[0];
  115946. x1[1] += x2[1];
  115947. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115948. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115949. x1-=8;
  115950. x2-=8;
  115951. T+=16;
  115952. }while(x2>=x);
  115953. }
  115954. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115955. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115956. DATA_TYPE *x,
  115957. int points,
  115958. int trigint){
  115959. DATA_TYPE *x1 = x + points - 8;
  115960. DATA_TYPE *x2 = x + (points>>1) - 8;
  115961. REG_TYPE r0;
  115962. REG_TYPE r1;
  115963. do{
  115964. r0 = x1[6] - x2[6];
  115965. r1 = x1[7] - x2[7];
  115966. x1[6] += x2[6];
  115967. x1[7] += x2[7];
  115968. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115969. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115970. T+=trigint;
  115971. r0 = x1[4] - x2[4];
  115972. r1 = x1[5] - x2[5];
  115973. x1[4] += x2[4];
  115974. x1[5] += x2[5];
  115975. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115976. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115977. T+=trigint;
  115978. r0 = x1[2] - x2[2];
  115979. r1 = x1[3] - x2[3];
  115980. x1[2] += x2[2];
  115981. x1[3] += x2[3];
  115982. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115983. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115984. T+=trigint;
  115985. r0 = x1[0] - x2[0];
  115986. r1 = x1[1] - x2[1];
  115987. x1[0] += x2[0];
  115988. x1[1] += x2[1];
  115989. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115990. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115991. T+=trigint;
  115992. x1-=8;
  115993. x2-=8;
  115994. }while(x2>=x);
  115995. }
  115996. STIN void mdct_butterflies(mdct_lookup *init,
  115997. DATA_TYPE *x,
  115998. int points){
  115999. DATA_TYPE *T=init->trig;
  116000. int stages=init->log2n-5;
  116001. int i,j;
  116002. if(--stages>0){
  116003. mdct_butterfly_first(T,x,points);
  116004. }
  116005. for(i=1;--stages>0;i++){
  116006. for(j=0;j<(1<<i);j++)
  116007. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116008. }
  116009. for(j=0;j<points;j+=32)
  116010. mdct_butterfly_32(x+j);
  116011. }
  116012. void mdct_clear(mdct_lookup *l){
  116013. if(l){
  116014. if(l->trig)_ogg_free(l->trig);
  116015. if(l->bitrev)_ogg_free(l->bitrev);
  116016. memset(l,0,sizeof(*l));
  116017. }
  116018. }
  116019. STIN void mdct_bitreverse(mdct_lookup *init,
  116020. DATA_TYPE *x){
  116021. int n = init->n;
  116022. int *bit = init->bitrev;
  116023. DATA_TYPE *w0 = x;
  116024. DATA_TYPE *w1 = x = w0+(n>>1);
  116025. DATA_TYPE *T = init->trig+n;
  116026. do{
  116027. DATA_TYPE *x0 = x+bit[0];
  116028. DATA_TYPE *x1 = x+bit[1];
  116029. REG_TYPE r0 = x0[1] - x1[1];
  116030. REG_TYPE r1 = x0[0] + x1[0];
  116031. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116032. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116033. w1 -= 4;
  116034. r0 = HALVE(x0[1] + x1[1]);
  116035. r1 = HALVE(x0[0] - x1[0]);
  116036. w0[0] = r0 + r2;
  116037. w1[2] = r0 - r2;
  116038. w0[1] = r1 + r3;
  116039. w1[3] = r3 - r1;
  116040. x0 = x+bit[2];
  116041. x1 = x+bit[3];
  116042. r0 = x0[1] - x1[1];
  116043. r1 = x0[0] + x1[0];
  116044. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116045. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116046. r0 = HALVE(x0[1] + x1[1]);
  116047. r1 = HALVE(x0[0] - x1[0]);
  116048. w0[2] = r0 + r2;
  116049. w1[0] = r0 - r2;
  116050. w0[3] = r1 + r3;
  116051. w1[1] = r3 - r1;
  116052. T += 4;
  116053. bit += 4;
  116054. w0 += 4;
  116055. }while(w0<w1);
  116056. }
  116057. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116058. int n=init->n;
  116059. int n2=n>>1;
  116060. int n4=n>>2;
  116061. /* rotate */
  116062. DATA_TYPE *iX = in+n2-7;
  116063. DATA_TYPE *oX = out+n2+n4;
  116064. DATA_TYPE *T = init->trig+n4;
  116065. do{
  116066. oX -= 4;
  116067. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116068. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116069. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116070. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116071. iX -= 8;
  116072. T += 4;
  116073. }while(iX>=in);
  116074. iX = in+n2-8;
  116075. oX = out+n2+n4;
  116076. T = init->trig+n4;
  116077. do{
  116078. T -= 4;
  116079. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116080. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116081. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116082. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116083. iX -= 8;
  116084. oX += 4;
  116085. }while(iX>=in);
  116086. mdct_butterflies(init,out+n2,n2);
  116087. mdct_bitreverse(init,out);
  116088. /* roatate + window */
  116089. {
  116090. DATA_TYPE *oX1=out+n2+n4;
  116091. DATA_TYPE *oX2=out+n2+n4;
  116092. DATA_TYPE *iX =out;
  116093. T =init->trig+n2;
  116094. do{
  116095. oX1-=4;
  116096. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116097. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116098. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116099. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116100. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116101. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116102. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116103. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116104. oX2+=4;
  116105. iX += 8;
  116106. T += 8;
  116107. }while(iX<oX1);
  116108. iX=out+n2+n4;
  116109. oX1=out+n4;
  116110. oX2=oX1;
  116111. do{
  116112. oX1-=4;
  116113. iX-=4;
  116114. oX2[0] = -(oX1[3] = iX[3]);
  116115. oX2[1] = -(oX1[2] = iX[2]);
  116116. oX2[2] = -(oX1[1] = iX[1]);
  116117. oX2[3] = -(oX1[0] = iX[0]);
  116118. oX2+=4;
  116119. }while(oX2<iX);
  116120. iX=out+n2+n4;
  116121. oX1=out+n2+n4;
  116122. oX2=out+n2;
  116123. do{
  116124. oX1-=4;
  116125. oX1[0]= iX[3];
  116126. oX1[1]= iX[2];
  116127. oX1[2]= iX[1];
  116128. oX1[3]= iX[0];
  116129. iX+=4;
  116130. }while(oX1>oX2);
  116131. }
  116132. }
  116133. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116134. int n=init->n;
  116135. int n2=n>>1;
  116136. int n4=n>>2;
  116137. int n8=n>>3;
  116138. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116139. DATA_TYPE *w2=w+n2;
  116140. /* rotate */
  116141. /* window + rotate + step 1 */
  116142. REG_TYPE r0;
  116143. REG_TYPE r1;
  116144. DATA_TYPE *x0=in+n2+n4;
  116145. DATA_TYPE *x1=x0+1;
  116146. DATA_TYPE *T=init->trig+n2;
  116147. int i=0;
  116148. for(i=0;i<n8;i+=2){
  116149. x0 -=4;
  116150. T-=2;
  116151. r0= x0[2] + x1[0];
  116152. r1= x0[0] + x1[2];
  116153. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116154. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116155. x1 +=4;
  116156. }
  116157. x1=in+1;
  116158. for(;i<n2-n8;i+=2){
  116159. T-=2;
  116160. x0 -=4;
  116161. r0= x0[2] - x1[0];
  116162. r1= x0[0] - x1[2];
  116163. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116164. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116165. x1 +=4;
  116166. }
  116167. x0=in+n;
  116168. for(;i<n2;i+=2){
  116169. T-=2;
  116170. x0 -=4;
  116171. r0= -x0[2] - x1[0];
  116172. r1= -x0[0] - x1[2];
  116173. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116174. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116175. x1 +=4;
  116176. }
  116177. mdct_butterflies(init,w+n2,n2);
  116178. mdct_bitreverse(init,w);
  116179. /* roatate + window */
  116180. T=init->trig+n2;
  116181. x0=out+n2;
  116182. for(i=0;i<n4;i++){
  116183. x0--;
  116184. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116185. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116186. w+=2;
  116187. T+=2;
  116188. }
  116189. }
  116190. #endif
  116191. /*** End of inlined file: mdct.c ***/
  116192. /*** Start of inlined file: psy.c ***/
  116193. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116194. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116195. // tasks..
  116196. #if JUCE_MSVC
  116197. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116198. #endif
  116199. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116200. #if JUCE_USE_OGGVORBIS
  116201. #include <stdlib.h>
  116202. #include <math.h>
  116203. #include <string.h>
  116204. /*** Start of inlined file: masking.h ***/
  116205. #ifndef _V_MASKING_H_
  116206. #define _V_MASKING_H_
  116207. /* more detailed ATH; the bass if flat to save stressing the floor
  116208. overly for only a bin or two of savings. */
  116209. #define MAX_ATH 88
  116210. static float ATH[]={
  116211. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116212. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116213. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116214. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116215. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116216. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116217. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116218. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116219. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116220. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116221. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116222. };
  116223. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116224. replaced by an empirically collected data set. The previously
  116225. published values were, far too often, simply on crack. */
  116226. #define EHMER_OFFSET 16
  116227. #define EHMER_MAX 56
  116228. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116229. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116230. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116231. for collection of these curves) */
  116232. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116233. /* 62.5 Hz */
  116234. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116235. -60, -60, -60, -60, -62, -62, -65, -73,
  116236. -69, -68, -68, -67, -70, -70, -72, -74,
  116237. -75, -79, -79, -80, -83, -88, -93, -100,
  116238. -110, -999, -999, -999, -999, -999, -999, -999,
  116239. -999, -999, -999, -999, -999, -999, -999, -999,
  116240. -999, -999, -999, -999, -999, -999, -999, -999},
  116241. { -48, -48, -48, -48, -48, -48, -48, -48,
  116242. -48, -48, -48, -48, -48, -53, -61, -66,
  116243. -66, -68, -67, -70, -76, -76, -72, -73,
  116244. -75, -76, -78, -79, -83, -88, -93, -100,
  116245. -110, -999, -999, -999, -999, -999, -999, -999,
  116246. -999, -999, -999, -999, -999, -999, -999, -999,
  116247. -999, -999, -999, -999, -999, -999, -999, -999},
  116248. { -37, -37, -37, -37, -37, -37, -37, -37,
  116249. -38, -40, -42, -46, -48, -53, -55, -62,
  116250. -65, -58, -56, -56, -61, -60, -65, -67,
  116251. -69, -71, -77, -77, -78, -80, -82, -84,
  116252. -88, -93, -98, -106, -112, -999, -999, -999,
  116253. -999, -999, -999, -999, -999, -999, -999, -999,
  116254. -999, -999, -999, -999, -999, -999, -999, -999},
  116255. { -25, -25, -25, -25, -25, -25, -25, -25,
  116256. -25, -26, -27, -29, -32, -38, -48, -52,
  116257. -52, -50, -48, -48, -51, -52, -54, -60,
  116258. -67, -67, -66, -68, -69, -73, -73, -76,
  116259. -80, -81, -81, -85, -85, -86, -88, -93,
  116260. -100, -110, -999, -999, -999, -999, -999, -999,
  116261. -999, -999, -999, -999, -999, -999, -999, -999},
  116262. { -16, -16, -16, -16, -16, -16, -16, -16,
  116263. -17, -19, -20, -22, -26, -28, -31, -40,
  116264. -47, -39, -39, -40, -42, -43, -47, -51,
  116265. -57, -52, -55, -55, -60, -58, -62, -63,
  116266. -70, -67, -69, -72, -73, -77, -80, -82,
  116267. -83, -87, -90, -94, -98, -104, -115, -999,
  116268. -999, -999, -999, -999, -999, -999, -999, -999},
  116269. { -8, -8, -8, -8, -8, -8, -8, -8,
  116270. -8, -8, -10, -11, -15, -19, -25, -30,
  116271. -34, -31, -30, -31, -29, -32, -35, -42,
  116272. -48, -42, -44, -46, -50, -50, -51, -52,
  116273. -59, -54, -55, -55, -58, -62, -63, -66,
  116274. -72, -73, -76, -75, -78, -80, -80, -81,
  116275. -84, -88, -90, -94, -98, -101, -106, -110}},
  116276. /* 88Hz */
  116277. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116278. -66, -66, -66, -66, -66, -67, -67, -67,
  116279. -76, -72, -71, -74, -76, -76, -75, -78,
  116280. -79, -79, -81, -83, -86, -89, -93, -97,
  116281. -100, -105, -110, -999, -999, -999, -999, -999,
  116282. -999, -999, -999, -999, -999, -999, -999, -999,
  116283. -999, -999, -999, -999, -999, -999, -999, -999},
  116284. { -47, -47, -47, -47, -47, -47, -47, -47,
  116285. -47, -47, -47, -48, -51, -55, -59, -66,
  116286. -66, -66, -67, -66, -68, -69, -70, -74,
  116287. -79, -77, -77, -78, -80, -81, -82, -84,
  116288. -86, -88, -91, -95, -100, -108, -116, -999,
  116289. -999, -999, -999, -999, -999, -999, -999, -999,
  116290. -999, -999, -999, -999, -999, -999, -999, -999},
  116291. { -36, -36, -36, -36, -36, -36, -36, -36,
  116292. -36, -37, -37, -41, -44, -48, -51, -58,
  116293. -62, -60, -57, -59, -59, -60, -63, -65,
  116294. -72, -71, -70, -72, -74, -77, -76, -78,
  116295. -81, -81, -80, -83, -86, -91, -96, -100,
  116296. -105, -110, -999, -999, -999, -999, -999, -999,
  116297. -999, -999, -999, -999, -999, -999, -999, -999},
  116298. { -28, -28, -28, -28, -28, -28, -28, -28,
  116299. -28, -30, -32, -32, -33, -35, -41, -49,
  116300. -50, -49, -47, -48, -48, -52, -51, -57,
  116301. -65, -61, -59, -61, -64, -69, -70, -74,
  116302. -77, -77, -78, -81, -84, -85, -87, -90,
  116303. -92, -96, -100, -107, -112, -999, -999, -999,
  116304. -999, -999, -999, -999, -999, -999, -999, -999},
  116305. { -19, -19, -19, -19, -19, -19, -19, -19,
  116306. -20, -21, -23, -27, -30, -35, -36, -41,
  116307. -46, -44, -42, -40, -41, -41, -43, -48,
  116308. -55, -53, -52, -53, -56, -59, -58, -60,
  116309. -67, -66, -69, -71, -72, -75, -79, -81,
  116310. -84, -87, -90, -93, -97, -101, -107, -114,
  116311. -999, -999, -999, -999, -999, -999, -999, -999},
  116312. { -9, -9, -9, -9, -9, -9, -9, -9,
  116313. -11, -12, -12, -15, -16, -20, -23, -30,
  116314. -37, -34, -33, -34, -31, -32, -32, -38,
  116315. -47, -44, -41, -40, -47, -49, -46, -46,
  116316. -58, -50, -50, -54, -58, -62, -64, -67,
  116317. -67, -70, -72, -76, -79, -83, -87, -91,
  116318. -96, -100, -104, -110, -999, -999, -999, -999}},
  116319. /* 125 Hz */
  116320. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116321. -62, -62, -63, -64, -66, -67, -66, -68,
  116322. -75, -72, -76, -75, -76, -78, -79, -82,
  116323. -84, -85, -90, -94, -101, -110, -999, -999,
  116324. -999, -999, -999, -999, -999, -999, -999, -999,
  116325. -999, -999, -999, -999, -999, -999, -999, -999,
  116326. -999, -999, -999, -999, -999, -999, -999, -999},
  116327. { -59, -59, -59, -59, -59, -59, -59, -59,
  116328. -59, -59, -59, -60, -60, -61, -63, -66,
  116329. -71, -68, -70, -70, -71, -72, -72, -75,
  116330. -81, -78, -79, -82, -83, -86, -90, -97,
  116331. -103, -113, -999, -999, -999, -999, -999, -999,
  116332. -999, -999, -999, -999, -999, -999, -999, -999,
  116333. -999, -999, -999, -999, -999, -999, -999, -999},
  116334. { -53, -53, -53, -53, -53, -53, -53, -53,
  116335. -53, -54, -55, -57, -56, -57, -55, -61,
  116336. -65, -60, -60, -62, -63, -63, -66, -68,
  116337. -74, -73, -75, -75, -78, -80, -80, -82,
  116338. -85, -90, -96, -101, -108, -999, -999, -999,
  116339. -999, -999, -999, -999, -999, -999, -999, -999,
  116340. -999, -999, -999, -999, -999, -999, -999, -999},
  116341. { -46, -46, -46, -46, -46, -46, -46, -46,
  116342. -46, -46, -47, -47, -47, -47, -48, -51,
  116343. -57, -51, -49, -50, -51, -53, -54, -59,
  116344. -66, -60, -62, -67, -67, -70, -72, -75,
  116345. -76, -78, -81, -85, -88, -94, -97, -104,
  116346. -112, -999, -999, -999, -999, -999, -999, -999,
  116347. -999, -999, -999, -999, -999, -999, -999, -999},
  116348. { -36, -36, -36, -36, -36, -36, -36, -36,
  116349. -39, -41, -42, -42, -39, -38, -41, -43,
  116350. -52, -44, -40, -39, -37, -37, -40, -47,
  116351. -54, -50, -48, -50, -55, -61, -59, -62,
  116352. -66, -66, -66, -69, -69, -73, -74, -74,
  116353. -75, -77, -79, -82, -87, -91, -95, -100,
  116354. -108, -115, -999, -999, -999, -999, -999, -999},
  116355. { -28, -26, -24, -22, -20, -20, -23, -29,
  116356. -30, -31, -28, -27, -28, -28, -28, -35,
  116357. -40, -33, -32, -29, -30, -30, -30, -37,
  116358. -45, -41, -37, -38, -45, -47, -47, -48,
  116359. -53, -49, -48, -50, -49, -49, -51, -52,
  116360. -58, -56, -57, -56, -60, -61, -62, -70,
  116361. -72, -74, -78, -83, -88, -93, -100, -106}},
  116362. /* 177 Hz */
  116363. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116364. -999, -110, -105, -100, -95, -91, -87, -83,
  116365. -80, -78, -76, -78, -78, -81, -83, -85,
  116366. -86, -85, -86, -87, -90, -97, -107, -999,
  116367. -999, -999, -999, -999, -999, -999, -999, -999,
  116368. -999, -999, -999, -999, -999, -999, -999, -999,
  116369. -999, -999, -999, -999, -999, -999, -999, -999},
  116370. {-999, -999, -999, -110, -105, -100, -95, -90,
  116371. -85, -81, -77, -73, -70, -67, -67, -68,
  116372. -75, -73, -70, -69, -70, -72, -75, -79,
  116373. -84, -83, -84, -86, -88, -89, -89, -93,
  116374. -98, -105, -112, -999, -999, -999, -999, -999,
  116375. -999, -999, -999, -999, -999, -999, -999, -999,
  116376. -999, -999, -999, -999, -999, -999, -999, -999},
  116377. {-105, -100, -95, -90, -85, -80, -76, -71,
  116378. -68, -68, -65, -63, -63, -62, -62, -64,
  116379. -65, -64, -61, -62, -63, -64, -66, -68,
  116380. -73, -73, -74, -75, -76, -81, -83, -85,
  116381. -88, -89, -92, -95, -100, -108, -999, -999,
  116382. -999, -999, -999, -999, -999, -999, -999, -999,
  116383. -999, -999, -999, -999, -999, -999, -999, -999},
  116384. { -80, -75, -71, -68, -65, -63, -62, -61,
  116385. -61, -61, -61, -59, -56, -57, -53, -50,
  116386. -58, -52, -50, -50, -52, -53, -54, -58,
  116387. -67, -63, -67, -68, -72, -75, -78, -80,
  116388. -81, -81, -82, -85, -89, -90, -93, -97,
  116389. -101, -107, -114, -999, -999, -999, -999, -999,
  116390. -999, -999, -999, -999, -999, -999, -999, -999},
  116391. { -65, -61, -59, -57, -56, -55, -55, -56,
  116392. -56, -57, -55, -53, -52, -47, -44, -44,
  116393. -50, -44, -41, -39, -39, -42, -40, -46,
  116394. -51, -49, -50, -53, -54, -63, -60, -61,
  116395. -62, -66, -66, -66, -70, -73, -74, -75,
  116396. -76, -75, -79, -85, -89, -91, -96, -102,
  116397. -110, -999, -999, -999, -999, -999, -999, -999},
  116398. { -52, -50, -49, -49, -48, -48, -48, -49,
  116399. -50, -50, -49, -46, -43, -39, -35, -33,
  116400. -38, -36, -32, -29, -32, -32, -32, -35,
  116401. -44, -39, -38, -38, -46, -50, -45, -46,
  116402. -53, -50, -50, -50, -54, -54, -53, -53,
  116403. -56, -57, -59, -66, -70, -72, -74, -79,
  116404. -83, -85, -90, -97, -114, -999, -999, -999}},
  116405. /* 250 Hz */
  116406. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116407. -100, -95, -90, -86, -80, -75, -75, -79,
  116408. -80, -79, -80, -81, -82, -88, -95, -103,
  116409. -110, -999, -999, -999, -999, -999, -999, -999,
  116410. -999, -999, -999, -999, -999, -999, -999, -999,
  116411. -999, -999, -999, -999, -999, -999, -999, -999,
  116412. -999, -999, -999, -999, -999, -999, -999, -999},
  116413. {-999, -999, -999, -999, -108, -103, -98, -93,
  116414. -88, -83, -79, -78, -75, -71, -67, -68,
  116415. -73, -73, -72, -73, -75, -77, -80, -82,
  116416. -88, -93, -100, -107, -114, -999, -999, -999,
  116417. -999, -999, -999, -999, -999, -999, -999, -999,
  116418. -999, -999, -999, -999, -999, -999, -999, -999,
  116419. -999, -999, -999, -999, -999, -999, -999, -999},
  116420. {-999, -999, -999, -110, -105, -101, -96, -90,
  116421. -86, -81, -77, -73, -69, -66, -61, -62,
  116422. -66, -64, -62, -65, -66, -70, -72, -76,
  116423. -81, -80, -84, -90, -95, -102, -110, -999,
  116424. -999, -999, -999, -999, -999, -999, -999, -999,
  116425. -999, -999, -999, -999, -999, -999, -999, -999,
  116426. -999, -999, -999, -999, -999, -999, -999, -999},
  116427. {-999, -999, -999, -107, -103, -97, -92, -88,
  116428. -83, -79, -74, -70, -66, -59, -53, -58,
  116429. -62, -55, -54, -54, -54, -58, -61, -62,
  116430. -72, -70, -72, -75, -78, -80, -81, -80,
  116431. -83, -83, -88, -93, -100, -107, -115, -999,
  116432. -999, -999, -999, -999, -999, -999, -999, -999,
  116433. -999, -999, -999, -999, -999, -999, -999, -999},
  116434. {-999, -999, -999, -105, -100, -95, -90, -85,
  116435. -80, -75, -70, -66, -62, -56, -48, -44,
  116436. -48, -46, -46, -43, -46, -48, -48, -51,
  116437. -58, -58, -59, -60, -62, -62, -61, -61,
  116438. -65, -64, -65, -68, -70, -74, -75, -78,
  116439. -81, -86, -95, -110, -999, -999, -999, -999,
  116440. -999, -999, -999, -999, -999, -999, -999, -999},
  116441. {-999, -999, -105, -100, -95, -90, -85, -80,
  116442. -75, -70, -65, -61, -55, -49, -39, -33,
  116443. -40, -35, -32, -38, -40, -33, -35, -37,
  116444. -46, -41, -45, -44, -46, -42, -45, -46,
  116445. -52, -50, -50, -50, -54, -54, -55, -57,
  116446. -62, -64, -66, -68, -70, -76, -81, -90,
  116447. -100, -110, -999, -999, -999, -999, -999, -999}},
  116448. /* 354 hz */
  116449. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116450. -105, -98, -90, -85, -82, -83, -80, -78,
  116451. -84, -79, -80, -83, -87, -89, -91, -93,
  116452. -99, -106, -117, -999, -999, -999, -999, -999,
  116453. -999, -999, -999, -999, -999, -999, -999, -999,
  116454. -999, -999, -999, -999, -999, -999, -999, -999,
  116455. -999, -999, -999, -999, -999, -999, -999, -999},
  116456. {-999, -999, -999, -999, -999, -999, -999, -999,
  116457. -105, -98, -90, -85, -80, -75, -70, -68,
  116458. -74, -72, -74, -77, -80, -82, -85, -87,
  116459. -92, -89, -91, -95, -100, -106, -112, -999,
  116460. -999, -999, -999, -999, -999, -999, -999, -999,
  116461. -999, -999, -999, -999, -999, -999, -999, -999,
  116462. -999, -999, -999, -999, -999, -999, -999, -999},
  116463. {-999, -999, -999, -999, -999, -999, -999, -999,
  116464. -105, -98, -90, -83, -75, -71, -63, -64,
  116465. -67, -62, -64, -67, -70, -73, -77, -81,
  116466. -84, -83, -85, -89, -90, -93, -98, -104,
  116467. -109, -114, -999, -999, -999, -999, -999, -999,
  116468. -999, -999, -999, -999, -999, -999, -999, -999,
  116469. -999, -999, -999, -999, -999, -999, -999, -999},
  116470. {-999, -999, -999, -999, -999, -999, -999, -999,
  116471. -103, -96, -88, -81, -75, -68, -58, -54,
  116472. -56, -54, -56, -56, -58, -60, -63, -66,
  116473. -74, -69, -72, -72, -75, -74, -77, -81,
  116474. -81, -82, -84, -87, -93, -96, -99, -104,
  116475. -110, -999, -999, -999, -999, -999, -999, -999,
  116476. -999, -999, -999, -999, -999, -999, -999, -999},
  116477. {-999, -999, -999, -999, -999, -108, -102, -96,
  116478. -91, -85, -80, -74, -68, -60, -51, -46,
  116479. -48, -46, -43, -45, -47, -47, -49, -48,
  116480. -56, -53, -55, -58, -57, -63, -58, -60,
  116481. -66, -64, -67, -70, -70, -74, -77, -84,
  116482. -86, -89, -91, -93, -94, -101, -109, -118,
  116483. -999, -999, -999, -999, -999, -999, -999, -999},
  116484. {-999, -999, -999, -108, -103, -98, -93, -88,
  116485. -83, -78, -73, -68, -60, -53, -44, -35,
  116486. -38, -38, -34, -34, -36, -40, -41, -44,
  116487. -51, -45, -46, -47, -46, -54, -50, -49,
  116488. -50, -50, -50, -51, -54, -57, -58, -60,
  116489. -66, -66, -66, -64, -65, -68, -77, -82,
  116490. -87, -95, -110, -999, -999, -999, -999, -999}},
  116491. /* 500 Hz */
  116492. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116493. -107, -102, -97, -92, -87, -83, -78, -75,
  116494. -82, -79, -83, -85, -89, -92, -95, -98,
  116495. -101, -105, -109, -113, -999, -999, -999, -999,
  116496. -999, -999, -999, -999, -999, -999, -999, -999,
  116497. -999, -999, -999, -999, -999, -999, -999, -999,
  116498. -999, -999, -999, -999, -999, -999, -999, -999},
  116499. {-999, -999, -999, -999, -999, -999, -999, -106,
  116500. -100, -95, -90, -86, -81, -78, -74, -69,
  116501. -74, -74, -76, -79, -83, -84, -86, -89,
  116502. -92, -97, -93, -100, -103, -107, -110, -999,
  116503. -999, -999, -999, -999, -999, -999, -999, -999,
  116504. -999, -999, -999, -999, -999, -999, -999, -999,
  116505. -999, -999, -999, -999, -999, -999, -999, -999},
  116506. {-999, -999, -999, -999, -999, -999, -106, -100,
  116507. -95, -90, -87, -83, -80, -75, -69, -60,
  116508. -66, -66, -68, -70, -74, -78, -79, -81,
  116509. -81, -83, -84, -87, -93, -96, -99, -103,
  116510. -107, -110, -999, -999, -999, -999, -999, -999,
  116511. -999, -999, -999, -999, -999, -999, -999, -999,
  116512. -999, -999, -999, -999, -999, -999, -999, -999},
  116513. {-999, -999, -999, -999, -999, -108, -103, -98,
  116514. -93, -89, -85, -82, -78, -71, -62, -55,
  116515. -58, -58, -54, -54, -55, -59, -61, -62,
  116516. -70, -66, -66, -67, -70, -72, -75, -78,
  116517. -84, -84, -84, -88, -91, -90, -95, -98,
  116518. -102, -103, -106, -110, -999, -999, -999, -999,
  116519. -999, -999, -999, -999, -999, -999, -999, -999},
  116520. {-999, -999, -999, -999, -108, -103, -98, -94,
  116521. -90, -87, -82, -79, -73, -67, -58, -47,
  116522. -50, -45, -41, -45, -48, -44, -44, -49,
  116523. -54, -51, -48, -47, -49, -50, -51, -57,
  116524. -58, -60, -63, -69, -70, -69, -71, -74,
  116525. -78, -82, -90, -95, -101, -105, -110, -999,
  116526. -999, -999, -999, -999, -999, -999, -999, -999},
  116527. {-999, -999, -999, -105, -101, -97, -93, -90,
  116528. -85, -80, -77, -72, -65, -56, -48, -37,
  116529. -40, -36, -34, -40, -50, -47, -38, -41,
  116530. -47, -38, -35, -39, -38, -43, -40, -45,
  116531. -50, -45, -44, -47, -50, -55, -48, -48,
  116532. -52, -66, -70, -76, -82, -90, -97, -105,
  116533. -110, -999, -999, -999, -999, -999, -999, -999}},
  116534. /* 707 Hz */
  116535. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116536. -999, -108, -103, -98, -93, -86, -79, -76,
  116537. -83, -81, -85, -87, -89, -93, -98, -102,
  116538. -107, -112, -999, -999, -999, -999, -999, -999,
  116539. -999, -999, -999, -999, -999, -999, -999, -999,
  116540. -999, -999, -999, -999, -999, -999, -999, -999,
  116541. -999, -999, -999, -999, -999, -999, -999, -999},
  116542. {-999, -999, -999, -999, -999, -999, -999, -999,
  116543. -999, -108, -103, -98, -93, -86, -79, -71,
  116544. -77, -74, -77, -79, -81, -84, -85, -90,
  116545. -92, -93, -92, -98, -101, -108, -112, -999,
  116546. -999, -999, -999, -999, -999, -999, -999, -999,
  116547. -999, -999, -999, -999, -999, -999, -999, -999,
  116548. -999, -999, -999, -999, -999, -999, -999, -999},
  116549. {-999, -999, -999, -999, -999, -999, -999, -999,
  116550. -108, -103, -98, -93, -87, -78, -68, -65,
  116551. -66, -62, -65, -67, -70, -73, -75, -78,
  116552. -82, -82, -83, -84, -91, -93, -98, -102,
  116553. -106, -110, -999, -999, -999, -999, -999, -999,
  116554. -999, -999, -999, -999, -999, -999, -999, -999,
  116555. -999, -999, -999, -999, -999, -999, -999, -999},
  116556. {-999, -999, -999, -999, -999, -999, -999, -999,
  116557. -105, -100, -95, -90, -82, -74, -62, -57,
  116558. -58, -56, -51, -52, -52, -54, -54, -58,
  116559. -66, -59, -60, -63, -66, -69, -73, -79,
  116560. -83, -84, -80, -81, -81, -82, -88, -92,
  116561. -98, -105, -113, -999, -999, -999, -999, -999,
  116562. -999, -999, -999, -999, -999, -999, -999, -999},
  116563. {-999, -999, -999, -999, -999, -999, -999, -107,
  116564. -102, -97, -92, -84, -79, -69, -57, -47,
  116565. -52, -47, -44, -45, -50, -52, -42, -42,
  116566. -53, -43, -43, -48, -51, -56, -55, -52,
  116567. -57, -59, -61, -62, -67, -71, -78, -83,
  116568. -86, -94, -98, -103, -110, -999, -999, -999,
  116569. -999, -999, -999, -999, -999, -999, -999, -999},
  116570. {-999, -999, -999, -999, -999, -999, -105, -100,
  116571. -95, -90, -84, -78, -70, -61, -51, -41,
  116572. -40, -38, -40, -46, -52, -51, -41, -40,
  116573. -46, -40, -38, -38, -41, -46, -41, -46,
  116574. -47, -43, -43, -45, -41, -45, -56, -67,
  116575. -68, -83, -87, -90, -95, -102, -107, -113,
  116576. -999, -999, -999, -999, -999, -999, -999, -999}},
  116577. /* 1000 Hz */
  116578. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116579. -999, -109, -105, -101, -96, -91, -84, -77,
  116580. -82, -82, -85, -89, -94, -100, -106, -110,
  116581. -999, -999, -999, -999, -999, -999, -999, -999,
  116582. -999, -999, -999, -999, -999, -999, -999, -999,
  116583. -999, -999, -999, -999, -999, -999, -999, -999,
  116584. -999, -999, -999, -999, -999, -999, -999, -999},
  116585. {-999, -999, -999, -999, -999, -999, -999, -999,
  116586. -999, -106, -103, -98, -92, -85, -80, -71,
  116587. -75, -72, -76, -80, -84, -86, -89, -93,
  116588. -100, -107, -113, -999, -999, -999, -999, -999,
  116589. -999, -999, -999, -999, -999, -999, -999, -999,
  116590. -999, -999, -999, -999, -999, -999, -999, -999,
  116591. -999, -999, -999, -999, -999, -999, -999, -999},
  116592. {-999, -999, -999, -999, -999, -999, -999, -107,
  116593. -104, -101, -97, -92, -88, -84, -80, -64,
  116594. -66, -63, -64, -66, -69, -73, -77, -83,
  116595. -83, -86, -91, -98, -104, -111, -999, -999,
  116596. -999, -999, -999, -999, -999, -999, -999, -999,
  116597. -999, -999, -999, -999, -999, -999, -999, -999,
  116598. -999, -999, -999, -999, -999, -999, -999, -999},
  116599. {-999, -999, -999, -999, -999, -999, -999, -107,
  116600. -104, -101, -97, -92, -90, -84, -74, -57,
  116601. -58, -52, -55, -54, -50, -52, -50, -52,
  116602. -63, -62, -69, -76, -77, -78, -78, -79,
  116603. -82, -88, -94, -100, -106, -111, -999, -999,
  116604. -999, -999, -999, -999, -999, -999, -999, -999,
  116605. -999, -999, -999, -999, -999, -999, -999, -999},
  116606. {-999, -999, -999, -999, -999, -999, -106, -102,
  116607. -98, -95, -90, -85, -83, -78, -70, -50,
  116608. -50, -41, -44, -49, -47, -50, -50, -44,
  116609. -55, -46, -47, -48, -48, -54, -49, -49,
  116610. -58, -62, -71, -81, -87, -92, -97, -102,
  116611. -108, -114, -999, -999, -999, -999, -999, -999,
  116612. -999, -999, -999, -999, -999, -999, -999, -999},
  116613. {-999, -999, -999, -999, -999, -999, -106, -102,
  116614. -98, -95, -90, -85, -83, -78, -70, -45,
  116615. -43, -41, -47, -50, -51, -50, -49, -45,
  116616. -47, -41, -44, -41, -39, -43, -38, -37,
  116617. -40, -41, -44, -50, -58, -65, -73, -79,
  116618. -85, -92, -97, -101, -105, -109, -113, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999}},
  116620. /* 1414 Hz */
  116621. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116622. -999, -999, -999, -107, -100, -95, -87, -81,
  116623. -85, -83, -88, -93, -100, -107, -114, -999,
  116624. -999, -999, -999, -999, -999, -999, -999, -999,
  116625. -999, -999, -999, -999, -999, -999, -999, -999,
  116626. -999, -999, -999, -999, -999, -999, -999, -999,
  116627. -999, -999, -999, -999, -999, -999, -999, -999},
  116628. {-999, -999, -999, -999, -999, -999, -999, -999,
  116629. -999, -999, -107, -101, -95, -88, -83, -76,
  116630. -73, -72, -79, -84, -90, -95, -100, -105,
  116631. -110, -115, -999, -999, -999, -999, -999, -999,
  116632. -999, -999, -999, -999, -999, -999, -999, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999,
  116634. -999, -999, -999, -999, -999, -999, -999, -999},
  116635. {-999, -999, -999, -999, -999, -999, -999, -999,
  116636. -999, -999, -104, -98, -92, -87, -81, -70,
  116637. -65, -62, -67, -71, -74, -80, -85, -91,
  116638. -95, -99, -103, -108, -111, -114, -999, -999,
  116639. -999, -999, -999, -999, -999, -999, -999, -999,
  116640. -999, -999, -999, -999, -999, -999, -999, -999,
  116641. -999, -999, -999, -999, -999, -999, -999, -999},
  116642. {-999, -999, -999, -999, -999, -999, -999, -999,
  116643. -999, -999, -103, -97, -90, -85, -76, -60,
  116644. -56, -54, -60, -62, -61, -56, -63, -65,
  116645. -73, -74, -77, -75, -78, -81, -86, -87,
  116646. -88, -91, -94, -98, -103, -110, -999, -999,
  116647. -999, -999, -999, -999, -999, -999, -999, -999,
  116648. -999, -999, -999, -999, -999, -999, -999, -999},
  116649. {-999, -999, -999, -999, -999, -999, -999, -105,
  116650. -100, -97, -92, -86, -81, -79, -70, -57,
  116651. -51, -47, -51, -58, -60, -56, -53, -50,
  116652. -58, -52, -50, -50, -53, -55, -64, -69,
  116653. -71, -85, -82, -78, -81, -85, -95, -102,
  116654. -112, -999, -999, -999, -999, -999, -999, -999,
  116655. -999, -999, -999, -999, -999, -999, -999, -999},
  116656. {-999, -999, -999, -999, -999, -999, -999, -105,
  116657. -100, -97, -92, -85, -83, -79, -72, -49,
  116658. -40, -43, -43, -54, -56, -51, -50, -40,
  116659. -43, -38, -36, -35, -37, -38, -37, -44,
  116660. -54, -60, -57, -60, -70, -75, -84, -92,
  116661. -103, -112, -999, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999}},
  116663. /* 2000 Hz */
  116664. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116665. -999, -999, -999, -110, -102, -95, -89, -82,
  116666. -83, -84, -90, -92, -99, -107, -113, -999,
  116667. -999, -999, -999, -999, -999, -999, -999, -999,
  116668. -999, -999, -999, -999, -999, -999, -999, -999,
  116669. -999, -999, -999, -999, -999, -999, -999, -999,
  116670. -999, -999, -999, -999, -999, -999, -999, -999},
  116671. {-999, -999, -999, -999, -999, -999, -999, -999,
  116672. -999, -999, -107, -101, -95, -89, -83, -72,
  116673. -74, -78, -85, -88, -88, -90, -92, -98,
  116674. -105, -111, -999, -999, -999, -999, -999, -999,
  116675. -999, -999, -999, -999, -999, -999, -999, -999,
  116676. -999, -999, -999, -999, -999, -999, -999, -999,
  116677. -999, -999, -999, -999, -999, -999, -999, -999},
  116678. {-999, -999, -999, -999, -999, -999, -999, -999,
  116679. -999, -109, -103, -97, -93, -87, -81, -70,
  116680. -70, -67, -75, -73, -76, -79, -81, -83,
  116681. -88, -89, -97, -103, -110, -999, -999, -999,
  116682. -999, -999, -999, -999, -999, -999, -999, -999,
  116683. -999, -999, -999, -999, -999, -999, -999, -999,
  116684. -999, -999, -999, -999, -999, -999, -999, -999},
  116685. {-999, -999, -999, -999, -999, -999, -999, -999,
  116686. -999, -107, -100, -94, -88, -83, -75, -63,
  116687. -59, -59, -63, -66, -60, -62, -67, -67,
  116688. -77, -76, -81, -88, -86, -92, -96, -102,
  116689. -109, -116, -999, -999, -999, -999, -999, -999,
  116690. -999, -999, -999, -999, -999, -999, -999, -999,
  116691. -999, -999, -999, -999, -999, -999, -999, -999},
  116692. {-999, -999, -999, -999, -999, -999, -999, -999,
  116693. -999, -105, -98, -92, -86, -81, -73, -56,
  116694. -52, -47, -55, -60, -58, -52, -51, -45,
  116695. -49, -50, -53, -54, -61, -71, -70, -69,
  116696. -78, -79, -87, -90, -96, -104, -112, -999,
  116697. -999, -999, -999, -999, -999, -999, -999, -999,
  116698. -999, -999, -999, -999, -999, -999, -999, -999},
  116699. {-999, -999, -999, -999, -999, -999, -999, -999,
  116700. -999, -103, -96, -90, -86, -78, -70, -51,
  116701. -42, -47, -48, -55, -54, -54, -53, -42,
  116702. -35, -28, -33, -38, -37, -44, -47, -49,
  116703. -54, -63, -68, -78, -82, -89, -94, -99,
  116704. -104, -109, -114, -999, -999, -999, -999, -999,
  116705. -999, -999, -999, -999, -999, -999, -999, -999}},
  116706. /* 2828 Hz */
  116707. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116708. -999, -999, -999, -999, -110, -100, -90, -79,
  116709. -85, -81, -82, -82, -89, -94, -99, -103,
  116710. -109, -115, -999, -999, -999, -999, -999, -999,
  116711. -999, -999, -999, -999, -999, -999, -999, -999,
  116712. -999, -999, -999, -999, -999, -999, -999, -999,
  116713. -999, -999, -999, -999, -999, -999, -999, -999},
  116714. {-999, -999, -999, -999, -999, -999, -999, -999,
  116715. -999, -999, -999, -999, -105, -97, -85, -72,
  116716. -74, -70, -70, -70, -76, -85, -91, -93,
  116717. -97, -103, -109, -115, -999, -999, -999, -999,
  116718. -999, -999, -999, -999, -999, -999, -999, -999,
  116719. -999, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -999, -999, -999, -999, -999, -999},
  116721. {-999, -999, -999, -999, -999, -999, -999, -999,
  116722. -999, -999, -999, -999, -112, -93, -81, -68,
  116723. -62, -60, -60, -57, -63, -70, -77, -82,
  116724. -90, -93, -98, -104, -109, -113, -999, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -999, -999, -999, -999, -999, -999, -999},
  116728. {-999, -999, -999, -999, -999, -999, -999, -999,
  116729. -999, -999, -999, -113, -100, -93, -84, -63,
  116730. -58, -48, -53, -54, -52, -52, -57, -64,
  116731. -66, -76, -83, -81, -85, -85, -90, -95,
  116732. -98, -101, -103, -106, -108, -111, -999, -999,
  116733. -999, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -999, -999, -999, -999, -999},
  116735. {-999, -999, -999, -999, -999, -999, -999, -999,
  116736. -999, -999, -999, -105, -95, -86, -74, -53,
  116737. -50, -38, -43, -49, -43, -42, -39, -39,
  116738. -46, -52, -57, -56, -72, -69, -74, -81,
  116739. -87, -92, -94, -97, -99, -102, -105, -108,
  116740. -999, -999, -999, -999, -999, -999, -999, -999,
  116741. -999, -999, -999, -999, -999, -999, -999, -999},
  116742. {-999, -999, -999, -999, -999, -999, -999, -999,
  116743. -999, -999, -108, -99, -90, -76, -66, -45,
  116744. -43, -41, -44, -47, -43, -47, -40, -30,
  116745. -31, -31, -39, -33, -40, -41, -43, -53,
  116746. -59, -70, -73, -77, -79, -82, -84, -87,
  116747. -999, -999, -999, -999, -999, -999, -999, -999,
  116748. -999, -999, -999, -999, -999, -999, -999, -999}},
  116749. /* 4000 Hz */
  116750. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116751. -999, -999, -999, -999, -999, -110, -91, -76,
  116752. -75, -85, -93, -98, -104, -110, -999, -999,
  116753. -999, -999, -999, -999, -999, -999, -999, -999,
  116754. -999, -999, -999, -999, -999, -999, -999, -999,
  116755. -999, -999, -999, -999, -999, -999, -999, -999,
  116756. -999, -999, -999, -999, -999, -999, -999, -999},
  116757. {-999, -999, -999, -999, -999, -999, -999, -999,
  116758. -999, -999, -999, -999, -999, -110, -91, -70,
  116759. -70, -75, -86, -89, -94, -98, -101, -106,
  116760. -110, -999, -999, -999, -999, -999, -999, -999,
  116761. -999, -999, -999, -999, -999, -999, -999, -999,
  116762. -999, -999, -999, -999, -999, -999, -999, -999,
  116763. -999, -999, -999, -999, -999, -999, -999, -999},
  116764. {-999, -999, -999, -999, -999, -999, -999, -999,
  116765. -999, -999, -999, -999, -110, -95, -80, -60,
  116766. -65, -64, -74, -83, -88, -91, -95, -99,
  116767. -103, -107, -110, -999, -999, -999, -999, -999,
  116768. -999, -999, -999, -999, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -999, -999, -999, -999, -999, -999, -999},
  116771. {-999, -999, -999, -999, -999, -999, -999, -999,
  116772. -999, -999, -999, -999, -110, -95, -80, -58,
  116773. -55, -49, -66, -68, -71, -78, -78, -80,
  116774. -88, -85, -89, -97, -100, -105, -110, -999,
  116775. -999, -999, -999, -999, -999, -999, -999, -999,
  116776. -999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -999, -999, -999, -999, -999, -999},
  116778. {-999, -999, -999, -999, -999, -999, -999, -999,
  116779. -999, -999, -999, -999, -110, -95, -80, -53,
  116780. -52, -41, -59, -59, -49, -58, -56, -63,
  116781. -86, -79, -90, -93, -98, -103, -107, -112,
  116782. -999, -999, -999, -999, -999, -999, -999, -999,
  116783. -999, -999, -999, -999, -999, -999, -999, -999,
  116784. -999, -999, -999, -999, -999, -999, -999, -999},
  116785. {-999, -999, -999, -999, -999, -999, -999, -999,
  116786. -999, -999, -999, -110, -97, -91, -73, -45,
  116787. -40, -33, -53, -61, -49, -54, -50, -50,
  116788. -60, -52, -67, -74, -81, -92, -96, -100,
  116789. -105, -110, -999, -999, -999, -999, -999, -999,
  116790. -999, -999, -999, -999, -999, -999, -999, -999,
  116791. -999, -999, -999, -999, -999, -999, -999, -999}},
  116792. /* 5657 Hz */
  116793. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116794. -999, -999, -999, -113, -106, -99, -92, -77,
  116795. -80, -88, -97, -106, -115, -999, -999, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999,
  116798. -999, -999, -999, -999, -999, -999, -999, -999,
  116799. -999, -999, -999, -999, -999, -999, -999, -999},
  116800. {-999, -999, -999, -999, -999, -999, -999, -999,
  116801. -999, -999, -116, -109, -102, -95, -89, -74,
  116802. -72, -88, -87, -95, -102, -109, -116, -999,
  116803. -999, -999, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999,
  116806. -999, -999, -999, -999, -999, -999, -999, -999},
  116807. {-999, -999, -999, -999, -999, -999, -999, -999,
  116808. -999, -999, -116, -109, -102, -95, -89, -75,
  116809. -66, -74, -77, -78, -86, -87, -90, -96,
  116810. -105, -115, -999, -999, -999, -999, -999, -999,
  116811. -999, -999, -999, -999, -999, -999, -999, -999,
  116812. -999, -999, -999, -999, -999, -999, -999, -999,
  116813. -999, -999, -999, -999, -999, -999, -999, -999},
  116814. {-999, -999, -999, -999, -999, -999, -999, -999,
  116815. -999, -999, -115, -108, -101, -94, -88, -66,
  116816. -56, -61, -70, -65, -78, -72, -83, -84,
  116817. -93, -98, -105, -110, -999, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -999, -999, -999, -999, -999, -999},
  116821. {-999, -999, -999, -999, -999, -999, -999, -999,
  116822. -999, -999, -110, -105, -95, -89, -82, -57,
  116823. -52, -52, -59, -56, -59, -58, -69, -67,
  116824. -88, -82, -82, -89, -94, -100, -108, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999,
  116826. -999, -999, -999, -999, -999, -999, -999, -999,
  116827. -999, -999, -999, -999, -999, -999, -999, -999},
  116828. {-999, -999, -999, -999, -999, -999, -999, -999,
  116829. -999, -110, -101, -96, -90, -83, -77, -54,
  116830. -43, -38, -50, -48, -52, -48, -42, -42,
  116831. -51, -52, -53, -59, -65, -71, -78, -85,
  116832. -95, -999, -999, -999, -999, -999, -999, -999,
  116833. -999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -999, -999, -999, -999, -999, -999, -999}},
  116835. /* 8000 Hz */
  116836. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116837. -999, -999, -999, -999, -120, -105, -86, -68,
  116838. -78, -79, -90, -100, -110, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999,
  116840. -999, -999, -999, -999, -999, -999, -999, -999,
  116841. -999, -999, -999, -999, -999, -999, -999, -999,
  116842. -999, -999, -999, -999, -999, -999, -999, -999},
  116843. {-999, -999, -999, -999, -999, -999, -999, -999,
  116844. -999, -999, -999, -999, -120, -105, -86, -66,
  116845. -73, -77, -88, -96, -105, -115, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -999, -999, -999, -999,
  116849. -999, -999, -999, -999, -999, -999, -999, -999},
  116850. {-999, -999, -999, -999, -999, -999, -999, -999,
  116851. -999, -999, -999, -120, -105, -92, -80, -61,
  116852. -64, -68, -80, -87, -92, -100, -110, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999,
  116854. -999, -999, -999, -999, -999, -999, -999, -999,
  116855. -999, -999, -999, -999, -999, -999, -999, -999,
  116856. -999, -999, -999, -999, -999, -999, -999, -999},
  116857. {-999, -999, -999, -999, -999, -999, -999, -999,
  116858. -999, -999, -999, -120, -104, -91, -79, -52,
  116859. -60, -54, -64, -69, -77, -80, -82, -84,
  116860. -85, -87, -88, -90, -999, -999, -999, -999,
  116861. -999, -999, -999, -999, -999, -999, -999, -999,
  116862. -999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -999, -999, -999, -999, -999, -999},
  116864. {-999, -999, -999, -999, -999, -999, -999, -999,
  116865. -999, -999, -999, -118, -100, -87, -77, -49,
  116866. -50, -44, -58, -61, -61, -67, -65, -62,
  116867. -62, -62, -65, -68, -999, -999, -999, -999,
  116868. -999, -999, -999, -999, -999, -999, -999, -999,
  116869. -999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -999, -999, -999, -999, -999, -999, -999},
  116871. {-999, -999, -999, -999, -999, -999, -999, -999,
  116872. -999, -999, -999, -115, -98, -84, -62, -49,
  116873. -44, -38, -46, -49, -49, -46, -39, -37,
  116874. -39, -40, -42, -43, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999,
  116876. -999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -999, -999, -999, -999, -999, -999, -999}},
  116878. /* 11314 Hz */
  116879. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116880. -999, -999, -999, -999, -999, -110, -88, -74,
  116881. -77, -82, -82, -85, -90, -94, -99, -104,
  116882. -999, -999, -999, -999, -999, -999, -999, -999,
  116883. -999, -999, -999, -999, -999, -999, -999, -999,
  116884. -999, -999, -999, -999, -999, -999, -999, -999,
  116885. -999, -999, -999, -999, -999, -999, -999, -999},
  116886. {-999, -999, -999, -999, -999, -999, -999, -999,
  116887. -999, -999, -999, -999, -999, -110, -88, -66,
  116888. -70, -81, -80, -81, -84, -88, -91, -93,
  116889. -999, -999, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999,
  116891. -999, -999, -999, -999, -999, -999, -999, -999,
  116892. -999, -999, -999, -999, -999, -999, -999, -999},
  116893. {-999, -999, -999, -999, -999, -999, -999, -999,
  116894. -999, -999, -999, -999, -999, -110, -88, -61,
  116895. -63, -70, -71, -74, -77, -80, -83, -85,
  116896. -999, -999, -999, -999, -999, -999, -999, -999,
  116897. -999, -999, -999, -999, -999, -999, -999, -999,
  116898. -999, -999, -999, -999, -999, -999, -999, -999,
  116899. -999, -999, -999, -999, -999, -999, -999, -999},
  116900. {-999, -999, -999, -999, -999, -999, -999, -999,
  116901. -999, -999, -999, -999, -999, -110, -86, -62,
  116902. -63, -62, -62, -58, -52, -50, -50, -52,
  116903. -54, -999, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -999, -999, -999, -999, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -999, -999, -999, -999, -999, -999, -999},
  116907. {-999, -999, -999, -999, -999, -999, -999, -999,
  116908. -999, -999, -999, -999, -118, -108, -84, -53,
  116909. -50, -50, -50, -55, -47, -45, -40, -40,
  116910. -40, -999, -999, -999, -999, -999, -999, -999,
  116911. -999, -999, -999, -999, -999, -999, -999, -999,
  116912. -999, -999, -999, -999, -999, -999, -999, -999,
  116913. -999, -999, -999, -999, -999, -999, -999, -999},
  116914. {-999, -999, -999, -999, -999, -999, -999, -999,
  116915. -999, -999, -999, -999, -118, -100, -73, -43,
  116916. -37, -42, -43, -53, -38, -37, -35, -35,
  116917. -38, -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, -999, -999, -999, -999, -999, -999}},
  116921. /* 16000 Hz */
  116922. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116923. -999, -999, -999, -110, -100, -91, -84, -74,
  116924. -80, -80, -80, -80, -80, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999,
  116926. -999, -999, -999, -999, -999, -999, -999, -999,
  116927. -999, -999, -999, -999, -999, -999, -999, -999,
  116928. -999, -999, -999, -999, -999, -999, -999, -999},
  116929. {-999, -999, -999, -999, -999, -999, -999, -999,
  116930. -999, -999, -999, -110, -100, -91, -84, -74,
  116931. -68, -68, -68, -68, -68, -999, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999,
  116934. -999, -999, -999, -999, -999, -999, -999, -999,
  116935. -999, -999, -999, -999, -999, -999, -999, -999},
  116936. {-999, -999, -999, -999, -999, -999, -999, -999,
  116937. -999, -999, -999, -110, -100, -86, -78, -70,
  116938. -60, -45, -30, -21, -999, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -999, -999, -999, -999, -999, -999,
  116942. -999, -999, -999, -999, -999, -999, -999, -999},
  116943. {-999, -999, -999, -999, -999, -999, -999, -999,
  116944. -999, -999, -999, -110, -100, -87, -78, -67,
  116945. -48, -38, -29, -21, -999, -999, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -999, -999, -999, -999, -999},
  116950. {-999, -999, -999, -999, -999, -999, -999, -999,
  116951. -999, -999, -999, -110, -100, -86, -69, -56,
  116952. -45, -35, -33, -29, -999, -999, -999, -999,
  116953. -999, -999, -999, -999, -999, -999, -999, -999,
  116954. -999, -999, -999, -999, -999, -999, -999, -999,
  116955. -999, -999, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -999, -999, -999, -999, -999, -999},
  116957. {-999, -999, -999, -999, -999, -999, -999, -999,
  116958. -999, -999, -999, -110, -100, -83, -71, -48,
  116959. -27, -38, -37, -34, -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, -999, -999, -999, -999, -999, -999}}
  116964. };
  116965. #endif
  116966. /*** End of inlined file: masking.h ***/
  116967. #define NEGINF -9999.f
  116968. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116969. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116970. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116971. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116972. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116973. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116974. look->channels=vi->channels;
  116975. look->ampmax=-9999.;
  116976. look->gi=gi;
  116977. return(look);
  116978. }
  116979. void _vp_global_free(vorbis_look_psy_global *look){
  116980. if(look){
  116981. memset(look,0,sizeof(*look));
  116982. _ogg_free(look);
  116983. }
  116984. }
  116985. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116986. if(i){
  116987. memset(i,0,sizeof(*i));
  116988. _ogg_free(i);
  116989. }
  116990. }
  116991. void _vi_psy_free(vorbis_info_psy *i){
  116992. if(i){
  116993. memset(i,0,sizeof(*i));
  116994. _ogg_free(i);
  116995. }
  116996. }
  116997. static void min_curve(float *c,
  116998. float *c2){
  116999. int i;
  117000. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117001. }
  117002. static void max_curve(float *c,
  117003. float *c2){
  117004. int i;
  117005. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117006. }
  117007. static void attenuate_curve(float *c,float att){
  117008. int i;
  117009. for(i=0;i<EHMER_MAX;i++)
  117010. c[i]+=att;
  117011. }
  117012. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117013. float center_boost, float center_decay_rate){
  117014. int i,j,k,m;
  117015. float ath[EHMER_MAX];
  117016. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117017. float athc[P_LEVELS][EHMER_MAX];
  117018. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117019. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117020. memset(workc,0,sizeof(workc));
  117021. for(i=0;i<P_BANDS;i++){
  117022. /* we add back in the ATH to avoid low level curves falling off to
  117023. -infinity and unnecessarily cutting off high level curves in the
  117024. curve limiting (last step). */
  117025. /* A half-band's settings must be valid over the whole band, and
  117026. it's better to mask too little than too much */
  117027. int ath_offset=i*4;
  117028. for(j=0;j<EHMER_MAX;j++){
  117029. float min=999.;
  117030. for(k=0;k<4;k++)
  117031. if(j+k+ath_offset<MAX_ATH){
  117032. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117033. }else{
  117034. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117035. }
  117036. ath[j]=min;
  117037. }
  117038. /* copy curves into working space, replicate the 50dB curve to 30
  117039. and 40, replicate the 100dB curve to 110 */
  117040. for(j=0;j<6;j++)
  117041. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117042. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117043. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117044. /* apply centered curve boost/decay */
  117045. for(j=0;j<P_LEVELS;j++){
  117046. for(k=0;k<EHMER_MAX;k++){
  117047. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117048. if(adj<0. && center_boost>0)adj=0.;
  117049. if(adj>0. && center_boost<0)adj=0.;
  117050. workc[i][j][k]+=adj;
  117051. }
  117052. }
  117053. /* normalize curves so the driving amplitude is 0dB */
  117054. /* make temp curves with the ATH overlayed */
  117055. for(j=0;j<P_LEVELS;j++){
  117056. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117057. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117058. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117059. max_curve(athc[j],workc[i][j]);
  117060. }
  117061. /* Now limit the louder curves.
  117062. the idea is this: We don't know what the playback attenuation
  117063. will be; 0dB SL moves every time the user twiddles the volume
  117064. knob. So that means we have to use a single 'most pessimal' curve
  117065. for all masking amplitudes, right? Wrong. The *loudest* sound
  117066. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117067. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117068. etc... */
  117069. for(j=1;j<P_LEVELS;j++){
  117070. min_curve(athc[j],athc[j-1]);
  117071. min_curve(workc[i][j],athc[j]);
  117072. }
  117073. }
  117074. for(i=0;i<P_BANDS;i++){
  117075. int hi_curve,lo_curve,bin;
  117076. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117077. /* low frequency curves are measured with greater resolution than
  117078. the MDCT/FFT will actually give us; we want the curve applied
  117079. to the tone data to be pessimistic and thus apply the minimum
  117080. masking possible for a given bin. That means that a single bin
  117081. could span more than one octave and that the curve will be a
  117082. composite of multiple octaves. It also may mean that a single
  117083. bin may span > an eighth of an octave and that the eighth
  117084. octave values may also be composited. */
  117085. /* which octave curves will we be compositing? */
  117086. bin=floor(fromOC(i*.5)/binHz);
  117087. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117088. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117089. if(lo_curve>i)lo_curve=i;
  117090. if(lo_curve<0)lo_curve=0;
  117091. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117092. for(m=0;m<P_LEVELS;m++){
  117093. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117094. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117095. /* render the curve into bins, then pull values back into curve.
  117096. The point is that any inherent subsampling aliasing results in
  117097. a safe minimum */
  117098. for(k=lo_curve;k<=hi_curve;k++){
  117099. int l=0;
  117100. for(j=0;j<EHMER_MAX;j++){
  117101. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117102. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117103. if(lo_bin<0)lo_bin=0;
  117104. if(lo_bin>n)lo_bin=n;
  117105. if(lo_bin<l)l=lo_bin;
  117106. if(hi_bin<0)hi_bin=0;
  117107. if(hi_bin>n)hi_bin=n;
  117108. for(;l<hi_bin && l<n;l++)
  117109. if(brute_buffer[l]>workc[k][m][j])
  117110. brute_buffer[l]=workc[k][m][j];
  117111. }
  117112. for(;l<n;l++)
  117113. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117114. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117115. }
  117116. /* be equally paranoid about being valid up to next half ocatve */
  117117. if(i+1<P_BANDS){
  117118. int l=0;
  117119. k=i+1;
  117120. for(j=0;j<EHMER_MAX;j++){
  117121. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117122. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117123. if(lo_bin<0)lo_bin=0;
  117124. if(lo_bin>n)lo_bin=n;
  117125. if(lo_bin<l)l=lo_bin;
  117126. if(hi_bin<0)hi_bin=0;
  117127. if(hi_bin>n)hi_bin=n;
  117128. for(;l<hi_bin && l<n;l++)
  117129. if(brute_buffer[l]>workc[k][m][j])
  117130. brute_buffer[l]=workc[k][m][j];
  117131. }
  117132. for(;l<n;l++)
  117133. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117134. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117135. }
  117136. for(j=0;j<EHMER_MAX;j++){
  117137. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117138. if(bin<0){
  117139. ret[i][m][j+2]=-999.;
  117140. }else{
  117141. if(bin>=n){
  117142. ret[i][m][j+2]=-999.;
  117143. }else{
  117144. ret[i][m][j+2]=brute_buffer[bin];
  117145. }
  117146. }
  117147. }
  117148. /* add fenceposts */
  117149. for(j=0;j<EHMER_OFFSET;j++)
  117150. if(ret[i][m][j+2]>-200.f)break;
  117151. ret[i][m][0]=j;
  117152. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117153. if(ret[i][m][j+2]>-200.f)
  117154. break;
  117155. ret[i][m][1]=j;
  117156. }
  117157. }
  117158. return(ret);
  117159. }
  117160. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117161. vorbis_info_psy_global *gi,int n,long rate){
  117162. long i,j,lo=-99,hi=1;
  117163. long maxoc;
  117164. memset(p,0,sizeof(*p));
  117165. p->eighth_octave_lines=gi->eighth_octave_lines;
  117166. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117167. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117168. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117169. p->total_octave_lines=maxoc-p->firstoc+1;
  117170. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117171. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117172. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117173. p->vi=vi;
  117174. p->n=n;
  117175. p->rate=rate;
  117176. /* AoTuV HF weighting */
  117177. p->m_val = 1.;
  117178. if(rate < 26000) p->m_val = 0;
  117179. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117180. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117181. /* set up the lookups for a given blocksize and sample rate */
  117182. for(i=0,j=0;i<MAX_ATH-1;i++){
  117183. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117184. float base=ATH[i];
  117185. if(j<endpos){
  117186. float delta=(ATH[i+1]-base)/(endpos-j);
  117187. for(;j<endpos && j<n;j++){
  117188. p->ath[j]=base+100.;
  117189. base+=delta;
  117190. }
  117191. }
  117192. }
  117193. for(i=0;i<n;i++){
  117194. float bark=toBARK(rate/(2*n)*i);
  117195. for(;lo+vi->noisewindowlomin<i &&
  117196. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117197. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117198. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117199. p->bark[i]=((lo-1)<<16)+(hi-1);
  117200. }
  117201. for(i=0;i<n;i++)
  117202. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117203. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117204. vi->tone_centerboost,vi->tone_decay);
  117205. /* set up rolling noise median */
  117206. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117207. for(i=0;i<P_NOISECURVES;i++)
  117208. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117209. for(i=0;i<n;i++){
  117210. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117211. int inthalfoc;
  117212. float del;
  117213. if(halfoc<0)halfoc=0;
  117214. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117215. inthalfoc=(int)halfoc;
  117216. del=halfoc-inthalfoc;
  117217. for(j=0;j<P_NOISECURVES;j++)
  117218. p->noiseoffset[j][i]=
  117219. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117220. p->vi->noiseoff[j][inthalfoc+1]*del;
  117221. }
  117222. #if 0
  117223. {
  117224. static int ls=0;
  117225. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117226. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117227. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117228. }
  117229. #endif
  117230. }
  117231. void _vp_psy_clear(vorbis_look_psy *p){
  117232. int i,j;
  117233. if(p){
  117234. if(p->ath)_ogg_free(p->ath);
  117235. if(p->octave)_ogg_free(p->octave);
  117236. if(p->bark)_ogg_free(p->bark);
  117237. if(p->tonecurves){
  117238. for(i=0;i<P_BANDS;i++){
  117239. for(j=0;j<P_LEVELS;j++){
  117240. _ogg_free(p->tonecurves[i][j]);
  117241. }
  117242. _ogg_free(p->tonecurves[i]);
  117243. }
  117244. _ogg_free(p->tonecurves);
  117245. }
  117246. if(p->noiseoffset){
  117247. for(i=0;i<P_NOISECURVES;i++){
  117248. _ogg_free(p->noiseoffset[i]);
  117249. }
  117250. _ogg_free(p->noiseoffset);
  117251. }
  117252. memset(p,0,sizeof(*p));
  117253. }
  117254. }
  117255. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117256. static void seed_curve(float *seed,
  117257. const float **curves,
  117258. float amp,
  117259. int oc, int n,
  117260. int linesper,float dBoffset){
  117261. int i,post1;
  117262. int seedptr;
  117263. const float *posts,*curve;
  117264. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117265. choice=max(choice,0);
  117266. choice=min(choice,P_LEVELS-1);
  117267. posts=curves[choice];
  117268. curve=posts+2;
  117269. post1=(int)posts[1];
  117270. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117271. for(i=posts[0];i<post1;i++){
  117272. if(seedptr>0){
  117273. float lin=amp+curve[i];
  117274. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117275. }
  117276. seedptr+=linesper;
  117277. if(seedptr>=n)break;
  117278. }
  117279. }
  117280. static void seed_loop(vorbis_look_psy *p,
  117281. const float ***curves,
  117282. const float *f,
  117283. const float *flr,
  117284. float *seed,
  117285. float specmax){
  117286. vorbis_info_psy *vi=p->vi;
  117287. long n=p->n,i;
  117288. float dBoffset=vi->max_curve_dB-specmax;
  117289. /* prime the working vector with peak values */
  117290. for(i=0;i<n;i++){
  117291. float max=f[i];
  117292. long oc=p->octave[i];
  117293. while(i+1<n && p->octave[i+1]==oc){
  117294. i++;
  117295. if(f[i]>max)max=f[i];
  117296. }
  117297. if(max+6.f>flr[i]){
  117298. oc=oc>>p->shiftoc;
  117299. if(oc>=P_BANDS)oc=P_BANDS-1;
  117300. if(oc<0)oc=0;
  117301. seed_curve(seed,
  117302. curves[oc],
  117303. max,
  117304. p->octave[i]-p->firstoc,
  117305. p->total_octave_lines,
  117306. p->eighth_octave_lines,
  117307. dBoffset);
  117308. }
  117309. }
  117310. }
  117311. static void seed_chase(float *seeds, int linesper, long n){
  117312. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117313. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117314. long stack=0;
  117315. long pos=0;
  117316. long i;
  117317. for(i=0;i<n;i++){
  117318. if(stack<2){
  117319. posstack[stack]=i;
  117320. ampstack[stack++]=seeds[i];
  117321. }else{
  117322. while(1){
  117323. if(seeds[i]<ampstack[stack-1]){
  117324. posstack[stack]=i;
  117325. ampstack[stack++]=seeds[i];
  117326. break;
  117327. }else{
  117328. if(i<posstack[stack-1]+linesper){
  117329. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117330. i<posstack[stack-2]+linesper){
  117331. /* we completely overlap, making stack-1 irrelevant. pop it */
  117332. stack--;
  117333. continue;
  117334. }
  117335. }
  117336. posstack[stack]=i;
  117337. ampstack[stack++]=seeds[i];
  117338. break;
  117339. }
  117340. }
  117341. }
  117342. }
  117343. /* the stack now contains only the positions that are relevant. Scan
  117344. 'em straight through */
  117345. for(i=0;i<stack;i++){
  117346. long endpos;
  117347. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117348. endpos=posstack[i+1];
  117349. }else{
  117350. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117351. discarded in short frames */
  117352. }
  117353. if(endpos>n)endpos=n;
  117354. for(;pos<endpos;pos++)
  117355. seeds[pos]=ampstack[i];
  117356. }
  117357. /* there. Linear time. I now remember this was on a problem set I
  117358. had in Grad Skool... I didn't solve it at the time ;-) */
  117359. }
  117360. /* bleaugh, this is more complicated than it needs to be */
  117361. #include<stdio.h>
  117362. static void max_seeds(vorbis_look_psy *p,
  117363. float *seed,
  117364. float *flr){
  117365. long n=p->total_octave_lines;
  117366. int linesper=p->eighth_octave_lines;
  117367. long linpos=0;
  117368. long pos;
  117369. seed_chase(seed,linesper,n); /* for masking */
  117370. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117371. while(linpos+1<p->n){
  117372. float minV=seed[pos];
  117373. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117374. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117375. while(pos+1<=end){
  117376. pos++;
  117377. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117378. minV=seed[pos];
  117379. }
  117380. end=pos+p->firstoc;
  117381. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117382. if(flr[linpos]<minV)flr[linpos]=minV;
  117383. }
  117384. {
  117385. float minV=seed[p->total_octave_lines-1];
  117386. for(;linpos<p->n;linpos++)
  117387. if(flr[linpos]<minV)flr[linpos]=minV;
  117388. }
  117389. }
  117390. static void bark_noise_hybridmp(int n,const long *b,
  117391. const float *f,
  117392. float *noise,
  117393. const float offset,
  117394. const int fixed){
  117395. float *N=(float*) alloca(n*sizeof(*N));
  117396. float *X=(float*) alloca(n*sizeof(*N));
  117397. float *XX=(float*) alloca(n*sizeof(*N));
  117398. float *Y=(float*) alloca(n*sizeof(*N));
  117399. float *XY=(float*) alloca(n*sizeof(*N));
  117400. float tN, tX, tXX, tY, tXY;
  117401. int i;
  117402. int lo, hi;
  117403. float R, A, B, D;
  117404. float w, x, y;
  117405. tN = tX = tXX = tY = tXY = 0.f;
  117406. y = f[0] + offset;
  117407. if (y < 1.f) y = 1.f;
  117408. w = y * y * .5;
  117409. tN += w;
  117410. tX += w;
  117411. tY += w * y;
  117412. N[0] = tN;
  117413. X[0] = tX;
  117414. XX[0] = tXX;
  117415. Y[0] = tY;
  117416. XY[0] = tXY;
  117417. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117418. y = f[i] + offset;
  117419. if (y < 1.f) y = 1.f;
  117420. w = y * y;
  117421. tN += w;
  117422. tX += w * x;
  117423. tXX += w * x * x;
  117424. tY += w * y;
  117425. tXY += w * x * y;
  117426. N[i] = tN;
  117427. X[i] = tX;
  117428. XX[i] = tXX;
  117429. Y[i] = tY;
  117430. XY[i] = tXY;
  117431. }
  117432. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117433. lo = b[i] >> 16;
  117434. if( lo>=0 ) break;
  117435. hi = b[i] & 0xffff;
  117436. tN = N[hi] + N[-lo];
  117437. tX = X[hi] - X[-lo];
  117438. tXX = XX[hi] + XX[-lo];
  117439. tY = Y[hi] + Y[-lo];
  117440. tXY = XY[hi] - XY[-lo];
  117441. A = tY * tXX - tX * tXY;
  117442. B = tN * tXY - tX * tY;
  117443. D = tN * tXX - tX * tX;
  117444. R = (A + x * B) / D;
  117445. if (R < 0.f)
  117446. R = 0.f;
  117447. noise[i] = R - offset;
  117448. }
  117449. for ( ;; i++, x += 1.f) {
  117450. lo = b[i] >> 16;
  117451. hi = b[i] & 0xffff;
  117452. if(hi>=n)break;
  117453. tN = N[hi] - N[lo];
  117454. tX = X[hi] - X[lo];
  117455. tXX = XX[hi] - XX[lo];
  117456. tY = Y[hi] - Y[lo];
  117457. tXY = XY[hi] - XY[lo];
  117458. A = tY * tXX - tX * tXY;
  117459. B = tN * tXY - tX * tY;
  117460. D = tN * tXX - tX * tX;
  117461. R = (A + x * B) / D;
  117462. if (R < 0.f) R = 0.f;
  117463. noise[i] = R - offset;
  117464. }
  117465. for ( ; i < n; i++, x += 1.f) {
  117466. R = (A + x * B) / D;
  117467. if (R < 0.f) R = 0.f;
  117468. noise[i] = R - offset;
  117469. }
  117470. if (fixed <= 0) return;
  117471. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117472. hi = i + fixed / 2;
  117473. lo = hi - fixed;
  117474. if(lo>=0)break;
  117475. tN = N[hi] + N[-lo];
  117476. tX = X[hi] - X[-lo];
  117477. tXX = XX[hi] + XX[-lo];
  117478. tY = Y[hi] + Y[-lo];
  117479. tXY = XY[hi] - XY[-lo];
  117480. A = tY * tXX - tX * tXY;
  117481. B = tN * tXY - tX * tY;
  117482. D = tN * tXX - tX * tX;
  117483. R = (A + x * B) / D;
  117484. if (R - offset < noise[i]) noise[i] = R - offset;
  117485. }
  117486. for ( ;; i++, x += 1.f) {
  117487. hi = i + fixed / 2;
  117488. lo = hi - fixed;
  117489. if(hi>=n)break;
  117490. tN = N[hi] - N[lo];
  117491. tX = X[hi] - X[lo];
  117492. tXX = XX[hi] - XX[lo];
  117493. tY = Y[hi] - Y[lo];
  117494. tXY = XY[hi] - XY[lo];
  117495. A = tY * tXX - tX * tXY;
  117496. B = tN * tXY - tX * tY;
  117497. D = tN * tXX - tX * tX;
  117498. R = (A + x * B) / D;
  117499. if (R - offset < noise[i]) noise[i] = R - offset;
  117500. }
  117501. for ( ; i < n; i++, x += 1.f) {
  117502. R = (A + x * B) / D;
  117503. if (R - offset < noise[i]) noise[i] = R - offset;
  117504. }
  117505. }
  117506. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117507. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117508. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117509. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117510. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117511. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117512. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117513. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117514. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117515. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117516. 973377.F, 913981.F, 858210.F, 805842.F,
  117517. 756669.F, 710497.F, 667142.F, 626433.F,
  117518. 588208.F, 552316.F, 518613.F, 486967.F,
  117519. 457252.F, 429351.F, 403152.F, 378551.F,
  117520. 355452.F, 333762.F, 313396.F, 294273.F,
  117521. 276316.F, 259455.F, 243623.F, 228757.F,
  117522. 214798.F, 201691.F, 189384.F, 177828.F,
  117523. 166977.F, 156788.F, 147221.F, 138237.F,
  117524. 129802.F, 121881.F, 114444.F, 107461.F,
  117525. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117526. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117527. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117528. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117529. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117530. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117531. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117532. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117533. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117534. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117535. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117536. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117537. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117538. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117539. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117540. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117541. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117542. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117543. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117544. 842.910F, 791.475F, 743.179F, 697.830F,
  117545. 655.249F, 615.265F, 577.722F, 542.469F,
  117546. 509.367F, 478.286F, 449.101F, 421.696F,
  117547. 395.964F, 371.803F, 349.115F, 327.812F,
  117548. 307.809F, 289.026F, 271.390F, 254.830F,
  117549. 239.280F, 224.679F, 210.969F, 198.096F,
  117550. 186.008F, 174.658F, 164.000F, 153.993F,
  117551. 144.596F, 135.773F, 127.488F, 119.708F,
  117552. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117553. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117554. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117555. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117556. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117557. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117558. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117559. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117560. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117561. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117562. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117563. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117564. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117565. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117566. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117567. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117568. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117569. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117570. 1.20790F, 1.13419F, 1.06499F, 1.F
  117571. };
  117572. void _vp_remove_floor(vorbis_look_psy *p,
  117573. float *mdct,
  117574. int *codedflr,
  117575. float *residue,
  117576. int sliding_lowpass){
  117577. int i,n=p->n;
  117578. if(sliding_lowpass>n)sliding_lowpass=n;
  117579. for(i=0;i<sliding_lowpass;i++){
  117580. residue[i]=
  117581. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117582. }
  117583. for(;i<n;i++)
  117584. residue[i]=0.;
  117585. }
  117586. void _vp_noisemask(vorbis_look_psy *p,
  117587. float *logmdct,
  117588. float *logmask){
  117589. int i,n=p->n;
  117590. float *work=(float*) alloca(n*sizeof(*work));
  117591. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117592. 140.,-1);
  117593. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117594. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117595. p->vi->noisewindowfixed);
  117596. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117597. #if 0
  117598. {
  117599. static int seq=0;
  117600. float work2[n];
  117601. for(i=0;i<n;i++){
  117602. work2[i]=logmask[i]+work[i];
  117603. }
  117604. if(seq&1)
  117605. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117606. else
  117607. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117608. if(seq&1)
  117609. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117610. else
  117611. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117612. seq++;
  117613. }
  117614. #endif
  117615. for(i=0;i<n;i++){
  117616. int dB=logmask[i]+.5;
  117617. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117618. if(dB<0)dB=0;
  117619. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117620. }
  117621. }
  117622. void _vp_tonemask(vorbis_look_psy *p,
  117623. float *logfft,
  117624. float *logmask,
  117625. float global_specmax,
  117626. float local_specmax){
  117627. int i,n=p->n;
  117628. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117629. float att=local_specmax+p->vi->ath_adjatt;
  117630. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117631. /* set the ATH (floating below localmax, not global max by a
  117632. specified att) */
  117633. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117634. for(i=0;i<n;i++)
  117635. logmask[i]=p->ath[i]+att;
  117636. /* tone masking */
  117637. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117638. max_seeds(p,seed,logmask);
  117639. }
  117640. void _vp_offset_and_mix(vorbis_look_psy *p,
  117641. float *noise,
  117642. float *tone,
  117643. int offset_select,
  117644. float *logmask,
  117645. float *mdct,
  117646. float *logmdct){
  117647. int i,n=p->n;
  117648. float de, coeffi, cx;/* AoTuV */
  117649. float toneatt=p->vi->tone_masteratt[offset_select];
  117650. cx = p->m_val;
  117651. for(i=0;i<n;i++){
  117652. float val= noise[i]+p->noiseoffset[offset_select][i];
  117653. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117654. logmask[i]=max(val,tone[i]+toneatt);
  117655. /* AoTuV */
  117656. /** @ M1 **
  117657. The following codes improve a noise problem.
  117658. A fundamental idea uses the value of masking and carries out
  117659. the relative compensation of the MDCT.
  117660. However, this code is not perfect and all noise problems cannot be solved.
  117661. by Aoyumi @ 2004/04/18
  117662. */
  117663. if(offset_select == 1) {
  117664. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117665. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117666. if(val > coeffi){
  117667. /* mdct value is > -17.2 dB below floor */
  117668. de = 1.0-((val-coeffi)*0.005*cx);
  117669. /* pro-rated attenuation:
  117670. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117671. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117672. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117673. etc... */
  117674. if(de < 0) de = 0.0001;
  117675. }else
  117676. /* mdct value is <= -17.2 dB below floor */
  117677. de = 1.0-((val-coeffi)*0.0003*cx);
  117678. /* pro-rated attenuation:
  117679. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117680. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117681. etc... */
  117682. mdct[i] *= de;
  117683. }
  117684. }
  117685. }
  117686. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117687. vorbis_info *vi=vd->vi;
  117688. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117689. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117690. int n=ci->blocksizes[vd->W]/2;
  117691. float secs=(float)n/vi->rate;
  117692. amp+=secs*gi->ampmax_att_per_sec;
  117693. if(amp<-9999)amp=-9999;
  117694. return(amp);
  117695. }
  117696. static void couple_lossless(float A, float B,
  117697. float *qA, float *qB){
  117698. int test1=fabs(*qA)>fabs(*qB);
  117699. test1-= fabs(*qA)<fabs(*qB);
  117700. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117701. if(test1==1){
  117702. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117703. }else{
  117704. float temp=*qB;
  117705. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117706. *qA=temp;
  117707. }
  117708. if(*qB>fabs(*qA)*1.9999f){
  117709. *qB= -fabs(*qA)*2.f;
  117710. *qA= -*qA;
  117711. }
  117712. }
  117713. static float hypot_lookup[32]={
  117714. -0.009935, -0.011245, -0.012726, -0.014397,
  117715. -0.016282, -0.018407, -0.020800, -0.023494,
  117716. -0.026522, -0.029923, -0.033737, -0.038010,
  117717. -0.042787, -0.048121, -0.054064, -0.060671,
  117718. -0.068000, -0.076109, -0.085054, -0.094892,
  117719. -0.105675, -0.117451, -0.130260, -0.144134,
  117720. -0.159093, -0.175146, -0.192286, -0.210490,
  117721. -0.229718, -0.249913, -0.271001, -0.292893};
  117722. static void precomputed_couple_point(float premag,
  117723. int floorA,int floorB,
  117724. float *mag, float *ang){
  117725. int test=(floorA>floorB)-1;
  117726. int offset=31-abs(floorA-floorB);
  117727. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117728. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117729. *mag=premag*floormag;
  117730. *ang=0.f;
  117731. }
  117732. /* just like below, this is currently set up to only do
  117733. single-step-depth coupling. Otherwise, we'd have to do more
  117734. copying (which will be inevitable later) */
  117735. /* doing the real circular magnitude calculation is audibly superior
  117736. to (A+B)/sqrt(2) */
  117737. static float dipole_hypot(float a, float b){
  117738. if(a>0.){
  117739. if(b>0.)return sqrt(a*a+b*b);
  117740. if(a>-b)return sqrt(a*a-b*b);
  117741. return -sqrt(b*b-a*a);
  117742. }
  117743. if(b<0.)return -sqrt(a*a+b*b);
  117744. if(-a>b)return -sqrt(a*a-b*b);
  117745. return sqrt(b*b-a*a);
  117746. }
  117747. static float round_hypot(float a, float b){
  117748. if(a>0.){
  117749. if(b>0.)return sqrt(a*a+b*b);
  117750. if(a>-b)return sqrt(a*a+b*b);
  117751. return -sqrt(b*b+a*a);
  117752. }
  117753. if(b<0.)return -sqrt(a*a+b*b);
  117754. if(-a>b)return -sqrt(a*a+b*b);
  117755. return sqrt(b*b+a*a);
  117756. }
  117757. /* revert to round hypot for now */
  117758. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117759. vorbis_info_psy_global *g,
  117760. vorbis_look_psy *p,
  117761. vorbis_info_mapping0 *vi,
  117762. float **mdct){
  117763. int i,j,n=p->n;
  117764. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117765. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117766. for(i=0;i<vi->coupling_steps;i++){
  117767. float *mdctM=mdct[vi->coupling_mag[i]];
  117768. float *mdctA=mdct[vi->coupling_ang[i]];
  117769. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117770. for(j=0;j<limit;j++)
  117771. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117772. for(;j<n;j++)
  117773. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117774. }
  117775. return(ret);
  117776. }
  117777. /* this is for per-channel noise normalization */
  117778. static int JUCE_CDECL apsort(const void *a, const void *b){
  117779. float f1=fabs(**(float**)a);
  117780. float f2=fabs(**(float**)b);
  117781. return (f1<f2)-(f1>f2);
  117782. }
  117783. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117784. vorbis_look_psy *p,
  117785. vorbis_info_mapping0 *vi,
  117786. float **mags){
  117787. if(p->vi->normal_point_p){
  117788. int i,j,k,n=p->n;
  117789. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117790. int partition=p->vi->normal_partition;
  117791. float **work=(float**) alloca(sizeof(*work)*partition);
  117792. for(i=0;i<vi->coupling_steps;i++){
  117793. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117794. for(j=0;j<n;j+=partition){
  117795. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117796. qsort(work,partition,sizeof(*work),apsort);
  117797. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117798. }
  117799. }
  117800. return(ret);
  117801. }
  117802. return(NULL);
  117803. }
  117804. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117805. float *magnitudes,int *sortedindex){
  117806. int i,j,n=p->n;
  117807. vorbis_info_psy *vi=p->vi;
  117808. int partition=vi->normal_partition;
  117809. float **work=(float**) alloca(sizeof(*work)*partition);
  117810. int start=vi->normal_start;
  117811. for(j=start;j<n;j+=partition){
  117812. if(j+partition>n)partition=n-j;
  117813. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117814. qsort(work,partition,sizeof(*work),apsort);
  117815. for(i=0;i<partition;i++){
  117816. sortedindex[i+j-start]=work[i]-magnitudes;
  117817. }
  117818. }
  117819. }
  117820. void _vp_noise_normalize(vorbis_look_psy *p,
  117821. float *in,float *out,int *sortedindex){
  117822. int flag=0,i,j=0,n=p->n;
  117823. vorbis_info_psy *vi=p->vi;
  117824. int partition=vi->normal_partition;
  117825. int start=vi->normal_start;
  117826. if(start>n)start=n;
  117827. if(vi->normal_channel_p){
  117828. for(;j<start;j++)
  117829. out[j]=rint(in[j]);
  117830. for(;j+partition<=n;j+=partition){
  117831. float acc=0.;
  117832. int k;
  117833. for(i=j;i<j+partition;i++)
  117834. acc+=in[i]*in[i];
  117835. for(i=0;i<partition;i++){
  117836. k=sortedindex[i+j-start];
  117837. if(in[k]*in[k]>=.25f){
  117838. out[k]=rint(in[k]);
  117839. acc-=in[k]*in[k];
  117840. flag=1;
  117841. }else{
  117842. if(acc<vi->normal_thresh)break;
  117843. out[k]=unitnorm(in[k]);
  117844. acc-=1.;
  117845. }
  117846. }
  117847. for(;i<partition;i++){
  117848. k=sortedindex[i+j-start];
  117849. out[k]=0.;
  117850. }
  117851. }
  117852. }
  117853. for(;j<n;j++)
  117854. out[j]=rint(in[j]);
  117855. }
  117856. void _vp_couple(int blobno,
  117857. vorbis_info_psy_global *g,
  117858. vorbis_look_psy *p,
  117859. vorbis_info_mapping0 *vi,
  117860. float **res,
  117861. float **mag_memo,
  117862. int **mag_sort,
  117863. int **ifloor,
  117864. int *nonzero,
  117865. int sliding_lowpass){
  117866. int i,j,k,n=p->n;
  117867. /* perform any requested channel coupling */
  117868. /* point stereo can only be used in a first stage (in this encoder)
  117869. because of the dependency on floor lookups */
  117870. for(i=0;i<vi->coupling_steps;i++){
  117871. /* once we're doing multistage coupling in which a channel goes
  117872. through more than one coupling step, the floor vector
  117873. magnitudes will also have to be recalculated an propogated
  117874. along with PCM. Right now, we're not (that will wait until 5.1
  117875. most likely), so the code isn't here yet. The memory management
  117876. here is all assuming single depth couplings anyway. */
  117877. /* make sure coupling a zero and a nonzero channel results in two
  117878. nonzero channels. */
  117879. if(nonzero[vi->coupling_mag[i]] ||
  117880. nonzero[vi->coupling_ang[i]]){
  117881. float *rM=res[vi->coupling_mag[i]];
  117882. float *rA=res[vi->coupling_ang[i]];
  117883. float *qM=rM+n;
  117884. float *qA=rA+n;
  117885. int *floorM=ifloor[vi->coupling_mag[i]];
  117886. int *floorA=ifloor[vi->coupling_ang[i]];
  117887. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117888. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117889. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117890. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117891. int pointlimit=limit;
  117892. nonzero[vi->coupling_mag[i]]=1;
  117893. nonzero[vi->coupling_ang[i]]=1;
  117894. /* The threshold of a stereo is changed with the size of n */
  117895. if(n > 1000)
  117896. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117897. for(j=0;j<p->n;j+=partition){
  117898. float acc=0.f;
  117899. for(k=0;k<partition;k++){
  117900. int l=k+j;
  117901. if(l<sliding_lowpass){
  117902. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117903. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117904. precomputed_couple_point(mag_memo[i][l],
  117905. floorM[l],floorA[l],
  117906. qM+l,qA+l);
  117907. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117908. }else{
  117909. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117910. }
  117911. }else{
  117912. qM[l]=0.;
  117913. qA[l]=0.;
  117914. }
  117915. }
  117916. if(p->vi->normal_point_p){
  117917. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117918. int l=mag_sort[i][j+k];
  117919. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117920. qM[l]=unitnorm(qM[l]);
  117921. acc-=1.f;
  117922. }
  117923. }
  117924. }
  117925. }
  117926. }
  117927. }
  117928. }
  117929. /* AoTuV */
  117930. /** @ M2 **
  117931. The boost problem by the combination of noise normalization and point stereo is eased.
  117932. However, this is a temporary patch.
  117933. by Aoyumi @ 2004/04/18
  117934. */
  117935. void hf_reduction(vorbis_info_psy_global *g,
  117936. vorbis_look_psy *p,
  117937. vorbis_info_mapping0 *vi,
  117938. float **mdct){
  117939. int i,j,n=p->n, de=0.3*p->m_val;
  117940. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117941. for(i=0; i<vi->coupling_steps; i++){
  117942. /* for(j=start; j<limit; j++){} // ???*/
  117943. for(j=limit; j<n; j++)
  117944. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117945. }
  117946. }
  117947. #endif
  117948. /*** End of inlined file: psy.c ***/
  117949. /*** Start of inlined file: registry.c ***/
  117950. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117951. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117952. // tasks..
  117953. #if JUCE_MSVC
  117954. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117955. #endif
  117956. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117957. #if JUCE_USE_OGGVORBIS
  117958. /* seems like major overkill now; the backend numbers will grow into
  117959. the infrastructure soon enough */
  117960. extern vorbis_func_floor floor0_exportbundle;
  117961. extern vorbis_func_floor floor1_exportbundle;
  117962. extern vorbis_func_residue residue0_exportbundle;
  117963. extern vorbis_func_residue residue1_exportbundle;
  117964. extern vorbis_func_residue residue2_exportbundle;
  117965. extern vorbis_func_mapping mapping0_exportbundle;
  117966. vorbis_func_floor *_floor_P[]={
  117967. &floor0_exportbundle,
  117968. &floor1_exportbundle,
  117969. };
  117970. vorbis_func_residue *_residue_P[]={
  117971. &residue0_exportbundle,
  117972. &residue1_exportbundle,
  117973. &residue2_exportbundle,
  117974. };
  117975. vorbis_func_mapping *_mapping_P[]={
  117976. &mapping0_exportbundle,
  117977. };
  117978. #endif
  117979. /*** End of inlined file: registry.c ***/
  117980. /*** Start of inlined file: res0.c ***/
  117981. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117982. encode/decode loops are coded for clarity and performance is not
  117983. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117984. it's slow. */
  117985. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117986. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117987. // tasks..
  117988. #if JUCE_MSVC
  117989. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117990. #endif
  117991. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117992. #if JUCE_USE_OGGVORBIS
  117993. #include <stdlib.h>
  117994. #include <string.h>
  117995. #include <math.h>
  117996. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117997. #include <stdio.h>
  117998. #endif
  117999. typedef struct {
  118000. vorbis_info_residue0 *info;
  118001. int parts;
  118002. int stages;
  118003. codebook *fullbooks;
  118004. codebook *phrasebook;
  118005. codebook ***partbooks;
  118006. int partvals;
  118007. int **decodemap;
  118008. long postbits;
  118009. long phrasebits;
  118010. long frames;
  118011. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118012. int train_seq;
  118013. long *training_data[8][64];
  118014. float training_max[8][64];
  118015. float training_min[8][64];
  118016. float tmin;
  118017. float tmax;
  118018. #endif
  118019. } vorbis_look_residue0;
  118020. void res0_free_info(vorbis_info_residue *i){
  118021. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118022. if(info){
  118023. memset(info,0,sizeof(*info));
  118024. _ogg_free(info);
  118025. }
  118026. }
  118027. void res0_free_look(vorbis_look_residue *i){
  118028. int j;
  118029. if(i){
  118030. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118031. #ifdef TRAIN_RES
  118032. {
  118033. int j,k,l;
  118034. for(j=0;j<look->parts;j++){
  118035. /*fprintf(stderr,"partition %d: ",j);*/
  118036. for(k=0;k<8;k++)
  118037. if(look->training_data[k][j]){
  118038. char buffer[80];
  118039. FILE *of;
  118040. codebook *statebook=look->partbooks[j][k];
  118041. /* long and short into the same bucket by current convention */
  118042. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118043. of=fopen(buffer,"a");
  118044. for(l=0;l<statebook->entries;l++)
  118045. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118046. fclose(of);
  118047. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118048. look->training_min[k][j],look->training_max[k][j]);*/
  118049. _ogg_free(look->training_data[k][j]);
  118050. look->training_data[k][j]=NULL;
  118051. }
  118052. /*fprintf(stderr,"\n");*/
  118053. }
  118054. }
  118055. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118056. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118057. (float)look->phrasebits/look->frames,
  118058. (float)look->postbits/look->frames,
  118059. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118060. #endif
  118061. /*vorbis_info_residue0 *info=look->info;
  118062. fprintf(stderr,
  118063. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118064. "(%g/frame) \n",look->frames,look->phrasebits,
  118065. look->resbitsflat,
  118066. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118067. for(j=0;j<look->parts;j++){
  118068. long acc=0;
  118069. fprintf(stderr,"\t[%d] == ",j);
  118070. for(k=0;k<look->stages;k++)
  118071. if((info->secondstages[j]>>k)&1){
  118072. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118073. acc+=look->resbits[j][k];
  118074. }
  118075. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118076. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118077. }
  118078. fprintf(stderr,"\n");*/
  118079. for(j=0;j<look->parts;j++)
  118080. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118081. _ogg_free(look->partbooks);
  118082. for(j=0;j<look->partvals;j++)
  118083. _ogg_free(look->decodemap[j]);
  118084. _ogg_free(look->decodemap);
  118085. memset(look,0,sizeof(*look));
  118086. _ogg_free(look);
  118087. }
  118088. }
  118089. static int icount(unsigned int v){
  118090. int ret=0;
  118091. while(v){
  118092. ret+=v&1;
  118093. v>>=1;
  118094. }
  118095. return(ret);
  118096. }
  118097. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118098. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118099. int j,acc=0;
  118100. oggpack_write(opb,info->begin,24);
  118101. oggpack_write(opb,info->end,24);
  118102. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118103. code with a partitioned book */
  118104. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118105. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118106. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118107. bitmask of one indicates this partition class has bits to write
  118108. this pass */
  118109. for(j=0;j<info->partitions;j++){
  118110. if(ilog(info->secondstages[j])>3){
  118111. /* yes, this is a minor hack due to not thinking ahead */
  118112. oggpack_write(opb,info->secondstages[j],3);
  118113. oggpack_write(opb,1,1);
  118114. oggpack_write(opb,info->secondstages[j]>>3,5);
  118115. }else
  118116. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118117. acc+=icount(info->secondstages[j]);
  118118. }
  118119. for(j=0;j<acc;j++)
  118120. oggpack_write(opb,info->booklist[j],8);
  118121. }
  118122. /* vorbis_info is for range checking */
  118123. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118124. int j,acc=0;
  118125. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118126. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118127. info->begin=oggpack_read(opb,24);
  118128. info->end=oggpack_read(opb,24);
  118129. info->grouping=oggpack_read(opb,24)+1;
  118130. info->partitions=oggpack_read(opb,6)+1;
  118131. info->groupbook=oggpack_read(opb,8);
  118132. for(j=0;j<info->partitions;j++){
  118133. int cascade=oggpack_read(opb,3);
  118134. if(oggpack_read(opb,1))
  118135. cascade|=(oggpack_read(opb,5)<<3);
  118136. info->secondstages[j]=cascade;
  118137. acc+=icount(cascade);
  118138. }
  118139. for(j=0;j<acc;j++)
  118140. info->booklist[j]=oggpack_read(opb,8);
  118141. if(info->groupbook>=ci->books)goto errout;
  118142. for(j=0;j<acc;j++)
  118143. if(info->booklist[j]>=ci->books)goto errout;
  118144. return(info);
  118145. errout:
  118146. res0_free_info(info);
  118147. return(NULL);
  118148. }
  118149. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118150. vorbis_info_residue *vr){
  118151. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118152. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118153. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118154. int j,k,acc=0;
  118155. int dim;
  118156. int maxstage=0;
  118157. look->info=info;
  118158. look->parts=info->partitions;
  118159. look->fullbooks=ci->fullbooks;
  118160. look->phrasebook=ci->fullbooks+info->groupbook;
  118161. dim=look->phrasebook->dim;
  118162. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118163. for(j=0;j<look->parts;j++){
  118164. int stages=ilog(info->secondstages[j]);
  118165. if(stages){
  118166. if(stages>maxstage)maxstage=stages;
  118167. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118168. for(k=0;k<stages;k++)
  118169. if(info->secondstages[j]&(1<<k)){
  118170. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118171. #ifdef TRAIN_RES
  118172. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118173. sizeof(***look->training_data));
  118174. #endif
  118175. }
  118176. }
  118177. }
  118178. look->partvals=rint(pow((float)look->parts,(float)dim));
  118179. look->stages=maxstage;
  118180. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118181. for(j=0;j<look->partvals;j++){
  118182. long val=j;
  118183. long mult=look->partvals/look->parts;
  118184. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118185. for(k=0;k<dim;k++){
  118186. long deco=val/mult;
  118187. val-=deco*mult;
  118188. mult/=look->parts;
  118189. look->decodemap[j][k]=deco;
  118190. }
  118191. }
  118192. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118193. {
  118194. static int train_seq=0;
  118195. look->train_seq=train_seq++;
  118196. }
  118197. #endif
  118198. return(look);
  118199. }
  118200. /* break an abstraction and copy some code for performance purposes */
  118201. static int local_book_besterror(codebook *book,float *a){
  118202. int dim=book->dim,i,k,o;
  118203. int best=0;
  118204. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118205. /* find the quant val of each scalar */
  118206. for(k=0,o=dim;k<dim;++k){
  118207. float val=a[--o];
  118208. i=tt->threshvals>>1;
  118209. if(val<tt->quantthresh[i]){
  118210. if(val<tt->quantthresh[i-1]){
  118211. for(--i;i>0;--i)
  118212. if(val>=tt->quantthresh[i-1])
  118213. break;
  118214. }
  118215. }else{
  118216. for(++i;i<tt->threshvals-1;++i)
  118217. if(val<tt->quantthresh[i])break;
  118218. }
  118219. best=(best*tt->quantvals)+tt->quantmap[i];
  118220. }
  118221. /* regular lattices are easy :-) */
  118222. if(book->c->lengthlist[best]<=0){
  118223. const static_codebook *c=book->c;
  118224. int i,j;
  118225. float bestf=0.f;
  118226. float *e=book->valuelist;
  118227. best=-1;
  118228. for(i=0;i<book->entries;i++){
  118229. if(c->lengthlist[i]>0){
  118230. float thisx=0.f;
  118231. for(j=0;j<dim;j++){
  118232. float val=(e[j]-a[j]);
  118233. thisx+=val*val;
  118234. }
  118235. if(best==-1 || thisx<bestf){
  118236. bestf=thisx;
  118237. best=i;
  118238. }
  118239. }
  118240. e+=dim;
  118241. }
  118242. }
  118243. {
  118244. float *ptr=book->valuelist+best*dim;
  118245. for(i=0;i<dim;i++)
  118246. *a++ -= *ptr++;
  118247. }
  118248. return(best);
  118249. }
  118250. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118251. codebook *book,long *acc){
  118252. int i,bits=0;
  118253. int dim=book->dim;
  118254. int step=n/dim;
  118255. for(i=0;i<step;i++){
  118256. int entry=local_book_besterror(book,vec+i*dim);
  118257. #ifdef TRAIN_RES
  118258. acc[entry]++;
  118259. #endif
  118260. bits+=vorbis_book_encode(book,entry,opb);
  118261. }
  118262. return(bits);
  118263. }
  118264. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118265. float **in,int ch){
  118266. long i,j,k;
  118267. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118268. vorbis_info_residue0 *info=look->info;
  118269. /* move all this setup out later */
  118270. int samples_per_partition=info->grouping;
  118271. int possible_partitions=info->partitions;
  118272. int n=info->end-info->begin;
  118273. int partvals=n/samples_per_partition;
  118274. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118275. float scale=100./samples_per_partition;
  118276. /* we find the partition type for each partition of each
  118277. channel. We'll go back and do the interleaved encoding in a
  118278. bit. For now, clarity */
  118279. for(i=0;i<ch;i++){
  118280. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118281. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118282. }
  118283. for(i=0;i<partvals;i++){
  118284. int offset=i*samples_per_partition+info->begin;
  118285. for(j=0;j<ch;j++){
  118286. float max=0.;
  118287. float ent=0.;
  118288. for(k=0;k<samples_per_partition;k++){
  118289. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118290. ent+=fabs(rint(in[j][offset+k]));
  118291. }
  118292. ent*=scale;
  118293. for(k=0;k<possible_partitions-1;k++)
  118294. if(max<=info->classmetric1[k] &&
  118295. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118296. break;
  118297. partword[j][i]=k;
  118298. }
  118299. }
  118300. #ifdef TRAIN_RESAUX
  118301. {
  118302. FILE *of;
  118303. char buffer[80];
  118304. for(i=0;i<ch;i++){
  118305. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118306. of=fopen(buffer,"a");
  118307. for(j=0;j<partvals;j++)
  118308. fprintf(of,"%ld, ",partword[i][j]);
  118309. fprintf(of,"\n");
  118310. fclose(of);
  118311. }
  118312. }
  118313. #endif
  118314. look->frames++;
  118315. return(partword);
  118316. }
  118317. /* designed for stereo or other modes where the partition size is an
  118318. integer multiple of the number of channels encoded in the current
  118319. submap */
  118320. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118321. int ch){
  118322. long i,j,k,l;
  118323. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118324. vorbis_info_residue0 *info=look->info;
  118325. /* move all this setup out later */
  118326. int samples_per_partition=info->grouping;
  118327. int possible_partitions=info->partitions;
  118328. int n=info->end-info->begin;
  118329. int partvals=n/samples_per_partition;
  118330. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118331. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118332. FILE *of;
  118333. char buffer[80];
  118334. #endif
  118335. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118336. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118337. for(i=0,l=info->begin/ch;i<partvals;i++){
  118338. float magmax=0.f;
  118339. float angmax=0.f;
  118340. for(j=0;j<samples_per_partition;j+=ch){
  118341. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118342. for(k=1;k<ch;k++)
  118343. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118344. l++;
  118345. }
  118346. for(j=0;j<possible_partitions-1;j++)
  118347. if(magmax<=info->classmetric1[j] &&
  118348. angmax<=info->classmetric2[j])
  118349. break;
  118350. partword[0][i]=j;
  118351. }
  118352. #ifdef TRAIN_RESAUX
  118353. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118354. of=fopen(buffer,"a");
  118355. for(i=0;i<partvals;i++)
  118356. fprintf(of,"%ld, ",partword[0][i]);
  118357. fprintf(of,"\n");
  118358. fclose(of);
  118359. #endif
  118360. look->frames++;
  118361. return(partword);
  118362. }
  118363. static int _01forward(oggpack_buffer *opb,
  118364. vorbis_block *vb,vorbis_look_residue *vl,
  118365. float **in,int ch,
  118366. long **partword,
  118367. int (*encode)(oggpack_buffer *,float *,int,
  118368. codebook *,long *)){
  118369. long i,j,k,s;
  118370. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118371. vorbis_info_residue0 *info=look->info;
  118372. /* move all this setup out later */
  118373. int samples_per_partition=info->grouping;
  118374. int possible_partitions=info->partitions;
  118375. int partitions_per_word=look->phrasebook->dim;
  118376. int n=info->end-info->begin;
  118377. int partvals=n/samples_per_partition;
  118378. long resbits[128];
  118379. long resvals[128];
  118380. #ifdef TRAIN_RES
  118381. for(i=0;i<ch;i++)
  118382. for(j=info->begin;j<info->end;j++){
  118383. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118384. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118385. }
  118386. #endif
  118387. memset(resbits,0,sizeof(resbits));
  118388. memset(resvals,0,sizeof(resvals));
  118389. /* we code the partition words for each channel, then the residual
  118390. words for a partition per channel until we've written all the
  118391. residual words for that partition word. Then write the next
  118392. partition channel words... */
  118393. for(s=0;s<look->stages;s++){
  118394. for(i=0;i<partvals;){
  118395. /* first we encode a partition codeword for each channel */
  118396. if(s==0){
  118397. for(j=0;j<ch;j++){
  118398. long val=partword[j][i];
  118399. for(k=1;k<partitions_per_word;k++){
  118400. val*=possible_partitions;
  118401. if(i+k<partvals)
  118402. val+=partword[j][i+k];
  118403. }
  118404. /* training hack */
  118405. if(val<look->phrasebook->entries)
  118406. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118407. #if 0 /*def TRAIN_RES*/
  118408. else
  118409. fprintf(stderr,"!");
  118410. #endif
  118411. }
  118412. }
  118413. /* now we encode interleaved residual values for the partitions */
  118414. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118415. long offset=i*samples_per_partition+info->begin;
  118416. for(j=0;j<ch;j++){
  118417. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118418. if(info->secondstages[partword[j][i]]&(1<<s)){
  118419. codebook *statebook=look->partbooks[partword[j][i]][s];
  118420. if(statebook){
  118421. int ret;
  118422. long *accumulator=NULL;
  118423. #ifdef TRAIN_RES
  118424. accumulator=look->training_data[s][partword[j][i]];
  118425. {
  118426. int l;
  118427. float *samples=in[j]+offset;
  118428. for(l=0;l<samples_per_partition;l++){
  118429. if(samples[l]<look->training_min[s][partword[j][i]])
  118430. look->training_min[s][partword[j][i]]=samples[l];
  118431. if(samples[l]>look->training_max[s][partword[j][i]])
  118432. look->training_max[s][partword[j][i]]=samples[l];
  118433. }
  118434. }
  118435. #endif
  118436. ret=encode(opb,in[j]+offset,samples_per_partition,
  118437. statebook,accumulator);
  118438. look->postbits+=ret;
  118439. resbits[partword[j][i]]+=ret;
  118440. }
  118441. }
  118442. }
  118443. }
  118444. }
  118445. }
  118446. /*{
  118447. long total=0;
  118448. long totalbits=0;
  118449. fprintf(stderr,"%d :: ",vb->mode);
  118450. for(k=0;k<possible_partitions;k++){
  118451. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118452. total+=resvals[k];
  118453. totalbits+=resbits[k];
  118454. }
  118455. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118456. }*/
  118457. return(0);
  118458. }
  118459. /* a truncated packet here just means 'stop working'; it's not an error */
  118460. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118461. float **in,int ch,
  118462. long (*decodepart)(codebook *, float *,
  118463. oggpack_buffer *,int)){
  118464. long i,j,k,l,s;
  118465. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118466. vorbis_info_residue0 *info=look->info;
  118467. /* move all this setup out later */
  118468. int samples_per_partition=info->grouping;
  118469. int partitions_per_word=look->phrasebook->dim;
  118470. int n=info->end-info->begin;
  118471. int partvals=n/samples_per_partition;
  118472. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118473. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118474. for(j=0;j<ch;j++)
  118475. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118476. for(s=0;s<look->stages;s++){
  118477. /* each loop decodes on partition codeword containing
  118478. partitions_pre_word partitions */
  118479. for(i=0,l=0;i<partvals;l++){
  118480. if(s==0){
  118481. /* fetch the partition word for each channel */
  118482. for(j=0;j<ch;j++){
  118483. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118484. if(temp==-1)goto eopbreak;
  118485. partword[j][l]=look->decodemap[temp];
  118486. if(partword[j][l]==NULL)goto errout;
  118487. }
  118488. }
  118489. /* now we decode residual values for the partitions */
  118490. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118491. for(j=0;j<ch;j++){
  118492. long offset=info->begin+i*samples_per_partition;
  118493. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118494. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118495. if(stagebook){
  118496. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118497. samples_per_partition)==-1)goto eopbreak;
  118498. }
  118499. }
  118500. }
  118501. }
  118502. }
  118503. errout:
  118504. eopbreak:
  118505. return(0);
  118506. }
  118507. #if 0
  118508. /* residue 0 and 1 are just slight variants of one another. 0 is
  118509. interleaved, 1 is not */
  118510. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118511. float **in,int *nonzero,int ch){
  118512. /* we encode only the nonzero parts of a bundle */
  118513. int i,used=0;
  118514. for(i=0;i<ch;i++)
  118515. if(nonzero[i])
  118516. in[used++]=in[i];
  118517. if(used)
  118518. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118519. return(_01class(vb,vl,in,used));
  118520. else
  118521. return(0);
  118522. }
  118523. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118524. float **in,float **out,int *nonzero,int ch,
  118525. long **partword){
  118526. /* we encode only the nonzero parts of a bundle */
  118527. int i,j,used=0,n=vb->pcmend/2;
  118528. for(i=0;i<ch;i++)
  118529. if(nonzero[i]){
  118530. if(out)
  118531. for(j=0;j<n;j++)
  118532. out[i][j]+=in[i][j];
  118533. in[used++]=in[i];
  118534. }
  118535. if(used){
  118536. int ret=_01forward(vb,vl,in,used,partword,
  118537. _interleaved_encodepart);
  118538. if(out){
  118539. used=0;
  118540. for(i=0;i<ch;i++)
  118541. if(nonzero[i]){
  118542. for(j=0;j<n;j++)
  118543. out[i][j]-=in[used][j];
  118544. used++;
  118545. }
  118546. }
  118547. return(ret);
  118548. }else{
  118549. return(0);
  118550. }
  118551. }
  118552. #endif
  118553. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118554. float **in,int *nonzero,int ch){
  118555. int i,used=0;
  118556. for(i=0;i<ch;i++)
  118557. if(nonzero[i])
  118558. in[used++]=in[i];
  118559. if(used)
  118560. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118561. else
  118562. return(0);
  118563. }
  118564. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118565. float **in,float **out,int *nonzero,int ch,
  118566. long **partword){
  118567. int i,j,used=0,n=vb->pcmend/2;
  118568. for(i=0;i<ch;i++)
  118569. if(nonzero[i]){
  118570. if(out)
  118571. for(j=0;j<n;j++)
  118572. out[i][j]+=in[i][j];
  118573. in[used++]=in[i];
  118574. }
  118575. if(used){
  118576. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118577. if(out){
  118578. used=0;
  118579. for(i=0;i<ch;i++)
  118580. if(nonzero[i]){
  118581. for(j=0;j<n;j++)
  118582. out[i][j]-=in[used][j];
  118583. used++;
  118584. }
  118585. }
  118586. return(ret);
  118587. }else{
  118588. return(0);
  118589. }
  118590. }
  118591. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118592. float **in,int *nonzero,int ch){
  118593. int i,used=0;
  118594. for(i=0;i<ch;i++)
  118595. if(nonzero[i])
  118596. in[used++]=in[i];
  118597. if(used)
  118598. return(_01class(vb,vl,in,used));
  118599. else
  118600. return(0);
  118601. }
  118602. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118603. float **in,int *nonzero,int ch){
  118604. int i,used=0;
  118605. for(i=0;i<ch;i++)
  118606. if(nonzero[i])
  118607. in[used++]=in[i];
  118608. if(used)
  118609. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118610. else
  118611. return(0);
  118612. }
  118613. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118614. float **in,int *nonzero,int ch){
  118615. int i,used=0;
  118616. for(i=0;i<ch;i++)
  118617. if(nonzero[i])used++;
  118618. if(used)
  118619. return(_2class(vb,vl,in,ch));
  118620. else
  118621. return(0);
  118622. }
  118623. /* res2 is slightly more different; all the channels are interleaved
  118624. into a single vector and encoded. */
  118625. int res2_forward(oggpack_buffer *opb,
  118626. vorbis_block *vb,vorbis_look_residue *vl,
  118627. float **in,float **out,int *nonzero,int ch,
  118628. long **partword){
  118629. long i,j,k,n=vb->pcmend/2,used=0;
  118630. /* don't duplicate the code; use a working vector hack for now and
  118631. reshape ourselves into a single channel res1 */
  118632. /* ugly; reallocs for each coupling pass :-( */
  118633. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118634. for(i=0;i<ch;i++){
  118635. float *pcm=in[i];
  118636. if(nonzero[i])used++;
  118637. for(j=0,k=i;j<n;j++,k+=ch)
  118638. work[k]=pcm[j];
  118639. }
  118640. if(used){
  118641. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118642. /* update the sofar vector */
  118643. if(out){
  118644. for(i=0;i<ch;i++){
  118645. float *pcm=in[i];
  118646. float *sofar=out[i];
  118647. for(j=0,k=i;j<n;j++,k+=ch)
  118648. sofar[j]+=pcm[j]-work[k];
  118649. }
  118650. }
  118651. return(ret);
  118652. }else{
  118653. return(0);
  118654. }
  118655. }
  118656. /* duplicate code here as speed is somewhat more important */
  118657. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118658. float **in,int *nonzero,int ch){
  118659. long i,k,l,s;
  118660. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118661. vorbis_info_residue0 *info=look->info;
  118662. /* move all this setup out later */
  118663. int samples_per_partition=info->grouping;
  118664. int partitions_per_word=look->phrasebook->dim;
  118665. int n=info->end-info->begin;
  118666. int partvals=n/samples_per_partition;
  118667. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118668. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118669. for(i=0;i<ch;i++)if(nonzero[i])break;
  118670. if(i==ch)return(0); /* no nonzero vectors */
  118671. for(s=0;s<look->stages;s++){
  118672. for(i=0,l=0;i<partvals;l++){
  118673. if(s==0){
  118674. /* fetch the partition word */
  118675. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118676. if(temp==-1)goto eopbreak;
  118677. partword[l]=look->decodemap[temp];
  118678. if(partword[l]==NULL)goto errout;
  118679. }
  118680. /* now we decode residual values for the partitions */
  118681. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118682. if(info->secondstages[partword[l][k]]&(1<<s)){
  118683. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118684. if(stagebook){
  118685. if(vorbis_book_decodevv_add(stagebook,in,
  118686. i*samples_per_partition+info->begin,ch,
  118687. &vb->opb,samples_per_partition)==-1)
  118688. goto eopbreak;
  118689. }
  118690. }
  118691. }
  118692. }
  118693. errout:
  118694. eopbreak:
  118695. return(0);
  118696. }
  118697. vorbis_func_residue residue0_exportbundle={
  118698. NULL,
  118699. &res0_unpack,
  118700. &res0_look,
  118701. &res0_free_info,
  118702. &res0_free_look,
  118703. NULL,
  118704. NULL,
  118705. &res0_inverse
  118706. };
  118707. vorbis_func_residue residue1_exportbundle={
  118708. &res0_pack,
  118709. &res0_unpack,
  118710. &res0_look,
  118711. &res0_free_info,
  118712. &res0_free_look,
  118713. &res1_class,
  118714. &res1_forward,
  118715. &res1_inverse
  118716. };
  118717. vorbis_func_residue residue2_exportbundle={
  118718. &res0_pack,
  118719. &res0_unpack,
  118720. &res0_look,
  118721. &res0_free_info,
  118722. &res0_free_look,
  118723. &res2_class,
  118724. &res2_forward,
  118725. &res2_inverse
  118726. };
  118727. #endif
  118728. /*** End of inlined file: res0.c ***/
  118729. /*** Start of inlined file: sharedbook.c ***/
  118730. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118731. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118732. // tasks..
  118733. #if JUCE_MSVC
  118734. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118735. #endif
  118736. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118737. #if JUCE_USE_OGGVORBIS
  118738. #include <stdlib.h>
  118739. #include <math.h>
  118740. #include <string.h>
  118741. /**** pack/unpack helpers ******************************************/
  118742. int _ilog(unsigned int v){
  118743. int ret=0;
  118744. while(v){
  118745. ret++;
  118746. v>>=1;
  118747. }
  118748. return(ret);
  118749. }
  118750. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118751. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118752. Why not IEEE? It's just not that important here. */
  118753. #define VQ_FEXP 10
  118754. #define VQ_FMAN 21
  118755. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118756. /* doesn't currently guard under/overflow */
  118757. long _float32_pack(float val){
  118758. int sign=0;
  118759. long exp;
  118760. long mant;
  118761. if(val<0){
  118762. sign=0x80000000;
  118763. val= -val;
  118764. }
  118765. exp= floor(log(val)/log(2.f));
  118766. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118767. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118768. return(sign|exp|mant);
  118769. }
  118770. float _float32_unpack(long val){
  118771. double mant=val&0x1fffff;
  118772. int sign=val&0x80000000;
  118773. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118774. if(sign)mant= -mant;
  118775. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118776. }
  118777. /* given a list of word lengths, generate a list of codewords. Works
  118778. for length ordered or unordered, always assigns the lowest valued
  118779. codewords first. Extended to handle unused entries (length 0) */
  118780. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118781. long i,j,count=0;
  118782. ogg_uint32_t marker[33];
  118783. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118784. memset(marker,0,sizeof(marker));
  118785. for(i=0;i<n;i++){
  118786. long length=l[i];
  118787. if(length>0){
  118788. ogg_uint32_t entry=marker[length];
  118789. /* when we claim a node for an entry, we also claim the nodes
  118790. below it (pruning off the imagined tree that may have dangled
  118791. from it) as well as blocking the use of any nodes directly
  118792. above for leaves */
  118793. /* update ourself */
  118794. if(length<32 && (entry>>length)){
  118795. /* error condition; the lengths must specify an overpopulated tree */
  118796. _ogg_free(r);
  118797. return(NULL);
  118798. }
  118799. r[count++]=entry;
  118800. /* Look to see if the next shorter marker points to the node
  118801. above. if so, update it and repeat. */
  118802. {
  118803. for(j=length;j>0;j--){
  118804. if(marker[j]&1){
  118805. /* have to jump branches */
  118806. if(j==1)
  118807. marker[1]++;
  118808. else
  118809. marker[j]=marker[j-1]<<1;
  118810. break; /* invariant says next upper marker would already
  118811. have been moved if it was on the same path */
  118812. }
  118813. marker[j]++;
  118814. }
  118815. }
  118816. /* prune the tree; the implicit invariant says all the longer
  118817. markers were dangling from our just-taken node. Dangle them
  118818. from our *new* node. */
  118819. for(j=length+1;j<33;j++)
  118820. if((marker[j]>>1) == entry){
  118821. entry=marker[j];
  118822. marker[j]=marker[j-1]<<1;
  118823. }else
  118824. break;
  118825. }else
  118826. if(sparsecount==0)count++;
  118827. }
  118828. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118829. endian */
  118830. for(i=0,count=0;i<n;i++){
  118831. ogg_uint32_t temp=0;
  118832. for(j=0;j<l[i];j++){
  118833. temp<<=1;
  118834. temp|=(r[count]>>j)&1;
  118835. }
  118836. if(sparsecount){
  118837. if(l[i])
  118838. r[count++]=temp;
  118839. }else
  118840. r[count++]=temp;
  118841. }
  118842. return(r);
  118843. }
  118844. /* there might be a straightforward one-line way to do the below
  118845. that's portable and totally safe against roundoff, but I haven't
  118846. thought of it. Therefore, we opt on the side of caution */
  118847. long _book_maptype1_quantvals(const static_codebook *b){
  118848. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118849. /* the above *should* be reliable, but we'll not assume that FP is
  118850. ever reliable when bitstream sync is at stake; verify via integer
  118851. means that vals really is the greatest value of dim for which
  118852. vals^b->bim <= b->entries */
  118853. /* treat the above as an initial guess */
  118854. while(1){
  118855. long acc=1;
  118856. long acc1=1;
  118857. int i;
  118858. for(i=0;i<b->dim;i++){
  118859. acc*=vals;
  118860. acc1*=vals+1;
  118861. }
  118862. if(acc<=b->entries && acc1>b->entries){
  118863. return(vals);
  118864. }else{
  118865. if(acc>b->entries){
  118866. vals--;
  118867. }else{
  118868. vals++;
  118869. }
  118870. }
  118871. }
  118872. }
  118873. /* unpack the quantized list of values for encode/decode ***********/
  118874. /* we need to deal with two map types: in map type 1, the values are
  118875. generated algorithmically (each column of the vector counts through
  118876. the values in the quant vector). in map type 2, all the values came
  118877. in in an explicit list. Both value lists must be unpacked */
  118878. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118879. long j,k,count=0;
  118880. if(b->maptype==1 || b->maptype==2){
  118881. int quantvals;
  118882. float mindel=_float32_unpack(b->q_min);
  118883. float delta=_float32_unpack(b->q_delta);
  118884. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118885. /* maptype 1 and 2 both use a quantized value vector, but
  118886. different sizes */
  118887. switch(b->maptype){
  118888. case 1:
  118889. /* most of the time, entries%dimensions == 0, but we need to be
  118890. well defined. We define that the possible vales at each
  118891. scalar is values == entries/dim. If entries%dim != 0, we'll
  118892. have 'too few' values (values*dim<entries), which means that
  118893. we'll have 'left over' entries; left over entries use zeroed
  118894. values (and are wasted). So don't generate codebooks like
  118895. that */
  118896. quantvals=_book_maptype1_quantvals(b);
  118897. for(j=0;j<b->entries;j++){
  118898. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118899. float last=0.f;
  118900. int indexdiv=1;
  118901. for(k=0;k<b->dim;k++){
  118902. int index= (j/indexdiv)%quantvals;
  118903. float val=b->quantlist[index];
  118904. val=fabs(val)*delta+mindel+last;
  118905. if(b->q_sequencep)last=val;
  118906. if(sparsemap)
  118907. r[sparsemap[count]*b->dim+k]=val;
  118908. else
  118909. r[count*b->dim+k]=val;
  118910. indexdiv*=quantvals;
  118911. }
  118912. count++;
  118913. }
  118914. }
  118915. break;
  118916. case 2:
  118917. for(j=0;j<b->entries;j++){
  118918. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118919. float last=0.f;
  118920. for(k=0;k<b->dim;k++){
  118921. float val=b->quantlist[j*b->dim+k];
  118922. val=fabs(val)*delta+mindel+last;
  118923. if(b->q_sequencep)last=val;
  118924. if(sparsemap)
  118925. r[sparsemap[count]*b->dim+k]=val;
  118926. else
  118927. r[count*b->dim+k]=val;
  118928. }
  118929. count++;
  118930. }
  118931. }
  118932. break;
  118933. }
  118934. return(r);
  118935. }
  118936. return(NULL);
  118937. }
  118938. void vorbis_staticbook_clear(static_codebook *b){
  118939. if(b->allocedp){
  118940. if(b->quantlist)_ogg_free(b->quantlist);
  118941. if(b->lengthlist)_ogg_free(b->lengthlist);
  118942. if(b->nearest_tree){
  118943. _ogg_free(b->nearest_tree->ptr0);
  118944. _ogg_free(b->nearest_tree->ptr1);
  118945. _ogg_free(b->nearest_tree->p);
  118946. _ogg_free(b->nearest_tree->q);
  118947. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118948. _ogg_free(b->nearest_tree);
  118949. }
  118950. if(b->thresh_tree){
  118951. _ogg_free(b->thresh_tree->quantthresh);
  118952. _ogg_free(b->thresh_tree->quantmap);
  118953. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118954. _ogg_free(b->thresh_tree);
  118955. }
  118956. memset(b,0,sizeof(*b));
  118957. }
  118958. }
  118959. void vorbis_staticbook_destroy(static_codebook *b){
  118960. if(b->allocedp){
  118961. vorbis_staticbook_clear(b);
  118962. _ogg_free(b);
  118963. }
  118964. }
  118965. void vorbis_book_clear(codebook *b){
  118966. /* static book is not cleared; we're likely called on the lookup and
  118967. the static codebook belongs to the info struct */
  118968. if(b->valuelist)_ogg_free(b->valuelist);
  118969. if(b->codelist)_ogg_free(b->codelist);
  118970. if(b->dec_index)_ogg_free(b->dec_index);
  118971. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118972. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118973. memset(b,0,sizeof(*b));
  118974. }
  118975. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118976. memset(c,0,sizeof(*c));
  118977. c->c=s;
  118978. c->entries=s->entries;
  118979. c->used_entries=s->entries;
  118980. c->dim=s->dim;
  118981. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118982. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118983. return(0);
  118984. }
  118985. static int JUCE_CDECL sort32a(const void *a,const void *b){
  118986. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118987. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118988. }
  118989. /* decode codebook arrangement is more heavily optimized than encode */
  118990. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118991. int i,j,n=0,tabn;
  118992. int *sortindex;
  118993. memset(c,0,sizeof(*c));
  118994. /* count actually used entries */
  118995. for(i=0;i<s->entries;i++)
  118996. if(s->lengthlist[i]>0)
  118997. n++;
  118998. c->entries=s->entries;
  118999. c->used_entries=n;
  119000. c->dim=s->dim;
  119001. /* two different remappings go on here.
  119002. First, we collapse the likely sparse codebook down only to
  119003. actually represented values/words. This collapsing needs to be
  119004. indexed as map-valueless books are used to encode original entry
  119005. positions as integers.
  119006. Second, we reorder all vectors, including the entry index above,
  119007. by sorted bitreversed codeword to allow treeless decode. */
  119008. {
  119009. /* perform sort */
  119010. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119011. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119012. if(codes==NULL)goto err_out;
  119013. for(i=0;i<n;i++){
  119014. codes[i]=ogg_bitreverse(codes[i]);
  119015. codep[i]=codes+i;
  119016. }
  119017. qsort(codep,n,sizeof(*codep),sort32a);
  119018. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119019. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119020. /* the index is a reverse index */
  119021. for(i=0;i<n;i++){
  119022. int position=codep[i]-codes;
  119023. sortindex[position]=i;
  119024. }
  119025. for(i=0;i<n;i++)
  119026. c->codelist[sortindex[i]]=codes[i];
  119027. _ogg_free(codes);
  119028. }
  119029. c->valuelist=_book_unquantize(s,n,sortindex);
  119030. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119031. for(n=0,i=0;i<s->entries;i++)
  119032. if(s->lengthlist[i]>0)
  119033. c->dec_index[sortindex[n++]]=i;
  119034. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119035. for(n=0,i=0;i<s->entries;i++)
  119036. if(s->lengthlist[i]>0)
  119037. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119038. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119039. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119040. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119041. tabn=1<<c->dec_firsttablen;
  119042. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119043. c->dec_maxlength=0;
  119044. for(i=0;i<n;i++){
  119045. if(c->dec_maxlength<c->dec_codelengths[i])
  119046. c->dec_maxlength=c->dec_codelengths[i];
  119047. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119048. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119049. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119050. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119051. }
  119052. }
  119053. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119054. hints for the non-direct-hits */
  119055. {
  119056. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119057. long lo=0,hi=0;
  119058. for(i=0;i<tabn;i++){
  119059. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119060. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119061. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119062. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119063. /* we only actually have 15 bits per hint to play with here.
  119064. In order to overflow gracefully (nothing breaks, efficiency
  119065. just drops), encode as the difference from the extremes. */
  119066. {
  119067. unsigned long loval=lo;
  119068. unsigned long hival=n-hi;
  119069. if(loval>0x7fff)loval=0x7fff;
  119070. if(hival>0x7fff)hival=0x7fff;
  119071. c->dec_firsttable[ogg_bitreverse(word)]=
  119072. 0x80000000UL | (loval<<15) | hival;
  119073. }
  119074. }
  119075. }
  119076. }
  119077. return(0);
  119078. err_out:
  119079. vorbis_book_clear(c);
  119080. return(-1);
  119081. }
  119082. static float _dist(int el,float *ref, float *b,int step){
  119083. int i;
  119084. float acc=0.f;
  119085. for(i=0;i<el;i++){
  119086. float val=(ref[i]-b[i*step]);
  119087. acc+=val*val;
  119088. }
  119089. return(acc);
  119090. }
  119091. int _best(codebook *book, float *a, int step){
  119092. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119093. #if 0
  119094. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119095. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119096. #endif
  119097. int dim=book->dim;
  119098. int k,o;
  119099. /*int savebest=-1;
  119100. float saverr;*/
  119101. /* do we have a threshhold encode hint? */
  119102. if(tt){
  119103. int index=0,i;
  119104. /* find the quant val of each scalar */
  119105. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119106. i=tt->threshvals>>1;
  119107. if(a[o]<tt->quantthresh[i]){
  119108. for(;i>0;i--)
  119109. if(a[o]>=tt->quantthresh[i-1])
  119110. break;
  119111. }else{
  119112. for(i++;i<tt->threshvals-1;i++)
  119113. if(a[o]<tt->quantthresh[i])break;
  119114. }
  119115. index=(index*tt->quantvals)+tt->quantmap[i];
  119116. }
  119117. /* regular lattices are easy :-) */
  119118. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119119. use a decision tree after all
  119120. and fall through*/
  119121. return(index);
  119122. }
  119123. #if 0
  119124. /* do we have a pigeonhole encode hint? */
  119125. if(pt){
  119126. const static_codebook *c=book->c;
  119127. int i,besti=-1;
  119128. float best=0.f;
  119129. int entry=0;
  119130. /* dealing with sequentialness is a pain in the ass */
  119131. if(c->q_sequencep){
  119132. int pv;
  119133. long mul=1;
  119134. float qlast=0;
  119135. for(k=0,o=0;k<dim;k++,o+=step){
  119136. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119137. if(pv<0 || pv>=pt->mapentries)break;
  119138. entry+=pt->pigeonmap[pv]*mul;
  119139. mul*=pt->quantvals;
  119140. qlast+=pv*pt->del+pt->min;
  119141. }
  119142. }else{
  119143. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119144. int pv=(int)((a[o]-pt->min)/pt->del);
  119145. if(pv<0 || pv>=pt->mapentries)break;
  119146. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119147. }
  119148. }
  119149. /* must be within the pigeonholable range; if we quant outside (or
  119150. in an entry that we define no list for), brute force it */
  119151. if(k==dim && pt->fitlength[entry]){
  119152. /* search the abbreviated list */
  119153. long *list=pt->fitlist+pt->fitmap[entry];
  119154. for(i=0;i<pt->fitlength[entry];i++){
  119155. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119156. if(besti==-1 || this<best){
  119157. best=this;
  119158. besti=list[i];
  119159. }
  119160. }
  119161. return(besti);
  119162. }
  119163. }
  119164. if(nt){
  119165. /* optimized using the decision tree */
  119166. while(1){
  119167. float c=0.f;
  119168. float *p=book->valuelist+nt->p[ptr];
  119169. float *q=book->valuelist+nt->q[ptr];
  119170. for(k=0,o=0;k<dim;k++,o+=step)
  119171. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119172. if(c>0.f) /* in A */
  119173. ptr= -nt->ptr0[ptr];
  119174. else /* in B */
  119175. ptr= -nt->ptr1[ptr];
  119176. if(ptr<=0)break;
  119177. }
  119178. return(-ptr);
  119179. }
  119180. #endif
  119181. /* brute force it! */
  119182. {
  119183. const static_codebook *c=book->c;
  119184. int i,besti=-1;
  119185. float best=0.f;
  119186. float *e=book->valuelist;
  119187. for(i=0;i<book->entries;i++){
  119188. if(c->lengthlist[i]>0){
  119189. float thisx=_dist(dim,e,a,step);
  119190. if(besti==-1 || thisx<best){
  119191. best=thisx;
  119192. besti=i;
  119193. }
  119194. }
  119195. e+=dim;
  119196. }
  119197. /*if(savebest!=-1 && savebest!=besti){
  119198. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119199. "original:");
  119200. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119201. fprintf(stderr,"\n"
  119202. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119203. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119204. (book->valuelist+savebest*dim)[i]);
  119205. fprintf(stderr,"\n"
  119206. "bruteforce (entry %d, err %g):",besti,best);
  119207. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119208. (book->valuelist+besti*dim)[i]);
  119209. fprintf(stderr,"\n");
  119210. }*/
  119211. return(besti);
  119212. }
  119213. }
  119214. long vorbis_book_codeword(codebook *book,int entry){
  119215. if(book->c) /* only use with encode; decode optimizations are
  119216. allowed to break this */
  119217. return book->codelist[entry];
  119218. return -1;
  119219. }
  119220. long vorbis_book_codelen(codebook *book,int entry){
  119221. if(book->c) /* only use with encode; decode optimizations are
  119222. allowed to break this */
  119223. return book->c->lengthlist[entry];
  119224. return -1;
  119225. }
  119226. #ifdef _V_SELFTEST
  119227. /* Unit tests of the dequantizer; this stuff will be OK
  119228. cross-platform, I simply want to be sure that special mapping cases
  119229. actually work properly; a bug could go unnoticed for a while */
  119230. #include <stdio.h>
  119231. /* cases:
  119232. no mapping
  119233. full, explicit mapping
  119234. algorithmic mapping
  119235. nonsequential
  119236. sequential
  119237. */
  119238. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119239. static long partial_quantlist1[]={0,7,2};
  119240. /* no mapping */
  119241. static_codebook test1={
  119242. 4,16,
  119243. NULL,
  119244. 0,
  119245. 0,0,0,0,
  119246. NULL,
  119247. NULL,NULL
  119248. };
  119249. static float *test1_result=NULL;
  119250. /* linear, full mapping, nonsequential */
  119251. static_codebook test2={
  119252. 4,3,
  119253. NULL,
  119254. 2,
  119255. -533200896,1611661312,4,0,
  119256. full_quantlist1,
  119257. NULL,NULL
  119258. };
  119259. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119260. /* linear, full mapping, sequential */
  119261. static_codebook test3={
  119262. 4,3,
  119263. NULL,
  119264. 2,
  119265. -533200896,1611661312,4,1,
  119266. full_quantlist1,
  119267. NULL,NULL
  119268. };
  119269. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119270. /* linear, algorithmic mapping, nonsequential */
  119271. static_codebook test4={
  119272. 3,27,
  119273. NULL,
  119274. 1,
  119275. -533200896,1611661312,4,0,
  119276. partial_quantlist1,
  119277. NULL,NULL
  119278. };
  119279. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119280. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119281. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119282. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119283. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119284. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119285. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119286. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119287. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119288. /* linear, algorithmic mapping, sequential */
  119289. static_codebook test5={
  119290. 3,27,
  119291. NULL,
  119292. 1,
  119293. -533200896,1611661312,4,1,
  119294. partial_quantlist1,
  119295. NULL,NULL
  119296. };
  119297. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119298. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119299. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119300. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119301. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119302. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119303. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119304. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119305. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119306. void run_test(static_codebook *b,float *comp){
  119307. float *out=_book_unquantize(b,b->entries,NULL);
  119308. int i;
  119309. if(comp){
  119310. if(!out){
  119311. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119312. exit(1);
  119313. }
  119314. for(i=0;i<b->entries*b->dim;i++)
  119315. if(fabs(out[i]-comp[i])>.0001){
  119316. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119317. "position %d, %g != %g\n",i,out[i],comp[i]);
  119318. exit(1);
  119319. }
  119320. }else{
  119321. if(out){
  119322. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119323. " correct result should have been NULL\n");
  119324. exit(1);
  119325. }
  119326. }
  119327. }
  119328. int main(){
  119329. /* run the nine dequant tests, and compare to the hand-rolled results */
  119330. fprintf(stderr,"Dequant test 1... ");
  119331. run_test(&test1,test1_result);
  119332. fprintf(stderr,"OK\nDequant test 2... ");
  119333. run_test(&test2,test2_result);
  119334. fprintf(stderr,"OK\nDequant test 3... ");
  119335. run_test(&test3,test3_result);
  119336. fprintf(stderr,"OK\nDequant test 4... ");
  119337. run_test(&test4,test4_result);
  119338. fprintf(stderr,"OK\nDequant test 5... ");
  119339. run_test(&test5,test5_result);
  119340. fprintf(stderr,"OK\n\n");
  119341. return(0);
  119342. }
  119343. #endif
  119344. #endif
  119345. /*** End of inlined file: sharedbook.c ***/
  119346. /*** Start of inlined file: smallft.c ***/
  119347. /* FFT implementation from OggSquish, minus cosine transforms,
  119348. * minus all but radix 2/4 case. In Vorbis we only need this
  119349. * cut-down version.
  119350. *
  119351. * To do more than just power-of-two sized vectors, see the full
  119352. * version I wrote for NetLib.
  119353. *
  119354. * Note that the packing is a little strange; rather than the FFT r/i
  119355. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119356. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119357. * FORTRAN version
  119358. */
  119359. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119360. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119361. // tasks..
  119362. #if JUCE_MSVC
  119363. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119364. #endif
  119365. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119366. #if JUCE_USE_OGGVORBIS
  119367. #include <stdlib.h>
  119368. #include <string.h>
  119369. #include <math.h>
  119370. static void drfti1(int n, float *wa, int *ifac){
  119371. static int ntryh[4] = { 4,2,3,5 };
  119372. static float tpi = 6.28318530717958648f;
  119373. float arg,argh,argld,fi;
  119374. int ntry=0,i,j=-1;
  119375. int k1, l1, l2, ib;
  119376. int ld, ii, ip, is, nq, nr;
  119377. int ido, ipm, nfm1;
  119378. int nl=n;
  119379. int nf=0;
  119380. L101:
  119381. j++;
  119382. if (j < 4)
  119383. ntry=ntryh[j];
  119384. else
  119385. ntry+=2;
  119386. L104:
  119387. nq=nl/ntry;
  119388. nr=nl-ntry*nq;
  119389. if (nr!=0) goto L101;
  119390. nf++;
  119391. ifac[nf+1]=ntry;
  119392. nl=nq;
  119393. if(ntry!=2)goto L107;
  119394. if(nf==1)goto L107;
  119395. for (i=1;i<nf;i++){
  119396. ib=nf-i+1;
  119397. ifac[ib+1]=ifac[ib];
  119398. }
  119399. ifac[2] = 2;
  119400. L107:
  119401. if(nl!=1)goto L104;
  119402. ifac[0]=n;
  119403. ifac[1]=nf;
  119404. argh=tpi/n;
  119405. is=0;
  119406. nfm1=nf-1;
  119407. l1=1;
  119408. if(nfm1==0)return;
  119409. for (k1=0;k1<nfm1;k1++){
  119410. ip=ifac[k1+2];
  119411. ld=0;
  119412. l2=l1*ip;
  119413. ido=n/l2;
  119414. ipm=ip-1;
  119415. for (j=0;j<ipm;j++){
  119416. ld+=l1;
  119417. i=is;
  119418. argld=(float)ld*argh;
  119419. fi=0.f;
  119420. for (ii=2;ii<ido;ii+=2){
  119421. fi+=1.f;
  119422. arg=fi*argld;
  119423. wa[i++]=cos(arg);
  119424. wa[i++]=sin(arg);
  119425. }
  119426. is+=ido;
  119427. }
  119428. l1=l2;
  119429. }
  119430. }
  119431. static void fdrffti(int n, float *wsave, int *ifac){
  119432. if (n == 1) return;
  119433. drfti1(n, wsave+n, ifac);
  119434. }
  119435. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119436. int i,k;
  119437. float ti2,tr2;
  119438. int t0,t1,t2,t3,t4,t5,t6;
  119439. t1=0;
  119440. t0=(t2=l1*ido);
  119441. t3=ido<<1;
  119442. for(k=0;k<l1;k++){
  119443. ch[t1<<1]=cc[t1]+cc[t2];
  119444. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119445. t1+=ido;
  119446. t2+=ido;
  119447. }
  119448. if(ido<2)return;
  119449. if(ido==2)goto L105;
  119450. t1=0;
  119451. t2=t0;
  119452. for(k=0;k<l1;k++){
  119453. t3=t2;
  119454. t4=(t1<<1)+(ido<<1);
  119455. t5=t1;
  119456. t6=t1+t1;
  119457. for(i=2;i<ido;i+=2){
  119458. t3+=2;
  119459. t4-=2;
  119460. t5+=2;
  119461. t6+=2;
  119462. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119463. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119464. ch[t6]=cc[t5]+ti2;
  119465. ch[t4]=ti2-cc[t5];
  119466. ch[t6-1]=cc[t5-1]+tr2;
  119467. ch[t4-1]=cc[t5-1]-tr2;
  119468. }
  119469. t1+=ido;
  119470. t2+=ido;
  119471. }
  119472. if(ido%2==1)return;
  119473. L105:
  119474. t3=(t2=(t1=ido)-1);
  119475. t2+=t0;
  119476. for(k=0;k<l1;k++){
  119477. ch[t1]=-cc[t2];
  119478. ch[t1-1]=cc[t3];
  119479. t1+=ido<<1;
  119480. t2+=ido;
  119481. t3+=ido;
  119482. }
  119483. }
  119484. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119485. float *wa2,float *wa3){
  119486. static float hsqt2 = .70710678118654752f;
  119487. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119488. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119489. t0=l1*ido;
  119490. t1=t0;
  119491. t4=t1<<1;
  119492. t2=t1+(t1<<1);
  119493. t3=0;
  119494. for(k=0;k<l1;k++){
  119495. tr1=cc[t1]+cc[t2];
  119496. tr2=cc[t3]+cc[t4];
  119497. ch[t5=t3<<2]=tr1+tr2;
  119498. ch[(ido<<2)+t5-1]=tr2-tr1;
  119499. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119500. ch[t5]=cc[t2]-cc[t1];
  119501. t1+=ido;
  119502. t2+=ido;
  119503. t3+=ido;
  119504. t4+=ido;
  119505. }
  119506. if(ido<2)return;
  119507. if(ido==2)goto L105;
  119508. t1=0;
  119509. for(k=0;k<l1;k++){
  119510. t2=t1;
  119511. t4=t1<<2;
  119512. t5=(t6=ido<<1)+t4;
  119513. for(i=2;i<ido;i+=2){
  119514. t3=(t2+=2);
  119515. t4+=2;
  119516. t5-=2;
  119517. t3+=t0;
  119518. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119519. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119520. t3+=t0;
  119521. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119522. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119523. t3+=t0;
  119524. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119525. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119526. tr1=cr2+cr4;
  119527. tr4=cr4-cr2;
  119528. ti1=ci2+ci4;
  119529. ti4=ci2-ci4;
  119530. ti2=cc[t2]+ci3;
  119531. ti3=cc[t2]-ci3;
  119532. tr2=cc[t2-1]+cr3;
  119533. tr3=cc[t2-1]-cr3;
  119534. ch[t4-1]=tr1+tr2;
  119535. ch[t4]=ti1+ti2;
  119536. ch[t5-1]=tr3-ti4;
  119537. ch[t5]=tr4-ti3;
  119538. ch[t4+t6-1]=ti4+tr3;
  119539. ch[t4+t6]=tr4+ti3;
  119540. ch[t5+t6-1]=tr2-tr1;
  119541. ch[t5+t6]=ti1-ti2;
  119542. }
  119543. t1+=ido;
  119544. }
  119545. if(ido&1)return;
  119546. L105:
  119547. t2=(t1=t0+ido-1)+(t0<<1);
  119548. t3=ido<<2;
  119549. t4=ido;
  119550. t5=ido<<1;
  119551. t6=ido;
  119552. for(k=0;k<l1;k++){
  119553. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119554. tr1=hsqt2*(cc[t1]-cc[t2]);
  119555. ch[t4-1]=tr1+cc[t6-1];
  119556. ch[t4+t5-1]=cc[t6-1]-tr1;
  119557. ch[t4]=ti1-cc[t1+t0];
  119558. ch[t4+t5]=ti1+cc[t1+t0];
  119559. t1+=ido;
  119560. t2+=ido;
  119561. t4+=t3;
  119562. t6+=ido;
  119563. }
  119564. }
  119565. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119566. float *c2,float *ch,float *ch2,float *wa){
  119567. static float tpi=6.283185307179586f;
  119568. int idij,ipph,i,j,k,l,ic,ik,is;
  119569. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119570. float dc2,ai1,ai2,ar1,ar2,ds2;
  119571. int nbd;
  119572. float dcp,arg,dsp,ar1h,ar2h;
  119573. int idp2,ipp2;
  119574. arg=tpi/(float)ip;
  119575. dcp=cos(arg);
  119576. dsp=sin(arg);
  119577. ipph=(ip+1)>>1;
  119578. ipp2=ip;
  119579. idp2=ido;
  119580. nbd=(ido-1)>>1;
  119581. t0=l1*ido;
  119582. t10=ip*ido;
  119583. if(ido==1)goto L119;
  119584. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119585. t1=0;
  119586. for(j=1;j<ip;j++){
  119587. t1+=t0;
  119588. t2=t1;
  119589. for(k=0;k<l1;k++){
  119590. ch[t2]=c1[t2];
  119591. t2+=ido;
  119592. }
  119593. }
  119594. is=-ido;
  119595. t1=0;
  119596. if(nbd>l1){
  119597. for(j=1;j<ip;j++){
  119598. t1+=t0;
  119599. is+=ido;
  119600. t2= -ido+t1;
  119601. for(k=0;k<l1;k++){
  119602. idij=is-1;
  119603. t2+=ido;
  119604. t3=t2;
  119605. for(i=2;i<ido;i+=2){
  119606. idij+=2;
  119607. t3+=2;
  119608. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119609. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119610. }
  119611. }
  119612. }
  119613. }else{
  119614. for(j=1;j<ip;j++){
  119615. is+=ido;
  119616. idij=is-1;
  119617. t1+=t0;
  119618. t2=t1;
  119619. for(i=2;i<ido;i+=2){
  119620. idij+=2;
  119621. t2+=2;
  119622. t3=t2;
  119623. for(k=0;k<l1;k++){
  119624. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119625. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119626. t3+=ido;
  119627. }
  119628. }
  119629. }
  119630. }
  119631. t1=0;
  119632. t2=ipp2*t0;
  119633. if(nbd<l1){
  119634. for(j=1;j<ipph;j++){
  119635. t1+=t0;
  119636. t2-=t0;
  119637. t3=t1;
  119638. t4=t2;
  119639. for(i=2;i<ido;i+=2){
  119640. t3+=2;
  119641. t4+=2;
  119642. t5=t3-ido;
  119643. t6=t4-ido;
  119644. for(k=0;k<l1;k++){
  119645. t5+=ido;
  119646. t6+=ido;
  119647. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119648. c1[t6-1]=ch[t5]-ch[t6];
  119649. c1[t5]=ch[t5]+ch[t6];
  119650. c1[t6]=ch[t6-1]-ch[t5-1];
  119651. }
  119652. }
  119653. }
  119654. }else{
  119655. for(j=1;j<ipph;j++){
  119656. t1+=t0;
  119657. t2-=t0;
  119658. t3=t1;
  119659. t4=t2;
  119660. for(k=0;k<l1;k++){
  119661. t5=t3;
  119662. t6=t4;
  119663. for(i=2;i<ido;i+=2){
  119664. t5+=2;
  119665. t6+=2;
  119666. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119667. c1[t6-1]=ch[t5]-ch[t6];
  119668. c1[t5]=ch[t5]+ch[t6];
  119669. c1[t6]=ch[t6-1]-ch[t5-1];
  119670. }
  119671. t3+=ido;
  119672. t4+=ido;
  119673. }
  119674. }
  119675. }
  119676. L119:
  119677. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119678. t1=0;
  119679. t2=ipp2*idl1;
  119680. for(j=1;j<ipph;j++){
  119681. t1+=t0;
  119682. t2-=t0;
  119683. t3=t1-ido;
  119684. t4=t2-ido;
  119685. for(k=0;k<l1;k++){
  119686. t3+=ido;
  119687. t4+=ido;
  119688. c1[t3]=ch[t3]+ch[t4];
  119689. c1[t4]=ch[t4]-ch[t3];
  119690. }
  119691. }
  119692. ar1=1.f;
  119693. ai1=0.f;
  119694. t1=0;
  119695. t2=ipp2*idl1;
  119696. t3=(ip-1)*idl1;
  119697. for(l=1;l<ipph;l++){
  119698. t1+=idl1;
  119699. t2-=idl1;
  119700. ar1h=dcp*ar1-dsp*ai1;
  119701. ai1=dcp*ai1+dsp*ar1;
  119702. ar1=ar1h;
  119703. t4=t1;
  119704. t5=t2;
  119705. t6=t3;
  119706. t7=idl1;
  119707. for(ik=0;ik<idl1;ik++){
  119708. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119709. ch2[t5++]=ai1*c2[t6++];
  119710. }
  119711. dc2=ar1;
  119712. ds2=ai1;
  119713. ar2=ar1;
  119714. ai2=ai1;
  119715. t4=idl1;
  119716. t5=(ipp2-1)*idl1;
  119717. for(j=2;j<ipph;j++){
  119718. t4+=idl1;
  119719. t5-=idl1;
  119720. ar2h=dc2*ar2-ds2*ai2;
  119721. ai2=dc2*ai2+ds2*ar2;
  119722. ar2=ar2h;
  119723. t6=t1;
  119724. t7=t2;
  119725. t8=t4;
  119726. t9=t5;
  119727. for(ik=0;ik<idl1;ik++){
  119728. ch2[t6++]+=ar2*c2[t8++];
  119729. ch2[t7++]+=ai2*c2[t9++];
  119730. }
  119731. }
  119732. }
  119733. t1=0;
  119734. for(j=1;j<ipph;j++){
  119735. t1+=idl1;
  119736. t2=t1;
  119737. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119738. }
  119739. if(ido<l1)goto L132;
  119740. t1=0;
  119741. t2=0;
  119742. for(k=0;k<l1;k++){
  119743. t3=t1;
  119744. t4=t2;
  119745. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119746. t1+=ido;
  119747. t2+=t10;
  119748. }
  119749. goto L135;
  119750. L132:
  119751. for(i=0;i<ido;i++){
  119752. t1=i;
  119753. t2=i;
  119754. for(k=0;k<l1;k++){
  119755. cc[t2]=ch[t1];
  119756. t1+=ido;
  119757. t2+=t10;
  119758. }
  119759. }
  119760. L135:
  119761. t1=0;
  119762. t2=ido<<1;
  119763. t3=0;
  119764. t4=ipp2*t0;
  119765. for(j=1;j<ipph;j++){
  119766. t1+=t2;
  119767. t3+=t0;
  119768. t4-=t0;
  119769. t5=t1;
  119770. t6=t3;
  119771. t7=t4;
  119772. for(k=0;k<l1;k++){
  119773. cc[t5-1]=ch[t6];
  119774. cc[t5]=ch[t7];
  119775. t5+=t10;
  119776. t6+=ido;
  119777. t7+=ido;
  119778. }
  119779. }
  119780. if(ido==1)return;
  119781. if(nbd<l1)goto L141;
  119782. t1=-ido;
  119783. t3=0;
  119784. t4=0;
  119785. t5=ipp2*t0;
  119786. for(j=1;j<ipph;j++){
  119787. t1+=t2;
  119788. t3+=t2;
  119789. t4+=t0;
  119790. t5-=t0;
  119791. t6=t1;
  119792. t7=t3;
  119793. t8=t4;
  119794. t9=t5;
  119795. for(k=0;k<l1;k++){
  119796. for(i=2;i<ido;i+=2){
  119797. ic=idp2-i;
  119798. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119799. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119800. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119801. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119802. }
  119803. t6+=t10;
  119804. t7+=t10;
  119805. t8+=ido;
  119806. t9+=ido;
  119807. }
  119808. }
  119809. return;
  119810. L141:
  119811. t1=-ido;
  119812. t3=0;
  119813. t4=0;
  119814. t5=ipp2*t0;
  119815. for(j=1;j<ipph;j++){
  119816. t1+=t2;
  119817. t3+=t2;
  119818. t4+=t0;
  119819. t5-=t0;
  119820. for(i=2;i<ido;i+=2){
  119821. t6=idp2+t1-i;
  119822. t7=i+t3;
  119823. t8=i+t4;
  119824. t9=i+t5;
  119825. for(k=0;k<l1;k++){
  119826. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119827. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119828. cc[t7]=ch[t8]+ch[t9];
  119829. cc[t6]=ch[t9]-ch[t8];
  119830. t6+=t10;
  119831. t7+=t10;
  119832. t8+=ido;
  119833. t9+=ido;
  119834. }
  119835. }
  119836. }
  119837. }
  119838. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119839. int i,k1,l1,l2;
  119840. int na,kh,nf;
  119841. int ip,iw,ido,idl1,ix2,ix3;
  119842. nf=ifac[1];
  119843. na=1;
  119844. l2=n;
  119845. iw=n;
  119846. for(k1=0;k1<nf;k1++){
  119847. kh=nf-k1;
  119848. ip=ifac[kh+1];
  119849. l1=l2/ip;
  119850. ido=n/l2;
  119851. idl1=ido*l1;
  119852. iw-=(ip-1)*ido;
  119853. na=1-na;
  119854. if(ip!=4)goto L102;
  119855. ix2=iw+ido;
  119856. ix3=ix2+ido;
  119857. if(na!=0)
  119858. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119859. else
  119860. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119861. goto L110;
  119862. L102:
  119863. if(ip!=2)goto L104;
  119864. if(na!=0)goto L103;
  119865. dradf2(ido,l1,c,ch,wa+iw-1);
  119866. goto L110;
  119867. L103:
  119868. dradf2(ido,l1,ch,c,wa+iw-1);
  119869. goto L110;
  119870. L104:
  119871. if(ido==1)na=1-na;
  119872. if(na!=0)goto L109;
  119873. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119874. na=1;
  119875. goto L110;
  119876. L109:
  119877. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119878. na=0;
  119879. L110:
  119880. l2=l1;
  119881. }
  119882. if(na==1)return;
  119883. for(i=0;i<n;i++)c[i]=ch[i];
  119884. }
  119885. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119886. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119887. float ti2,tr2;
  119888. t0=l1*ido;
  119889. t1=0;
  119890. t2=0;
  119891. t3=(ido<<1)-1;
  119892. for(k=0;k<l1;k++){
  119893. ch[t1]=cc[t2]+cc[t3+t2];
  119894. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119895. t2=(t1+=ido)<<1;
  119896. }
  119897. if(ido<2)return;
  119898. if(ido==2)goto L105;
  119899. t1=0;
  119900. t2=0;
  119901. for(k=0;k<l1;k++){
  119902. t3=t1;
  119903. t5=(t4=t2)+(ido<<1);
  119904. t6=t0+t1;
  119905. for(i=2;i<ido;i+=2){
  119906. t3+=2;
  119907. t4+=2;
  119908. t5-=2;
  119909. t6+=2;
  119910. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119911. tr2=cc[t4-1]-cc[t5-1];
  119912. ch[t3]=cc[t4]-cc[t5];
  119913. ti2=cc[t4]+cc[t5];
  119914. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119915. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119916. }
  119917. t2=(t1+=ido)<<1;
  119918. }
  119919. if(ido%2==1)return;
  119920. L105:
  119921. t1=ido-1;
  119922. t2=ido-1;
  119923. for(k=0;k<l1;k++){
  119924. ch[t1]=cc[t2]+cc[t2];
  119925. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119926. t1+=ido;
  119927. t2+=ido<<1;
  119928. }
  119929. }
  119930. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119931. float *wa2){
  119932. static float taur = -.5f;
  119933. static float taui = .8660254037844386f;
  119934. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119935. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119936. t0=l1*ido;
  119937. t1=0;
  119938. t2=t0<<1;
  119939. t3=ido<<1;
  119940. t4=ido+(ido<<1);
  119941. t5=0;
  119942. for(k=0;k<l1;k++){
  119943. tr2=cc[t3-1]+cc[t3-1];
  119944. cr2=cc[t5]+(taur*tr2);
  119945. ch[t1]=cc[t5]+tr2;
  119946. ci3=taui*(cc[t3]+cc[t3]);
  119947. ch[t1+t0]=cr2-ci3;
  119948. ch[t1+t2]=cr2+ci3;
  119949. t1+=ido;
  119950. t3+=t4;
  119951. t5+=t4;
  119952. }
  119953. if(ido==1)return;
  119954. t1=0;
  119955. t3=ido<<1;
  119956. for(k=0;k<l1;k++){
  119957. t7=t1+(t1<<1);
  119958. t6=(t5=t7+t3);
  119959. t8=t1;
  119960. t10=(t9=t1+t0)+t0;
  119961. for(i=2;i<ido;i+=2){
  119962. t5+=2;
  119963. t6-=2;
  119964. t7+=2;
  119965. t8+=2;
  119966. t9+=2;
  119967. t10+=2;
  119968. tr2=cc[t5-1]+cc[t6-1];
  119969. cr2=cc[t7-1]+(taur*tr2);
  119970. ch[t8-1]=cc[t7-1]+tr2;
  119971. ti2=cc[t5]-cc[t6];
  119972. ci2=cc[t7]+(taur*ti2);
  119973. ch[t8]=cc[t7]+ti2;
  119974. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119975. ci3=taui*(cc[t5]+cc[t6]);
  119976. dr2=cr2-ci3;
  119977. dr3=cr2+ci3;
  119978. di2=ci2+cr3;
  119979. di3=ci2-cr3;
  119980. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119981. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119982. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119983. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119984. }
  119985. t1+=ido;
  119986. }
  119987. }
  119988. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119989. float *wa2,float *wa3){
  119990. static float sqrt2=1.414213562373095f;
  119991. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119992. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119993. t0=l1*ido;
  119994. t1=0;
  119995. t2=ido<<2;
  119996. t3=0;
  119997. t6=ido<<1;
  119998. for(k=0;k<l1;k++){
  119999. t4=t3+t6;
  120000. t5=t1;
  120001. tr3=cc[t4-1]+cc[t4-1];
  120002. tr4=cc[t4]+cc[t4];
  120003. tr1=cc[t3]-cc[(t4+=t6)-1];
  120004. tr2=cc[t3]+cc[t4-1];
  120005. ch[t5]=tr2+tr3;
  120006. ch[t5+=t0]=tr1-tr4;
  120007. ch[t5+=t0]=tr2-tr3;
  120008. ch[t5+=t0]=tr1+tr4;
  120009. t1+=ido;
  120010. t3+=t2;
  120011. }
  120012. if(ido<2)return;
  120013. if(ido==2)goto L105;
  120014. t1=0;
  120015. for(k=0;k<l1;k++){
  120016. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120017. t7=t1;
  120018. for(i=2;i<ido;i+=2){
  120019. t2+=2;
  120020. t3+=2;
  120021. t4-=2;
  120022. t5-=2;
  120023. t7+=2;
  120024. ti1=cc[t2]+cc[t5];
  120025. ti2=cc[t2]-cc[t5];
  120026. ti3=cc[t3]-cc[t4];
  120027. tr4=cc[t3]+cc[t4];
  120028. tr1=cc[t2-1]-cc[t5-1];
  120029. tr2=cc[t2-1]+cc[t5-1];
  120030. ti4=cc[t3-1]-cc[t4-1];
  120031. tr3=cc[t3-1]+cc[t4-1];
  120032. ch[t7-1]=tr2+tr3;
  120033. cr3=tr2-tr3;
  120034. ch[t7]=ti2+ti3;
  120035. ci3=ti2-ti3;
  120036. cr2=tr1-tr4;
  120037. cr4=tr1+tr4;
  120038. ci2=ti1+ti4;
  120039. ci4=ti1-ti4;
  120040. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120041. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120042. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120043. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120044. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120045. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120046. }
  120047. t1+=ido;
  120048. }
  120049. if(ido%2 == 1)return;
  120050. L105:
  120051. t1=ido;
  120052. t2=ido<<2;
  120053. t3=ido-1;
  120054. t4=ido+(ido<<1);
  120055. for(k=0;k<l1;k++){
  120056. t5=t3;
  120057. ti1=cc[t1]+cc[t4];
  120058. ti2=cc[t4]-cc[t1];
  120059. tr1=cc[t1-1]-cc[t4-1];
  120060. tr2=cc[t1-1]+cc[t4-1];
  120061. ch[t5]=tr2+tr2;
  120062. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120063. ch[t5+=t0]=ti2+ti2;
  120064. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120065. t3+=ido;
  120066. t1+=t2;
  120067. t4+=t2;
  120068. }
  120069. }
  120070. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120071. float *c2,float *ch,float *ch2,float *wa){
  120072. static float tpi=6.283185307179586f;
  120073. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120074. t11,t12;
  120075. float dc2,ai1,ai2,ar1,ar2,ds2;
  120076. int nbd;
  120077. float dcp,arg,dsp,ar1h,ar2h;
  120078. int ipp2;
  120079. t10=ip*ido;
  120080. t0=l1*ido;
  120081. arg=tpi/(float)ip;
  120082. dcp=cos(arg);
  120083. dsp=sin(arg);
  120084. nbd=(ido-1)>>1;
  120085. ipp2=ip;
  120086. ipph=(ip+1)>>1;
  120087. if(ido<l1)goto L103;
  120088. t1=0;
  120089. t2=0;
  120090. for(k=0;k<l1;k++){
  120091. t3=t1;
  120092. t4=t2;
  120093. for(i=0;i<ido;i++){
  120094. ch[t3]=cc[t4];
  120095. t3++;
  120096. t4++;
  120097. }
  120098. t1+=ido;
  120099. t2+=t10;
  120100. }
  120101. goto L106;
  120102. L103:
  120103. t1=0;
  120104. for(i=0;i<ido;i++){
  120105. t2=t1;
  120106. t3=t1;
  120107. for(k=0;k<l1;k++){
  120108. ch[t2]=cc[t3];
  120109. t2+=ido;
  120110. t3+=t10;
  120111. }
  120112. t1++;
  120113. }
  120114. L106:
  120115. t1=0;
  120116. t2=ipp2*t0;
  120117. t7=(t5=ido<<1);
  120118. for(j=1;j<ipph;j++){
  120119. t1+=t0;
  120120. t2-=t0;
  120121. t3=t1;
  120122. t4=t2;
  120123. t6=t5;
  120124. for(k=0;k<l1;k++){
  120125. ch[t3]=cc[t6-1]+cc[t6-1];
  120126. ch[t4]=cc[t6]+cc[t6];
  120127. t3+=ido;
  120128. t4+=ido;
  120129. t6+=t10;
  120130. }
  120131. t5+=t7;
  120132. }
  120133. if (ido == 1)goto L116;
  120134. if(nbd<l1)goto L112;
  120135. t1=0;
  120136. t2=ipp2*t0;
  120137. t7=0;
  120138. for(j=1;j<ipph;j++){
  120139. t1+=t0;
  120140. t2-=t0;
  120141. t3=t1;
  120142. t4=t2;
  120143. t7+=(ido<<1);
  120144. t8=t7;
  120145. for(k=0;k<l1;k++){
  120146. t5=t3;
  120147. t6=t4;
  120148. t9=t8;
  120149. t11=t8;
  120150. for(i=2;i<ido;i+=2){
  120151. t5+=2;
  120152. t6+=2;
  120153. t9+=2;
  120154. t11-=2;
  120155. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120156. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120157. ch[t5]=cc[t9]-cc[t11];
  120158. ch[t6]=cc[t9]+cc[t11];
  120159. }
  120160. t3+=ido;
  120161. t4+=ido;
  120162. t8+=t10;
  120163. }
  120164. }
  120165. goto L116;
  120166. L112:
  120167. t1=0;
  120168. t2=ipp2*t0;
  120169. t7=0;
  120170. for(j=1;j<ipph;j++){
  120171. t1+=t0;
  120172. t2-=t0;
  120173. t3=t1;
  120174. t4=t2;
  120175. t7+=(ido<<1);
  120176. t8=t7;
  120177. t9=t7;
  120178. for(i=2;i<ido;i+=2){
  120179. t3+=2;
  120180. t4+=2;
  120181. t8+=2;
  120182. t9-=2;
  120183. t5=t3;
  120184. t6=t4;
  120185. t11=t8;
  120186. t12=t9;
  120187. for(k=0;k<l1;k++){
  120188. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120189. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120190. ch[t5]=cc[t11]-cc[t12];
  120191. ch[t6]=cc[t11]+cc[t12];
  120192. t5+=ido;
  120193. t6+=ido;
  120194. t11+=t10;
  120195. t12+=t10;
  120196. }
  120197. }
  120198. }
  120199. L116:
  120200. ar1=1.f;
  120201. ai1=0.f;
  120202. t1=0;
  120203. t9=(t2=ipp2*idl1);
  120204. t3=(ip-1)*idl1;
  120205. for(l=1;l<ipph;l++){
  120206. t1+=idl1;
  120207. t2-=idl1;
  120208. ar1h=dcp*ar1-dsp*ai1;
  120209. ai1=dcp*ai1+dsp*ar1;
  120210. ar1=ar1h;
  120211. t4=t1;
  120212. t5=t2;
  120213. t6=0;
  120214. t7=idl1;
  120215. t8=t3;
  120216. for(ik=0;ik<idl1;ik++){
  120217. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120218. c2[t5++]=ai1*ch2[t8++];
  120219. }
  120220. dc2=ar1;
  120221. ds2=ai1;
  120222. ar2=ar1;
  120223. ai2=ai1;
  120224. t6=idl1;
  120225. t7=t9-idl1;
  120226. for(j=2;j<ipph;j++){
  120227. t6+=idl1;
  120228. t7-=idl1;
  120229. ar2h=dc2*ar2-ds2*ai2;
  120230. ai2=dc2*ai2+ds2*ar2;
  120231. ar2=ar2h;
  120232. t4=t1;
  120233. t5=t2;
  120234. t11=t6;
  120235. t12=t7;
  120236. for(ik=0;ik<idl1;ik++){
  120237. c2[t4++]+=ar2*ch2[t11++];
  120238. c2[t5++]+=ai2*ch2[t12++];
  120239. }
  120240. }
  120241. }
  120242. t1=0;
  120243. for(j=1;j<ipph;j++){
  120244. t1+=idl1;
  120245. t2=t1;
  120246. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120247. }
  120248. t1=0;
  120249. t2=ipp2*t0;
  120250. for(j=1;j<ipph;j++){
  120251. t1+=t0;
  120252. t2-=t0;
  120253. t3=t1;
  120254. t4=t2;
  120255. for(k=0;k<l1;k++){
  120256. ch[t3]=c1[t3]-c1[t4];
  120257. ch[t4]=c1[t3]+c1[t4];
  120258. t3+=ido;
  120259. t4+=ido;
  120260. }
  120261. }
  120262. if(ido==1)goto L132;
  120263. if(nbd<l1)goto L128;
  120264. t1=0;
  120265. t2=ipp2*t0;
  120266. for(j=1;j<ipph;j++){
  120267. t1+=t0;
  120268. t2-=t0;
  120269. t3=t1;
  120270. t4=t2;
  120271. for(k=0;k<l1;k++){
  120272. t5=t3;
  120273. t6=t4;
  120274. for(i=2;i<ido;i+=2){
  120275. t5+=2;
  120276. t6+=2;
  120277. ch[t5-1]=c1[t5-1]-c1[t6];
  120278. ch[t6-1]=c1[t5-1]+c1[t6];
  120279. ch[t5]=c1[t5]+c1[t6-1];
  120280. ch[t6]=c1[t5]-c1[t6-1];
  120281. }
  120282. t3+=ido;
  120283. t4+=ido;
  120284. }
  120285. }
  120286. goto L132;
  120287. L128:
  120288. t1=0;
  120289. t2=ipp2*t0;
  120290. for(j=1;j<ipph;j++){
  120291. t1+=t0;
  120292. t2-=t0;
  120293. t3=t1;
  120294. t4=t2;
  120295. for(i=2;i<ido;i+=2){
  120296. t3+=2;
  120297. t4+=2;
  120298. t5=t3;
  120299. t6=t4;
  120300. for(k=0;k<l1;k++){
  120301. ch[t5-1]=c1[t5-1]-c1[t6];
  120302. ch[t6-1]=c1[t5-1]+c1[t6];
  120303. ch[t5]=c1[t5]+c1[t6-1];
  120304. ch[t6]=c1[t5]-c1[t6-1];
  120305. t5+=ido;
  120306. t6+=ido;
  120307. }
  120308. }
  120309. }
  120310. L132:
  120311. if(ido==1)return;
  120312. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120313. t1=0;
  120314. for(j=1;j<ip;j++){
  120315. t2=(t1+=t0);
  120316. for(k=0;k<l1;k++){
  120317. c1[t2]=ch[t2];
  120318. t2+=ido;
  120319. }
  120320. }
  120321. if(nbd>l1)goto L139;
  120322. is= -ido-1;
  120323. t1=0;
  120324. for(j=1;j<ip;j++){
  120325. is+=ido;
  120326. t1+=t0;
  120327. idij=is;
  120328. t2=t1;
  120329. for(i=2;i<ido;i+=2){
  120330. t2+=2;
  120331. idij+=2;
  120332. t3=t2;
  120333. for(k=0;k<l1;k++){
  120334. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120335. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120336. t3+=ido;
  120337. }
  120338. }
  120339. }
  120340. return;
  120341. L139:
  120342. is= -ido-1;
  120343. t1=0;
  120344. for(j=1;j<ip;j++){
  120345. is+=ido;
  120346. t1+=t0;
  120347. t2=t1;
  120348. for(k=0;k<l1;k++){
  120349. idij=is;
  120350. t3=t2;
  120351. for(i=2;i<ido;i+=2){
  120352. idij+=2;
  120353. t3+=2;
  120354. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120355. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120356. }
  120357. t2+=ido;
  120358. }
  120359. }
  120360. }
  120361. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120362. int i,k1,l1,l2;
  120363. int na;
  120364. int nf,ip,iw,ix2,ix3,ido,idl1;
  120365. nf=ifac[1];
  120366. na=0;
  120367. l1=1;
  120368. iw=1;
  120369. for(k1=0;k1<nf;k1++){
  120370. ip=ifac[k1 + 2];
  120371. l2=ip*l1;
  120372. ido=n/l2;
  120373. idl1=ido*l1;
  120374. if(ip!=4)goto L103;
  120375. ix2=iw+ido;
  120376. ix3=ix2+ido;
  120377. if(na!=0)
  120378. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120379. else
  120380. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120381. na=1-na;
  120382. goto L115;
  120383. L103:
  120384. if(ip!=2)goto L106;
  120385. if(na!=0)
  120386. dradb2(ido,l1,ch,c,wa+iw-1);
  120387. else
  120388. dradb2(ido,l1,c,ch,wa+iw-1);
  120389. na=1-na;
  120390. goto L115;
  120391. L106:
  120392. if(ip!=3)goto L109;
  120393. ix2=iw+ido;
  120394. if(na!=0)
  120395. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120396. else
  120397. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120398. na=1-na;
  120399. goto L115;
  120400. L109:
  120401. /* The radix five case can be translated later..... */
  120402. /* if(ip!=5)goto L112;
  120403. ix2=iw+ido;
  120404. ix3=ix2+ido;
  120405. ix4=ix3+ido;
  120406. if(na!=0)
  120407. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120408. else
  120409. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120410. na=1-na;
  120411. goto L115;
  120412. L112:*/
  120413. if(na!=0)
  120414. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120415. else
  120416. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120417. if(ido==1)na=1-na;
  120418. L115:
  120419. l1=l2;
  120420. iw+=(ip-1)*ido;
  120421. }
  120422. if(na==0)return;
  120423. for(i=0;i<n;i++)c[i]=ch[i];
  120424. }
  120425. void drft_forward(drft_lookup *l,float *data){
  120426. if(l->n==1)return;
  120427. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120428. }
  120429. void drft_backward(drft_lookup *l,float *data){
  120430. if (l->n==1)return;
  120431. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120432. }
  120433. void drft_init(drft_lookup *l,int n){
  120434. l->n=n;
  120435. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120436. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120437. fdrffti(n, l->trigcache, l->splitcache);
  120438. }
  120439. void drft_clear(drft_lookup *l){
  120440. if(l){
  120441. if(l->trigcache)_ogg_free(l->trigcache);
  120442. if(l->splitcache)_ogg_free(l->splitcache);
  120443. memset(l,0,sizeof(*l));
  120444. }
  120445. }
  120446. #endif
  120447. /*** End of inlined file: smallft.c ***/
  120448. /*** Start of inlined file: synthesis.c ***/
  120449. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120450. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120451. // tasks..
  120452. #if JUCE_MSVC
  120453. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120454. #endif
  120455. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120456. #if JUCE_USE_OGGVORBIS
  120457. #include <stdio.h>
  120458. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120459. vorbis_dsp_state *vd=vb->vd;
  120460. private_state *b=(private_state*)vd->backend_state;
  120461. vorbis_info *vi=vd->vi;
  120462. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120463. oggpack_buffer *opb=&vb->opb;
  120464. int type,mode,i;
  120465. /* first things first. Make sure decode is ready */
  120466. _vorbis_block_ripcord(vb);
  120467. oggpack_readinit(opb,op->packet,op->bytes);
  120468. /* Check the packet type */
  120469. if(oggpack_read(opb,1)!=0){
  120470. /* Oops. This is not an audio data packet */
  120471. return(OV_ENOTAUDIO);
  120472. }
  120473. /* read our mode and pre/post windowsize */
  120474. mode=oggpack_read(opb,b->modebits);
  120475. if(mode==-1)return(OV_EBADPACKET);
  120476. vb->mode=mode;
  120477. vb->W=ci->mode_param[mode]->blockflag;
  120478. if(vb->W){
  120479. /* this doesn;t get mapped through mode selection as it's used
  120480. only for window selection */
  120481. vb->lW=oggpack_read(opb,1);
  120482. vb->nW=oggpack_read(opb,1);
  120483. if(vb->nW==-1) return(OV_EBADPACKET);
  120484. }else{
  120485. vb->lW=0;
  120486. vb->nW=0;
  120487. }
  120488. /* more setup */
  120489. vb->granulepos=op->granulepos;
  120490. vb->sequence=op->packetno;
  120491. vb->eofflag=op->e_o_s;
  120492. /* alloc pcm passback storage */
  120493. vb->pcmend=ci->blocksizes[vb->W];
  120494. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120495. for(i=0;i<vi->channels;i++)
  120496. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120497. /* unpack_header enforces range checking */
  120498. type=ci->map_type[ci->mode_param[mode]->mapping];
  120499. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120500. mapping]));
  120501. }
  120502. /* used to track pcm position without actually performing decode.
  120503. Useful for sequential 'fast forward' */
  120504. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120505. vorbis_dsp_state *vd=vb->vd;
  120506. private_state *b=(private_state*)vd->backend_state;
  120507. vorbis_info *vi=vd->vi;
  120508. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120509. oggpack_buffer *opb=&vb->opb;
  120510. int mode;
  120511. /* first things first. Make sure decode is ready */
  120512. _vorbis_block_ripcord(vb);
  120513. oggpack_readinit(opb,op->packet,op->bytes);
  120514. /* Check the packet type */
  120515. if(oggpack_read(opb,1)!=0){
  120516. /* Oops. This is not an audio data packet */
  120517. return(OV_ENOTAUDIO);
  120518. }
  120519. /* read our mode and pre/post windowsize */
  120520. mode=oggpack_read(opb,b->modebits);
  120521. if(mode==-1)return(OV_EBADPACKET);
  120522. vb->mode=mode;
  120523. vb->W=ci->mode_param[mode]->blockflag;
  120524. if(vb->W){
  120525. vb->lW=oggpack_read(opb,1);
  120526. vb->nW=oggpack_read(opb,1);
  120527. if(vb->nW==-1) return(OV_EBADPACKET);
  120528. }else{
  120529. vb->lW=0;
  120530. vb->nW=0;
  120531. }
  120532. /* more setup */
  120533. vb->granulepos=op->granulepos;
  120534. vb->sequence=op->packetno;
  120535. vb->eofflag=op->e_o_s;
  120536. /* no pcm */
  120537. vb->pcmend=0;
  120538. vb->pcm=NULL;
  120539. return(0);
  120540. }
  120541. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120542. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120543. oggpack_buffer opb;
  120544. int mode;
  120545. oggpack_readinit(&opb,op->packet,op->bytes);
  120546. /* Check the packet type */
  120547. if(oggpack_read(&opb,1)!=0){
  120548. /* Oops. This is not an audio data packet */
  120549. return(OV_ENOTAUDIO);
  120550. }
  120551. {
  120552. int modebits=0;
  120553. int v=ci->modes;
  120554. while(v>1){
  120555. modebits++;
  120556. v>>=1;
  120557. }
  120558. /* read our mode and pre/post windowsize */
  120559. mode=oggpack_read(&opb,modebits);
  120560. }
  120561. if(mode==-1)return(OV_EBADPACKET);
  120562. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120563. }
  120564. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120565. /* set / clear half-sample-rate mode */
  120566. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120567. /* right now, our MDCT can't handle < 64 sample windows. */
  120568. if(ci->blocksizes[0]<=64 && flag)return -1;
  120569. ci->halfrate_flag=(flag?1:0);
  120570. return 0;
  120571. }
  120572. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120573. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120574. return ci->halfrate_flag;
  120575. }
  120576. #endif
  120577. /*** End of inlined file: synthesis.c ***/
  120578. /*** Start of inlined file: vorbisenc.c ***/
  120579. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120580. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120581. // tasks..
  120582. #if JUCE_MSVC
  120583. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120584. #endif
  120585. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120586. #if JUCE_USE_OGGVORBIS
  120587. #include <stdlib.h>
  120588. #include <string.h>
  120589. #include <math.h>
  120590. /* careful with this; it's using static array sizing to make managing
  120591. all the modes a little less annoying. If we use a residue backend
  120592. with > 12 partition types, or a different division of iteration,
  120593. this needs to be updated. */
  120594. typedef struct {
  120595. static_codebook *books[12][3];
  120596. } static_bookblock;
  120597. typedef struct {
  120598. int res_type;
  120599. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120600. vorbis_info_residue0 *res;
  120601. static_codebook *book_aux;
  120602. static_codebook *book_aux_managed;
  120603. static_bookblock *books_base;
  120604. static_bookblock *books_base_managed;
  120605. } vorbis_residue_template;
  120606. typedef struct {
  120607. vorbis_info_mapping0 *map;
  120608. vorbis_residue_template *res;
  120609. } vorbis_mapping_template;
  120610. typedef struct vp_adjblock{
  120611. int block[P_BANDS];
  120612. } vp_adjblock;
  120613. typedef struct {
  120614. int data[NOISE_COMPAND_LEVELS];
  120615. } compandblock;
  120616. /* high level configuration information for setting things up
  120617. step-by-step with the detailed vorbis_encode_ctl interface.
  120618. There's a fair amount of redundancy such that interactive setup
  120619. does not directly deal with any vorbis_info or codec_setup_info
  120620. initialization; it's all stored (until full init) in this highlevel
  120621. setup, then flushed out to the real codec setup structs later. */
  120622. typedef struct {
  120623. int att[P_NOISECURVES];
  120624. float boost;
  120625. float decay;
  120626. } att3;
  120627. typedef struct { int data[P_NOISECURVES]; } adj3;
  120628. typedef struct {
  120629. int pre[PACKETBLOBS];
  120630. int post[PACKETBLOBS];
  120631. float kHz[PACKETBLOBS];
  120632. float lowpasskHz[PACKETBLOBS];
  120633. } adj_stereo;
  120634. typedef struct {
  120635. int lo;
  120636. int hi;
  120637. int fixed;
  120638. } noiseguard;
  120639. typedef struct {
  120640. int data[P_NOISECURVES][17];
  120641. } noise3;
  120642. typedef struct {
  120643. int mappings;
  120644. double *rate_mapping;
  120645. double *quality_mapping;
  120646. int coupling_restriction;
  120647. long samplerate_min_restriction;
  120648. long samplerate_max_restriction;
  120649. int *blocksize_short;
  120650. int *blocksize_long;
  120651. att3 *psy_tone_masteratt;
  120652. int *psy_tone_0dB;
  120653. int *psy_tone_dBsuppress;
  120654. vp_adjblock *psy_tone_adj_impulse;
  120655. vp_adjblock *psy_tone_adj_long;
  120656. vp_adjblock *psy_tone_adj_other;
  120657. noiseguard *psy_noiseguards;
  120658. noise3 *psy_noise_bias_impulse;
  120659. noise3 *psy_noise_bias_padding;
  120660. noise3 *psy_noise_bias_trans;
  120661. noise3 *psy_noise_bias_long;
  120662. int *psy_noise_dBsuppress;
  120663. compandblock *psy_noise_compand;
  120664. double *psy_noise_compand_short_mapping;
  120665. double *psy_noise_compand_long_mapping;
  120666. int *psy_noise_normal_start[2];
  120667. int *psy_noise_normal_partition[2];
  120668. double *psy_noise_normal_thresh;
  120669. int *psy_ath_float;
  120670. int *psy_ath_abs;
  120671. double *psy_lowpass;
  120672. vorbis_info_psy_global *global_params;
  120673. double *global_mapping;
  120674. adj_stereo *stereo_modes;
  120675. static_codebook ***floor_books;
  120676. vorbis_info_floor1 *floor_params;
  120677. int *floor_short_mapping;
  120678. int *floor_long_mapping;
  120679. vorbis_mapping_template *maps;
  120680. } ve_setup_data_template;
  120681. /* a few static coder conventions */
  120682. static vorbis_info_mode _mode_template[2]={
  120683. {0,0,0,0},
  120684. {1,0,0,1}
  120685. };
  120686. static vorbis_info_mapping0 _map_nominal[2]={
  120687. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120688. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120689. };
  120690. /*** Start of inlined file: setup_44.h ***/
  120691. /*** Start of inlined file: floor_all.h ***/
  120692. /*** Start of inlined file: floor_books.h ***/
  120693. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120694. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120695. };
  120696. static static_codebook _huff_book_line_256x7_0sub1 = {
  120697. 1, 9,
  120698. _huff_lengthlist_line_256x7_0sub1,
  120699. 0, 0, 0, 0, 0,
  120700. NULL,
  120701. NULL,
  120702. NULL,
  120703. NULL,
  120704. 0
  120705. };
  120706. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120708. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120709. };
  120710. static static_codebook _huff_book_line_256x7_0sub2 = {
  120711. 1, 25,
  120712. _huff_lengthlist_line_256x7_0sub2,
  120713. 0, 0, 0, 0, 0,
  120714. NULL,
  120715. NULL,
  120716. NULL,
  120717. NULL,
  120718. 0
  120719. };
  120720. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120723. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120724. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120725. };
  120726. static static_codebook _huff_book_line_256x7_0sub3 = {
  120727. 1, 64,
  120728. _huff_lengthlist_line_256x7_0sub3,
  120729. 0, 0, 0, 0, 0,
  120730. NULL,
  120731. NULL,
  120732. NULL,
  120733. NULL,
  120734. 0
  120735. };
  120736. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120737. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120738. };
  120739. static static_codebook _huff_book_line_256x7_1sub1 = {
  120740. 1, 9,
  120741. _huff_lengthlist_line_256x7_1sub1,
  120742. 0, 0, 0, 0, 0,
  120743. NULL,
  120744. NULL,
  120745. NULL,
  120746. NULL,
  120747. 0
  120748. };
  120749. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120751. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120752. };
  120753. static static_codebook _huff_book_line_256x7_1sub2 = {
  120754. 1, 25,
  120755. _huff_lengthlist_line_256x7_1sub2,
  120756. 0, 0, 0, 0, 0,
  120757. NULL,
  120758. NULL,
  120759. NULL,
  120760. NULL,
  120761. 0
  120762. };
  120763. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120766. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120767. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120768. };
  120769. static static_codebook _huff_book_line_256x7_1sub3 = {
  120770. 1, 64,
  120771. _huff_lengthlist_line_256x7_1sub3,
  120772. 0, 0, 0, 0, 0,
  120773. NULL,
  120774. NULL,
  120775. NULL,
  120776. NULL,
  120777. 0
  120778. };
  120779. static long _huff_lengthlist_line_256x7_class0[] = {
  120780. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120781. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120782. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120783. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120784. };
  120785. static static_codebook _huff_book_line_256x7_class0 = {
  120786. 1, 64,
  120787. _huff_lengthlist_line_256x7_class0,
  120788. 0, 0, 0, 0, 0,
  120789. NULL,
  120790. NULL,
  120791. NULL,
  120792. NULL,
  120793. 0
  120794. };
  120795. static long _huff_lengthlist_line_256x7_class1[] = {
  120796. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120797. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120798. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120799. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120800. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120801. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120802. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120803. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120804. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120805. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120806. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120807. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120808. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120809. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120810. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120811. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120812. };
  120813. static static_codebook _huff_book_line_256x7_class1 = {
  120814. 1, 256,
  120815. _huff_lengthlist_line_256x7_class1,
  120816. 0, 0, 0, 0, 0,
  120817. NULL,
  120818. NULL,
  120819. NULL,
  120820. NULL,
  120821. 0
  120822. };
  120823. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120824. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120825. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120826. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120827. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120828. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120829. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120830. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120831. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120832. };
  120833. static static_codebook _huff_book_line_512x17_0sub0 = {
  120834. 1, 128,
  120835. _huff_lengthlist_line_512x17_0sub0,
  120836. 0, 0, 0, 0, 0,
  120837. NULL,
  120838. NULL,
  120839. NULL,
  120840. NULL,
  120841. 0
  120842. };
  120843. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120844. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120845. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120846. };
  120847. static static_codebook _huff_book_line_512x17_1sub0 = {
  120848. 1, 32,
  120849. _huff_lengthlist_line_512x17_1sub0,
  120850. 0, 0, 0, 0, 0,
  120851. NULL,
  120852. NULL,
  120853. NULL,
  120854. NULL,
  120855. 0
  120856. };
  120857. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120860. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120861. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120862. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120863. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120864. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120865. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120866. };
  120867. static static_codebook _huff_book_line_512x17_1sub1 = {
  120868. 1, 128,
  120869. _huff_lengthlist_line_512x17_1sub1,
  120870. 0, 0, 0, 0, 0,
  120871. NULL,
  120872. NULL,
  120873. NULL,
  120874. NULL,
  120875. 0
  120876. };
  120877. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120878. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120879. 5, 3,
  120880. };
  120881. static static_codebook _huff_book_line_512x17_2sub1 = {
  120882. 1, 18,
  120883. _huff_lengthlist_line_512x17_2sub1,
  120884. 0, 0, 0, 0, 0,
  120885. NULL,
  120886. NULL,
  120887. NULL,
  120888. NULL,
  120889. 0
  120890. };
  120891. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120893. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120894. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120895. 9, 8,
  120896. };
  120897. static static_codebook _huff_book_line_512x17_2sub2 = {
  120898. 1, 50,
  120899. _huff_lengthlist_line_512x17_2sub2,
  120900. 0, 0, 0, 0, 0,
  120901. NULL,
  120902. NULL,
  120903. NULL,
  120904. NULL,
  120905. 0
  120906. };
  120907. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120911. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120912. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120913. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120914. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120915. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120916. };
  120917. static static_codebook _huff_book_line_512x17_2sub3 = {
  120918. 1, 128,
  120919. _huff_lengthlist_line_512x17_2sub3,
  120920. 0, 0, 0, 0, 0,
  120921. NULL,
  120922. NULL,
  120923. NULL,
  120924. NULL,
  120925. 0
  120926. };
  120927. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120928. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120929. 5, 5,
  120930. };
  120931. static static_codebook _huff_book_line_512x17_3sub1 = {
  120932. 1, 18,
  120933. _huff_lengthlist_line_512x17_3sub1,
  120934. 0, 0, 0, 0, 0,
  120935. NULL,
  120936. NULL,
  120937. NULL,
  120938. NULL,
  120939. 0
  120940. };
  120941. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120943. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120944. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120945. 11,14,
  120946. };
  120947. static static_codebook _huff_book_line_512x17_3sub2 = {
  120948. 1, 50,
  120949. _huff_lengthlist_line_512x17_3sub2,
  120950. 0, 0, 0, 0, 0,
  120951. NULL,
  120952. NULL,
  120953. NULL,
  120954. NULL,
  120955. 0
  120956. };
  120957. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120961. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120962. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120963. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120964. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120965. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120966. };
  120967. static static_codebook _huff_book_line_512x17_3sub3 = {
  120968. 1, 128,
  120969. _huff_lengthlist_line_512x17_3sub3,
  120970. 0, 0, 0, 0, 0,
  120971. NULL,
  120972. NULL,
  120973. NULL,
  120974. NULL,
  120975. 0
  120976. };
  120977. static long _huff_lengthlist_line_512x17_class1[] = {
  120978. 1, 2, 3, 6, 5, 4, 7, 7,
  120979. };
  120980. static static_codebook _huff_book_line_512x17_class1 = {
  120981. 1, 8,
  120982. _huff_lengthlist_line_512x17_class1,
  120983. 0, 0, 0, 0, 0,
  120984. NULL,
  120985. NULL,
  120986. NULL,
  120987. NULL,
  120988. 0
  120989. };
  120990. static long _huff_lengthlist_line_512x17_class2[] = {
  120991. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120992. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120993. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120994. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120995. };
  120996. static static_codebook _huff_book_line_512x17_class2 = {
  120997. 1, 64,
  120998. _huff_lengthlist_line_512x17_class2,
  120999. 0, 0, 0, 0, 0,
  121000. NULL,
  121001. NULL,
  121002. NULL,
  121003. NULL,
  121004. 0
  121005. };
  121006. static long _huff_lengthlist_line_512x17_class3[] = {
  121007. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121008. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121009. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121010. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121011. };
  121012. static static_codebook _huff_book_line_512x17_class3 = {
  121013. 1, 64,
  121014. _huff_lengthlist_line_512x17_class3,
  121015. 0, 0, 0, 0, 0,
  121016. NULL,
  121017. NULL,
  121018. NULL,
  121019. NULL,
  121020. 0
  121021. };
  121022. static long _huff_lengthlist_line_128x4_class0[] = {
  121023. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121024. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121025. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121026. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121027. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121028. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121029. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121030. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121031. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121032. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121033. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121034. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121035. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121036. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121037. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121038. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121039. };
  121040. static static_codebook _huff_book_line_128x4_class0 = {
  121041. 1, 256,
  121042. _huff_lengthlist_line_128x4_class0,
  121043. 0, 0, 0, 0, 0,
  121044. NULL,
  121045. NULL,
  121046. NULL,
  121047. NULL,
  121048. 0
  121049. };
  121050. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121051. 2, 2, 2, 2,
  121052. };
  121053. static static_codebook _huff_book_line_128x4_0sub0 = {
  121054. 1, 4,
  121055. _huff_lengthlist_line_128x4_0sub0,
  121056. 0, 0, 0, 0, 0,
  121057. NULL,
  121058. NULL,
  121059. NULL,
  121060. NULL,
  121061. 0
  121062. };
  121063. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121064. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121065. };
  121066. static static_codebook _huff_book_line_128x4_0sub1 = {
  121067. 1, 10,
  121068. _huff_lengthlist_line_128x4_0sub1,
  121069. 0, 0, 0, 0, 0,
  121070. NULL,
  121071. NULL,
  121072. NULL,
  121073. NULL,
  121074. 0
  121075. };
  121076. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121078. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121079. };
  121080. static static_codebook _huff_book_line_128x4_0sub2 = {
  121081. 1, 25,
  121082. _huff_lengthlist_line_128x4_0sub2,
  121083. 0, 0, 0, 0, 0,
  121084. NULL,
  121085. NULL,
  121086. NULL,
  121087. NULL,
  121088. 0
  121089. };
  121090. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121093. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121094. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121095. };
  121096. static static_codebook _huff_book_line_128x4_0sub3 = {
  121097. 1, 64,
  121098. _huff_lengthlist_line_128x4_0sub3,
  121099. 0, 0, 0, 0, 0,
  121100. NULL,
  121101. NULL,
  121102. NULL,
  121103. NULL,
  121104. 0
  121105. };
  121106. static long _huff_lengthlist_line_256x4_class0[] = {
  121107. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121108. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121109. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121110. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121111. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121112. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121113. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121114. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121115. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121116. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121117. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121118. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121119. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121120. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121121. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121122. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121123. };
  121124. static static_codebook _huff_book_line_256x4_class0 = {
  121125. 1, 256,
  121126. _huff_lengthlist_line_256x4_class0,
  121127. 0, 0, 0, 0, 0,
  121128. NULL,
  121129. NULL,
  121130. NULL,
  121131. NULL,
  121132. 0
  121133. };
  121134. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121135. 2, 2, 2, 2,
  121136. };
  121137. static static_codebook _huff_book_line_256x4_0sub0 = {
  121138. 1, 4,
  121139. _huff_lengthlist_line_256x4_0sub0,
  121140. 0, 0, 0, 0, 0,
  121141. NULL,
  121142. NULL,
  121143. NULL,
  121144. NULL,
  121145. 0
  121146. };
  121147. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121148. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121149. };
  121150. static static_codebook _huff_book_line_256x4_0sub1 = {
  121151. 1, 10,
  121152. _huff_lengthlist_line_256x4_0sub1,
  121153. 0, 0, 0, 0, 0,
  121154. NULL,
  121155. NULL,
  121156. NULL,
  121157. NULL,
  121158. 0
  121159. };
  121160. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121162. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121163. };
  121164. static static_codebook _huff_book_line_256x4_0sub2 = {
  121165. 1, 25,
  121166. _huff_lengthlist_line_256x4_0sub2,
  121167. 0, 0, 0, 0, 0,
  121168. NULL,
  121169. NULL,
  121170. NULL,
  121171. NULL,
  121172. 0
  121173. };
  121174. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121177. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121178. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121179. };
  121180. static static_codebook _huff_book_line_256x4_0sub3 = {
  121181. 1, 64,
  121182. _huff_lengthlist_line_256x4_0sub3,
  121183. 0, 0, 0, 0, 0,
  121184. NULL,
  121185. NULL,
  121186. NULL,
  121187. NULL,
  121188. 0
  121189. };
  121190. static long _huff_lengthlist_line_128x7_class0[] = {
  121191. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121192. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121193. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121194. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121195. };
  121196. static static_codebook _huff_book_line_128x7_class0 = {
  121197. 1, 64,
  121198. _huff_lengthlist_line_128x7_class0,
  121199. 0, 0, 0, 0, 0,
  121200. NULL,
  121201. NULL,
  121202. NULL,
  121203. NULL,
  121204. 0
  121205. };
  121206. static long _huff_lengthlist_line_128x7_class1[] = {
  121207. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121208. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121209. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121210. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121211. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121212. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121213. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121214. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121215. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121216. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121217. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121218. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121219. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121220. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121221. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121222. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121223. };
  121224. static static_codebook _huff_book_line_128x7_class1 = {
  121225. 1, 256,
  121226. _huff_lengthlist_line_128x7_class1,
  121227. 0, 0, 0, 0, 0,
  121228. NULL,
  121229. NULL,
  121230. NULL,
  121231. NULL,
  121232. 0
  121233. };
  121234. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121235. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121236. };
  121237. static static_codebook _huff_book_line_128x7_0sub1 = {
  121238. 1, 9,
  121239. _huff_lengthlist_line_128x7_0sub1,
  121240. 0, 0, 0, 0, 0,
  121241. NULL,
  121242. NULL,
  121243. NULL,
  121244. NULL,
  121245. 0
  121246. };
  121247. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121249. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121250. };
  121251. static static_codebook _huff_book_line_128x7_0sub2 = {
  121252. 1, 25,
  121253. _huff_lengthlist_line_128x7_0sub2,
  121254. 0, 0, 0, 0, 0,
  121255. NULL,
  121256. NULL,
  121257. NULL,
  121258. NULL,
  121259. 0
  121260. };
  121261. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121264. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121265. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121266. };
  121267. static static_codebook _huff_book_line_128x7_0sub3 = {
  121268. 1, 64,
  121269. _huff_lengthlist_line_128x7_0sub3,
  121270. 0, 0, 0, 0, 0,
  121271. NULL,
  121272. NULL,
  121273. NULL,
  121274. NULL,
  121275. 0
  121276. };
  121277. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121278. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121279. };
  121280. static static_codebook _huff_book_line_128x7_1sub1 = {
  121281. 1, 9,
  121282. _huff_lengthlist_line_128x7_1sub1,
  121283. 0, 0, 0, 0, 0,
  121284. NULL,
  121285. NULL,
  121286. NULL,
  121287. NULL,
  121288. 0
  121289. };
  121290. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121292. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121293. };
  121294. static static_codebook _huff_book_line_128x7_1sub2 = {
  121295. 1, 25,
  121296. _huff_lengthlist_line_128x7_1sub2,
  121297. 0, 0, 0, 0, 0,
  121298. NULL,
  121299. NULL,
  121300. NULL,
  121301. NULL,
  121302. 0
  121303. };
  121304. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121307. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121308. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121309. };
  121310. static static_codebook _huff_book_line_128x7_1sub3 = {
  121311. 1, 64,
  121312. _huff_lengthlist_line_128x7_1sub3,
  121313. 0, 0, 0, 0, 0,
  121314. NULL,
  121315. NULL,
  121316. NULL,
  121317. NULL,
  121318. 0
  121319. };
  121320. static long _huff_lengthlist_line_128x11_class1[] = {
  121321. 1, 6, 3, 7, 2, 4, 5, 7,
  121322. };
  121323. static static_codebook _huff_book_line_128x11_class1 = {
  121324. 1, 8,
  121325. _huff_lengthlist_line_128x11_class1,
  121326. 0, 0, 0, 0, 0,
  121327. NULL,
  121328. NULL,
  121329. NULL,
  121330. NULL,
  121331. 0
  121332. };
  121333. static long _huff_lengthlist_line_128x11_class2[] = {
  121334. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121335. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121336. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121337. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121338. };
  121339. static static_codebook _huff_book_line_128x11_class2 = {
  121340. 1, 64,
  121341. _huff_lengthlist_line_128x11_class2,
  121342. 0, 0, 0, 0, 0,
  121343. NULL,
  121344. NULL,
  121345. NULL,
  121346. NULL,
  121347. 0
  121348. };
  121349. static long _huff_lengthlist_line_128x11_class3[] = {
  121350. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121351. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121352. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121353. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121354. };
  121355. static static_codebook _huff_book_line_128x11_class3 = {
  121356. 1, 64,
  121357. _huff_lengthlist_line_128x11_class3,
  121358. 0, 0, 0, 0, 0,
  121359. NULL,
  121360. NULL,
  121361. NULL,
  121362. NULL,
  121363. 0
  121364. };
  121365. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121366. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121367. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121368. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121369. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121370. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121371. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121372. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121373. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121374. };
  121375. static static_codebook _huff_book_line_128x11_0sub0 = {
  121376. 1, 128,
  121377. _huff_lengthlist_line_128x11_0sub0,
  121378. 0, 0, 0, 0, 0,
  121379. NULL,
  121380. NULL,
  121381. NULL,
  121382. NULL,
  121383. 0
  121384. };
  121385. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121386. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121387. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121388. };
  121389. static static_codebook _huff_book_line_128x11_1sub0 = {
  121390. 1, 32,
  121391. _huff_lengthlist_line_128x11_1sub0,
  121392. 0, 0, 0, 0, 0,
  121393. NULL,
  121394. NULL,
  121395. NULL,
  121396. NULL,
  121397. 0
  121398. };
  121399. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121402. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121403. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121404. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121405. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121406. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121407. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121408. };
  121409. static static_codebook _huff_book_line_128x11_1sub1 = {
  121410. 1, 128,
  121411. _huff_lengthlist_line_128x11_1sub1,
  121412. 0, 0, 0, 0, 0,
  121413. NULL,
  121414. NULL,
  121415. NULL,
  121416. NULL,
  121417. 0
  121418. };
  121419. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121420. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121421. 5, 5,
  121422. };
  121423. static static_codebook _huff_book_line_128x11_2sub1 = {
  121424. 1, 18,
  121425. _huff_lengthlist_line_128x11_2sub1,
  121426. 0, 0, 0, 0, 0,
  121427. NULL,
  121428. NULL,
  121429. NULL,
  121430. NULL,
  121431. 0
  121432. };
  121433. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121435. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121436. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121437. 8,11,
  121438. };
  121439. static static_codebook _huff_book_line_128x11_2sub2 = {
  121440. 1, 50,
  121441. _huff_lengthlist_line_128x11_2sub2,
  121442. 0, 0, 0, 0, 0,
  121443. NULL,
  121444. NULL,
  121445. NULL,
  121446. NULL,
  121447. 0
  121448. };
  121449. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121453. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121454. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121455. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121456. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121457. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121458. };
  121459. static static_codebook _huff_book_line_128x11_2sub3 = {
  121460. 1, 128,
  121461. _huff_lengthlist_line_128x11_2sub3,
  121462. 0, 0, 0, 0, 0,
  121463. NULL,
  121464. NULL,
  121465. NULL,
  121466. NULL,
  121467. 0
  121468. };
  121469. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121470. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121471. 5, 4,
  121472. };
  121473. static static_codebook _huff_book_line_128x11_3sub1 = {
  121474. 1, 18,
  121475. _huff_lengthlist_line_128x11_3sub1,
  121476. 0, 0, 0, 0, 0,
  121477. NULL,
  121478. NULL,
  121479. NULL,
  121480. NULL,
  121481. 0
  121482. };
  121483. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121485. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121486. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121487. 12, 6,
  121488. };
  121489. static static_codebook _huff_book_line_128x11_3sub2 = {
  121490. 1, 50,
  121491. _huff_lengthlist_line_128x11_3sub2,
  121492. 0, 0, 0, 0, 0,
  121493. NULL,
  121494. NULL,
  121495. NULL,
  121496. NULL,
  121497. 0
  121498. };
  121499. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121503. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121504. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121505. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121506. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121507. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121508. };
  121509. static static_codebook _huff_book_line_128x11_3sub3 = {
  121510. 1, 128,
  121511. _huff_lengthlist_line_128x11_3sub3,
  121512. 0, 0, 0, 0, 0,
  121513. NULL,
  121514. NULL,
  121515. NULL,
  121516. NULL,
  121517. 0
  121518. };
  121519. static long _huff_lengthlist_line_128x17_class1[] = {
  121520. 1, 3, 4, 7, 2, 5, 6, 7,
  121521. };
  121522. static static_codebook _huff_book_line_128x17_class1 = {
  121523. 1, 8,
  121524. _huff_lengthlist_line_128x17_class1,
  121525. 0, 0, 0, 0, 0,
  121526. NULL,
  121527. NULL,
  121528. NULL,
  121529. NULL,
  121530. 0
  121531. };
  121532. static long _huff_lengthlist_line_128x17_class2[] = {
  121533. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121534. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121535. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121536. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121537. };
  121538. static static_codebook _huff_book_line_128x17_class2 = {
  121539. 1, 64,
  121540. _huff_lengthlist_line_128x17_class2,
  121541. 0, 0, 0, 0, 0,
  121542. NULL,
  121543. NULL,
  121544. NULL,
  121545. NULL,
  121546. 0
  121547. };
  121548. static long _huff_lengthlist_line_128x17_class3[] = {
  121549. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121550. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121551. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121552. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121553. };
  121554. static static_codebook _huff_book_line_128x17_class3 = {
  121555. 1, 64,
  121556. _huff_lengthlist_line_128x17_class3,
  121557. 0, 0, 0, 0, 0,
  121558. NULL,
  121559. NULL,
  121560. NULL,
  121561. NULL,
  121562. 0
  121563. };
  121564. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121565. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121566. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121567. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121568. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121569. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121570. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121571. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121572. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121573. };
  121574. static static_codebook _huff_book_line_128x17_0sub0 = {
  121575. 1, 128,
  121576. _huff_lengthlist_line_128x17_0sub0,
  121577. 0, 0, 0, 0, 0,
  121578. NULL,
  121579. NULL,
  121580. NULL,
  121581. NULL,
  121582. 0
  121583. };
  121584. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121585. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121586. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121587. };
  121588. static static_codebook _huff_book_line_128x17_1sub0 = {
  121589. 1, 32,
  121590. _huff_lengthlist_line_128x17_1sub0,
  121591. 0, 0, 0, 0, 0,
  121592. NULL,
  121593. NULL,
  121594. NULL,
  121595. NULL,
  121596. 0
  121597. };
  121598. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121601. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121602. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121603. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121604. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121605. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121606. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121607. };
  121608. static static_codebook _huff_book_line_128x17_1sub1 = {
  121609. 1, 128,
  121610. _huff_lengthlist_line_128x17_1sub1,
  121611. 0, 0, 0, 0, 0,
  121612. NULL,
  121613. NULL,
  121614. NULL,
  121615. NULL,
  121616. 0
  121617. };
  121618. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121619. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121620. 9, 4,
  121621. };
  121622. static static_codebook _huff_book_line_128x17_2sub1 = {
  121623. 1, 18,
  121624. _huff_lengthlist_line_128x17_2sub1,
  121625. 0, 0, 0, 0, 0,
  121626. NULL,
  121627. NULL,
  121628. NULL,
  121629. NULL,
  121630. 0
  121631. };
  121632. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121634. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121635. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121636. 13,13,
  121637. };
  121638. static static_codebook _huff_book_line_128x17_2sub2 = {
  121639. 1, 50,
  121640. _huff_lengthlist_line_128x17_2sub2,
  121641. 0, 0, 0, 0, 0,
  121642. NULL,
  121643. NULL,
  121644. NULL,
  121645. NULL,
  121646. 0
  121647. };
  121648. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121652. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121653. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121654. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121655. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121656. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121657. };
  121658. static static_codebook _huff_book_line_128x17_2sub3 = {
  121659. 1, 128,
  121660. _huff_lengthlist_line_128x17_2sub3,
  121661. 0, 0, 0, 0, 0,
  121662. NULL,
  121663. NULL,
  121664. NULL,
  121665. NULL,
  121666. 0
  121667. };
  121668. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121669. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121670. 6, 4,
  121671. };
  121672. static static_codebook _huff_book_line_128x17_3sub1 = {
  121673. 1, 18,
  121674. _huff_lengthlist_line_128x17_3sub1,
  121675. 0, 0, 0, 0, 0,
  121676. NULL,
  121677. NULL,
  121678. NULL,
  121679. NULL,
  121680. 0
  121681. };
  121682. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121684. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121685. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121686. 10, 8,
  121687. };
  121688. static static_codebook _huff_book_line_128x17_3sub2 = {
  121689. 1, 50,
  121690. _huff_lengthlist_line_128x17_3sub2,
  121691. 0, 0, 0, 0, 0,
  121692. NULL,
  121693. NULL,
  121694. NULL,
  121695. NULL,
  121696. 0
  121697. };
  121698. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121702. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121703. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121704. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121707. };
  121708. static static_codebook _huff_book_line_128x17_3sub3 = {
  121709. 1, 128,
  121710. _huff_lengthlist_line_128x17_3sub3,
  121711. 0, 0, 0, 0, 0,
  121712. NULL,
  121713. NULL,
  121714. NULL,
  121715. NULL,
  121716. 0
  121717. };
  121718. static long _huff_lengthlist_line_1024x27_class1[] = {
  121719. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121720. };
  121721. static static_codebook _huff_book_line_1024x27_class1 = {
  121722. 1, 16,
  121723. _huff_lengthlist_line_1024x27_class1,
  121724. 0, 0, 0, 0, 0,
  121725. NULL,
  121726. NULL,
  121727. NULL,
  121728. NULL,
  121729. 0
  121730. };
  121731. static long _huff_lengthlist_line_1024x27_class2[] = {
  121732. 1, 4, 2, 6, 3, 7, 5, 7,
  121733. };
  121734. static static_codebook _huff_book_line_1024x27_class2 = {
  121735. 1, 8,
  121736. _huff_lengthlist_line_1024x27_class2,
  121737. 0, 0, 0, 0, 0,
  121738. NULL,
  121739. NULL,
  121740. NULL,
  121741. NULL,
  121742. 0
  121743. };
  121744. static long _huff_lengthlist_line_1024x27_class3[] = {
  121745. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121746. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121747. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121748. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121749. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121750. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121751. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121752. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121753. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121754. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121755. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121756. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121757. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121758. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121759. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121760. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121761. };
  121762. static static_codebook _huff_book_line_1024x27_class3 = {
  121763. 1, 256,
  121764. _huff_lengthlist_line_1024x27_class3,
  121765. 0, 0, 0, 0, 0,
  121766. NULL,
  121767. NULL,
  121768. NULL,
  121769. NULL,
  121770. 0
  121771. };
  121772. static long _huff_lengthlist_line_1024x27_class4[] = {
  121773. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121774. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121775. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121776. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121777. };
  121778. static static_codebook _huff_book_line_1024x27_class4 = {
  121779. 1, 64,
  121780. _huff_lengthlist_line_1024x27_class4,
  121781. 0, 0, 0, 0, 0,
  121782. NULL,
  121783. NULL,
  121784. NULL,
  121785. NULL,
  121786. 0
  121787. };
  121788. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121789. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121790. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121791. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121792. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121793. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121794. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121795. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121796. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121797. };
  121798. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121799. 1, 128,
  121800. _huff_lengthlist_line_1024x27_0sub0,
  121801. 0, 0, 0, 0, 0,
  121802. NULL,
  121803. NULL,
  121804. NULL,
  121805. NULL,
  121806. 0
  121807. };
  121808. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121809. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121810. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121811. };
  121812. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121813. 1, 32,
  121814. _huff_lengthlist_line_1024x27_1sub0,
  121815. 0, 0, 0, 0, 0,
  121816. NULL,
  121817. NULL,
  121818. NULL,
  121819. NULL,
  121820. 0
  121821. };
  121822. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121825. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121826. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121827. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121828. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121829. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121830. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121831. };
  121832. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121833. 1, 128,
  121834. _huff_lengthlist_line_1024x27_1sub1,
  121835. 0, 0, 0, 0, 0,
  121836. NULL,
  121837. NULL,
  121838. NULL,
  121839. NULL,
  121840. 0
  121841. };
  121842. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121843. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121844. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121845. };
  121846. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121847. 1, 32,
  121848. _huff_lengthlist_line_1024x27_2sub0,
  121849. 0, 0, 0, 0, 0,
  121850. NULL,
  121851. NULL,
  121852. NULL,
  121853. NULL,
  121854. 0
  121855. };
  121856. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121859. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121860. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121861. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121862. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121863. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121864. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121865. };
  121866. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121867. 1, 128,
  121868. _huff_lengthlist_line_1024x27_2sub1,
  121869. 0, 0, 0, 0, 0,
  121870. NULL,
  121871. NULL,
  121872. NULL,
  121873. NULL,
  121874. 0
  121875. };
  121876. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121877. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121878. 5, 5,
  121879. };
  121880. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121881. 1, 18,
  121882. _huff_lengthlist_line_1024x27_3sub1,
  121883. 0, 0, 0, 0, 0,
  121884. NULL,
  121885. NULL,
  121886. NULL,
  121887. NULL,
  121888. 0
  121889. };
  121890. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121892. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121893. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121894. 9,11,
  121895. };
  121896. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121897. 1, 50,
  121898. _huff_lengthlist_line_1024x27_3sub2,
  121899. 0, 0, 0, 0, 0,
  121900. NULL,
  121901. NULL,
  121902. NULL,
  121903. NULL,
  121904. 0
  121905. };
  121906. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121910. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121911. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121912. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121913. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121914. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121915. };
  121916. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121917. 1, 128,
  121918. _huff_lengthlist_line_1024x27_3sub3,
  121919. 0, 0, 0, 0, 0,
  121920. NULL,
  121921. NULL,
  121922. NULL,
  121923. NULL,
  121924. 0
  121925. };
  121926. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121927. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121928. 5, 4,
  121929. };
  121930. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121931. 1, 18,
  121932. _huff_lengthlist_line_1024x27_4sub1,
  121933. 0, 0, 0, 0, 0,
  121934. NULL,
  121935. NULL,
  121936. NULL,
  121937. NULL,
  121938. 0
  121939. };
  121940. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121942. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121943. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121944. 9,12,
  121945. };
  121946. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121947. 1, 50,
  121948. _huff_lengthlist_line_1024x27_4sub2,
  121949. 0, 0, 0, 0, 0,
  121950. NULL,
  121951. NULL,
  121952. NULL,
  121953. NULL,
  121954. 0
  121955. };
  121956. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121960. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121961. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121962. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121963. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121964. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121965. };
  121966. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121967. 1, 128,
  121968. _huff_lengthlist_line_1024x27_4sub3,
  121969. 0, 0, 0, 0, 0,
  121970. NULL,
  121971. NULL,
  121972. NULL,
  121973. NULL,
  121974. 0
  121975. };
  121976. static long _huff_lengthlist_line_2048x27_class1[] = {
  121977. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121978. };
  121979. static static_codebook _huff_book_line_2048x27_class1 = {
  121980. 1, 16,
  121981. _huff_lengthlist_line_2048x27_class1,
  121982. 0, 0, 0, 0, 0,
  121983. NULL,
  121984. NULL,
  121985. NULL,
  121986. NULL,
  121987. 0
  121988. };
  121989. static long _huff_lengthlist_line_2048x27_class2[] = {
  121990. 1, 2, 3, 6, 4, 7, 5, 7,
  121991. };
  121992. static static_codebook _huff_book_line_2048x27_class2 = {
  121993. 1, 8,
  121994. _huff_lengthlist_line_2048x27_class2,
  121995. 0, 0, 0, 0, 0,
  121996. NULL,
  121997. NULL,
  121998. NULL,
  121999. NULL,
  122000. 0
  122001. };
  122002. static long _huff_lengthlist_line_2048x27_class3[] = {
  122003. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122004. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122005. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122006. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122007. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122008. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122009. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122010. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122011. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122012. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122013. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122014. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122015. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122016. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122017. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122018. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122019. };
  122020. static static_codebook _huff_book_line_2048x27_class3 = {
  122021. 1, 256,
  122022. _huff_lengthlist_line_2048x27_class3,
  122023. 0, 0, 0, 0, 0,
  122024. NULL,
  122025. NULL,
  122026. NULL,
  122027. NULL,
  122028. 0
  122029. };
  122030. static long _huff_lengthlist_line_2048x27_class4[] = {
  122031. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122032. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122033. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122034. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122035. };
  122036. static static_codebook _huff_book_line_2048x27_class4 = {
  122037. 1, 64,
  122038. _huff_lengthlist_line_2048x27_class4,
  122039. 0, 0, 0, 0, 0,
  122040. NULL,
  122041. NULL,
  122042. NULL,
  122043. NULL,
  122044. 0
  122045. };
  122046. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122047. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122048. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122049. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122050. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122051. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122052. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122053. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122054. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122055. };
  122056. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122057. 1, 128,
  122058. _huff_lengthlist_line_2048x27_0sub0,
  122059. 0, 0, 0, 0, 0,
  122060. NULL,
  122061. NULL,
  122062. NULL,
  122063. NULL,
  122064. 0
  122065. };
  122066. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122067. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122068. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122069. };
  122070. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122071. 1, 32,
  122072. _huff_lengthlist_line_2048x27_1sub0,
  122073. 0, 0, 0, 0, 0,
  122074. NULL,
  122075. NULL,
  122076. NULL,
  122077. NULL,
  122078. 0
  122079. };
  122080. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122084. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122085. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122086. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122087. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122088. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122089. };
  122090. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122091. 1, 128,
  122092. _huff_lengthlist_line_2048x27_1sub1,
  122093. 0, 0, 0, 0, 0,
  122094. NULL,
  122095. NULL,
  122096. NULL,
  122097. NULL,
  122098. 0
  122099. };
  122100. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122101. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122102. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122103. };
  122104. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122105. 1, 32,
  122106. _huff_lengthlist_line_2048x27_2sub0,
  122107. 0, 0, 0, 0, 0,
  122108. NULL,
  122109. NULL,
  122110. NULL,
  122111. NULL,
  122112. 0
  122113. };
  122114. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122117. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122118. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122119. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122120. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122121. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122122. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122123. };
  122124. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122125. 1, 128,
  122126. _huff_lengthlist_line_2048x27_2sub1,
  122127. 0, 0, 0, 0, 0,
  122128. NULL,
  122129. NULL,
  122130. NULL,
  122131. NULL,
  122132. 0
  122133. };
  122134. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122135. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122136. 5, 5,
  122137. };
  122138. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122139. 1, 18,
  122140. _huff_lengthlist_line_2048x27_3sub1,
  122141. 0, 0, 0, 0, 0,
  122142. NULL,
  122143. NULL,
  122144. NULL,
  122145. NULL,
  122146. 0
  122147. };
  122148. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122151. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122152. 10,12,
  122153. };
  122154. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122155. 1, 50,
  122156. _huff_lengthlist_line_2048x27_3sub2,
  122157. 0, 0, 0, 0, 0,
  122158. NULL,
  122159. NULL,
  122160. NULL,
  122161. NULL,
  122162. 0
  122163. };
  122164. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122169. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122170. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122171. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122172. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122173. };
  122174. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122175. 1, 128,
  122176. _huff_lengthlist_line_2048x27_3sub3,
  122177. 0, 0, 0, 0, 0,
  122178. NULL,
  122179. NULL,
  122180. NULL,
  122181. NULL,
  122182. 0
  122183. };
  122184. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122185. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122186. 4, 5,
  122187. };
  122188. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122189. 1, 18,
  122190. _huff_lengthlist_line_2048x27_4sub1,
  122191. 0, 0, 0, 0, 0,
  122192. NULL,
  122193. NULL,
  122194. NULL,
  122195. NULL,
  122196. 0
  122197. };
  122198. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122200. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122201. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122202. 10,10,
  122203. };
  122204. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122205. 1, 50,
  122206. _huff_lengthlist_line_2048x27_4sub2,
  122207. 0, 0, 0, 0, 0,
  122208. NULL,
  122209. NULL,
  122210. NULL,
  122211. NULL,
  122212. 0
  122213. };
  122214. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122218. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122219. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122220. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122221. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122222. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122223. };
  122224. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122225. 1, 128,
  122226. _huff_lengthlist_line_2048x27_4sub3,
  122227. 0, 0, 0, 0, 0,
  122228. NULL,
  122229. NULL,
  122230. NULL,
  122231. NULL,
  122232. 0
  122233. };
  122234. static long _huff_lengthlist_line_256x4low_class0[] = {
  122235. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122236. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122237. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122238. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122239. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122240. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122241. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122242. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122243. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122244. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122245. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122246. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122247. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122248. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122249. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122250. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122251. };
  122252. static static_codebook _huff_book_line_256x4low_class0 = {
  122253. 1, 256,
  122254. _huff_lengthlist_line_256x4low_class0,
  122255. 0, 0, 0, 0, 0,
  122256. NULL,
  122257. NULL,
  122258. NULL,
  122259. NULL,
  122260. 0
  122261. };
  122262. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122263. 1, 3, 2, 3,
  122264. };
  122265. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122266. 1, 4,
  122267. _huff_lengthlist_line_256x4low_0sub0,
  122268. 0, 0, 0, 0, 0,
  122269. NULL,
  122270. NULL,
  122271. NULL,
  122272. NULL,
  122273. 0
  122274. };
  122275. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122276. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122277. };
  122278. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122279. 1, 10,
  122280. _huff_lengthlist_line_256x4low_0sub1,
  122281. 0, 0, 0, 0, 0,
  122282. NULL,
  122283. NULL,
  122284. NULL,
  122285. NULL,
  122286. 0
  122287. };
  122288. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122290. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122291. };
  122292. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122293. 1, 25,
  122294. _huff_lengthlist_line_256x4low_0sub2,
  122295. 0, 0, 0, 0, 0,
  122296. NULL,
  122297. NULL,
  122298. NULL,
  122299. NULL,
  122300. 0
  122301. };
  122302. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122305. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122306. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122307. };
  122308. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122309. 1, 64,
  122310. _huff_lengthlist_line_256x4low_0sub3,
  122311. 0, 0, 0, 0, 0,
  122312. NULL,
  122313. NULL,
  122314. NULL,
  122315. NULL,
  122316. 0
  122317. };
  122318. /*** End of inlined file: floor_books.h ***/
  122319. static static_codebook *_floor_128x4_books[]={
  122320. &_huff_book_line_128x4_class0,
  122321. &_huff_book_line_128x4_0sub0,
  122322. &_huff_book_line_128x4_0sub1,
  122323. &_huff_book_line_128x4_0sub2,
  122324. &_huff_book_line_128x4_0sub3,
  122325. };
  122326. static static_codebook *_floor_256x4_books[]={
  122327. &_huff_book_line_256x4_class0,
  122328. &_huff_book_line_256x4_0sub0,
  122329. &_huff_book_line_256x4_0sub1,
  122330. &_huff_book_line_256x4_0sub2,
  122331. &_huff_book_line_256x4_0sub3,
  122332. };
  122333. static static_codebook *_floor_128x7_books[]={
  122334. &_huff_book_line_128x7_class0,
  122335. &_huff_book_line_128x7_class1,
  122336. &_huff_book_line_128x7_0sub1,
  122337. &_huff_book_line_128x7_0sub2,
  122338. &_huff_book_line_128x7_0sub3,
  122339. &_huff_book_line_128x7_1sub1,
  122340. &_huff_book_line_128x7_1sub2,
  122341. &_huff_book_line_128x7_1sub3,
  122342. };
  122343. static static_codebook *_floor_256x7_books[]={
  122344. &_huff_book_line_256x7_class0,
  122345. &_huff_book_line_256x7_class1,
  122346. &_huff_book_line_256x7_0sub1,
  122347. &_huff_book_line_256x7_0sub2,
  122348. &_huff_book_line_256x7_0sub3,
  122349. &_huff_book_line_256x7_1sub1,
  122350. &_huff_book_line_256x7_1sub2,
  122351. &_huff_book_line_256x7_1sub3,
  122352. };
  122353. static static_codebook *_floor_128x11_books[]={
  122354. &_huff_book_line_128x11_class1,
  122355. &_huff_book_line_128x11_class2,
  122356. &_huff_book_line_128x11_class3,
  122357. &_huff_book_line_128x11_0sub0,
  122358. &_huff_book_line_128x11_1sub0,
  122359. &_huff_book_line_128x11_1sub1,
  122360. &_huff_book_line_128x11_2sub1,
  122361. &_huff_book_line_128x11_2sub2,
  122362. &_huff_book_line_128x11_2sub3,
  122363. &_huff_book_line_128x11_3sub1,
  122364. &_huff_book_line_128x11_3sub2,
  122365. &_huff_book_line_128x11_3sub3,
  122366. };
  122367. static static_codebook *_floor_128x17_books[]={
  122368. &_huff_book_line_128x17_class1,
  122369. &_huff_book_line_128x17_class2,
  122370. &_huff_book_line_128x17_class3,
  122371. &_huff_book_line_128x17_0sub0,
  122372. &_huff_book_line_128x17_1sub0,
  122373. &_huff_book_line_128x17_1sub1,
  122374. &_huff_book_line_128x17_2sub1,
  122375. &_huff_book_line_128x17_2sub2,
  122376. &_huff_book_line_128x17_2sub3,
  122377. &_huff_book_line_128x17_3sub1,
  122378. &_huff_book_line_128x17_3sub2,
  122379. &_huff_book_line_128x17_3sub3,
  122380. };
  122381. static static_codebook *_floor_256x4low_books[]={
  122382. &_huff_book_line_256x4low_class0,
  122383. &_huff_book_line_256x4low_0sub0,
  122384. &_huff_book_line_256x4low_0sub1,
  122385. &_huff_book_line_256x4low_0sub2,
  122386. &_huff_book_line_256x4low_0sub3,
  122387. };
  122388. static static_codebook *_floor_1024x27_books[]={
  122389. &_huff_book_line_1024x27_class1,
  122390. &_huff_book_line_1024x27_class2,
  122391. &_huff_book_line_1024x27_class3,
  122392. &_huff_book_line_1024x27_class4,
  122393. &_huff_book_line_1024x27_0sub0,
  122394. &_huff_book_line_1024x27_1sub0,
  122395. &_huff_book_line_1024x27_1sub1,
  122396. &_huff_book_line_1024x27_2sub0,
  122397. &_huff_book_line_1024x27_2sub1,
  122398. &_huff_book_line_1024x27_3sub1,
  122399. &_huff_book_line_1024x27_3sub2,
  122400. &_huff_book_line_1024x27_3sub3,
  122401. &_huff_book_line_1024x27_4sub1,
  122402. &_huff_book_line_1024x27_4sub2,
  122403. &_huff_book_line_1024x27_4sub3,
  122404. };
  122405. static static_codebook *_floor_2048x27_books[]={
  122406. &_huff_book_line_2048x27_class1,
  122407. &_huff_book_line_2048x27_class2,
  122408. &_huff_book_line_2048x27_class3,
  122409. &_huff_book_line_2048x27_class4,
  122410. &_huff_book_line_2048x27_0sub0,
  122411. &_huff_book_line_2048x27_1sub0,
  122412. &_huff_book_line_2048x27_1sub1,
  122413. &_huff_book_line_2048x27_2sub0,
  122414. &_huff_book_line_2048x27_2sub1,
  122415. &_huff_book_line_2048x27_3sub1,
  122416. &_huff_book_line_2048x27_3sub2,
  122417. &_huff_book_line_2048x27_3sub3,
  122418. &_huff_book_line_2048x27_4sub1,
  122419. &_huff_book_line_2048x27_4sub2,
  122420. &_huff_book_line_2048x27_4sub3,
  122421. };
  122422. static static_codebook *_floor_512x17_books[]={
  122423. &_huff_book_line_512x17_class1,
  122424. &_huff_book_line_512x17_class2,
  122425. &_huff_book_line_512x17_class3,
  122426. &_huff_book_line_512x17_0sub0,
  122427. &_huff_book_line_512x17_1sub0,
  122428. &_huff_book_line_512x17_1sub1,
  122429. &_huff_book_line_512x17_2sub1,
  122430. &_huff_book_line_512x17_2sub2,
  122431. &_huff_book_line_512x17_2sub3,
  122432. &_huff_book_line_512x17_3sub1,
  122433. &_huff_book_line_512x17_3sub2,
  122434. &_huff_book_line_512x17_3sub3,
  122435. };
  122436. static static_codebook **_floor_books[10]={
  122437. _floor_128x4_books,
  122438. _floor_256x4_books,
  122439. _floor_128x7_books,
  122440. _floor_256x7_books,
  122441. _floor_128x11_books,
  122442. _floor_128x17_books,
  122443. _floor_256x4low_books,
  122444. _floor_1024x27_books,
  122445. _floor_2048x27_books,
  122446. _floor_512x17_books,
  122447. };
  122448. static vorbis_info_floor1 _floor[10]={
  122449. /* 128 x 4 */
  122450. {
  122451. 1,{0},{4},{2},{0},
  122452. {{1,2,3,4}},
  122453. 4,{0,128, 33,8,16,70},
  122454. 60,30,500, 1.,18., -1
  122455. },
  122456. /* 256 x 4 */
  122457. {
  122458. 1,{0},{4},{2},{0},
  122459. {{1,2,3,4}},
  122460. 4,{0,256, 66,16,32,140},
  122461. 60,30,500, 1.,18., -1
  122462. },
  122463. /* 128 x 7 */
  122464. {
  122465. 2,{0,1},{3,4},{2,2},{0,1},
  122466. {{-1,2,3,4},{-1,5,6,7}},
  122467. 4,{0,128, 14,4,58, 2,8,28,90},
  122468. 60,30,500, 1.,18., -1
  122469. },
  122470. /* 256 x 7 */
  122471. {
  122472. 2,{0,1},{3,4},{2,2},{0,1},
  122473. {{-1,2,3,4},{-1,5,6,7}},
  122474. 4,{0,256, 28,8,116, 4,16,56,180},
  122475. 60,30,500, 1.,18., -1
  122476. },
  122477. /* 128 x 11 */
  122478. {
  122479. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122480. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122481. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122482. 60,30,500, 1,18., -1
  122483. },
  122484. /* 128 x 17 */
  122485. {
  122486. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122487. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122488. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122489. 60,30,500, 1,18., -1
  122490. },
  122491. /* 256 x 4 (low bitrate version) */
  122492. {
  122493. 1,{0},{4},{2},{0},
  122494. {{1,2,3,4}},
  122495. 4,{0,256, 66,16,32,140},
  122496. 60,30,500, 1.,18., -1
  122497. },
  122498. /* 1024 x 27 */
  122499. {
  122500. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122501. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122502. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122503. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122504. 60,30,500, 3,18., -1 /* lowpass */
  122505. },
  122506. /* 2048 x 27 */
  122507. {
  122508. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122509. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122510. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122511. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122512. 60,30,500, 3,18., -1 /* lowpass */
  122513. },
  122514. /* 512 x 17 */
  122515. {
  122516. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122517. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122518. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122519. 7,23,39, 55,79,110, 156,232,360},
  122520. 60,30,500, 1,18., -1 /* lowpass! */
  122521. },
  122522. };
  122523. /*** End of inlined file: floor_all.h ***/
  122524. /*** Start of inlined file: residue_44.h ***/
  122525. /*** Start of inlined file: res_books_stereo.h ***/
  122526. static long _vq_quantlist__16c0_s_p1_0[] = {
  122527. 1,
  122528. 0,
  122529. 2,
  122530. };
  122531. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122532. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122533. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122538. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122543. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122578. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122583. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122588. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122624. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122629. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122634. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0,
  122943. };
  122944. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122945. -0.5, 0.5,
  122946. };
  122947. static long _vq_quantmap__16c0_s_p1_0[] = {
  122948. 1, 0, 2,
  122949. };
  122950. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122951. _vq_quantthresh__16c0_s_p1_0,
  122952. _vq_quantmap__16c0_s_p1_0,
  122953. 3,
  122954. 3
  122955. };
  122956. static static_codebook _16c0_s_p1_0 = {
  122957. 8, 6561,
  122958. _vq_lengthlist__16c0_s_p1_0,
  122959. 1, -535822336, 1611661312, 2, 0,
  122960. _vq_quantlist__16c0_s_p1_0,
  122961. NULL,
  122962. &_vq_auxt__16c0_s_p1_0,
  122963. NULL,
  122964. 0
  122965. };
  122966. static long _vq_quantlist__16c0_s_p2_0[] = {
  122967. 2,
  122968. 1,
  122969. 3,
  122970. 0,
  122971. 4,
  122972. };
  122973. static long _vq_lengthlist__16c0_s_p2_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,
  123014. };
  123015. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123016. -1.5, -0.5, 0.5, 1.5,
  123017. };
  123018. static long _vq_quantmap__16c0_s_p2_0[] = {
  123019. 3, 1, 0, 2, 4,
  123020. };
  123021. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123022. _vq_quantthresh__16c0_s_p2_0,
  123023. _vq_quantmap__16c0_s_p2_0,
  123024. 5,
  123025. 5
  123026. };
  123027. static static_codebook _16c0_s_p2_0 = {
  123028. 4, 625,
  123029. _vq_lengthlist__16c0_s_p2_0,
  123030. 1, -533725184, 1611661312, 3, 0,
  123031. _vq_quantlist__16c0_s_p2_0,
  123032. NULL,
  123033. &_vq_auxt__16c0_s_p2_0,
  123034. NULL,
  123035. 0
  123036. };
  123037. static long _vq_quantlist__16c0_s_p3_0[] = {
  123038. 2,
  123039. 1,
  123040. 3,
  123041. 0,
  123042. 4,
  123043. };
  123044. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123045. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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,
  123085. };
  123086. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123087. -1.5, -0.5, 0.5, 1.5,
  123088. };
  123089. static long _vq_quantmap__16c0_s_p3_0[] = {
  123090. 3, 1, 0, 2, 4,
  123091. };
  123092. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123093. _vq_quantthresh__16c0_s_p3_0,
  123094. _vq_quantmap__16c0_s_p3_0,
  123095. 5,
  123096. 5
  123097. };
  123098. static static_codebook _16c0_s_p3_0 = {
  123099. 4, 625,
  123100. _vq_lengthlist__16c0_s_p3_0,
  123101. 1, -533725184, 1611661312, 3, 0,
  123102. _vq_quantlist__16c0_s_p3_0,
  123103. NULL,
  123104. &_vq_auxt__16c0_s_p3_0,
  123105. NULL,
  123106. 0
  123107. };
  123108. static long _vq_quantlist__16c0_s_p4_0[] = {
  123109. 4,
  123110. 3,
  123111. 5,
  123112. 2,
  123113. 6,
  123114. 1,
  123115. 7,
  123116. 0,
  123117. 8,
  123118. };
  123119. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123120. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123121. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123122. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123123. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123124. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0,
  123126. };
  123127. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123128. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123129. };
  123130. static long _vq_quantmap__16c0_s_p4_0[] = {
  123131. 7, 5, 3, 1, 0, 2, 4, 6,
  123132. 8,
  123133. };
  123134. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123135. _vq_quantthresh__16c0_s_p4_0,
  123136. _vq_quantmap__16c0_s_p4_0,
  123137. 9,
  123138. 9
  123139. };
  123140. static static_codebook _16c0_s_p4_0 = {
  123141. 2, 81,
  123142. _vq_lengthlist__16c0_s_p4_0,
  123143. 1, -531628032, 1611661312, 4, 0,
  123144. _vq_quantlist__16c0_s_p4_0,
  123145. NULL,
  123146. &_vq_auxt__16c0_s_p4_0,
  123147. NULL,
  123148. 0
  123149. };
  123150. static long _vq_quantlist__16c0_s_p5_0[] = {
  123151. 4,
  123152. 3,
  123153. 5,
  123154. 2,
  123155. 6,
  123156. 1,
  123157. 7,
  123158. 0,
  123159. 8,
  123160. };
  123161. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123162. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123163. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123164. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123165. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123166. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123167. 10,
  123168. };
  123169. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123170. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123171. };
  123172. static long _vq_quantmap__16c0_s_p5_0[] = {
  123173. 7, 5, 3, 1, 0, 2, 4, 6,
  123174. 8,
  123175. };
  123176. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123177. _vq_quantthresh__16c0_s_p5_0,
  123178. _vq_quantmap__16c0_s_p5_0,
  123179. 9,
  123180. 9
  123181. };
  123182. static static_codebook _16c0_s_p5_0 = {
  123183. 2, 81,
  123184. _vq_lengthlist__16c0_s_p5_0,
  123185. 1, -531628032, 1611661312, 4, 0,
  123186. _vq_quantlist__16c0_s_p5_0,
  123187. NULL,
  123188. &_vq_auxt__16c0_s_p5_0,
  123189. NULL,
  123190. 0
  123191. };
  123192. static long _vq_quantlist__16c0_s_p6_0[] = {
  123193. 8,
  123194. 7,
  123195. 9,
  123196. 6,
  123197. 10,
  123198. 5,
  123199. 11,
  123200. 4,
  123201. 12,
  123202. 3,
  123203. 13,
  123204. 2,
  123205. 14,
  123206. 1,
  123207. 15,
  123208. 0,
  123209. 16,
  123210. };
  123211. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123212. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123213. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123214. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123215. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123216. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123217. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123218. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123219. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123220. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123221. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123222. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123223. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123224. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123225. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123226. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123227. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123228. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123230. 14,
  123231. };
  123232. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123233. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123234. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123235. };
  123236. static long _vq_quantmap__16c0_s_p6_0[] = {
  123237. 15, 13, 11, 9, 7, 5, 3, 1,
  123238. 0, 2, 4, 6, 8, 10, 12, 14,
  123239. 16,
  123240. };
  123241. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123242. _vq_quantthresh__16c0_s_p6_0,
  123243. _vq_quantmap__16c0_s_p6_0,
  123244. 17,
  123245. 17
  123246. };
  123247. static static_codebook _16c0_s_p6_0 = {
  123248. 2, 289,
  123249. _vq_lengthlist__16c0_s_p6_0,
  123250. 1, -529530880, 1611661312, 5, 0,
  123251. _vq_quantlist__16c0_s_p6_0,
  123252. NULL,
  123253. &_vq_auxt__16c0_s_p6_0,
  123254. NULL,
  123255. 0
  123256. };
  123257. static long _vq_quantlist__16c0_s_p7_0[] = {
  123258. 1,
  123259. 0,
  123260. 2,
  123261. };
  123262. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123263. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123264. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123265. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123266. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123267. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123268. 13,
  123269. };
  123270. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123271. -5.5, 5.5,
  123272. };
  123273. static long _vq_quantmap__16c0_s_p7_0[] = {
  123274. 1, 0, 2,
  123275. };
  123276. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123277. _vq_quantthresh__16c0_s_p7_0,
  123278. _vq_quantmap__16c0_s_p7_0,
  123279. 3,
  123280. 3
  123281. };
  123282. static static_codebook _16c0_s_p7_0 = {
  123283. 4, 81,
  123284. _vq_lengthlist__16c0_s_p7_0,
  123285. 1, -529137664, 1618345984, 2, 0,
  123286. _vq_quantlist__16c0_s_p7_0,
  123287. NULL,
  123288. &_vq_auxt__16c0_s_p7_0,
  123289. NULL,
  123290. 0
  123291. };
  123292. static long _vq_quantlist__16c0_s_p7_1[] = {
  123293. 5,
  123294. 4,
  123295. 6,
  123296. 3,
  123297. 7,
  123298. 2,
  123299. 8,
  123300. 1,
  123301. 9,
  123302. 0,
  123303. 10,
  123304. };
  123305. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123306. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123307. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123308. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123309. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123310. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123311. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123312. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123313. 11,11,11, 9, 9, 9, 9,10,10,
  123314. };
  123315. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123316. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123317. 3.5, 4.5,
  123318. };
  123319. static long _vq_quantmap__16c0_s_p7_1[] = {
  123320. 9, 7, 5, 3, 1, 0, 2, 4,
  123321. 6, 8, 10,
  123322. };
  123323. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123324. _vq_quantthresh__16c0_s_p7_1,
  123325. _vq_quantmap__16c0_s_p7_1,
  123326. 11,
  123327. 11
  123328. };
  123329. static static_codebook _16c0_s_p7_1 = {
  123330. 2, 121,
  123331. _vq_lengthlist__16c0_s_p7_1,
  123332. 1, -531365888, 1611661312, 4, 0,
  123333. _vq_quantlist__16c0_s_p7_1,
  123334. NULL,
  123335. &_vq_auxt__16c0_s_p7_1,
  123336. NULL,
  123337. 0
  123338. };
  123339. static long _vq_quantlist__16c0_s_p8_0[] = {
  123340. 6,
  123341. 5,
  123342. 7,
  123343. 4,
  123344. 8,
  123345. 3,
  123346. 9,
  123347. 2,
  123348. 10,
  123349. 1,
  123350. 11,
  123351. 0,
  123352. 12,
  123353. };
  123354. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123355. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123356. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123357. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123358. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123359. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123360. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123361. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123362. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123363. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123364. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123365. 0,12,13,13,12,13,14,14,14,
  123366. };
  123367. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123368. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123369. 12.5, 17.5, 22.5, 27.5,
  123370. };
  123371. static long _vq_quantmap__16c0_s_p8_0[] = {
  123372. 11, 9, 7, 5, 3, 1, 0, 2,
  123373. 4, 6, 8, 10, 12,
  123374. };
  123375. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123376. _vq_quantthresh__16c0_s_p8_0,
  123377. _vq_quantmap__16c0_s_p8_0,
  123378. 13,
  123379. 13
  123380. };
  123381. static static_codebook _16c0_s_p8_0 = {
  123382. 2, 169,
  123383. _vq_lengthlist__16c0_s_p8_0,
  123384. 1, -526516224, 1616117760, 4, 0,
  123385. _vq_quantlist__16c0_s_p8_0,
  123386. NULL,
  123387. &_vq_auxt__16c0_s_p8_0,
  123388. NULL,
  123389. 0
  123390. };
  123391. static long _vq_quantlist__16c0_s_p8_1[] = {
  123392. 2,
  123393. 1,
  123394. 3,
  123395. 0,
  123396. 4,
  123397. };
  123398. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123399. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123400. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123401. };
  123402. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123403. -1.5, -0.5, 0.5, 1.5,
  123404. };
  123405. static long _vq_quantmap__16c0_s_p8_1[] = {
  123406. 3, 1, 0, 2, 4,
  123407. };
  123408. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123409. _vq_quantthresh__16c0_s_p8_1,
  123410. _vq_quantmap__16c0_s_p8_1,
  123411. 5,
  123412. 5
  123413. };
  123414. static static_codebook _16c0_s_p8_1 = {
  123415. 2, 25,
  123416. _vq_lengthlist__16c0_s_p8_1,
  123417. 1, -533725184, 1611661312, 3, 0,
  123418. _vq_quantlist__16c0_s_p8_1,
  123419. NULL,
  123420. &_vq_auxt__16c0_s_p8_1,
  123421. NULL,
  123422. 0
  123423. };
  123424. static long _vq_quantlist__16c0_s_p9_0[] = {
  123425. 1,
  123426. 0,
  123427. 2,
  123428. };
  123429. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123430. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123431. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123432. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123433. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123434. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123435. 7,
  123436. };
  123437. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123438. -157.5, 157.5,
  123439. };
  123440. static long _vq_quantmap__16c0_s_p9_0[] = {
  123441. 1, 0, 2,
  123442. };
  123443. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123444. _vq_quantthresh__16c0_s_p9_0,
  123445. _vq_quantmap__16c0_s_p9_0,
  123446. 3,
  123447. 3
  123448. };
  123449. static static_codebook _16c0_s_p9_0 = {
  123450. 4, 81,
  123451. _vq_lengthlist__16c0_s_p9_0,
  123452. 1, -518803456, 1628680192, 2, 0,
  123453. _vq_quantlist__16c0_s_p9_0,
  123454. NULL,
  123455. &_vq_auxt__16c0_s_p9_0,
  123456. NULL,
  123457. 0
  123458. };
  123459. static long _vq_quantlist__16c0_s_p9_1[] = {
  123460. 7,
  123461. 6,
  123462. 8,
  123463. 5,
  123464. 9,
  123465. 4,
  123466. 10,
  123467. 3,
  123468. 11,
  123469. 2,
  123470. 12,
  123471. 1,
  123472. 13,
  123473. 0,
  123474. 14,
  123475. };
  123476. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123477. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123478. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123479. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123480. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123481. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123482. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123483. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123484. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123485. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123486. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123487. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123488. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123489. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123490. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123491. 10,
  123492. };
  123493. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123494. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123495. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123496. };
  123497. static long _vq_quantmap__16c0_s_p9_1[] = {
  123498. 13, 11, 9, 7, 5, 3, 1, 0,
  123499. 2, 4, 6, 8, 10, 12, 14,
  123500. };
  123501. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123502. _vq_quantthresh__16c0_s_p9_1,
  123503. _vq_quantmap__16c0_s_p9_1,
  123504. 15,
  123505. 15
  123506. };
  123507. static static_codebook _16c0_s_p9_1 = {
  123508. 2, 225,
  123509. _vq_lengthlist__16c0_s_p9_1,
  123510. 1, -520986624, 1620377600, 4, 0,
  123511. _vq_quantlist__16c0_s_p9_1,
  123512. NULL,
  123513. &_vq_auxt__16c0_s_p9_1,
  123514. NULL,
  123515. 0
  123516. };
  123517. static long _vq_quantlist__16c0_s_p9_2[] = {
  123518. 10,
  123519. 9,
  123520. 11,
  123521. 8,
  123522. 12,
  123523. 7,
  123524. 13,
  123525. 6,
  123526. 14,
  123527. 5,
  123528. 15,
  123529. 4,
  123530. 16,
  123531. 3,
  123532. 17,
  123533. 2,
  123534. 18,
  123535. 1,
  123536. 19,
  123537. 0,
  123538. 20,
  123539. };
  123540. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123541. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123542. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123543. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123544. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123545. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123546. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123547. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123548. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123549. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123550. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123551. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123552. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123553. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123554. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123555. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123556. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123557. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123558. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123559. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123560. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123561. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123562. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123563. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123564. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123565. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123566. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123567. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123568. 10,11,10,10,11, 9,10,10,10,
  123569. };
  123570. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123571. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123572. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123573. 6.5, 7.5, 8.5, 9.5,
  123574. };
  123575. static long _vq_quantmap__16c0_s_p9_2[] = {
  123576. 19, 17, 15, 13, 11, 9, 7, 5,
  123577. 3, 1, 0, 2, 4, 6, 8, 10,
  123578. 12, 14, 16, 18, 20,
  123579. };
  123580. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123581. _vq_quantthresh__16c0_s_p9_2,
  123582. _vq_quantmap__16c0_s_p9_2,
  123583. 21,
  123584. 21
  123585. };
  123586. static static_codebook _16c0_s_p9_2 = {
  123587. 2, 441,
  123588. _vq_lengthlist__16c0_s_p9_2,
  123589. 1, -529268736, 1611661312, 5, 0,
  123590. _vq_quantlist__16c0_s_p9_2,
  123591. NULL,
  123592. &_vq_auxt__16c0_s_p9_2,
  123593. NULL,
  123594. 0
  123595. };
  123596. static long _huff_lengthlist__16c0_s_single[] = {
  123597. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123598. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123599. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123600. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123601. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123602. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123603. 16,16,18,18,
  123604. };
  123605. static static_codebook _huff_book__16c0_s_single = {
  123606. 2, 100,
  123607. _huff_lengthlist__16c0_s_single,
  123608. 0, 0, 0, 0, 0,
  123609. NULL,
  123610. NULL,
  123611. NULL,
  123612. NULL,
  123613. 0
  123614. };
  123615. static long _huff_lengthlist__16c1_s_long[] = {
  123616. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123617. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123618. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123619. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123620. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123621. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123622. 12,11,11,13,
  123623. };
  123624. static static_codebook _huff_book__16c1_s_long = {
  123625. 2, 100,
  123626. _huff_lengthlist__16c1_s_long,
  123627. 0, 0, 0, 0, 0,
  123628. NULL,
  123629. NULL,
  123630. NULL,
  123631. NULL,
  123632. 0
  123633. };
  123634. static long _vq_quantlist__16c1_s_p1_0[] = {
  123635. 1,
  123636. 0,
  123637. 2,
  123638. };
  123639. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123640. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123641. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123645. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123646. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123651. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123686. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123691. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123696. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123732. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123737. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123742. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0,
  124051. };
  124052. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124053. -0.5, 0.5,
  124054. };
  124055. static long _vq_quantmap__16c1_s_p1_0[] = {
  124056. 1, 0, 2,
  124057. };
  124058. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124059. _vq_quantthresh__16c1_s_p1_0,
  124060. _vq_quantmap__16c1_s_p1_0,
  124061. 3,
  124062. 3
  124063. };
  124064. static static_codebook _16c1_s_p1_0 = {
  124065. 8, 6561,
  124066. _vq_lengthlist__16c1_s_p1_0,
  124067. 1, -535822336, 1611661312, 2, 0,
  124068. _vq_quantlist__16c1_s_p1_0,
  124069. NULL,
  124070. &_vq_auxt__16c1_s_p1_0,
  124071. NULL,
  124072. 0
  124073. };
  124074. static long _vq_quantlist__16c1_s_p2_0[] = {
  124075. 2,
  124076. 1,
  124077. 3,
  124078. 0,
  124079. 4,
  124080. };
  124081. static long _vq_lengthlist__16c1_s_p2_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,
  124122. };
  124123. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124124. -1.5, -0.5, 0.5, 1.5,
  124125. };
  124126. static long _vq_quantmap__16c1_s_p2_0[] = {
  124127. 3, 1, 0, 2, 4,
  124128. };
  124129. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124130. _vq_quantthresh__16c1_s_p2_0,
  124131. _vq_quantmap__16c1_s_p2_0,
  124132. 5,
  124133. 5
  124134. };
  124135. static static_codebook _16c1_s_p2_0 = {
  124136. 4, 625,
  124137. _vq_lengthlist__16c1_s_p2_0,
  124138. 1, -533725184, 1611661312, 3, 0,
  124139. _vq_quantlist__16c1_s_p2_0,
  124140. NULL,
  124141. &_vq_auxt__16c1_s_p2_0,
  124142. NULL,
  124143. 0
  124144. };
  124145. static long _vq_quantlist__16c1_s_p3_0[] = {
  124146. 2,
  124147. 1,
  124148. 3,
  124149. 0,
  124150. 4,
  124151. };
  124152. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124153. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  124193. };
  124194. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124195. -1.5, -0.5, 0.5, 1.5,
  124196. };
  124197. static long _vq_quantmap__16c1_s_p3_0[] = {
  124198. 3, 1, 0, 2, 4,
  124199. };
  124200. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124201. _vq_quantthresh__16c1_s_p3_0,
  124202. _vq_quantmap__16c1_s_p3_0,
  124203. 5,
  124204. 5
  124205. };
  124206. static static_codebook _16c1_s_p3_0 = {
  124207. 4, 625,
  124208. _vq_lengthlist__16c1_s_p3_0,
  124209. 1, -533725184, 1611661312, 3, 0,
  124210. _vq_quantlist__16c1_s_p3_0,
  124211. NULL,
  124212. &_vq_auxt__16c1_s_p3_0,
  124213. NULL,
  124214. 0
  124215. };
  124216. static long _vq_quantlist__16c1_s_p4_0[] = {
  124217. 4,
  124218. 3,
  124219. 5,
  124220. 2,
  124221. 6,
  124222. 1,
  124223. 7,
  124224. 0,
  124225. 8,
  124226. };
  124227. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124228. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124229. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124230. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124231. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124232. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0,
  124234. };
  124235. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124236. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124237. };
  124238. static long _vq_quantmap__16c1_s_p4_0[] = {
  124239. 7, 5, 3, 1, 0, 2, 4, 6,
  124240. 8,
  124241. };
  124242. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124243. _vq_quantthresh__16c1_s_p4_0,
  124244. _vq_quantmap__16c1_s_p4_0,
  124245. 9,
  124246. 9
  124247. };
  124248. static static_codebook _16c1_s_p4_0 = {
  124249. 2, 81,
  124250. _vq_lengthlist__16c1_s_p4_0,
  124251. 1, -531628032, 1611661312, 4, 0,
  124252. _vq_quantlist__16c1_s_p4_0,
  124253. NULL,
  124254. &_vq_auxt__16c1_s_p4_0,
  124255. NULL,
  124256. 0
  124257. };
  124258. static long _vq_quantlist__16c1_s_p5_0[] = {
  124259. 4,
  124260. 3,
  124261. 5,
  124262. 2,
  124263. 6,
  124264. 1,
  124265. 7,
  124266. 0,
  124267. 8,
  124268. };
  124269. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124270. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124271. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124272. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124273. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124274. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124275. 10,
  124276. };
  124277. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124278. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124279. };
  124280. static long _vq_quantmap__16c1_s_p5_0[] = {
  124281. 7, 5, 3, 1, 0, 2, 4, 6,
  124282. 8,
  124283. };
  124284. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124285. _vq_quantthresh__16c1_s_p5_0,
  124286. _vq_quantmap__16c1_s_p5_0,
  124287. 9,
  124288. 9
  124289. };
  124290. static static_codebook _16c1_s_p5_0 = {
  124291. 2, 81,
  124292. _vq_lengthlist__16c1_s_p5_0,
  124293. 1, -531628032, 1611661312, 4, 0,
  124294. _vq_quantlist__16c1_s_p5_0,
  124295. NULL,
  124296. &_vq_auxt__16c1_s_p5_0,
  124297. NULL,
  124298. 0
  124299. };
  124300. static long _vq_quantlist__16c1_s_p6_0[] = {
  124301. 8,
  124302. 7,
  124303. 9,
  124304. 6,
  124305. 10,
  124306. 5,
  124307. 11,
  124308. 4,
  124309. 12,
  124310. 3,
  124311. 13,
  124312. 2,
  124313. 14,
  124314. 1,
  124315. 15,
  124316. 0,
  124317. 16,
  124318. };
  124319. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124320. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124321. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124322. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124323. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124324. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124325. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124326. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124327. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124328. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124329. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124330. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124331. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124332. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124333. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124334. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124335. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124336. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124338. 14,
  124339. };
  124340. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124341. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124342. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124343. };
  124344. static long _vq_quantmap__16c1_s_p6_0[] = {
  124345. 15, 13, 11, 9, 7, 5, 3, 1,
  124346. 0, 2, 4, 6, 8, 10, 12, 14,
  124347. 16,
  124348. };
  124349. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124350. _vq_quantthresh__16c1_s_p6_0,
  124351. _vq_quantmap__16c1_s_p6_0,
  124352. 17,
  124353. 17
  124354. };
  124355. static static_codebook _16c1_s_p6_0 = {
  124356. 2, 289,
  124357. _vq_lengthlist__16c1_s_p6_0,
  124358. 1, -529530880, 1611661312, 5, 0,
  124359. _vq_quantlist__16c1_s_p6_0,
  124360. NULL,
  124361. &_vq_auxt__16c1_s_p6_0,
  124362. NULL,
  124363. 0
  124364. };
  124365. static long _vq_quantlist__16c1_s_p7_0[] = {
  124366. 1,
  124367. 0,
  124368. 2,
  124369. };
  124370. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124371. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124372. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124373. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124374. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124375. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124376. 11,
  124377. };
  124378. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124379. -5.5, 5.5,
  124380. };
  124381. static long _vq_quantmap__16c1_s_p7_0[] = {
  124382. 1, 0, 2,
  124383. };
  124384. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124385. _vq_quantthresh__16c1_s_p7_0,
  124386. _vq_quantmap__16c1_s_p7_0,
  124387. 3,
  124388. 3
  124389. };
  124390. static static_codebook _16c1_s_p7_0 = {
  124391. 4, 81,
  124392. _vq_lengthlist__16c1_s_p7_0,
  124393. 1, -529137664, 1618345984, 2, 0,
  124394. _vq_quantlist__16c1_s_p7_0,
  124395. NULL,
  124396. &_vq_auxt__16c1_s_p7_0,
  124397. NULL,
  124398. 0
  124399. };
  124400. static long _vq_quantlist__16c1_s_p7_1[] = {
  124401. 5,
  124402. 4,
  124403. 6,
  124404. 3,
  124405. 7,
  124406. 2,
  124407. 8,
  124408. 1,
  124409. 9,
  124410. 0,
  124411. 10,
  124412. };
  124413. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124414. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124415. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124416. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124417. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124418. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124419. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124420. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124421. 10,10,10, 8, 8, 8, 8, 9, 9,
  124422. };
  124423. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124424. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124425. 3.5, 4.5,
  124426. };
  124427. static long _vq_quantmap__16c1_s_p7_1[] = {
  124428. 9, 7, 5, 3, 1, 0, 2, 4,
  124429. 6, 8, 10,
  124430. };
  124431. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124432. _vq_quantthresh__16c1_s_p7_1,
  124433. _vq_quantmap__16c1_s_p7_1,
  124434. 11,
  124435. 11
  124436. };
  124437. static static_codebook _16c1_s_p7_1 = {
  124438. 2, 121,
  124439. _vq_lengthlist__16c1_s_p7_1,
  124440. 1, -531365888, 1611661312, 4, 0,
  124441. _vq_quantlist__16c1_s_p7_1,
  124442. NULL,
  124443. &_vq_auxt__16c1_s_p7_1,
  124444. NULL,
  124445. 0
  124446. };
  124447. static long _vq_quantlist__16c1_s_p8_0[] = {
  124448. 6,
  124449. 5,
  124450. 7,
  124451. 4,
  124452. 8,
  124453. 3,
  124454. 9,
  124455. 2,
  124456. 10,
  124457. 1,
  124458. 11,
  124459. 0,
  124460. 12,
  124461. };
  124462. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124463. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124464. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124465. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124466. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124467. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124468. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124469. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124470. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124471. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124472. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124473. 0,12,12,12,12,13,13,14,15,
  124474. };
  124475. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124476. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124477. 12.5, 17.5, 22.5, 27.5,
  124478. };
  124479. static long _vq_quantmap__16c1_s_p8_0[] = {
  124480. 11, 9, 7, 5, 3, 1, 0, 2,
  124481. 4, 6, 8, 10, 12,
  124482. };
  124483. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124484. _vq_quantthresh__16c1_s_p8_0,
  124485. _vq_quantmap__16c1_s_p8_0,
  124486. 13,
  124487. 13
  124488. };
  124489. static static_codebook _16c1_s_p8_0 = {
  124490. 2, 169,
  124491. _vq_lengthlist__16c1_s_p8_0,
  124492. 1, -526516224, 1616117760, 4, 0,
  124493. _vq_quantlist__16c1_s_p8_0,
  124494. NULL,
  124495. &_vq_auxt__16c1_s_p8_0,
  124496. NULL,
  124497. 0
  124498. };
  124499. static long _vq_quantlist__16c1_s_p8_1[] = {
  124500. 2,
  124501. 1,
  124502. 3,
  124503. 0,
  124504. 4,
  124505. };
  124506. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124507. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124508. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124509. };
  124510. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124511. -1.5, -0.5, 0.5, 1.5,
  124512. };
  124513. static long _vq_quantmap__16c1_s_p8_1[] = {
  124514. 3, 1, 0, 2, 4,
  124515. };
  124516. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124517. _vq_quantthresh__16c1_s_p8_1,
  124518. _vq_quantmap__16c1_s_p8_1,
  124519. 5,
  124520. 5
  124521. };
  124522. static static_codebook _16c1_s_p8_1 = {
  124523. 2, 25,
  124524. _vq_lengthlist__16c1_s_p8_1,
  124525. 1, -533725184, 1611661312, 3, 0,
  124526. _vq_quantlist__16c1_s_p8_1,
  124527. NULL,
  124528. &_vq_auxt__16c1_s_p8_1,
  124529. NULL,
  124530. 0
  124531. };
  124532. static long _vq_quantlist__16c1_s_p9_0[] = {
  124533. 6,
  124534. 5,
  124535. 7,
  124536. 4,
  124537. 8,
  124538. 3,
  124539. 9,
  124540. 2,
  124541. 10,
  124542. 1,
  124543. 11,
  124544. 0,
  124545. 12,
  124546. };
  124547. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124548. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124549. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124550. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124551. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124552. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124553. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124554. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124555. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124556. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124557. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124558. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124559. };
  124560. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124561. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124562. 787.5, 1102.5, 1417.5, 1732.5,
  124563. };
  124564. static long _vq_quantmap__16c1_s_p9_0[] = {
  124565. 11, 9, 7, 5, 3, 1, 0, 2,
  124566. 4, 6, 8, 10, 12,
  124567. };
  124568. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124569. _vq_quantthresh__16c1_s_p9_0,
  124570. _vq_quantmap__16c1_s_p9_0,
  124571. 13,
  124572. 13
  124573. };
  124574. static static_codebook _16c1_s_p9_0 = {
  124575. 2, 169,
  124576. _vq_lengthlist__16c1_s_p9_0,
  124577. 1, -513964032, 1628680192, 4, 0,
  124578. _vq_quantlist__16c1_s_p9_0,
  124579. NULL,
  124580. &_vq_auxt__16c1_s_p9_0,
  124581. NULL,
  124582. 0
  124583. };
  124584. static long _vq_quantlist__16c1_s_p9_1[] = {
  124585. 7,
  124586. 6,
  124587. 8,
  124588. 5,
  124589. 9,
  124590. 4,
  124591. 10,
  124592. 3,
  124593. 11,
  124594. 2,
  124595. 12,
  124596. 1,
  124597. 13,
  124598. 0,
  124599. 14,
  124600. };
  124601. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124602. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124603. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124604. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124605. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124606. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124607. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124608. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124609. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124610. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124611. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124612. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124613. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124614. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124615. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124616. 13,
  124617. };
  124618. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124619. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124620. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124621. };
  124622. static long _vq_quantmap__16c1_s_p9_1[] = {
  124623. 13, 11, 9, 7, 5, 3, 1, 0,
  124624. 2, 4, 6, 8, 10, 12, 14,
  124625. };
  124626. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124627. _vq_quantthresh__16c1_s_p9_1,
  124628. _vq_quantmap__16c1_s_p9_1,
  124629. 15,
  124630. 15
  124631. };
  124632. static static_codebook _16c1_s_p9_1 = {
  124633. 2, 225,
  124634. _vq_lengthlist__16c1_s_p9_1,
  124635. 1, -520986624, 1620377600, 4, 0,
  124636. _vq_quantlist__16c1_s_p9_1,
  124637. NULL,
  124638. &_vq_auxt__16c1_s_p9_1,
  124639. NULL,
  124640. 0
  124641. };
  124642. static long _vq_quantlist__16c1_s_p9_2[] = {
  124643. 10,
  124644. 9,
  124645. 11,
  124646. 8,
  124647. 12,
  124648. 7,
  124649. 13,
  124650. 6,
  124651. 14,
  124652. 5,
  124653. 15,
  124654. 4,
  124655. 16,
  124656. 3,
  124657. 17,
  124658. 2,
  124659. 18,
  124660. 1,
  124661. 19,
  124662. 0,
  124663. 20,
  124664. };
  124665. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124666. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124667. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124668. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124669. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124670. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124671. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124672. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124673. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124674. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124675. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124676. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124677. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124678. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124679. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124680. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124681. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124682. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124683. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124684. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124685. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124686. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124687. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124688. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124689. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124690. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124691. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124692. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124693. 11,11,11,11,12,11,11,12,11,
  124694. };
  124695. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124696. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124697. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124698. 6.5, 7.5, 8.5, 9.5,
  124699. };
  124700. static long _vq_quantmap__16c1_s_p9_2[] = {
  124701. 19, 17, 15, 13, 11, 9, 7, 5,
  124702. 3, 1, 0, 2, 4, 6, 8, 10,
  124703. 12, 14, 16, 18, 20,
  124704. };
  124705. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124706. _vq_quantthresh__16c1_s_p9_2,
  124707. _vq_quantmap__16c1_s_p9_2,
  124708. 21,
  124709. 21
  124710. };
  124711. static static_codebook _16c1_s_p9_2 = {
  124712. 2, 441,
  124713. _vq_lengthlist__16c1_s_p9_2,
  124714. 1, -529268736, 1611661312, 5, 0,
  124715. _vq_quantlist__16c1_s_p9_2,
  124716. NULL,
  124717. &_vq_auxt__16c1_s_p9_2,
  124718. NULL,
  124719. 0
  124720. };
  124721. static long _huff_lengthlist__16c1_s_short[] = {
  124722. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124723. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124724. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124725. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124726. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124727. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124728. 9, 9,10,13,
  124729. };
  124730. static static_codebook _huff_book__16c1_s_short = {
  124731. 2, 100,
  124732. _huff_lengthlist__16c1_s_short,
  124733. 0, 0, 0, 0, 0,
  124734. NULL,
  124735. NULL,
  124736. NULL,
  124737. NULL,
  124738. 0
  124739. };
  124740. static long _huff_lengthlist__16c2_s_long[] = {
  124741. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124742. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124743. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124744. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124745. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124746. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124747. 14,14,16,18,
  124748. };
  124749. static static_codebook _huff_book__16c2_s_long = {
  124750. 2, 100,
  124751. _huff_lengthlist__16c2_s_long,
  124752. 0, 0, 0, 0, 0,
  124753. NULL,
  124754. NULL,
  124755. NULL,
  124756. NULL,
  124757. 0
  124758. };
  124759. static long _vq_quantlist__16c2_s_p1_0[] = {
  124760. 1,
  124761. 0,
  124762. 2,
  124763. };
  124764. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124765. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124766. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124770. 0,
  124771. };
  124772. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124773. -0.5, 0.5,
  124774. };
  124775. static long _vq_quantmap__16c2_s_p1_0[] = {
  124776. 1, 0, 2,
  124777. };
  124778. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124779. _vq_quantthresh__16c2_s_p1_0,
  124780. _vq_quantmap__16c2_s_p1_0,
  124781. 3,
  124782. 3
  124783. };
  124784. static static_codebook _16c2_s_p1_0 = {
  124785. 4, 81,
  124786. _vq_lengthlist__16c2_s_p1_0,
  124787. 1, -535822336, 1611661312, 2, 0,
  124788. _vq_quantlist__16c2_s_p1_0,
  124789. NULL,
  124790. &_vq_auxt__16c2_s_p1_0,
  124791. NULL,
  124792. 0
  124793. };
  124794. static long _vq_quantlist__16c2_s_p2_0[] = {
  124795. 2,
  124796. 1,
  124797. 3,
  124798. 0,
  124799. 4,
  124800. };
  124801. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124802. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124803. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124804. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124805. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124806. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124807. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124808. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124809. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124815. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124816. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124817. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124822. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124823. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124824. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124825. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124830. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124831. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124832. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124833. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124838. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124839. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124840. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124841. 13,
  124842. };
  124843. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124844. -1.5, -0.5, 0.5, 1.5,
  124845. };
  124846. static long _vq_quantmap__16c2_s_p2_0[] = {
  124847. 3, 1, 0, 2, 4,
  124848. };
  124849. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124850. _vq_quantthresh__16c2_s_p2_0,
  124851. _vq_quantmap__16c2_s_p2_0,
  124852. 5,
  124853. 5
  124854. };
  124855. static static_codebook _16c2_s_p2_0 = {
  124856. 4, 625,
  124857. _vq_lengthlist__16c2_s_p2_0,
  124858. 1, -533725184, 1611661312, 3, 0,
  124859. _vq_quantlist__16c2_s_p2_0,
  124860. NULL,
  124861. &_vq_auxt__16c2_s_p2_0,
  124862. NULL,
  124863. 0
  124864. };
  124865. static long _vq_quantlist__16c2_s_p3_0[] = {
  124866. 4,
  124867. 3,
  124868. 5,
  124869. 2,
  124870. 6,
  124871. 1,
  124872. 7,
  124873. 0,
  124874. 8,
  124875. };
  124876. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124877. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124878. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124879. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124880. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0,
  124883. };
  124884. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124885. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124886. };
  124887. static long _vq_quantmap__16c2_s_p3_0[] = {
  124888. 7, 5, 3, 1, 0, 2, 4, 6,
  124889. 8,
  124890. };
  124891. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124892. _vq_quantthresh__16c2_s_p3_0,
  124893. _vq_quantmap__16c2_s_p3_0,
  124894. 9,
  124895. 9
  124896. };
  124897. static static_codebook _16c2_s_p3_0 = {
  124898. 2, 81,
  124899. _vq_lengthlist__16c2_s_p3_0,
  124900. 1, -531628032, 1611661312, 4, 0,
  124901. _vq_quantlist__16c2_s_p3_0,
  124902. NULL,
  124903. &_vq_auxt__16c2_s_p3_0,
  124904. NULL,
  124905. 0
  124906. };
  124907. static long _vq_quantlist__16c2_s_p4_0[] = {
  124908. 8,
  124909. 7,
  124910. 9,
  124911. 6,
  124912. 10,
  124913. 5,
  124914. 11,
  124915. 4,
  124916. 12,
  124917. 3,
  124918. 13,
  124919. 2,
  124920. 14,
  124921. 1,
  124922. 15,
  124923. 0,
  124924. 16,
  124925. };
  124926. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124927. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124928. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124929. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124930. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124931. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124932. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124933. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124934. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124935. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124936. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0,
  124946. };
  124947. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124948. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124949. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124950. };
  124951. static long _vq_quantmap__16c2_s_p4_0[] = {
  124952. 15, 13, 11, 9, 7, 5, 3, 1,
  124953. 0, 2, 4, 6, 8, 10, 12, 14,
  124954. 16,
  124955. };
  124956. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124957. _vq_quantthresh__16c2_s_p4_0,
  124958. _vq_quantmap__16c2_s_p4_0,
  124959. 17,
  124960. 17
  124961. };
  124962. static static_codebook _16c2_s_p4_0 = {
  124963. 2, 289,
  124964. _vq_lengthlist__16c2_s_p4_0,
  124965. 1, -529530880, 1611661312, 5, 0,
  124966. _vq_quantlist__16c2_s_p4_0,
  124967. NULL,
  124968. &_vq_auxt__16c2_s_p4_0,
  124969. NULL,
  124970. 0
  124971. };
  124972. static long _vq_quantlist__16c2_s_p5_0[] = {
  124973. 1,
  124974. 0,
  124975. 2,
  124976. };
  124977. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124978. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124979. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124980. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124981. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124982. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124983. 12,
  124984. };
  124985. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124986. -5.5, 5.5,
  124987. };
  124988. static long _vq_quantmap__16c2_s_p5_0[] = {
  124989. 1, 0, 2,
  124990. };
  124991. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124992. _vq_quantthresh__16c2_s_p5_0,
  124993. _vq_quantmap__16c2_s_p5_0,
  124994. 3,
  124995. 3
  124996. };
  124997. static static_codebook _16c2_s_p5_0 = {
  124998. 4, 81,
  124999. _vq_lengthlist__16c2_s_p5_0,
  125000. 1, -529137664, 1618345984, 2, 0,
  125001. _vq_quantlist__16c2_s_p5_0,
  125002. NULL,
  125003. &_vq_auxt__16c2_s_p5_0,
  125004. NULL,
  125005. 0
  125006. };
  125007. static long _vq_quantlist__16c2_s_p5_1[] = {
  125008. 5,
  125009. 4,
  125010. 6,
  125011. 3,
  125012. 7,
  125013. 2,
  125014. 8,
  125015. 1,
  125016. 9,
  125017. 0,
  125018. 10,
  125019. };
  125020. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125021. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125022. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125023. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125024. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125025. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125026. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125027. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125028. 11,11,11, 7, 7, 8, 8, 8, 8,
  125029. };
  125030. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125031. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125032. 3.5, 4.5,
  125033. };
  125034. static long _vq_quantmap__16c2_s_p5_1[] = {
  125035. 9, 7, 5, 3, 1, 0, 2, 4,
  125036. 6, 8, 10,
  125037. };
  125038. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125039. _vq_quantthresh__16c2_s_p5_1,
  125040. _vq_quantmap__16c2_s_p5_1,
  125041. 11,
  125042. 11
  125043. };
  125044. static static_codebook _16c2_s_p5_1 = {
  125045. 2, 121,
  125046. _vq_lengthlist__16c2_s_p5_1,
  125047. 1, -531365888, 1611661312, 4, 0,
  125048. _vq_quantlist__16c2_s_p5_1,
  125049. NULL,
  125050. &_vq_auxt__16c2_s_p5_1,
  125051. NULL,
  125052. 0
  125053. };
  125054. static long _vq_quantlist__16c2_s_p6_0[] = {
  125055. 6,
  125056. 5,
  125057. 7,
  125058. 4,
  125059. 8,
  125060. 3,
  125061. 9,
  125062. 2,
  125063. 10,
  125064. 1,
  125065. 11,
  125066. 0,
  125067. 12,
  125068. };
  125069. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125070. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125071. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125072. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125073. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125074. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125075. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. };
  125082. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125083. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125084. 12.5, 17.5, 22.5, 27.5,
  125085. };
  125086. static long _vq_quantmap__16c2_s_p6_0[] = {
  125087. 11, 9, 7, 5, 3, 1, 0, 2,
  125088. 4, 6, 8, 10, 12,
  125089. };
  125090. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125091. _vq_quantthresh__16c2_s_p6_0,
  125092. _vq_quantmap__16c2_s_p6_0,
  125093. 13,
  125094. 13
  125095. };
  125096. static static_codebook _16c2_s_p6_0 = {
  125097. 2, 169,
  125098. _vq_lengthlist__16c2_s_p6_0,
  125099. 1, -526516224, 1616117760, 4, 0,
  125100. _vq_quantlist__16c2_s_p6_0,
  125101. NULL,
  125102. &_vq_auxt__16c2_s_p6_0,
  125103. NULL,
  125104. 0
  125105. };
  125106. static long _vq_quantlist__16c2_s_p6_1[] = {
  125107. 2,
  125108. 1,
  125109. 3,
  125110. 0,
  125111. 4,
  125112. };
  125113. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125114. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125115. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125116. };
  125117. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125118. -1.5, -0.5, 0.5, 1.5,
  125119. };
  125120. static long _vq_quantmap__16c2_s_p6_1[] = {
  125121. 3, 1, 0, 2, 4,
  125122. };
  125123. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125124. _vq_quantthresh__16c2_s_p6_1,
  125125. _vq_quantmap__16c2_s_p6_1,
  125126. 5,
  125127. 5
  125128. };
  125129. static static_codebook _16c2_s_p6_1 = {
  125130. 2, 25,
  125131. _vq_lengthlist__16c2_s_p6_1,
  125132. 1, -533725184, 1611661312, 3, 0,
  125133. _vq_quantlist__16c2_s_p6_1,
  125134. NULL,
  125135. &_vq_auxt__16c2_s_p6_1,
  125136. NULL,
  125137. 0
  125138. };
  125139. static long _vq_quantlist__16c2_s_p7_0[] = {
  125140. 6,
  125141. 5,
  125142. 7,
  125143. 4,
  125144. 8,
  125145. 3,
  125146. 9,
  125147. 2,
  125148. 10,
  125149. 1,
  125150. 11,
  125151. 0,
  125152. 12,
  125153. };
  125154. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125155. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125156. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125157. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125158. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125159. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125160. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125161. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125162. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125163. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125164. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125165. 18,13,14,13,13,14,13,15,14,
  125166. };
  125167. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125168. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125169. 27.5, 38.5, 49.5, 60.5,
  125170. };
  125171. static long _vq_quantmap__16c2_s_p7_0[] = {
  125172. 11, 9, 7, 5, 3, 1, 0, 2,
  125173. 4, 6, 8, 10, 12,
  125174. };
  125175. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125176. _vq_quantthresh__16c2_s_p7_0,
  125177. _vq_quantmap__16c2_s_p7_0,
  125178. 13,
  125179. 13
  125180. };
  125181. static static_codebook _16c2_s_p7_0 = {
  125182. 2, 169,
  125183. _vq_lengthlist__16c2_s_p7_0,
  125184. 1, -523206656, 1618345984, 4, 0,
  125185. _vq_quantlist__16c2_s_p7_0,
  125186. NULL,
  125187. &_vq_auxt__16c2_s_p7_0,
  125188. NULL,
  125189. 0
  125190. };
  125191. static long _vq_quantlist__16c2_s_p7_1[] = {
  125192. 5,
  125193. 4,
  125194. 6,
  125195. 3,
  125196. 7,
  125197. 2,
  125198. 8,
  125199. 1,
  125200. 9,
  125201. 0,
  125202. 10,
  125203. };
  125204. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125205. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125206. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125207. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125208. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125209. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125210. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125211. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125212. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125213. };
  125214. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125215. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125216. 3.5, 4.5,
  125217. };
  125218. static long _vq_quantmap__16c2_s_p7_1[] = {
  125219. 9, 7, 5, 3, 1, 0, 2, 4,
  125220. 6, 8, 10,
  125221. };
  125222. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125223. _vq_quantthresh__16c2_s_p7_1,
  125224. _vq_quantmap__16c2_s_p7_1,
  125225. 11,
  125226. 11
  125227. };
  125228. static static_codebook _16c2_s_p7_1 = {
  125229. 2, 121,
  125230. _vq_lengthlist__16c2_s_p7_1,
  125231. 1, -531365888, 1611661312, 4, 0,
  125232. _vq_quantlist__16c2_s_p7_1,
  125233. NULL,
  125234. &_vq_auxt__16c2_s_p7_1,
  125235. NULL,
  125236. 0
  125237. };
  125238. static long _vq_quantlist__16c2_s_p8_0[] = {
  125239. 7,
  125240. 6,
  125241. 8,
  125242. 5,
  125243. 9,
  125244. 4,
  125245. 10,
  125246. 3,
  125247. 11,
  125248. 2,
  125249. 12,
  125250. 1,
  125251. 13,
  125252. 0,
  125253. 14,
  125254. };
  125255. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125256. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125257. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125258. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125259. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125260. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125261. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125262. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125263. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125264. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125265. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125266. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125267. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125268. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125269. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125270. 13,
  125271. };
  125272. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125273. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125274. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125275. };
  125276. static long _vq_quantmap__16c2_s_p8_0[] = {
  125277. 13, 11, 9, 7, 5, 3, 1, 0,
  125278. 2, 4, 6, 8, 10, 12, 14,
  125279. };
  125280. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125281. _vq_quantthresh__16c2_s_p8_0,
  125282. _vq_quantmap__16c2_s_p8_0,
  125283. 15,
  125284. 15
  125285. };
  125286. static static_codebook _16c2_s_p8_0 = {
  125287. 2, 225,
  125288. _vq_lengthlist__16c2_s_p8_0,
  125289. 1, -520986624, 1620377600, 4, 0,
  125290. _vq_quantlist__16c2_s_p8_0,
  125291. NULL,
  125292. &_vq_auxt__16c2_s_p8_0,
  125293. NULL,
  125294. 0
  125295. };
  125296. static long _vq_quantlist__16c2_s_p8_1[] = {
  125297. 10,
  125298. 9,
  125299. 11,
  125300. 8,
  125301. 12,
  125302. 7,
  125303. 13,
  125304. 6,
  125305. 14,
  125306. 5,
  125307. 15,
  125308. 4,
  125309. 16,
  125310. 3,
  125311. 17,
  125312. 2,
  125313. 18,
  125314. 1,
  125315. 19,
  125316. 0,
  125317. 20,
  125318. };
  125319. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125320. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125321. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125322. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125323. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125324. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125325. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125326. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125327. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125328. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125329. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125330. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125331. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125332. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125333. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125334. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125335. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125336. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125337. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125338. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125339. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125340. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125341. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125342. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125343. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125344. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125345. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125346. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125347. 10,11,10,10,10,10,10,10,10,
  125348. };
  125349. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125350. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125351. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125352. 6.5, 7.5, 8.5, 9.5,
  125353. };
  125354. static long _vq_quantmap__16c2_s_p8_1[] = {
  125355. 19, 17, 15, 13, 11, 9, 7, 5,
  125356. 3, 1, 0, 2, 4, 6, 8, 10,
  125357. 12, 14, 16, 18, 20,
  125358. };
  125359. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125360. _vq_quantthresh__16c2_s_p8_1,
  125361. _vq_quantmap__16c2_s_p8_1,
  125362. 21,
  125363. 21
  125364. };
  125365. static static_codebook _16c2_s_p8_1 = {
  125366. 2, 441,
  125367. _vq_lengthlist__16c2_s_p8_1,
  125368. 1, -529268736, 1611661312, 5, 0,
  125369. _vq_quantlist__16c2_s_p8_1,
  125370. NULL,
  125371. &_vq_auxt__16c2_s_p8_1,
  125372. NULL,
  125373. 0
  125374. };
  125375. static long _vq_quantlist__16c2_s_p9_0[] = {
  125376. 6,
  125377. 5,
  125378. 7,
  125379. 4,
  125380. 8,
  125381. 3,
  125382. 9,
  125383. 2,
  125384. 10,
  125385. 1,
  125386. 11,
  125387. 0,
  125388. 12,
  125389. };
  125390. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125391. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125392. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125393. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125394. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125395. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125396. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125397. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125398. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125399. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125400. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125401. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125402. };
  125403. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125404. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125405. 2327.5, 3258.5, 4189.5, 5120.5,
  125406. };
  125407. static long _vq_quantmap__16c2_s_p9_0[] = {
  125408. 11, 9, 7, 5, 3, 1, 0, 2,
  125409. 4, 6, 8, 10, 12,
  125410. };
  125411. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125412. _vq_quantthresh__16c2_s_p9_0,
  125413. _vq_quantmap__16c2_s_p9_0,
  125414. 13,
  125415. 13
  125416. };
  125417. static static_codebook _16c2_s_p9_0 = {
  125418. 2, 169,
  125419. _vq_lengthlist__16c2_s_p9_0,
  125420. 1, -510275072, 1631393792, 4, 0,
  125421. _vq_quantlist__16c2_s_p9_0,
  125422. NULL,
  125423. &_vq_auxt__16c2_s_p9_0,
  125424. NULL,
  125425. 0
  125426. };
  125427. static long _vq_quantlist__16c2_s_p9_1[] = {
  125428. 8,
  125429. 7,
  125430. 9,
  125431. 6,
  125432. 10,
  125433. 5,
  125434. 11,
  125435. 4,
  125436. 12,
  125437. 3,
  125438. 13,
  125439. 2,
  125440. 14,
  125441. 1,
  125442. 15,
  125443. 0,
  125444. 16,
  125445. };
  125446. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125447. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125448. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125449. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125450. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125451. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125452. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125453. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125454. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125455. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125456. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125457. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125458. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125459. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125460. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125461. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125462. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125463. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125464. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125465. 10,
  125466. };
  125467. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125468. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125469. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125470. };
  125471. static long _vq_quantmap__16c2_s_p9_1[] = {
  125472. 15, 13, 11, 9, 7, 5, 3, 1,
  125473. 0, 2, 4, 6, 8, 10, 12, 14,
  125474. 16,
  125475. };
  125476. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125477. _vq_quantthresh__16c2_s_p9_1,
  125478. _vq_quantmap__16c2_s_p9_1,
  125479. 17,
  125480. 17
  125481. };
  125482. static static_codebook _16c2_s_p9_1 = {
  125483. 2, 289,
  125484. _vq_lengthlist__16c2_s_p9_1,
  125485. 1, -518488064, 1622704128, 5, 0,
  125486. _vq_quantlist__16c2_s_p9_1,
  125487. NULL,
  125488. &_vq_auxt__16c2_s_p9_1,
  125489. NULL,
  125490. 0
  125491. };
  125492. static long _vq_quantlist__16c2_s_p9_2[] = {
  125493. 13,
  125494. 12,
  125495. 14,
  125496. 11,
  125497. 15,
  125498. 10,
  125499. 16,
  125500. 9,
  125501. 17,
  125502. 8,
  125503. 18,
  125504. 7,
  125505. 19,
  125506. 6,
  125507. 20,
  125508. 5,
  125509. 21,
  125510. 4,
  125511. 22,
  125512. 3,
  125513. 23,
  125514. 2,
  125515. 24,
  125516. 1,
  125517. 25,
  125518. 0,
  125519. 26,
  125520. };
  125521. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125522. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125523. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125524. };
  125525. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125526. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125527. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125528. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125529. 11.5, 12.5,
  125530. };
  125531. static long _vq_quantmap__16c2_s_p9_2[] = {
  125532. 25, 23, 21, 19, 17, 15, 13, 11,
  125533. 9, 7, 5, 3, 1, 0, 2, 4,
  125534. 6, 8, 10, 12, 14, 16, 18, 20,
  125535. 22, 24, 26,
  125536. };
  125537. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125538. _vq_quantthresh__16c2_s_p9_2,
  125539. _vq_quantmap__16c2_s_p9_2,
  125540. 27,
  125541. 27
  125542. };
  125543. static static_codebook _16c2_s_p9_2 = {
  125544. 1, 27,
  125545. _vq_lengthlist__16c2_s_p9_2,
  125546. 1, -528875520, 1611661312, 5, 0,
  125547. _vq_quantlist__16c2_s_p9_2,
  125548. NULL,
  125549. &_vq_auxt__16c2_s_p9_2,
  125550. NULL,
  125551. 0
  125552. };
  125553. static long _huff_lengthlist__16c2_s_short[] = {
  125554. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125555. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125556. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125557. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125558. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125559. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125560. 15,12,14,14,
  125561. };
  125562. static static_codebook _huff_book__16c2_s_short = {
  125563. 2, 100,
  125564. _huff_lengthlist__16c2_s_short,
  125565. 0, 0, 0, 0, 0,
  125566. NULL,
  125567. NULL,
  125568. NULL,
  125569. NULL,
  125570. 0
  125571. };
  125572. static long _vq_quantlist__8c0_s_p1_0[] = {
  125573. 1,
  125574. 0,
  125575. 2,
  125576. };
  125577. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125578. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125579. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125583. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125584. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125588. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125589. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125624. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125629. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125634. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125670. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125675. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125680. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 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,
  125989. };
  125990. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125991. -0.5, 0.5,
  125992. };
  125993. static long _vq_quantmap__8c0_s_p1_0[] = {
  125994. 1, 0, 2,
  125995. };
  125996. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125997. _vq_quantthresh__8c0_s_p1_0,
  125998. _vq_quantmap__8c0_s_p1_0,
  125999. 3,
  126000. 3
  126001. };
  126002. static static_codebook _8c0_s_p1_0 = {
  126003. 8, 6561,
  126004. _vq_lengthlist__8c0_s_p1_0,
  126005. 1, -535822336, 1611661312, 2, 0,
  126006. _vq_quantlist__8c0_s_p1_0,
  126007. NULL,
  126008. &_vq_auxt__8c0_s_p1_0,
  126009. NULL,
  126010. 0
  126011. };
  126012. static long _vq_quantlist__8c0_s_p2_0[] = {
  126013. 2,
  126014. 1,
  126015. 3,
  126016. 0,
  126017. 4,
  126018. };
  126019. static long _vq_lengthlist__8c0_s_p2_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,
  126060. };
  126061. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126062. -1.5, -0.5, 0.5, 1.5,
  126063. };
  126064. static long _vq_quantmap__8c0_s_p2_0[] = {
  126065. 3, 1, 0, 2, 4,
  126066. };
  126067. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126068. _vq_quantthresh__8c0_s_p2_0,
  126069. _vq_quantmap__8c0_s_p2_0,
  126070. 5,
  126071. 5
  126072. };
  126073. static static_codebook _8c0_s_p2_0 = {
  126074. 4, 625,
  126075. _vq_lengthlist__8c0_s_p2_0,
  126076. 1, -533725184, 1611661312, 3, 0,
  126077. _vq_quantlist__8c0_s_p2_0,
  126078. NULL,
  126079. &_vq_auxt__8c0_s_p2_0,
  126080. NULL,
  126081. 0
  126082. };
  126083. static long _vq_quantlist__8c0_s_p3_0[] = {
  126084. 2,
  126085. 1,
  126086. 3,
  126087. 0,
  126088. 4,
  126089. };
  126090. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126091. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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,
  126131. };
  126132. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126133. -1.5, -0.5, 0.5, 1.5,
  126134. };
  126135. static long _vq_quantmap__8c0_s_p3_0[] = {
  126136. 3, 1, 0, 2, 4,
  126137. };
  126138. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126139. _vq_quantthresh__8c0_s_p3_0,
  126140. _vq_quantmap__8c0_s_p3_0,
  126141. 5,
  126142. 5
  126143. };
  126144. static static_codebook _8c0_s_p3_0 = {
  126145. 4, 625,
  126146. _vq_lengthlist__8c0_s_p3_0,
  126147. 1, -533725184, 1611661312, 3, 0,
  126148. _vq_quantlist__8c0_s_p3_0,
  126149. NULL,
  126150. &_vq_auxt__8c0_s_p3_0,
  126151. NULL,
  126152. 0
  126153. };
  126154. static long _vq_quantlist__8c0_s_p4_0[] = {
  126155. 4,
  126156. 3,
  126157. 5,
  126158. 2,
  126159. 6,
  126160. 1,
  126161. 7,
  126162. 0,
  126163. 8,
  126164. };
  126165. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126166. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126167. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126168. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126169. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126170. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0,
  126172. };
  126173. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126174. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126175. };
  126176. static long _vq_quantmap__8c0_s_p4_0[] = {
  126177. 7, 5, 3, 1, 0, 2, 4, 6,
  126178. 8,
  126179. };
  126180. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126181. _vq_quantthresh__8c0_s_p4_0,
  126182. _vq_quantmap__8c0_s_p4_0,
  126183. 9,
  126184. 9
  126185. };
  126186. static static_codebook _8c0_s_p4_0 = {
  126187. 2, 81,
  126188. _vq_lengthlist__8c0_s_p4_0,
  126189. 1, -531628032, 1611661312, 4, 0,
  126190. _vq_quantlist__8c0_s_p4_0,
  126191. NULL,
  126192. &_vq_auxt__8c0_s_p4_0,
  126193. NULL,
  126194. 0
  126195. };
  126196. static long _vq_quantlist__8c0_s_p5_0[] = {
  126197. 4,
  126198. 3,
  126199. 5,
  126200. 2,
  126201. 6,
  126202. 1,
  126203. 7,
  126204. 0,
  126205. 8,
  126206. };
  126207. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126208. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126209. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126210. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126211. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126212. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126213. 10,
  126214. };
  126215. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126216. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126217. };
  126218. static long _vq_quantmap__8c0_s_p5_0[] = {
  126219. 7, 5, 3, 1, 0, 2, 4, 6,
  126220. 8,
  126221. };
  126222. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126223. _vq_quantthresh__8c0_s_p5_0,
  126224. _vq_quantmap__8c0_s_p5_0,
  126225. 9,
  126226. 9
  126227. };
  126228. static static_codebook _8c0_s_p5_0 = {
  126229. 2, 81,
  126230. _vq_lengthlist__8c0_s_p5_0,
  126231. 1, -531628032, 1611661312, 4, 0,
  126232. _vq_quantlist__8c0_s_p5_0,
  126233. NULL,
  126234. &_vq_auxt__8c0_s_p5_0,
  126235. NULL,
  126236. 0
  126237. };
  126238. static long _vq_quantlist__8c0_s_p6_0[] = {
  126239. 8,
  126240. 7,
  126241. 9,
  126242. 6,
  126243. 10,
  126244. 5,
  126245. 11,
  126246. 4,
  126247. 12,
  126248. 3,
  126249. 13,
  126250. 2,
  126251. 14,
  126252. 1,
  126253. 15,
  126254. 0,
  126255. 16,
  126256. };
  126257. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126258. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126259. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126260. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126261. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126262. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126263. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126264. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126265. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126266. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126267. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126268. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126269. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126270. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126271. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126272. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126273. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126274. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126276. 14,
  126277. };
  126278. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126279. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126280. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126281. };
  126282. static long _vq_quantmap__8c0_s_p6_0[] = {
  126283. 15, 13, 11, 9, 7, 5, 3, 1,
  126284. 0, 2, 4, 6, 8, 10, 12, 14,
  126285. 16,
  126286. };
  126287. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126288. _vq_quantthresh__8c0_s_p6_0,
  126289. _vq_quantmap__8c0_s_p6_0,
  126290. 17,
  126291. 17
  126292. };
  126293. static static_codebook _8c0_s_p6_0 = {
  126294. 2, 289,
  126295. _vq_lengthlist__8c0_s_p6_0,
  126296. 1, -529530880, 1611661312, 5, 0,
  126297. _vq_quantlist__8c0_s_p6_0,
  126298. NULL,
  126299. &_vq_auxt__8c0_s_p6_0,
  126300. NULL,
  126301. 0
  126302. };
  126303. static long _vq_quantlist__8c0_s_p7_0[] = {
  126304. 1,
  126305. 0,
  126306. 2,
  126307. };
  126308. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126309. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126310. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126311. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126312. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126313. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126314. 10,
  126315. };
  126316. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126317. -5.5, 5.5,
  126318. };
  126319. static long _vq_quantmap__8c0_s_p7_0[] = {
  126320. 1, 0, 2,
  126321. };
  126322. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126323. _vq_quantthresh__8c0_s_p7_0,
  126324. _vq_quantmap__8c0_s_p7_0,
  126325. 3,
  126326. 3
  126327. };
  126328. static static_codebook _8c0_s_p7_0 = {
  126329. 4, 81,
  126330. _vq_lengthlist__8c0_s_p7_0,
  126331. 1, -529137664, 1618345984, 2, 0,
  126332. _vq_quantlist__8c0_s_p7_0,
  126333. NULL,
  126334. &_vq_auxt__8c0_s_p7_0,
  126335. NULL,
  126336. 0
  126337. };
  126338. static long _vq_quantlist__8c0_s_p7_1[] = {
  126339. 5,
  126340. 4,
  126341. 6,
  126342. 3,
  126343. 7,
  126344. 2,
  126345. 8,
  126346. 1,
  126347. 9,
  126348. 0,
  126349. 10,
  126350. };
  126351. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126352. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126353. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126354. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126355. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126356. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126357. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126358. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126359. 10,10,10, 9, 9, 9,10,10,10,
  126360. };
  126361. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126362. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126363. 3.5, 4.5,
  126364. };
  126365. static long _vq_quantmap__8c0_s_p7_1[] = {
  126366. 9, 7, 5, 3, 1, 0, 2, 4,
  126367. 6, 8, 10,
  126368. };
  126369. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126370. _vq_quantthresh__8c0_s_p7_1,
  126371. _vq_quantmap__8c0_s_p7_1,
  126372. 11,
  126373. 11
  126374. };
  126375. static static_codebook _8c0_s_p7_1 = {
  126376. 2, 121,
  126377. _vq_lengthlist__8c0_s_p7_1,
  126378. 1, -531365888, 1611661312, 4, 0,
  126379. _vq_quantlist__8c0_s_p7_1,
  126380. NULL,
  126381. &_vq_auxt__8c0_s_p7_1,
  126382. NULL,
  126383. 0
  126384. };
  126385. static long _vq_quantlist__8c0_s_p8_0[] = {
  126386. 6,
  126387. 5,
  126388. 7,
  126389. 4,
  126390. 8,
  126391. 3,
  126392. 9,
  126393. 2,
  126394. 10,
  126395. 1,
  126396. 11,
  126397. 0,
  126398. 12,
  126399. };
  126400. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126401. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126402. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126403. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126404. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126405. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126406. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126407. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126408. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126409. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126410. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126411. 0, 0,13,13,11,13,13,11,12,
  126412. };
  126413. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126414. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126415. 12.5, 17.5, 22.5, 27.5,
  126416. };
  126417. static long _vq_quantmap__8c0_s_p8_0[] = {
  126418. 11, 9, 7, 5, 3, 1, 0, 2,
  126419. 4, 6, 8, 10, 12,
  126420. };
  126421. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126422. _vq_quantthresh__8c0_s_p8_0,
  126423. _vq_quantmap__8c0_s_p8_0,
  126424. 13,
  126425. 13
  126426. };
  126427. static static_codebook _8c0_s_p8_0 = {
  126428. 2, 169,
  126429. _vq_lengthlist__8c0_s_p8_0,
  126430. 1, -526516224, 1616117760, 4, 0,
  126431. _vq_quantlist__8c0_s_p8_0,
  126432. NULL,
  126433. &_vq_auxt__8c0_s_p8_0,
  126434. NULL,
  126435. 0
  126436. };
  126437. static long _vq_quantlist__8c0_s_p8_1[] = {
  126438. 2,
  126439. 1,
  126440. 3,
  126441. 0,
  126442. 4,
  126443. };
  126444. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126445. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126446. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126447. };
  126448. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126449. -1.5, -0.5, 0.5, 1.5,
  126450. };
  126451. static long _vq_quantmap__8c0_s_p8_1[] = {
  126452. 3, 1, 0, 2, 4,
  126453. };
  126454. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126455. _vq_quantthresh__8c0_s_p8_1,
  126456. _vq_quantmap__8c0_s_p8_1,
  126457. 5,
  126458. 5
  126459. };
  126460. static static_codebook _8c0_s_p8_1 = {
  126461. 2, 25,
  126462. _vq_lengthlist__8c0_s_p8_1,
  126463. 1, -533725184, 1611661312, 3, 0,
  126464. _vq_quantlist__8c0_s_p8_1,
  126465. NULL,
  126466. &_vq_auxt__8c0_s_p8_1,
  126467. NULL,
  126468. 0
  126469. };
  126470. static long _vq_quantlist__8c0_s_p9_0[] = {
  126471. 1,
  126472. 0,
  126473. 2,
  126474. };
  126475. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126476. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126477. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126478. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126479. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126480. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126481. 7,
  126482. };
  126483. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126484. -157.5, 157.5,
  126485. };
  126486. static long _vq_quantmap__8c0_s_p9_0[] = {
  126487. 1, 0, 2,
  126488. };
  126489. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126490. _vq_quantthresh__8c0_s_p9_0,
  126491. _vq_quantmap__8c0_s_p9_0,
  126492. 3,
  126493. 3
  126494. };
  126495. static static_codebook _8c0_s_p9_0 = {
  126496. 4, 81,
  126497. _vq_lengthlist__8c0_s_p9_0,
  126498. 1, -518803456, 1628680192, 2, 0,
  126499. _vq_quantlist__8c0_s_p9_0,
  126500. NULL,
  126501. &_vq_auxt__8c0_s_p9_0,
  126502. NULL,
  126503. 0
  126504. };
  126505. static long _vq_quantlist__8c0_s_p9_1[] = {
  126506. 7,
  126507. 6,
  126508. 8,
  126509. 5,
  126510. 9,
  126511. 4,
  126512. 10,
  126513. 3,
  126514. 11,
  126515. 2,
  126516. 12,
  126517. 1,
  126518. 13,
  126519. 0,
  126520. 14,
  126521. };
  126522. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126523. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126524. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126525. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126526. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126527. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126528. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126534. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126537. 11,
  126538. };
  126539. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126540. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126541. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126542. };
  126543. static long _vq_quantmap__8c0_s_p9_1[] = {
  126544. 13, 11, 9, 7, 5, 3, 1, 0,
  126545. 2, 4, 6, 8, 10, 12, 14,
  126546. };
  126547. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126548. _vq_quantthresh__8c0_s_p9_1,
  126549. _vq_quantmap__8c0_s_p9_1,
  126550. 15,
  126551. 15
  126552. };
  126553. static static_codebook _8c0_s_p9_1 = {
  126554. 2, 225,
  126555. _vq_lengthlist__8c0_s_p9_1,
  126556. 1, -520986624, 1620377600, 4, 0,
  126557. _vq_quantlist__8c0_s_p9_1,
  126558. NULL,
  126559. &_vq_auxt__8c0_s_p9_1,
  126560. NULL,
  126561. 0
  126562. };
  126563. static long _vq_quantlist__8c0_s_p9_2[] = {
  126564. 10,
  126565. 9,
  126566. 11,
  126567. 8,
  126568. 12,
  126569. 7,
  126570. 13,
  126571. 6,
  126572. 14,
  126573. 5,
  126574. 15,
  126575. 4,
  126576. 16,
  126577. 3,
  126578. 17,
  126579. 2,
  126580. 18,
  126581. 1,
  126582. 19,
  126583. 0,
  126584. 20,
  126585. };
  126586. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126587. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126588. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126589. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126590. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126591. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126592. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126593. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126594. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126595. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126596. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126597. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126598. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126599. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126600. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126601. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126602. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126603. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126604. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126605. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126606. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126607. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126608. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126609. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126610. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126611. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126612. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126613. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126614. 10,11, 9,11,10, 9,10, 9,10,
  126615. };
  126616. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126617. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126618. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126619. 6.5, 7.5, 8.5, 9.5,
  126620. };
  126621. static long _vq_quantmap__8c0_s_p9_2[] = {
  126622. 19, 17, 15, 13, 11, 9, 7, 5,
  126623. 3, 1, 0, 2, 4, 6, 8, 10,
  126624. 12, 14, 16, 18, 20,
  126625. };
  126626. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126627. _vq_quantthresh__8c0_s_p9_2,
  126628. _vq_quantmap__8c0_s_p9_2,
  126629. 21,
  126630. 21
  126631. };
  126632. static static_codebook _8c0_s_p9_2 = {
  126633. 2, 441,
  126634. _vq_lengthlist__8c0_s_p9_2,
  126635. 1, -529268736, 1611661312, 5, 0,
  126636. _vq_quantlist__8c0_s_p9_2,
  126637. NULL,
  126638. &_vq_auxt__8c0_s_p9_2,
  126639. NULL,
  126640. 0
  126641. };
  126642. static long _huff_lengthlist__8c0_s_single[] = {
  126643. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126644. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126645. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126646. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126647. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126648. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126649. 17,16,17,17,
  126650. };
  126651. static static_codebook _huff_book__8c0_s_single = {
  126652. 2, 100,
  126653. _huff_lengthlist__8c0_s_single,
  126654. 0, 0, 0, 0, 0,
  126655. NULL,
  126656. NULL,
  126657. NULL,
  126658. NULL,
  126659. 0
  126660. };
  126661. static long _vq_quantlist__8c1_s_p1_0[] = {
  126662. 1,
  126663. 0,
  126664. 2,
  126665. };
  126666. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126667. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126668. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126672. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126673. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126678. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126713. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126718. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126723. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126759. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126764. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126769. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0,
  127078. };
  127079. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127080. -0.5, 0.5,
  127081. };
  127082. static long _vq_quantmap__8c1_s_p1_0[] = {
  127083. 1, 0, 2,
  127084. };
  127085. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127086. _vq_quantthresh__8c1_s_p1_0,
  127087. _vq_quantmap__8c1_s_p1_0,
  127088. 3,
  127089. 3
  127090. };
  127091. static static_codebook _8c1_s_p1_0 = {
  127092. 8, 6561,
  127093. _vq_lengthlist__8c1_s_p1_0,
  127094. 1, -535822336, 1611661312, 2, 0,
  127095. _vq_quantlist__8c1_s_p1_0,
  127096. NULL,
  127097. &_vq_auxt__8c1_s_p1_0,
  127098. NULL,
  127099. 0
  127100. };
  127101. static long _vq_quantlist__8c1_s_p2_0[] = {
  127102. 2,
  127103. 1,
  127104. 3,
  127105. 0,
  127106. 4,
  127107. };
  127108. static long _vq_lengthlist__8c1_s_p2_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,
  127149. };
  127150. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127151. -1.5, -0.5, 0.5, 1.5,
  127152. };
  127153. static long _vq_quantmap__8c1_s_p2_0[] = {
  127154. 3, 1, 0, 2, 4,
  127155. };
  127156. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127157. _vq_quantthresh__8c1_s_p2_0,
  127158. _vq_quantmap__8c1_s_p2_0,
  127159. 5,
  127160. 5
  127161. };
  127162. static static_codebook _8c1_s_p2_0 = {
  127163. 4, 625,
  127164. _vq_lengthlist__8c1_s_p2_0,
  127165. 1, -533725184, 1611661312, 3, 0,
  127166. _vq_quantlist__8c1_s_p2_0,
  127167. NULL,
  127168. &_vq_auxt__8c1_s_p2_0,
  127169. NULL,
  127170. 0
  127171. };
  127172. static long _vq_quantlist__8c1_s_p3_0[] = {
  127173. 2,
  127174. 1,
  127175. 3,
  127176. 0,
  127177. 4,
  127178. };
  127179. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127180. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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,
  127220. };
  127221. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127222. -1.5, -0.5, 0.5, 1.5,
  127223. };
  127224. static long _vq_quantmap__8c1_s_p3_0[] = {
  127225. 3, 1, 0, 2, 4,
  127226. };
  127227. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127228. _vq_quantthresh__8c1_s_p3_0,
  127229. _vq_quantmap__8c1_s_p3_0,
  127230. 5,
  127231. 5
  127232. };
  127233. static static_codebook _8c1_s_p3_0 = {
  127234. 4, 625,
  127235. _vq_lengthlist__8c1_s_p3_0,
  127236. 1, -533725184, 1611661312, 3, 0,
  127237. _vq_quantlist__8c1_s_p3_0,
  127238. NULL,
  127239. &_vq_auxt__8c1_s_p3_0,
  127240. NULL,
  127241. 0
  127242. };
  127243. static long _vq_quantlist__8c1_s_p4_0[] = {
  127244. 4,
  127245. 3,
  127246. 5,
  127247. 2,
  127248. 6,
  127249. 1,
  127250. 7,
  127251. 0,
  127252. 8,
  127253. };
  127254. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127255. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127256. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127257. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127258. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127259. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0,
  127261. };
  127262. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127263. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127264. };
  127265. static long _vq_quantmap__8c1_s_p4_0[] = {
  127266. 7, 5, 3, 1, 0, 2, 4, 6,
  127267. 8,
  127268. };
  127269. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127270. _vq_quantthresh__8c1_s_p4_0,
  127271. _vq_quantmap__8c1_s_p4_0,
  127272. 9,
  127273. 9
  127274. };
  127275. static static_codebook _8c1_s_p4_0 = {
  127276. 2, 81,
  127277. _vq_lengthlist__8c1_s_p4_0,
  127278. 1, -531628032, 1611661312, 4, 0,
  127279. _vq_quantlist__8c1_s_p4_0,
  127280. NULL,
  127281. &_vq_auxt__8c1_s_p4_0,
  127282. NULL,
  127283. 0
  127284. };
  127285. static long _vq_quantlist__8c1_s_p5_0[] = {
  127286. 4,
  127287. 3,
  127288. 5,
  127289. 2,
  127290. 6,
  127291. 1,
  127292. 7,
  127293. 0,
  127294. 8,
  127295. };
  127296. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127297. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127298. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127299. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127300. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127301. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127302. 10,
  127303. };
  127304. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127305. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127306. };
  127307. static long _vq_quantmap__8c1_s_p5_0[] = {
  127308. 7, 5, 3, 1, 0, 2, 4, 6,
  127309. 8,
  127310. };
  127311. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127312. _vq_quantthresh__8c1_s_p5_0,
  127313. _vq_quantmap__8c1_s_p5_0,
  127314. 9,
  127315. 9
  127316. };
  127317. static static_codebook _8c1_s_p5_0 = {
  127318. 2, 81,
  127319. _vq_lengthlist__8c1_s_p5_0,
  127320. 1, -531628032, 1611661312, 4, 0,
  127321. _vq_quantlist__8c1_s_p5_0,
  127322. NULL,
  127323. &_vq_auxt__8c1_s_p5_0,
  127324. NULL,
  127325. 0
  127326. };
  127327. static long _vq_quantlist__8c1_s_p6_0[] = {
  127328. 8,
  127329. 7,
  127330. 9,
  127331. 6,
  127332. 10,
  127333. 5,
  127334. 11,
  127335. 4,
  127336. 12,
  127337. 3,
  127338. 13,
  127339. 2,
  127340. 14,
  127341. 1,
  127342. 15,
  127343. 0,
  127344. 16,
  127345. };
  127346. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127347. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127348. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127349. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127350. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127351. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127352. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127353. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127354. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127355. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127356. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127357. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127358. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127359. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127360. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127361. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127362. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127363. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127365. 14,
  127366. };
  127367. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127368. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127369. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127370. };
  127371. static long _vq_quantmap__8c1_s_p6_0[] = {
  127372. 15, 13, 11, 9, 7, 5, 3, 1,
  127373. 0, 2, 4, 6, 8, 10, 12, 14,
  127374. 16,
  127375. };
  127376. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127377. _vq_quantthresh__8c1_s_p6_0,
  127378. _vq_quantmap__8c1_s_p6_0,
  127379. 17,
  127380. 17
  127381. };
  127382. static static_codebook _8c1_s_p6_0 = {
  127383. 2, 289,
  127384. _vq_lengthlist__8c1_s_p6_0,
  127385. 1, -529530880, 1611661312, 5, 0,
  127386. _vq_quantlist__8c1_s_p6_0,
  127387. NULL,
  127388. &_vq_auxt__8c1_s_p6_0,
  127389. NULL,
  127390. 0
  127391. };
  127392. static long _vq_quantlist__8c1_s_p7_0[] = {
  127393. 1,
  127394. 0,
  127395. 2,
  127396. };
  127397. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127398. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127399. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127400. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127401. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127402. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127403. 9,
  127404. };
  127405. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127406. -5.5, 5.5,
  127407. };
  127408. static long _vq_quantmap__8c1_s_p7_0[] = {
  127409. 1, 0, 2,
  127410. };
  127411. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127412. _vq_quantthresh__8c1_s_p7_0,
  127413. _vq_quantmap__8c1_s_p7_0,
  127414. 3,
  127415. 3
  127416. };
  127417. static static_codebook _8c1_s_p7_0 = {
  127418. 4, 81,
  127419. _vq_lengthlist__8c1_s_p7_0,
  127420. 1, -529137664, 1618345984, 2, 0,
  127421. _vq_quantlist__8c1_s_p7_0,
  127422. NULL,
  127423. &_vq_auxt__8c1_s_p7_0,
  127424. NULL,
  127425. 0
  127426. };
  127427. static long _vq_quantlist__8c1_s_p7_1[] = {
  127428. 5,
  127429. 4,
  127430. 6,
  127431. 3,
  127432. 7,
  127433. 2,
  127434. 8,
  127435. 1,
  127436. 9,
  127437. 0,
  127438. 10,
  127439. };
  127440. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127441. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127442. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127443. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127444. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127445. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127446. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127447. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127448. 10,10,10, 8, 8, 8, 8, 8, 8,
  127449. };
  127450. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127451. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127452. 3.5, 4.5,
  127453. };
  127454. static long _vq_quantmap__8c1_s_p7_1[] = {
  127455. 9, 7, 5, 3, 1, 0, 2, 4,
  127456. 6, 8, 10,
  127457. };
  127458. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127459. _vq_quantthresh__8c1_s_p7_1,
  127460. _vq_quantmap__8c1_s_p7_1,
  127461. 11,
  127462. 11
  127463. };
  127464. static static_codebook _8c1_s_p7_1 = {
  127465. 2, 121,
  127466. _vq_lengthlist__8c1_s_p7_1,
  127467. 1, -531365888, 1611661312, 4, 0,
  127468. _vq_quantlist__8c1_s_p7_1,
  127469. NULL,
  127470. &_vq_auxt__8c1_s_p7_1,
  127471. NULL,
  127472. 0
  127473. };
  127474. static long _vq_quantlist__8c1_s_p8_0[] = {
  127475. 6,
  127476. 5,
  127477. 7,
  127478. 4,
  127479. 8,
  127480. 3,
  127481. 9,
  127482. 2,
  127483. 10,
  127484. 1,
  127485. 11,
  127486. 0,
  127487. 12,
  127488. };
  127489. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127490. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127491. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127492. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127493. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127494. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127495. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127496. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127497. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127498. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127499. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127500. 0,12,12,11,10,12,11,13,12,
  127501. };
  127502. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127503. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127504. 12.5, 17.5, 22.5, 27.5,
  127505. };
  127506. static long _vq_quantmap__8c1_s_p8_0[] = {
  127507. 11, 9, 7, 5, 3, 1, 0, 2,
  127508. 4, 6, 8, 10, 12,
  127509. };
  127510. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127511. _vq_quantthresh__8c1_s_p8_0,
  127512. _vq_quantmap__8c1_s_p8_0,
  127513. 13,
  127514. 13
  127515. };
  127516. static static_codebook _8c1_s_p8_0 = {
  127517. 2, 169,
  127518. _vq_lengthlist__8c1_s_p8_0,
  127519. 1, -526516224, 1616117760, 4, 0,
  127520. _vq_quantlist__8c1_s_p8_0,
  127521. NULL,
  127522. &_vq_auxt__8c1_s_p8_0,
  127523. NULL,
  127524. 0
  127525. };
  127526. static long _vq_quantlist__8c1_s_p8_1[] = {
  127527. 2,
  127528. 1,
  127529. 3,
  127530. 0,
  127531. 4,
  127532. };
  127533. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127534. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127535. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127536. };
  127537. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127538. -1.5, -0.5, 0.5, 1.5,
  127539. };
  127540. static long _vq_quantmap__8c1_s_p8_1[] = {
  127541. 3, 1, 0, 2, 4,
  127542. };
  127543. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127544. _vq_quantthresh__8c1_s_p8_1,
  127545. _vq_quantmap__8c1_s_p8_1,
  127546. 5,
  127547. 5
  127548. };
  127549. static static_codebook _8c1_s_p8_1 = {
  127550. 2, 25,
  127551. _vq_lengthlist__8c1_s_p8_1,
  127552. 1, -533725184, 1611661312, 3, 0,
  127553. _vq_quantlist__8c1_s_p8_1,
  127554. NULL,
  127555. &_vq_auxt__8c1_s_p8_1,
  127556. NULL,
  127557. 0
  127558. };
  127559. static long _vq_quantlist__8c1_s_p9_0[] = {
  127560. 6,
  127561. 5,
  127562. 7,
  127563. 4,
  127564. 8,
  127565. 3,
  127566. 9,
  127567. 2,
  127568. 10,
  127569. 1,
  127570. 11,
  127571. 0,
  127572. 12,
  127573. };
  127574. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127575. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127576. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127577. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127578. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127579. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127580. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127581. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127582. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127583. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127584. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127585. 10,10,10,10,10, 9, 9, 9, 9,
  127586. };
  127587. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127588. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127589. 787.5, 1102.5, 1417.5, 1732.5,
  127590. };
  127591. static long _vq_quantmap__8c1_s_p9_0[] = {
  127592. 11, 9, 7, 5, 3, 1, 0, 2,
  127593. 4, 6, 8, 10, 12,
  127594. };
  127595. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127596. _vq_quantthresh__8c1_s_p9_0,
  127597. _vq_quantmap__8c1_s_p9_0,
  127598. 13,
  127599. 13
  127600. };
  127601. static static_codebook _8c1_s_p9_0 = {
  127602. 2, 169,
  127603. _vq_lengthlist__8c1_s_p9_0,
  127604. 1, -513964032, 1628680192, 4, 0,
  127605. _vq_quantlist__8c1_s_p9_0,
  127606. NULL,
  127607. &_vq_auxt__8c1_s_p9_0,
  127608. NULL,
  127609. 0
  127610. };
  127611. static long _vq_quantlist__8c1_s_p9_1[] = {
  127612. 7,
  127613. 6,
  127614. 8,
  127615. 5,
  127616. 9,
  127617. 4,
  127618. 10,
  127619. 3,
  127620. 11,
  127621. 2,
  127622. 12,
  127623. 1,
  127624. 13,
  127625. 0,
  127626. 14,
  127627. };
  127628. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127629. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127630. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127631. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127632. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127633. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127634. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127635. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127636. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127637. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127638. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127639. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127640. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127641. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127642. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127643. 15,
  127644. };
  127645. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127646. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127647. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127648. };
  127649. static long _vq_quantmap__8c1_s_p9_1[] = {
  127650. 13, 11, 9, 7, 5, 3, 1, 0,
  127651. 2, 4, 6, 8, 10, 12, 14,
  127652. };
  127653. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127654. _vq_quantthresh__8c1_s_p9_1,
  127655. _vq_quantmap__8c1_s_p9_1,
  127656. 15,
  127657. 15
  127658. };
  127659. static static_codebook _8c1_s_p9_1 = {
  127660. 2, 225,
  127661. _vq_lengthlist__8c1_s_p9_1,
  127662. 1, -520986624, 1620377600, 4, 0,
  127663. _vq_quantlist__8c1_s_p9_1,
  127664. NULL,
  127665. &_vq_auxt__8c1_s_p9_1,
  127666. NULL,
  127667. 0
  127668. };
  127669. static long _vq_quantlist__8c1_s_p9_2[] = {
  127670. 10,
  127671. 9,
  127672. 11,
  127673. 8,
  127674. 12,
  127675. 7,
  127676. 13,
  127677. 6,
  127678. 14,
  127679. 5,
  127680. 15,
  127681. 4,
  127682. 16,
  127683. 3,
  127684. 17,
  127685. 2,
  127686. 18,
  127687. 1,
  127688. 19,
  127689. 0,
  127690. 20,
  127691. };
  127692. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127693. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127694. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127695. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127696. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127697. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127698. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127699. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127700. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127701. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127702. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127703. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127704. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127705. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127706. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127707. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127708. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127709. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127710. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127711. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127712. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127713. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127714. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127715. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127716. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127717. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127718. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127719. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127720. 10,10,10,10,10,10,10,10,10,
  127721. };
  127722. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127723. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127724. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127725. 6.5, 7.5, 8.5, 9.5,
  127726. };
  127727. static long _vq_quantmap__8c1_s_p9_2[] = {
  127728. 19, 17, 15, 13, 11, 9, 7, 5,
  127729. 3, 1, 0, 2, 4, 6, 8, 10,
  127730. 12, 14, 16, 18, 20,
  127731. };
  127732. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127733. _vq_quantthresh__8c1_s_p9_2,
  127734. _vq_quantmap__8c1_s_p9_2,
  127735. 21,
  127736. 21
  127737. };
  127738. static static_codebook _8c1_s_p9_2 = {
  127739. 2, 441,
  127740. _vq_lengthlist__8c1_s_p9_2,
  127741. 1, -529268736, 1611661312, 5, 0,
  127742. _vq_quantlist__8c1_s_p9_2,
  127743. NULL,
  127744. &_vq_auxt__8c1_s_p9_2,
  127745. NULL,
  127746. 0
  127747. };
  127748. static long _huff_lengthlist__8c1_s_single[] = {
  127749. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127750. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127751. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127752. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127753. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127754. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127755. 9, 7, 7, 8,
  127756. };
  127757. static static_codebook _huff_book__8c1_s_single = {
  127758. 2, 100,
  127759. _huff_lengthlist__8c1_s_single,
  127760. 0, 0, 0, 0, 0,
  127761. NULL,
  127762. NULL,
  127763. NULL,
  127764. NULL,
  127765. 0
  127766. };
  127767. static long _huff_lengthlist__44c2_s_long[] = {
  127768. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127769. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127770. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127771. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127772. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127773. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127774. 10, 8, 8, 9,
  127775. };
  127776. static static_codebook _huff_book__44c2_s_long = {
  127777. 2, 100,
  127778. _huff_lengthlist__44c2_s_long,
  127779. 0, 0, 0, 0, 0,
  127780. NULL,
  127781. NULL,
  127782. NULL,
  127783. NULL,
  127784. 0
  127785. };
  127786. static long _vq_quantlist__44c2_s_p1_0[] = {
  127787. 1,
  127788. 0,
  127789. 2,
  127790. };
  127791. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127792. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127793. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127797. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127798. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127802. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127803. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127838. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127843. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127848. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127884. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127889. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127894. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 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,
  128203. };
  128204. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128205. -0.5, 0.5,
  128206. };
  128207. static long _vq_quantmap__44c2_s_p1_0[] = {
  128208. 1, 0, 2,
  128209. };
  128210. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128211. _vq_quantthresh__44c2_s_p1_0,
  128212. _vq_quantmap__44c2_s_p1_0,
  128213. 3,
  128214. 3
  128215. };
  128216. static static_codebook _44c2_s_p1_0 = {
  128217. 8, 6561,
  128218. _vq_lengthlist__44c2_s_p1_0,
  128219. 1, -535822336, 1611661312, 2, 0,
  128220. _vq_quantlist__44c2_s_p1_0,
  128221. NULL,
  128222. &_vq_auxt__44c2_s_p1_0,
  128223. NULL,
  128224. 0
  128225. };
  128226. static long _vq_quantlist__44c2_s_p2_0[] = {
  128227. 2,
  128228. 1,
  128229. 3,
  128230. 0,
  128231. 4,
  128232. };
  128233. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128234. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128235. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128236. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128237. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128238. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128244. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128245. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128246. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128252. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128253. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128260. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128261. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  128274. };
  128275. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128276. -1.5, -0.5, 0.5, 1.5,
  128277. };
  128278. static long _vq_quantmap__44c2_s_p2_0[] = {
  128279. 3, 1, 0, 2, 4,
  128280. };
  128281. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128282. _vq_quantthresh__44c2_s_p2_0,
  128283. _vq_quantmap__44c2_s_p2_0,
  128284. 5,
  128285. 5
  128286. };
  128287. static static_codebook _44c2_s_p2_0 = {
  128288. 4, 625,
  128289. _vq_lengthlist__44c2_s_p2_0,
  128290. 1, -533725184, 1611661312, 3, 0,
  128291. _vq_quantlist__44c2_s_p2_0,
  128292. NULL,
  128293. &_vq_auxt__44c2_s_p2_0,
  128294. NULL,
  128295. 0
  128296. };
  128297. static long _vq_quantlist__44c2_s_p3_0[] = {
  128298. 2,
  128299. 1,
  128300. 3,
  128301. 0,
  128302. 4,
  128303. };
  128304. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128305. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  128345. };
  128346. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128347. -1.5, -0.5, 0.5, 1.5,
  128348. };
  128349. static long _vq_quantmap__44c2_s_p3_0[] = {
  128350. 3, 1, 0, 2, 4,
  128351. };
  128352. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128353. _vq_quantthresh__44c2_s_p3_0,
  128354. _vq_quantmap__44c2_s_p3_0,
  128355. 5,
  128356. 5
  128357. };
  128358. static static_codebook _44c2_s_p3_0 = {
  128359. 4, 625,
  128360. _vq_lengthlist__44c2_s_p3_0,
  128361. 1, -533725184, 1611661312, 3, 0,
  128362. _vq_quantlist__44c2_s_p3_0,
  128363. NULL,
  128364. &_vq_auxt__44c2_s_p3_0,
  128365. NULL,
  128366. 0
  128367. };
  128368. static long _vq_quantlist__44c2_s_p4_0[] = {
  128369. 4,
  128370. 3,
  128371. 5,
  128372. 2,
  128373. 6,
  128374. 1,
  128375. 7,
  128376. 0,
  128377. 8,
  128378. };
  128379. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128380. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128381. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128382. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128383. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128384. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0,
  128386. };
  128387. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128388. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128389. };
  128390. static long _vq_quantmap__44c2_s_p4_0[] = {
  128391. 7, 5, 3, 1, 0, 2, 4, 6,
  128392. 8,
  128393. };
  128394. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128395. _vq_quantthresh__44c2_s_p4_0,
  128396. _vq_quantmap__44c2_s_p4_0,
  128397. 9,
  128398. 9
  128399. };
  128400. static static_codebook _44c2_s_p4_0 = {
  128401. 2, 81,
  128402. _vq_lengthlist__44c2_s_p4_0,
  128403. 1, -531628032, 1611661312, 4, 0,
  128404. _vq_quantlist__44c2_s_p4_0,
  128405. NULL,
  128406. &_vq_auxt__44c2_s_p4_0,
  128407. NULL,
  128408. 0
  128409. };
  128410. static long _vq_quantlist__44c2_s_p5_0[] = {
  128411. 4,
  128412. 3,
  128413. 5,
  128414. 2,
  128415. 6,
  128416. 1,
  128417. 7,
  128418. 0,
  128419. 8,
  128420. };
  128421. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128422. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128423. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128424. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128425. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128426. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128427. 11,
  128428. };
  128429. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128430. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128431. };
  128432. static long _vq_quantmap__44c2_s_p5_0[] = {
  128433. 7, 5, 3, 1, 0, 2, 4, 6,
  128434. 8,
  128435. };
  128436. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128437. _vq_quantthresh__44c2_s_p5_0,
  128438. _vq_quantmap__44c2_s_p5_0,
  128439. 9,
  128440. 9
  128441. };
  128442. static static_codebook _44c2_s_p5_0 = {
  128443. 2, 81,
  128444. _vq_lengthlist__44c2_s_p5_0,
  128445. 1, -531628032, 1611661312, 4, 0,
  128446. _vq_quantlist__44c2_s_p5_0,
  128447. NULL,
  128448. &_vq_auxt__44c2_s_p5_0,
  128449. NULL,
  128450. 0
  128451. };
  128452. static long _vq_quantlist__44c2_s_p6_0[] = {
  128453. 8,
  128454. 7,
  128455. 9,
  128456. 6,
  128457. 10,
  128458. 5,
  128459. 11,
  128460. 4,
  128461. 12,
  128462. 3,
  128463. 13,
  128464. 2,
  128465. 14,
  128466. 1,
  128467. 15,
  128468. 0,
  128469. 16,
  128470. };
  128471. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128472. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128473. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128474. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128475. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128476. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128477. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128478. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128479. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128480. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128481. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128482. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128483. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128484. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128485. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128486. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128487. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128488. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128490. 14,
  128491. };
  128492. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128493. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128494. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128495. };
  128496. static long _vq_quantmap__44c2_s_p6_0[] = {
  128497. 15, 13, 11, 9, 7, 5, 3, 1,
  128498. 0, 2, 4, 6, 8, 10, 12, 14,
  128499. 16,
  128500. };
  128501. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128502. _vq_quantthresh__44c2_s_p6_0,
  128503. _vq_quantmap__44c2_s_p6_0,
  128504. 17,
  128505. 17
  128506. };
  128507. static static_codebook _44c2_s_p6_0 = {
  128508. 2, 289,
  128509. _vq_lengthlist__44c2_s_p6_0,
  128510. 1, -529530880, 1611661312, 5, 0,
  128511. _vq_quantlist__44c2_s_p6_0,
  128512. NULL,
  128513. &_vq_auxt__44c2_s_p6_0,
  128514. NULL,
  128515. 0
  128516. };
  128517. static long _vq_quantlist__44c2_s_p7_0[] = {
  128518. 1,
  128519. 0,
  128520. 2,
  128521. };
  128522. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128523. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128524. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128525. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128526. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128527. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128528. 11,
  128529. };
  128530. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128531. -5.5, 5.5,
  128532. };
  128533. static long _vq_quantmap__44c2_s_p7_0[] = {
  128534. 1, 0, 2,
  128535. };
  128536. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128537. _vq_quantthresh__44c2_s_p7_0,
  128538. _vq_quantmap__44c2_s_p7_0,
  128539. 3,
  128540. 3
  128541. };
  128542. static static_codebook _44c2_s_p7_0 = {
  128543. 4, 81,
  128544. _vq_lengthlist__44c2_s_p7_0,
  128545. 1, -529137664, 1618345984, 2, 0,
  128546. _vq_quantlist__44c2_s_p7_0,
  128547. NULL,
  128548. &_vq_auxt__44c2_s_p7_0,
  128549. NULL,
  128550. 0
  128551. };
  128552. static long _vq_quantlist__44c2_s_p7_1[] = {
  128553. 5,
  128554. 4,
  128555. 6,
  128556. 3,
  128557. 7,
  128558. 2,
  128559. 8,
  128560. 1,
  128561. 9,
  128562. 0,
  128563. 10,
  128564. };
  128565. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128566. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128567. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128568. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128569. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128570. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128571. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128572. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128573. 10,10,10, 8, 8, 8, 8, 8, 8,
  128574. };
  128575. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128576. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128577. 3.5, 4.5,
  128578. };
  128579. static long _vq_quantmap__44c2_s_p7_1[] = {
  128580. 9, 7, 5, 3, 1, 0, 2, 4,
  128581. 6, 8, 10,
  128582. };
  128583. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128584. _vq_quantthresh__44c2_s_p7_1,
  128585. _vq_quantmap__44c2_s_p7_1,
  128586. 11,
  128587. 11
  128588. };
  128589. static static_codebook _44c2_s_p7_1 = {
  128590. 2, 121,
  128591. _vq_lengthlist__44c2_s_p7_1,
  128592. 1, -531365888, 1611661312, 4, 0,
  128593. _vq_quantlist__44c2_s_p7_1,
  128594. NULL,
  128595. &_vq_auxt__44c2_s_p7_1,
  128596. NULL,
  128597. 0
  128598. };
  128599. static long _vq_quantlist__44c2_s_p8_0[] = {
  128600. 6,
  128601. 5,
  128602. 7,
  128603. 4,
  128604. 8,
  128605. 3,
  128606. 9,
  128607. 2,
  128608. 10,
  128609. 1,
  128610. 11,
  128611. 0,
  128612. 12,
  128613. };
  128614. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128615. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128616. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128617. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128618. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128619. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128620. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128621. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128622. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128623. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128624. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128625. 0,12,12,12,12,13,12,14,14,
  128626. };
  128627. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128628. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128629. 12.5, 17.5, 22.5, 27.5,
  128630. };
  128631. static long _vq_quantmap__44c2_s_p8_0[] = {
  128632. 11, 9, 7, 5, 3, 1, 0, 2,
  128633. 4, 6, 8, 10, 12,
  128634. };
  128635. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128636. _vq_quantthresh__44c2_s_p8_0,
  128637. _vq_quantmap__44c2_s_p8_0,
  128638. 13,
  128639. 13
  128640. };
  128641. static static_codebook _44c2_s_p8_0 = {
  128642. 2, 169,
  128643. _vq_lengthlist__44c2_s_p8_0,
  128644. 1, -526516224, 1616117760, 4, 0,
  128645. _vq_quantlist__44c2_s_p8_0,
  128646. NULL,
  128647. &_vq_auxt__44c2_s_p8_0,
  128648. NULL,
  128649. 0
  128650. };
  128651. static long _vq_quantlist__44c2_s_p8_1[] = {
  128652. 2,
  128653. 1,
  128654. 3,
  128655. 0,
  128656. 4,
  128657. };
  128658. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128659. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128660. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128661. };
  128662. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128663. -1.5, -0.5, 0.5, 1.5,
  128664. };
  128665. static long _vq_quantmap__44c2_s_p8_1[] = {
  128666. 3, 1, 0, 2, 4,
  128667. };
  128668. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128669. _vq_quantthresh__44c2_s_p8_1,
  128670. _vq_quantmap__44c2_s_p8_1,
  128671. 5,
  128672. 5
  128673. };
  128674. static static_codebook _44c2_s_p8_1 = {
  128675. 2, 25,
  128676. _vq_lengthlist__44c2_s_p8_1,
  128677. 1, -533725184, 1611661312, 3, 0,
  128678. _vq_quantlist__44c2_s_p8_1,
  128679. NULL,
  128680. &_vq_auxt__44c2_s_p8_1,
  128681. NULL,
  128682. 0
  128683. };
  128684. static long _vq_quantlist__44c2_s_p9_0[] = {
  128685. 6,
  128686. 5,
  128687. 7,
  128688. 4,
  128689. 8,
  128690. 3,
  128691. 9,
  128692. 2,
  128693. 10,
  128694. 1,
  128695. 11,
  128696. 0,
  128697. 12,
  128698. };
  128699. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128700. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128701. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128703. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128710. 11,11,11,11,11,11,11,11,11,
  128711. };
  128712. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128713. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128714. 552.5, 773.5, 994.5, 1215.5,
  128715. };
  128716. static long _vq_quantmap__44c2_s_p9_0[] = {
  128717. 11, 9, 7, 5, 3, 1, 0, 2,
  128718. 4, 6, 8, 10, 12,
  128719. };
  128720. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128721. _vq_quantthresh__44c2_s_p9_0,
  128722. _vq_quantmap__44c2_s_p9_0,
  128723. 13,
  128724. 13
  128725. };
  128726. static static_codebook _44c2_s_p9_0 = {
  128727. 2, 169,
  128728. _vq_lengthlist__44c2_s_p9_0,
  128729. 1, -514541568, 1627103232, 4, 0,
  128730. _vq_quantlist__44c2_s_p9_0,
  128731. NULL,
  128732. &_vq_auxt__44c2_s_p9_0,
  128733. NULL,
  128734. 0
  128735. };
  128736. static long _vq_quantlist__44c2_s_p9_1[] = {
  128737. 6,
  128738. 5,
  128739. 7,
  128740. 4,
  128741. 8,
  128742. 3,
  128743. 9,
  128744. 2,
  128745. 10,
  128746. 1,
  128747. 11,
  128748. 0,
  128749. 12,
  128750. };
  128751. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128752. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128753. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128754. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128755. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128756. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128757. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128758. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128759. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128760. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128761. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128762. 17,13,12,12,10,13,11,14,14,
  128763. };
  128764. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128765. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128766. 42.5, 59.5, 76.5, 93.5,
  128767. };
  128768. static long _vq_quantmap__44c2_s_p9_1[] = {
  128769. 11, 9, 7, 5, 3, 1, 0, 2,
  128770. 4, 6, 8, 10, 12,
  128771. };
  128772. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128773. _vq_quantthresh__44c2_s_p9_1,
  128774. _vq_quantmap__44c2_s_p9_1,
  128775. 13,
  128776. 13
  128777. };
  128778. static static_codebook _44c2_s_p9_1 = {
  128779. 2, 169,
  128780. _vq_lengthlist__44c2_s_p9_1,
  128781. 1, -522616832, 1620115456, 4, 0,
  128782. _vq_quantlist__44c2_s_p9_1,
  128783. NULL,
  128784. &_vq_auxt__44c2_s_p9_1,
  128785. NULL,
  128786. 0
  128787. };
  128788. static long _vq_quantlist__44c2_s_p9_2[] = {
  128789. 8,
  128790. 7,
  128791. 9,
  128792. 6,
  128793. 10,
  128794. 5,
  128795. 11,
  128796. 4,
  128797. 12,
  128798. 3,
  128799. 13,
  128800. 2,
  128801. 14,
  128802. 1,
  128803. 15,
  128804. 0,
  128805. 16,
  128806. };
  128807. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128808. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128809. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128810. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128811. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128812. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128813. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128814. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128815. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128816. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128817. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128818. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128819. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128820. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128821. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128822. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128823. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128824. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128825. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128826. 10,
  128827. };
  128828. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128829. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128830. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128831. };
  128832. static long _vq_quantmap__44c2_s_p9_2[] = {
  128833. 15, 13, 11, 9, 7, 5, 3, 1,
  128834. 0, 2, 4, 6, 8, 10, 12, 14,
  128835. 16,
  128836. };
  128837. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128838. _vq_quantthresh__44c2_s_p9_2,
  128839. _vq_quantmap__44c2_s_p9_2,
  128840. 17,
  128841. 17
  128842. };
  128843. static static_codebook _44c2_s_p9_2 = {
  128844. 2, 289,
  128845. _vq_lengthlist__44c2_s_p9_2,
  128846. 1, -529530880, 1611661312, 5, 0,
  128847. _vq_quantlist__44c2_s_p9_2,
  128848. NULL,
  128849. &_vq_auxt__44c2_s_p9_2,
  128850. NULL,
  128851. 0
  128852. };
  128853. static long _huff_lengthlist__44c2_s_short[] = {
  128854. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128855. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128856. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128857. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128858. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128859. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128860. 6, 8, 9,12,
  128861. };
  128862. static static_codebook _huff_book__44c2_s_short = {
  128863. 2, 100,
  128864. _huff_lengthlist__44c2_s_short,
  128865. 0, 0, 0, 0, 0,
  128866. NULL,
  128867. NULL,
  128868. NULL,
  128869. NULL,
  128870. 0
  128871. };
  128872. static long _huff_lengthlist__44c3_s_long[] = {
  128873. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128874. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128875. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128876. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128877. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128878. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128879. 9, 8, 8, 8,
  128880. };
  128881. static static_codebook _huff_book__44c3_s_long = {
  128882. 2, 100,
  128883. _huff_lengthlist__44c3_s_long,
  128884. 0, 0, 0, 0, 0,
  128885. NULL,
  128886. NULL,
  128887. NULL,
  128888. NULL,
  128889. 0
  128890. };
  128891. static long _vq_quantlist__44c3_s_p1_0[] = {
  128892. 1,
  128893. 0,
  128894. 2,
  128895. };
  128896. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128897. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128898. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128902. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128903. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128907. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128908. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128943. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128948. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128953. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128989. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128994. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128999. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0,
  129308. };
  129309. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129310. -0.5, 0.5,
  129311. };
  129312. static long _vq_quantmap__44c3_s_p1_0[] = {
  129313. 1, 0, 2,
  129314. };
  129315. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129316. _vq_quantthresh__44c3_s_p1_0,
  129317. _vq_quantmap__44c3_s_p1_0,
  129318. 3,
  129319. 3
  129320. };
  129321. static static_codebook _44c3_s_p1_0 = {
  129322. 8, 6561,
  129323. _vq_lengthlist__44c3_s_p1_0,
  129324. 1, -535822336, 1611661312, 2, 0,
  129325. _vq_quantlist__44c3_s_p1_0,
  129326. NULL,
  129327. &_vq_auxt__44c3_s_p1_0,
  129328. NULL,
  129329. 0
  129330. };
  129331. static long _vq_quantlist__44c3_s_p2_0[] = {
  129332. 2,
  129333. 1,
  129334. 3,
  129335. 0,
  129336. 4,
  129337. };
  129338. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129339. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129340. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129341. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129342. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129343. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129349. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129350. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129351. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129357. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129358. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129365. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129366. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  129379. };
  129380. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129381. -1.5, -0.5, 0.5, 1.5,
  129382. };
  129383. static long _vq_quantmap__44c3_s_p2_0[] = {
  129384. 3, 1, 0, 2, 4,
  129385. };
  129386. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129387. _vq_quantthresh__44c3_s_p2_0,
  129388. _vq_quantmap__44c3_s_p2_0,
  129389. 5,
  129390. 5
  129391. };
  129392. static static_codebook _44c3_s_p2_0 = {
  129393. 4, 625,
  129394. _vq_lengthlist__44c3_s_p2_0,
  129395. 1, -533725184, 1611661312, 3, 0,
  129396. _vq_quantlist__44c3_s_p2_0,
  129397. NULL,
  129398. &_vq_auxt__44c3_s_p2_0,
  129399. NULL,
  129400. 0
  129401. };
  129402. static long _vq_quantlist__44c3_s_p3_0[] = {
  129403. 2,
  129404. 1,
  129405. 3,
  129406. 0,
  129407. 4,
  129408. };
  129409. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129410. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  129450. };
  129451. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129452. -1.5, -0.5, 0.5, 1.5,
  129453. };
  129454. static long _vq_quantmap__44c3_s_p3_0[] = {
  129455. 3, 1, 0, 2, 4,
  129456. };
  129457. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129458. _vq_quantthresh__44c3_s_p3_0,
  129459. _vq_quantmap__44c3_s_p3_0,
  129460. 5,
  129461. 5
  129462. };
  129463. static static_codebook _44c3_s_p3_0 = {
  129464. 4, 625,
  129465. _vq_lengthlist__44c3_s_p3_0,
  129466. 1, -533725184, 1611661312, 3, 0,
  129467. _vq_quantlist__44c3_s_p3_0,
  129468. NULL,
  129469. &_vq_auxt__44c3_s_p3_0,
  129470. NULL,
  129471. 0
  129472. };
  129473. static long _vq_quantlist__44c3_s_p4_0[] = {
  129474. 4,
  129475. 3,
  129476. 5,
  129477. 2,
  129478. 6,
  129479. 1,
  129480. 7,
  129481. 0,
  129482. 8,
  129483. };
  129484. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129485. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129486. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129487. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129488. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129489. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0,
  129491. };
  129492. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129493. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129494. };
  129495. static long _vq_quantmap__44c3_s_p4_0[] = {
  129496. 7, 5, 3, 1, 0, 2, 4, 6,
  129497. 8,
  129498. };
  129499. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129500. _vq_quantthresh__44c3_s_p4_0,
  129501. _vq_quantmap__44c3_s_p4_0,
  129502. 9,
  129503. 9
  129504. };
  129505. static static_codebook _44c3_s_p4_0 = {
  129506. 2, 81,
  129507. _vq_lengthlist__44c3_s_p4_0,
  129508. 1, -531628032, 1611661312, 4, 0,
  129509. _vq_quantlist__44c3_s_p4_0,
  129510. NULL,
  129511. &_vq_auxt__44c3_s_p4_0,
  129512. NULL,
  129513. 0
  129514. };
  129515. static long _vq_quantlist__44c3_s_p5_0[] = {
  129516. 4,
  129517. 3,
  129518. 5,
  129519. 2,
  129520. 6,
  129521. 1,
  129522. 7,
  129523. 0,
  129524. 8,
  129525. };
  129526. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129527. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129528. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129529. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129530. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129531. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129532. 11,
  129533. };
  129534. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129535. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129536. };
  129537. static long _vq_quantmap__44c3_s_p5_0[] = {
  129538. 7, 5, 3, 1, 0, 2, 4, 6,
  129539. 8,
  129540. };
  129541. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129542. _vq_quantthresh__44c3_s_p5_0,
  129543. _vq_quantmap__44c3_s_p5_0,
  129544. 9,
  129545. 9
  129546. };
  129547. static static_codebook _44c3_s_p5_0 = {
  129548. 2, 81,
  129549. _vq_lengthlist__44c3_s_p5_0,
  129550. 1, -531628032, 1611661312, 4, 0,
  129551. _vq_quantlist__44c3_s_p5_0,
  129552. NULL,
  129553. &_vq_auxt__44c3_s_p5_0,
  129554. NULL,
  129555. 0
  129556. };
  129557. static long _vq_quantlist__44c3_s_p6_0[] = {
  129558. 8,
  129559. 7,
  129560. 9,
  129561. 6,
  129562. 10,
  129563. 5,
  129564. 11,
  129565. 4,
  129566. 12,
  129567. 3,
  129568. 13,
  129569. 2,
  129570. 14,
  129571. 1,
  129572. 15,
  129573. 0,
  129574. 16,
  129575. };
  129576. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129577. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129578. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129579. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129580. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129581. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129582. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129583. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129584. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129585. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129586. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129587. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129588. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129589. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129590. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129591. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129592. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129593. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129595. 13,
  129596. };
  129597. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129598. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129599. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129600. };
  129601. static long _vq_quantmap__44c3_s_p6_0[] = {
  129602. 15, 13, 11, 9, 7, 5, 3, 1,
  129603. 0, 2, 4, 6, 8, 10, 12, 14,
  129604. 16,
  129605. };
  129606. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129607. _vq_quantthresh__44c3_s_p6_0,
  129608. _vq_quantmap__44c3_s_p6_0,
  129609. 17,
  129610. 17
  129611. };
  129612. static static_codebook _44c3_s_p6_0 = {
  129613. 2, 289,
  129614. _vq_lengthlist__44c3_s_p6_0,
  129615. 1, -529530880, 1611661312, 5, 0,
  129616. _vq_quantlist__44c3_s_p6_0,
  129617. NULL,
  129618. &_vq_auxt__44c3_s_p6_0,
  129619. NULL,
  129620. 0
  129621. };
  129622. static long _vq_quantlist__44c3_s_p7_0[] = {
  129623. 1,
  129624. 0,
  129625. 2,
  129626. };
  129627. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129628. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129629. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129630. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129631. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129632. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129633. 10,
  129634. };
  129635. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129636. -5.5, 5.5,
  129637. };
  129638. static long _vq_quantmap__44c3_s_p7_0[] = {
  129639. 1, 0, 2,
  129640. };
  129641. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129642. _vq_quantthresh__44c3_s_p7_0,
  129643. _vq_quantmap__44c3_s_p7_0,
  129644. 3,
  129645. 3
  129646. };
  129647. static static_codebook _44c3_s_p7_0 = {
  129648. 4, 81,
  129649. _vq_lengthlist__44c3_s_p7_0,
  129650. 1, -529137664, 1618345984, 2, 0,
  129651. _vq_quantlist__44c3_s_p7_0,
  129652. NULL,
  129653. &_vq_auxt__44c3_s_p7_0,
  129654. NULL,
  129655. 0
  129656. };
  129657. static long _vq_quantlist__44c3_s_p7_1[] = {
  129658. 5,
  129659. 4,
  129660. 6,
  129661. 3,
  129662. 7,
  129663. 2,
  129664. 8,
  129665. 1,
  129666. 9,
  129667. 0,
  129668. 10,
  129669. };
  129670. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129671. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129672. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129673. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129674. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129675. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129676. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129677. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129678. 10,10,10, 8, 8, 8, 8, 8, 8,
  129679. };
  129680. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129681. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129682. 3.5, 4.5,
  129683. };
  129684. static long _vq_quantmap__44c3_s_p7_1[] = {
  129685. 9, 7, 5, 3, 1, 0, 2, 4,
  129686. 6, 8, 10,
  129687. };
  129688. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129689. _vq_quantthresh__44c3_s_p7_1,
  129690. _vq_quantmap__44c3_s_p7_1,
  129691. 11,
  129692. 11
  129693. };
  129694. static static_codebook _44c3_s_p7_1 = {
  129695. 2, 121,
  129696. _vq_lengthlist__44c3_s_p7_1,
  129697. 1, -531365888, 1611661312, 4, 0,
  129698. _vq_quantlist__44c3_s_p7_1,
  129699. NULL,
  129700. &_vq_auxt__44c3_s_p7_1,
  129701. NULL,
  129702. 0
  129703. };
  129704. static long _vq_quantlist__44c3_s_p8_0[] = {
  129705. 6,
  129706. 5,
  129707. 7,
  129708. 4,
  129709. 8,
  129710. 3,
  129711. 9,
  129712. 2,
  129713. 10,
  129714. 1,
  129715. 11,
  129716. 0,
  129717. 12,
  129718. };
  129719. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129720. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129721. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129722. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129723. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129724. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129725. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129726. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129727. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129728. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129729. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129730. 0,13,13,12,12,13,12,14,13,
  129731. };
  129732. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129733. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129734. 12.5, 17.5, 22.5, 27.5,
  129735. };
  129736. static long _vq_quantmap__44c3_s_p8_0[] = {
  129737. 11, 9, 7, 5, 3, 1, 0, 2,
  129738. 4, 6, 8, 10, 12,
  129739. };
  129740. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129741. _vq_quantthresh__44c3_s_p8_0,
  129742. _vq_quantmap__44c3_s_p8_0,
  129743. 13,
  129744. 13
  129745. };
  129746. static static_codebook _44c3_s_p8_0 = {
  129747. 2, 169,
  129748. _vq_lengthlist__44c3_s_p8_0,
  129749. 1, -526516224, 1616117760, 4, 0,
  129750. _vq_quantlist__44c3_s_p8_0,
  129751. NULL,
  129752. &_vq_auxt__44c3_s_p8_0,
  129753. NULL,
  129754. 0
  129755. };
  129756. static long _vq_quantlist__44c3_s_p8_1[] = {
  129757. 2,
  129758. 1,
  129759. 3,
  129760. 0,
  129761. 4,
  129762. };
  129763. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129764. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129765. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129766. };
  129767. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129768. -1.5, -0.5, 0.5, 1.5,
  129769. };
  129770. static long _vq_quantmap__44c3_s_p8_1[] = {
  129771. 3, 1, 0, 2, 4,
  129772. };
  129773. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129774. _vq_quantthresh__44c3_s_p8_1,
  129775. _vq_quantmap__44c3_s_p8_1,
  129776. 5,
  129777. 5
  129778. };
  129779. static static_codebook _44c3_s_p8_1 = {
  129780. 2, 25,
  129781. _vq_lengthlist__44c3_s_p8_1,
  129782. 1, -533725184, 1611661312, 3, 0,
  129783. _vq_quantlist__44c3_s_p8_1,
  129784. NULL,
  129785. &_vq_auxt__44c3_s_p8_1,
  129786. NULL,
  129787. 0
  129788. };
  129789. static long _vq_quantlist__44c3_s_p9_0[] = {
  129790. 6,
  129791. 5,
  129792. 7,
  129793. 4,
  129794. 8,
  129795. 3,
  129796. 9,
  129797. 2,
  129798. 10,
  129799. 1,
  129800. 11,
  129801. 0,
  129802. 12,
  129803. };
  129804. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129805. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129806. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129807. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129808. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129809. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129810. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129811. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129812. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129813. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129815. 11,11,11,11,11,11,11,11,11,
  129816. };
  129817. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129818. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129819. 637.5, 892.5, 1147.5, 1402.5,
  129820. };
  129821. static long _vq_quantmap__44c3_s_p9_0[] = {
  129822. 11, 9, 7, 5, 3, 1, 0, 2,
  129823. 4, 6, 8, 10, 12,
  129824. };
  129825. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129826. _vq_quantthresh__44c3_s_p9_0,
  129827. _vq_quantmap__44c3_s_p9_0,
  129828. 13,
  129829. 13
  129830. };
  129831. static static_codebook _44c3_s_p9_0 = {
  129832. 2, 169,
  129833. _vq_lengthlist__44c3_s_p9_0,
  129834. 1, -514332672, 1627381760, 4, 0,
  129835. _vq_quantlist__44c3_s_p9_0,
  129836. NULL,
  129837. &_vq_auxt__44c3_s_p9_0,
  129838. NULL,
  129839. 0
  129840. };
  129841. static long _vq_quantlist__44c3_s_p9_1[] = {
  129842. 7,
  129843. 6,
  129844. 8,
  129845. 5,
  129846. 9,
  129847. 4,
  129848. 10,
  129849. 3,
  129850. 11,
  129851. 2,
  129852. 12,
  129853. 1,
  129854. 13,
  129855. 0,
  129856. 14,
  129857. };
  129858. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129859. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129860. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129861. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129862. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129863. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129864. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129865. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129866. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129867. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129868. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129869. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129870. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129871. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129872. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129873. 15,
  129874. };
  129875. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129876. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129877. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129878. };
  129879. static long _vq_quantmap__44c3_s_p9_1[] = {
  129880. 13, 11, 9, 7, 5, 3, 1, 0,
  129881. 2, 4, 6, 8, 10, 12, 14,
  129882. };
  129883. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129884. _vq_quantthresh__44c3_s_p9_1,
  129885. _vq_quantmap__44c3_s_p9_1,
  129886. 15,
  129887. 15
  129888. };
  129889. static static_codebook _44c3_s_p9_1 = {
  129890. 2, 225,
  129891. _vq_lengthlist__44c3_s_p9_1,
  129892. 1, -522338304, 1620115456, 4, 0,
  129893. _vq_quantlist__44c3_s_p9_1,
  129894. NULL,
  129895. &_vq_auxt__44c3_s_p9_1,
  129896. NULL,
  129897. 0
  129898. };
  129899. static long _vq_quantlist__44c3_s_p9_2[] = {
  129900. 8,
  129901. 7,
  129902. 9,
  129903. 6,
  129904. 10,
  129905. 5,
  129906. 11,
  129907. 4,
  129908. 12,
  129909. 3,
  129910. 13,
  129911. 2,
  129912. 14,
  129913. 1,
  129914. 15,
  129915. 0,
  129916. 16,
  129917. };
  129918. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129919. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129920. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129921. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129922. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129923. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129924. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129925. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129926. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129927. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129928. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129929. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129930. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129931. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129932. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129933. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129934. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129935. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129936. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129937. 10,
  129938. };
  129939. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129940. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129941. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129942. };
  129943. static long _vq_quantmap__44c3_s_p9_2[] = {
  129944. 15, 13, 11, 9, 7, 5, 3, 1,
  129945. 0, 2, 4, 6, 8, 10, 12, 14,
  129946. 16,
  129947. };
  129948. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129949. _vq_quantthresh__44c3_s_p9_2,
  129950. _vq_quantmap__44c3_s_p9_2,
  129951. 17,
  129952. 17
  129953. };
  129954. static static_codebook _44c3_s_p9_2 = {
  129955. 2, 289,
  129956. _vq_lengthlist__44c3_s_p9_2,
  129957. 1, -529530880, 1611661312, 5, 0,
  129958. _vq_quantlist__44c3_s_p9_2,
  129959. NULL,
  129960. &_vq_auxt__44c3_s_p9_2,
  129961. NULL,
  129962. 0
  129963. };
  129964. static long _huff_lengthlist__44c3_s_short[] = {
  129965. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129966. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129967. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129968. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129969. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129970. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129971. 6, 8, 9,11,
  129972. };
  129973. static static_codebook _huff_book__44c3_s_short = {
  129974. 2, 100,
  129975. _huff_lengthlist__44c3_s_short,
  129976. 0, 0, 0, 0, 0,
  129977. NULL,
  129978. NULL,
  129979. NULL,
  129980. NULL,
  129981. 0
  129982. };
  129983. static long _huff_lengthlist__44c4_s_long[] = {
  129984. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129985. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129986. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129987. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129988. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129989. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129990. 9, 8, 7, 7,
  129991. };
  129992. static static_codebook _huff_book__44c4_s_long = {
  129993. 2, 100,
  129994. _huff_lengthlist__44c4_s_long,
  129995. 0, 0, 0, 0, 0,
  129996. NULL,
  129997. NULL,
  129998. NULL,
  129999. NULL,
  130000. 0
  130001. };
  130002. static long _vq_quantlist__44c4_s_p1_0[] = {
  130003. 1,
  130004. 0,
  130005. 2,
  130006. };
  130007. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130008. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130009. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130013. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130014. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130018. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130019. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130054. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130059. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130064. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130100. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130105. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130110. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0,
  130419. };
  130420. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130421. -0.5, 0.5,
  130422. };
  130423. static long _vq_quantmap__44c4_s_p1_0[] = {
  130424. 1, 0, 2,
  130425. };
  130426. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130427. _vq_quantthresh__44c4_s_p1_0,
  130428. _vq_quantmap__44c4_s_p1_0,
  130429. 3,
  130430. 3
  130431. };
  130432. static static_codebook _44c4_s_p1_0 = {
  130433. 8, 6561,
  130434. _vq_lengthlist__44c4_s_p1_0,
  130435. 1, -535822336, 1611661312, 2, 0,
  130436. _vq_quantlist__44c4_s_p1_0,
  130437. NULL,
  130438. &_vq_auxt__44c4_s_p1_0,
  130439. NULL,
  130440. 0
  130441. };
  130442. static long _vq_quantlist__44c4_s_p2_0[] = {
  130443. 2,
  130444. 1,
  130445. 3,
  130446. 0,
  130447. 4,
  130448. };
  130449. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130450. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130451. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130452. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130453. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130454. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130460. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130461. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130462. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130468. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130469. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130476. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130477. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  130490. };
  130491. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130492. -1.5, -0.5, 0.5, 1.5,
  130493. };
  130494. static long _vq_quantmap__44c4_s_p2_0[] = {
  130495. 3, 1, 0, 2, 4,
  130496. };
  130497. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130498. _vq_quantthresh__44c4_s_p2_0,
  130499. _vq_quantmap__44c4_s_p2_0,
  130500. 5,
  130501. 5
  130502. };
  130503. static static_codebook _44c4_s_p2_0 = {
  130504. 4, 625,
  130505. _vq_lengthlist__44c4_s_p2_0,
  130506. 1, -533725184, 1611661312, 3, 0,
  130507. _vq_quantlist__44c4_s_p2_0,
  130508. NULL,
  130509. &_vq_auxt__44c4_s_p2_0,
  130510. NULL,
  130511. 0
  130512. };
  130513. static long _vq_quantlist__44c4_s_p3_0[] = {
  130514. 2,
  130515. 1,
  130516. 3,
  130517. 0,
  130518. 4,
  130519. };
  130520. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130521. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  130561. };
  130562. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130563. -1.5, -0.5, 0.5, 1.5,
  130564. };
  130565. static long _vq_quantmap__44c4_s_p3_0[] = {
  130566. 3, 1, 0, 2, 4,
  130567. };
  130568. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130569. _vq_quantthresh__44c4_s_p3_0,
  130570. _vq_quantmap__44c4_s_p3_0,
  130571. 5,
  130572. 5
  130573. };
  130574. static static_codebook _44c4_s_p3_0 = {
  130575. 4, 625,
  130576. _vq_lengthlist__44c4_s_p3_0,
  130577. 1, -533725184, 1611661312, 3, 0,
  130578. _vq_quantlist__44c4_s_p3_0,
  130579. NULL,
  130580. &_vq_auxt__44c4_s_p3_0,
  130581. NULL,
  130582. 0
  130583. };
  130584. static long _vq_quantlist__44c4_s_p4_0[] = {
  130585. 4,
  130586. 3,
  130587. 5,
  130588. 2,
  130589. 6,
  130590. 1,
  130591. 7,
  130592. 0,
  130593. 8,
  130594. };
  130595. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130596. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130597. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130598. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130599. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130600. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0,
  130602. };
  130603. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130604. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130605. };
  130606. static long _vq_quantmap__44c4_s_p4_0[] = {
  130607. 7, 5, 3, 1, 0, 2, 4, 6,
  130608. 8,
  130609. };
  130610. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130611. _vq_quantthresh__44c4_s_p4_0,
  130612. _vq_quantmap__44c4_s_p4_0,
  130613. 9,
  130614. 9
  130615. };
  130616. static static_codebook _44c4_s_p4_0 = {
  130617. 2, 81,
  130618. _vq_lengthlist__44c4_s_p4_0,
  130619. 1, -531628032, 1611661312, 4, 0,
  130620. _vq_quantlist__44c4_s_p4_0,
  130621. NULL,
  130622. &_vq_auxt__44c4_s_p4_0,
  130623. NULL,
  130624. 0
  130625. };
  130626. static long _vq_quantlist__44c4_s_p5_0[] = {
  130627. 4,
  130628. 3,
  130629. 5,
  130630. 2,
  130631. 6,
  130632. 1,
  130633. 7,
  130634. 0,
  130635. 8,
  130636. };
  130637. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130638. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130639. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130640. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130641. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130642. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130643. 10,
  130644. };
  130645. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130646. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130647. };
  130648. static long _vq_quantmap__44c4_s_p5_0[] = {
  130649. 7, 5, 3, 1, 0, 2, 4, 6,
  130650. 8,
  130651. };
  130652. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130653. _vq_quantthresh__44c4_s_p5_0,
  130654. _vq_quantmap__44c4_s_p5_0,
  130655. 9,
  130656. 9
  130657. };
  130658. static static_codebook _44c4_s_p5_0 = {
  130659. 2, 81,
  130660. _vq_lengthlist__44c4_s_p5_0,
  130661. 1, -531628032, 1611661312, 4, 0,
  130662. _vq_quantlist__44c4_s_p5_0,
  130663. NULL,
  130664. &_vq_auxt__44c4_s_p5_0,
  130665. NULL,
  130666. 0
  130667. };
  130668. static long _vq_quantlist__44c4_s_p6_0[] = {
  130669. 8,
  130670. 7,
  130671. 9,
  130672. 6,
  130673. 10,
  130674. 5,
  130675. 11,
  130676. 4,
  130677. 12,
  130678. 3,
  130679. 13,
  130680. 2,
  130681. 14,
  130682. 1,
  130683. 15,
  130684. 0,
  130685. 16,
  130686. };
  130687. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130688. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130689. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130690. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130691. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130692. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130693. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130694. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130695. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130696. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130697. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130698. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130699. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130700. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130701. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130702. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130703. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130704. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130706. 13,
  130707. };
  130708. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130709. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130710. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130711. };
  130712. static long _vq_quantmap__44c4_s_p6_0[] = {
  130713. 15, 13, 11, 9, 7, 5, 3, 1,
  130714. 0, 2, 4, 6, 8, 10, 12, 14,
  130715. 16,
  130716. };
  130717. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130718. _vq_quantthresh__44c4_s_p6_0,
  130719. _vq_quantmap__44c4_s_p6_0,
  130720. 17,
  130721. 17
  130722. };
  130723. static static_codebook _44c4_s_p6_0 = {
  130724. 2, 289,
  130725. _vq_lengthlist__44c4_s_p6_0,
  130726. 1, -529530880, 1611661312, 5, 0,
  130727. _vq_quantlist__44c4_s_p6_0,
  130728. NULL,
  130729. &_vq_auxt__44c4_s_p6_0,
  130730. NULL,
  130731. 0
  130732. };
  130733. static long _vq_quantlist__44c4_s_p7_0[] = {
  130734. 1,
  130735. 0,
  130736. 2,
  130737. };
  130738. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130739. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130740. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130741. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130742. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130743. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130744. 10,
  130745. };
  130746. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130747. -5.5, 5.5,
  130748. };
  130749. static long _vq_quantmap__44c4_s_p7_0[] = {
  130750. 1, 0, 2,
  130751. };
  130752. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130753. _vq_quantthresh__44c4_s_p7_0,
  130754. _vq_quantmap__44c4_s_p7_0,
  130755. 3,
  130756. 3
  130757. };
  130758. static static_codebook _44c4_s_p7_0 = {
  130759. 4, 81,
  130760. _vq_lengthlist__44c4_s_p7_0,
  130761. 1, -529137664, 1618345984, 2, 0,
  130762. _vq_quantlist__44c4_s_p7_0,
  130763. NULL,
  130764. &_vq_auxt__44c4_s_p7_0,
  130765. NULL,
  130766. 0
  130767. };
  130768. static long _vq_quantlist__44c4_s_p7_1[] = {
  130769. 5,
  130770. 4,
  130771. 6,
  130772. 3,
  130773. 7,
  130774. 2,
  130775. 8,
  130776. 1,
  130777. 9,
  130778. 0,
  130779. 10,
  130780. };
  130781. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130782. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130783. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130784. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130785. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130786. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130787. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130788. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130789. 10,10,10, 8, 8, 8, 8, 9, 9,
  130790. };
  130791. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130792. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130793. 3.5, 4.5,
  130794. };
  130795. static long _vq_quantmap__44c4_s_p7_1[] = {
  130796. 9, 7, 5, 3, 1, 0, 2, 4,
  130797. 6, 8, 10,
  130798. };
  130799. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130800. _vq_quantthresh__44c4_s_p7_1,
  130801. _vq_quantmap__44c4_s_p7_1,
  130802. 11,
  130803. 11
  130804. };
  130805. static static_codebook _44c4_s_p7_1 = {
  130806. 2, 121,
  130807. _vq_lengthlist__44c4_s_p7_1,
  130808. 1, -531365888, 1611661312, 4, 0,
  130809. _vq_quantlist__44c4_s_p7_1,
  130810. NULL,
  130811. &_vq_auxt__44c4_s_p7_1,
  130812. NULL,
  130813. 0
  130814. };
  130815. static long _vq_quantlist__44c4_s_p8_0[] = {
  130816. 6,
  130817. 5,
  130818. 7,
  130819. 4,
  130820. 8,
  130821. 3,
  130822. 9,
  130823. 2,
  130824. 10,
  130825. 1,
  130826. 11,
  130827. 0,
  130828. 12,
  130829. };
  130830. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130831. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130832. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130833. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130834. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130835. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130836. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130837. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130838. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130839. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130840. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130841. 0,13,12,12,12,12,12,13,13,
  130842. };
  130843. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130844. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130845. 12.5, 17.5, 22.5, 27.5,
  130846. };
  130847. static long _vq_quantmap__44c4_s_p8_0[] = {
  130848. 11, 9, 7, 5, 3, 1, 0, 2,
  130849. 4, 6, 8, 10, 12,
  130850. };
  130851. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130852. _vq_quantthresh__44c4_s_p8_0,
  130853. _vq_quantmap__44c4_s_p8_0,
  130854. 13,
  130855. 13
  130856. };
  130857. static static_codebook _44c4_s_p8_0 = {
  130858. 2, 169,
  130859. _vq_lengthlist__44c4_s_p8_0,
  130860. 1, -526516224, 1616117760, 4, 0,
  130861. _vq_quantlist__44c4_s_p8_0,
  130862. NULL,
  130863. &_vq_auxt__44c4_s_p8_0,
  130864. NULL,
  130865. 0
  130866. };
  130867. static long _vq_quantlist__44c4_s_p8_1[] = {
  130868. 2,
  130869. 1,
  130870. 3,
  130871. 0,
  130872. 4,
  130873. };
  130874. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130875. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130876. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130877. };
  130878. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130879. -1.5, -0.5, 0.5, 1.5,
  130880. };
  130881. static long _vq_quantmap__44c4_s_p8_1[] = {
  130882. 3, 1, 0, 2, 4,
  130883. };
  130884. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130885. _vq_quantthresh__44c4_s_p8_1,
  130886. _vq_quantmap__44c4_s_p8_1,
  130887. 5,
  130888. 5
  130889. };
  130890. static static_codebook _44c4_s_p8_1 = {
  130891. 2, 25,
  130892. _vq_lengthlist__44c4_s_p8_1,
  130893. 1, -533725184, 1611661312, 3, 0,
  130894. _vq_quantlist__44c4_s_p8_1,
  130895. NULL,
  130896. &_vq_auxt__44c4_s_p8_1,
  130897. NULL,
  130898. 0
  130899. };
  130900. static long _vq_quantlist__44c4_s_p9_0[] = {
  130901. 6,
  130902. 5,
  130903. 7,
  130904. 4,
  130905. 8,
  130906. 3,
  130907. 9,
  130908. 2,
  130909. 10,
  130910. 1,
  130911. 11,
  130912. 0,
  130913. 12,
  130914. };
  130915. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130916. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130917. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130918. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130919. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130920. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130921. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130922. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130923. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130924. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130925. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130926. 12,12,12,12,12,12,12,12,12,
  130927. };
  130928. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130929. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130930. 787.5, 1102.5, 1417.5, 1732.5,
  130931. };
  130932. static long _vq_quantmap__44c4_s_p9_0[] = {
  130933. 11, 9, 7, 5, 3, 1, 0, 2,
  130934. 4, 6, 8, 10, 12,
  130935. };
  130936. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130937. _vq_quantthresh__44c4_s_p9_0,
  130938. _vq_quantmap__44c4_s_p9_0,
  130939. 13,
  130940. 13
  130941. };
  130942. static static_codebook _44c4_s_p9_0 = {
  130943. 2, 169,
  130944. _vq_lengthlist__44c4_s_p9_0,
  130945. 1, -513964032, 1628680192, 4, 0,
  130946. _vq_quantlist__44c4_s_p9_0,
  130947. NULL,
  130948. &_vq_auxt__44c4_s_p9_0,
  130949. NULL,
  130950. 0
  130951. };
  130952. static long _vq_quantlist__44c4_s_p9_1[] = {
  130953. 7,
  130954. 6,
  130955. 8,
  130956. 5,
  130957. 9,
  130958. 4,
  130959. 10,
  130960. 3,
  130961. 11,
  130962. 2,
  130963. 12,
  130964. 1,
  130965. 13,
  130966. 0,
  130967. 14,
  130968. };
  130969. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130970. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130971. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130972. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130973. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130974. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130975. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130976. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130977. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130978. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130979. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130980. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130981. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130982. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130983. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130984. 15,
  130985. };
  130986. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130987. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130988. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130989. };
  130990. static long _vq_quantmap__44c4_s_p9_1[] = {
  130991. 13, 11, 9, 7, 5, 3, 1, 0,
  130992. 2, 4, 6, 8, 10, 12, 14,
  130993. };
  130994. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130995. _vq_quantthresh__44c4_s_p9_1,
  130996. _vq_quantmap__44c4_s_p9_1,
  130997. 15,
  130998. 15
  130999. };
  131000. static static_codebook _44c4_s_p9_1 = {
  131001. 2, 225,
  131002. _vq_lengthlist__44c4_s_p9_1,
  131003. 1, -520986624, 1620377600, 4, 0,
  131004. _vq_quantlist__44c4_s_p9_1,
  131005. NULL,
  131006. &_vq_auxt__44c4_s_p9_1,
  131007. NULL,
  131008. 0
  131009. };
  131010. static long _vq_quantlist__44c4_s_p9_2[] = {
  131011. 10,
  131012. 9,
  131013. 11,
  131014. 8,
  131015. 12,
  131016. 7,
  131017. 13,
  131018. 6,
  131019. 14,
  131020. 5,
  131021. 15,
  131022. 4,
  131023. 16,
  131024. 3,
  131025. 17,
  131026. 2,
  131027. 18,
  131028. 1,
  131029. 19,
  131030. 0,
  131031. 20,
  131032. };
  131033. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131034. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131035. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131036. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131037. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131038. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131039. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131040. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131041. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131042. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131043. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131044. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131045. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131046. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131047. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131048. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131049. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131050. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131051. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131052. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131053. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131054. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131055. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131056. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131057. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131058. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131059. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131060. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131061. 10,10,10,10,10,10,10,10,10,
  131062. };
  131063. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131064. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131065. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131066. 6.5, 7.5, 8.5, 9.5,
  131067. };
  131068. static long _vq_quantmap__44c4_s_p9_2[] = {
  131069. 19, 17, 15, 13, 11, 9, 7, 5,
  131070. 3, 1, 0, 2, 4, 6, 8, 10,
  131071. 12, 14, 16, 18, 20,
  131072. };
  131073. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131074. _vq_quantthresh__44c4_s_p9_2,
  131075. _vq_quantmap__44c4_s_p9_2,
  131076. 21,
  131077. 21
  131078. };
  131079. static static_codebook _44c4_s_p9_2 = {
  131080. 2, 441,
  131081. _vq_lengthlist__44c4_s_p9_2,
  131082. 1, -529268736, 1611661312, 5, 0,
  131083. _vq_quantlist__44c4_s_p9_2,
  131084. NULL,
  131085. &_vq_auxt__44c4_s_p9_2,
  131086. NULL,
  131087. 0
  131088. };
  131089. static long _huff_lengthlist__44c4_s_short[] = {
  131090. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131091. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131092. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131093. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131094. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131095. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131096. 7, 9,12,17,
  131097. };
  131098. static static_codebook _huff_book__44c4_s_short = {
  131099. 2, 100,
  131100. _huff_lengthlist__44c4_s_short,
  131101. 0, 0, 0, 0, 0,
  131102. NULL,
  131103. NULL,
  131104. NULL,
  131105. NULL,
  131106. 0
  131107. };
  131108. static long _huff_lengthlist__44c5_s_long[] = {
  131109. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131110. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131111. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131112. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131113. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131114. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131115. 9, 8, 7, 7,
  131116. };
  131117. static static_codebook _huff_book__44c5_s_long = {
  131118. 2, 100,
  131119. _huff_lengthlist__44c5_s_long,
  131120. 0, 0, 0, 0, 0,
  131121. NULL,
  131122. NULL,
  131123. NULL,
  131124. NULL,
  131125. 0
  131126. };
  131127. static long _vq_quantlist__44c5_s_p1_0[] = {
  131128. 1,
  131129. 0,
  131130. 2,
  131131. };
  131132. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131133. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131134. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131139. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131144. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131179. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131184. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131189. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131225. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131230. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131235. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  131544. };
  131545. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131546. -0.5, 0.5,
  131547. };
  131548. static long _vq_quantmap__44c5_s_p1_0[] = {
  131549. 1, 0, 2,
  131550. };
  131551. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131552. _vq_quantthresh__44c5_s_p1_0,
  131553. _vq_quantmap__44c5_s_p1_0,
  131554. 3,
  131555. 3
  131556. };
  131557. static static_codebook _44c5_s_p1_0 = {
  131558. 8, 6561,
  131559. _vq_lengthlist__44c5_s_p1_0,
  131560. 1, -535822336, 1611661312, 2, 0,
  131561. _vq_quantlist__44c5_s_p1_0,
  131562. NULL,
  131563. &_vq_auxt__44c5_s_p1_0,
  131564. NULL,
  131565. 0
  131566. };
  131567. static long _vq_quantlist__44c5_s_p2_0[] = {
  131568. 2,
  131569. 1,
  131570. 3,
  131571. 0,
  131572. 4,
  131573. };
  131574. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131575. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131576. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131577. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131578. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131579. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131585. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131586. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131587. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131593. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131594. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131601. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131602. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  131615. };
  131616. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131617. -1.5, -0.5, 0.5, 1.5,
  131618. };
  131619. static long _vq_quantmap__44c5_s_p2_0[] = {
  131620. 3, 1, 0, 2, 4,
  131621. };
  131622. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131623. _vq_quantthresh__44c5_s_p2_0,
  131624. _vq_quantmap__44c5_s_p2_0,
  131625. 5,
  131626. 5
  131627. };
  131628. static static_codebook _44c5_s_p2_0 = {
  131629. 4, 625,
  131630. _vq_lengthlist__44c5_s_p2_0,
  131631. 1, -533725184, 1611661312, 3, 0,
  131632. _vq_quantlist__44c5_s_p2_0,
  131633. NULL,
  131634. &_vq_auxt__44c5_s_p2_0,
  131635. NULL,
  131636. 0
  131637. };
  131638. static long _vq_quantlist__44c5_s_p3_0[] = {
  131639. 2,
  131640. 1,
  131641. 3,
  131642. 0,
  131643. 4,
  131644. };
  131645. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131646. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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,
  131686. };
  131687. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131688. -1.5, -0.5, 0.5, 1.5,
  131689. };
  131690. static long _vq_quantmap__44c5_s_p3_0[] = {
  131691. 3, 1, 0, 2, 4,
  131692. };
  131693. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131694. _vq_quantthresh__44c5_s_p3_0,
  131695. _vq_quantmap__44c5_s_p3_0,
  131696. 5,
  131697. 5
  131698. };
  131699. static static_codebook _44c5_s_p3_0 = {
  131700. 4, 625,
  131701. _vq_lengthlist__44c5_s_p3_0,
  131702. 1, -533725184, 1611661312, 3, 0,
  131703. _vq_quantlist__44c5_s_p3_0,
  131704. NULL,
  131705. &_vq_auxt__44c5_s_p3_0,
  131706. NULL,
  131707. 0
  131708. };
  131709. static long _vq_quantlist__44c5_s_p4_0[] = {
  131710. 4,
  131711. 3,
  131712. 5,
  131713. 2,
  131714. 6,
  131715. 1,
  131716. 7,
  131717. 0,
  131718. 8,
  131719. };
  131720. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131721. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131722. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131723. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131724. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131725. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0,
  131727. };
  131728. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131729. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131730. };
  131731. static long _vq_quantmap__44c5_s_p4_0[] = {
  131732. 7, 5, 3, 1, 0, 2, 4, 6,
  131733. 8,
  131734. };
  131735. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131736. _vq_quantthresh__44c5_s_p4_0,
  131737. _vq_quantmap__44c5_s_p4_0,
  131738. 9,
  131739. 9
  131740. };
  131741. static static_codebook _44c5_s_p4_0 = {
  131742. 2, 81,
  131743. _vq_lengthlist__44c5_s_p4_0,
  131744. 1, -531628032, 1611661312, 4, 0,
  131745. _vq_quantlist__44c5_s_p4_0,
  131746. NULL,
  131747. &_vq_auxt__44c5_s_p4_0,
  131748. NULL,
  131749. 0
  131750. };
  131751. static long _vq_quantlist__44c5_s_p5_0[] = {
  131752. 4,
  131753. 3,
  131754. 5,
  131755. 2,
  131756. 6,
  131757. 1,
  131758. 7,
  131759. 0,
  131760. 8,
  131761. };
  131762. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131763. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131764. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131765. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131766. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131767. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131768. 10,
  131769. };
  131770. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131771. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131772. };
  131773. static long _vq_quantmap__44c5_s_p5_0[] = {
  131774. 7, 5, 3, 1, 0, 2, 4, 6,
  131775. 8,
  131776. };
  131777. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131778. _vq_quantthresh__44c5_s_p5_0,
  131779. _vq_quantmap__44c5_s_p5_0,
  131780. 9,
  131781. 9
  131782. };
  131783. static static_codebook _44c5_s_p5_0 = {
  131784. 2, 81,
  131785. _vq_lengthlist__44c5_s_p5_0,
  131786. 1, -531628032, 1611661312, 4, 0,
  131787. _vq_quantlist__44c5_s_p5_0,
  131788. NULL,
  131789. &_vq_auxt__44c5_s_p5_0,
  131790. NULL,
  131791. 0
  131792. };
  131793. static long _vq_quantlist__44c5_s_p6_0[] = {
  131794. 8,
  131795. 7,
  131796. 9,
  131797. 6,
  131798. 10,
  131799. 5,
  131800. 11,
  131801. 4,
  131802. 12,
  131803. 3,
  131804. 13,
  131805. 2,
  131806. 14,
  131807. 1,
  131808. 15,
  131809. 0,
  131810. 16,
  131811. };
  131812. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131813. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131814. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131815. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131816. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131817. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131818. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131819. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131820. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131821. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131822. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131823. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131824. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131825. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131826. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131827. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131828. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131829. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131831. 13,
  131832. };
  131833. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131834. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131835. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131836. };
  131837. static long _vq_quantmap__44c5_s_p6_0[] = {
  131838. 15, 13, 11, 9, 7, 5, 3, 1,
  131839. 0, 2, 4, 6, 8, 10, 12, 14,
  131840. 16,
  131841. };
  131842. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131843. _vq_quantthresh__44c5_s_p6_0,
  131844. _vq_quantmap__44c5_s_p6_0,
  131845. 17,
  131846. 17
  131847. };
  131848. static static_codebook _44c5_s_p6_0 = {
  131849. 2, 289,
  131850. _vq_lengthlist__44c5_s_p6_0,
  131851. 1, -529530880, 1611661312, 5, 0,
  131852. _vq_quantlist__44c5_s_p6_0,
  131853. NULL,
  131854. &_vq_auxt__44c5_s_p6_0,
  131855. NULL,
  131856. 0
  131857. };
  131858. static long _vq_quantlist__44c5_s_p7_0[] = {
  131859. 1,
  131860. 0,
  131861. 2,
  131862. };
  131863. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131864. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131865. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131866. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131867. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131868. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131869. 10,
  131870. };
  131871. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131872. -5.5, 5.5,
  131873. };
  131874. static long _vq_quantmap__44c5_s_p7_0[] = {
  131875. 1, 0, 2,
  131876. };
  131877. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131878. _vq_quantthresh__44c5_s_p7_0,
  131879. _vq_quantmap__44c5_s_p7_0,
  131880. 3,
  131881. 3
  131882. };
  131883. static static_codebook _44c5_s_p7_0 = {
  131884. 4, 81,
  131885. _vq_lengthlist__44c5_s_p7_0,
  131886. 1, -529137664, 1618345984, 2, 0,
  131887. _vq_quantlist__44c5_s_p7_0,
  131888. NULL,
  131889. &_vq_auxt__44c5_s_p7_0,
  131890. NULL,
  131891. 0
  131892. };
  131893. static long _vq_quantlist__44c5_s_p7_1[] = {
  131894. 5,
  131895. 4,
  131896. 6,
  131897. 3,
  131898. 7,
  131899. 2,
  131900. 8,
  131901. 1,
  131902. 9,
  131903. 0,
  131904. 10,
  131905. };
  131906. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131907. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131908. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131909. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131910. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131911. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131912. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131913. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131914. 10,10,10, 8, 8, 8, 8, 8, 8,
  131915. };
  131916. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131917. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131918. 3.5, 4.5,
  131919. };
  131920. static long _vq_quantmap__44c5_s_p7_1[] = {
  131921. 9, 7, 5, 3, 1, 0, 2, 4,
  131922. 6, 8, 10,
  131923. };
  131924. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131925. _vq_quantthresh__44c5_s_p7_1,
  131926. _vq_quantmap__44c5_s_p7_1,
  131927. 11,
  131928. 11
  131929. };
  131930. static static_codebook _44c5_s_p7_1 = {
  131931. 2, 121,
  131932. _vq_lengthlist__44c5_s_p7_1,
  131933. 1, -531365888, 1611661312, 4, 0,
  131934. _vq_quantlist__44c5_s_p7_1,
  131935. NULL,
  131936. &_vq_auxt__44c5_s_p7_1,
  131937. NULL,
  131938. 0
  131939. };
  131940. static long _vq_quantlist__44c5_s_p8_0[] = {
  131941. 6,
  131942. 5,
  131943. 7,
  131944. 4,
  131945. 8,
  131946. 3,
  131947. 9,
  131948. 2,
  131949. 10,
  131950. 1,
  131951. 11,
  131952. 0,
  131953. 12,
  131954. };
  131955. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131956. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131957. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131958. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131959. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131960. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131961. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131962. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131963. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131964. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131965. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131966. 0,12,12,12,12,12,12,13,13,
  131967. };
  131968. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131969. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131970. 12.5, 17.5, 22.5, 27.5,
  131971. };
  131972. static long _vq_quantmap__44c5_s_p8_0[] = {
  131973. 11, 9, 7, 5, 3, 1, 0, 2,
  131974. 4, 6, 8, 10, 12,
  131975. };
  131976. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131977. _vq_quantthresh__44c5_s_p8_0,
  131978. _vq_quantmap__44c5_s_p8_0,
  131979. 13,
  131980. 13
  131981. };
  131982. static static_codebook _44c5_s_p8_0 = {
  131983. 2, 169,
  131984. _vq_lengthlist__44c5_s_p8_0,
  131985. 1, -526516224, 1616117760, 4, 0,
  131986. _vq_quantlist__44c5_s_p8_0,
  131987. NULL,
  131988. &_vq_auxt__44c5_s_p8_0,
  131989. NULL,
  131990. 0
  131991. };
  131992. static long _vq_quantlist__44c5_s_p8_1[] = {
  131993. 2,
  131994. 1,
  131995. 3,
  131996. 0,
  131997. 4,
  131998. };
  131999. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132000. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132001. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132002. };
  132003. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132004. -1.5, -0.5, 0.5, 1.5,
  132005. };
  132006. static long _vq_quantmap__44c5_s_p8_1[] = {
  132007. 3, 1, 0, 2, 4,
  132008. };
  132009. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132010. _vq_quantthresh__44c5_s_p8_1,
  132011. _vq_quantmap__44c5_s_p8_1,
  132012. 5,
  132013. 5
  132014. };
  132015. static static_codebook _44c5_s_p8_1 = {
  132016. 2, 25,
  132017. _vq_lengthlist__44c5_s_p8_1,
  132018. 1, -533725184, 1611661312, 3, 0,
  132019. _vq_quantlist__44c5_s_p8_1,
  132020. NULL,
  132021. &_vq_auxt__44c5_s_p8_1,
  132022. NULL,
  132023. 0
  132024. };
  132025. static long _vq_quantlist__44c5_s_p9_0[] = {
  132026. 7,
  132027. 6,
  132028. 8,
  132029. 5,
  132030. 9,
  132031. 4,
  132032. 10,
  132033. 3,
  132034. 11,
  132035. 2,
  132036. 12,
  132037. 1,
  132038. 13,
  132039. 0,
  132040. 14,
  132041. };
  132042. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132043. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132044. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132045. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132046. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132047. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132048. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132049. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132050. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132051. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132052. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132053. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132054. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132055. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132056. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132057. 12,
  132058. };
  132059. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132060. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132061. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132062. };
  132063. static long _vq_quantmap__44c5_s_p9_0[] = {
  132064. 13, 11, 9, 7, 5, 3, 1, 0,
  132065. 2, 4, 6, 8, 10, 12, 14,
  132066. };
  132067. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132068. _vq_quantthresh__44c5_s_p9_0,
  132069. _vq_quantmap__44c5_s_p9_0,
  132070. 15,
  132071. 15
  132072. };
  132073. static static_codebook _44c5_s_p9_0 = {
  132074. 2, 225,
  132075. _vq_lengthlist__44c5_s_p9_0,
  132076. 1, -512522752, 1628852224, 4, 0,
  132077. _vq_quantlist__44c5_s_p9_0,
  132078. NULL,
  132079. &_vq_auxt__44c5_s_p9_0,
  132080. NULL,
  132081. 0
  132082. };
  132083. static long _vq_quantlist__44c5_s_p9_1[] = {
  132084. 8,
  132085. 7,
  132086. 9,
  132087. 6,
  132088. 10,
  132089. 5,
  132090. 11,
  132091. 4,
  132092. 12,
  132093. 3,
  132094. 13,
  132095. 2,
  132096. 14,
  132097. 1,
  132098. 15,
  132099. 0,
  132100. 16,
  132101. };
  132102. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132103. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132104. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132105. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132106. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132107. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132108. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132109. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132110. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132111. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132112. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132113. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132114. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132115. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132116. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132117. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132118. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132119. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132120. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132121. 15,
  132122. };
  132123. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132124. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132125. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132126. };
  132127. static long _vq_quantmap__44c5_s_p9_1[] = {
  132128. 15, 13, 11, 9, 7, 5, 3, 1,
  132129. 0, 2, 4, 6, 8, 10, 12, 14,
  132130. 16,
  132131. };
  132132. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132133. _vq_quantthresh__44c5_s_p9_1,
  132134. _vq_quantmap__44c5_s_p9_1,
  132135. 17,
  132136. 17
  132137. };
  132138. static static_codebook _44c5_s_p9_1 = {
  132139. 2, 289,
  132140. _vq_lengthlist__44c5_s_p9_1,
  132141. 1, -520814592, 1620377600, 5, 0,
  132142. _vq_quantlist__44c5_s_p9_1,
  132143. NULL,
  132144. &_vq_auxt__44c5_s_p9_1,
  132145. NULL,
  132146. 0
  132147. };
  132148. static long _vq_quantlist__44c5_s_p9_2[] = {
  132149. 10,
  132150. 9,
  132151. 11,
  132152. 8,
  132153. 12,
  132154. 7,
  132155. 13,
  132156. 6,
  132157. 14,
  132158. 5,
  132159. 15,
  132160. 4,
  132161. 16,
  132162. 3,
  132163. 17,
  132164. 2,
  132165. 18,
  132166. 1,
  132167. 19,
  132168. 0,
  132169. 20,
  132170. };
  132171. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132172. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132173. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132174. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132175. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132176. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132177. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132178. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132179. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132180. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132181. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132182. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132183. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132184. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132185. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132186. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132187. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132188. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132189. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132190. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132191. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132192. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132193. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132194. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132195. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132196. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132197. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132198. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132199. 10,10,10,10,10,10,10,10,10,
  132200. };
  132201. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132202. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132203. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132204. 6.5, 7.5, 8.5, 9.5,
  132205. };
  132206. static long _vq_quantmap__44c5_s_p9_2[] = {
  132207. 19, 17, 15, 13, 11, 9, 7, 5,
  132208. 3, 1, 0, 2, 4, 6, 8, 10,
  132209. 12, 14, 16, 18, 20,
  132210. };
  132211. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132212. _vq_quantthresh__44c5_s_p9_2,
  132213. _vq_quantmap__44c5_s_p9_2,
  132214. 21,
  132215. 21
  132216. };
  132217. static static_codebook _44c5_s_p9_2 = {
  132218. 2, 441,
  132219. _vq_lengthlist__44c5_s_p9_2,
  132220. 1, -529268736, 1611661312, 5, 0,
  132221. _vq_quantlist__44c5_s_p9_2,
  132222. NULL,
  132223. &_vq_auxt__44c5_s_p9_2,
  132224. NULL,
  132225. 0
  132226. };
  132227. static long _huff_lengthlist__44c5_s_short[] = {
  132228. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132229. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132230. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132231. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132232. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132233. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132234. 6, 8,11,16,
  132235. };
  132236. static static_codebook _huff_book__44c5_s_short = {
  132237. 2, 100,
  132238. _huff_lengthlist__44c5_s_short,
  132239. 0, 0, 0, 0, 0,
  132240. NULL,
  132241. NULL,
  132242. NULL,
  132243. NULL,
  132244. 0
  132245. };
  132246. static long _huff_lengthlist__44c6_s_long[] = {
  132247. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132248. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132249. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132250. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132251. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132252. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132253. 11,10,10,12,
  132254. };
  132255. static static_codebook _huff_book__44c6_s_long = {
  132256. 2, 100,
  132257. _huff_lengthlist__44c6_s_long,
  132258. 0, 0, 0, 0, 0,
  132259. NULL,
  132260. NULL,
  132261. NULL,
  132262. NULL,
  132263. 0
  132264. };
  132265. static long _vq_quantlist__44c6_s_p1_0[] = {
  132266. 1,
  132267. 0,
  132268. 2,
  132269. };
  132270. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132271. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132272. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132273. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132274. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132275. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132276. 8,
  132277. };
  132278. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132279. -0.5, 0.5,
  132280. };
  132281. static long _vq_quantmap__44c6_s_p1_0[] = {
  132282. 1, 0, 2,
  132283. };
  132284. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132285. _vq_quantthresh__44c6_s_p1_0,
  132286. _vq_quantmap__44c6_s_p1_0,
  132287. 3,
  132288. 3
  132289. };
  132290. static static_codebook _44c6_s_p1_0 = {
  132291. 4, 81,
  132292. _vq_lengthlist__44c6_s_p1_0,
  132293. 1, -535822336, 1611661312, 2, 0,
  132294. _vq_quantlist__44c6_s_p1_0,
  132295. NULL,
  132296. &_vq_auxt__44c6_s_p1_0,
  132297. NULL,
  132298. 0
  132299. };
  132300. static long _vq_quantlist__44c6_s_p2_0[] = {
  132301. 2,
  132302. 1,
  132303. 3,
  132304. 0,
  132305. 4,
  132306. };
  132307. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132308. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132309. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132310. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132311. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132312. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132313. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132314. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132315. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132317. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132318. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132319. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132320. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132321. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132322. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132323. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132325. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132326. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132327. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132328. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132329. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132330. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132331. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132333. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132334. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132335. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132336. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132337. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132338. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132339. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132344. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132345. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132346. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132347. 13,
  132348. };
  132349. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132350. -1.5, -0.5, 0.5, 1.5,
  132351. };
  132352. static long _vq_quantmap__44c6_s_p2_0[] = {
  132353. 3, 1, 0, 2, 4,
  132354. };
  132355. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132356. _vq_quantthresh__44c6_s_p2_0,
  132357. _vq_quantmap__44c6_s_p2_0,
  132358. 5,
  132359. 5
  132360. };
  132361. static static_codebook _44c6_s_p2_0 = {
  132362. 4, 625,
  132363. _vq_lengthlist__44c6_s_p2_0,
  132364. 1, -533725184, 1611661312, 3, 0,
  132365. _vq_quantlist__44c6_s_p2_0,
  132366. NULL,
  132367. &_vq_auxt__44c6_s_p2_0,
  132368. NULL,
  132369. 0
  132370. };
  132371. static long _vq_quantlist__44c6_s_p3_0[] = {
  132372. 4,
  132373. 3,
  132374. 5,
  132375. 2,
  132376. 6,
  132377. 1,
  132378. 7,
  132379. 0,
  132380. 8,
  132381. };
  132382. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132383. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132384. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132385. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132386. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132388. 0,
  132389. };
  132390. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132391. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132392. };
  132393. static long _vq_quantmap__44c6_s_p3_0[] = {
  132394. 7, 5, 3, 1, 0, 2, 4, 6,
  132395. 8,
  132396. };
  132397. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132398. _vq_quantthresh__44c6_s_p3_0,
  132399. _vq_quantmap__44c6_s_p3_0,
  132400. 9,
  132401. 9
  132402. };
  132403. static static_codebook _44c6_s_p3_0 = {
  132404. 2, 81,
  132405. _vq_lengthlist__44c6_s_p3_0,
  132406. 1, -531628032, 1611661312, 4, 0,
  132407. _vq_quantlist__44c6_s_p3_0,
  132408. NULL,
  132409. &_vq_auxt__44c6_s_p3_0,
  132410. NULL,
  132411. 0
  132412. };
  132413. static long _vq_quantlist__44c6_s_p4_0[] = {
  132414. 8,
  132415. 7,
  132416. 9,
  132417. 6,
  132418. 10,
  132419. 5,
  132420. 11,
  132421. 4,
  132422. 12,
  132423. 3,
  132424. 13,
  132425. 2,
  132426. 14,
  132427. 1,
  132428. 15,
  132429. 0,
  132430. 16,
  132431. };
  132432. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132433. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132434. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132435. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132436. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132437. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132438. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132439. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132440. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132441. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132442. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132451. 0,
  132452. };
  132453. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132454. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132455. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132456. };
  132457. static long _vq_quantmap__44c6_s_p4_0[] = {
  132458. 15, 13, 11, 9, 7, 5, 3, 1,
  132459. 0, 2, 4, 6, 8, 10, 12, 14,
  132460. 16,
  132461. };
  132462. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132463. _vq_quantthresh__44c6_s_p4_0,
  132464. _vq_quantmap__44c6_s_p4_0,
  132465. 17,
  132466. 17
  132467. };
  132468. static static_codebook _44c6_s_p4_0 = {
  132469. 2, 289,
  132470. _vq_lengthlist__44c6_s_p4_0,
  132471. 1, -529530880, 1611661312, 5, 0,
  132472. _vq_quantlist__44c6_s_p4_0,
  132473. NULL,
  132474. &_vq_auxt__44c6_s_p4_0,
  132475. NULL,
  132476. 0
  132477. };
  132478. static long _vq_quantlist__44c6_s_p5_0[] = {
  132479. 1,
  132480. 0,
  132481. 2,
  132482. };
  132483. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132484. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132485. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132486. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132487. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132488. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132489. 12,
  132490. };
  132491. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132492. -5.5, 5.5,
  132493. };
  132494. static long _vq_quantmap__44c6_s_p5_0[] = {
  132495. 1, 0, 2,
  132496. };
  132497. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132498. _vq_quantthresh__44c6_s_p5_0,
  132499. _vq_quantmap__44c6_s_p5_0,
  132500. 3,
  132501. 3
  132502. };
  132503. static static_codebook _44c6_s_p5_0 = {
  132504. 4, 81,
  132505. _vq_lengthlist__44c6_s_p5_0,
  132506. 1, -529137664, 1618345984, 2, 0,
  132507. _vq_quantlist__44c6_s_p5_0,
  132508. NULL,
  132509. &_vq_auxt__44c6_s_p5_0,
  132510. NULL,
  132511. 0
  132512. };
  132513. static long _vq_quantlist__44c6_s_p5_1[] = {
  132514. 5,
  132515. 4,
  132516. 6,
  132517. 3,
  132518. 7,
  132519. 2,
  132520. 8,
  132521. 1,
  132522. 9,
  132523. 0,
  132524. 10,
  132525. };
  132526. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132527. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132528. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132529. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132530. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132531. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132532. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132533. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132534. 11,10,10, 7, 7, 8, 8, 8, 8,
  132535. };
  132536. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132537. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132538. 3.5, 4.5,
  132539. };
  132540. static long _vq_quantmap__44c6_s_p5_1[] = {
  132541. 9, 7, 5, 3, 1, 0, 2, 4,
  132542. 6, 8, 10,
  132543. };
  132544. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132545. _vq_quantthresh__44c6_s_p5_1,
  132546. _vq_quantmap__44c6_s_p5_1,
  132547. 11,
  132548. 11
  132549. };
  132550. static static_codebook _44c6_s_p5_1 = {
  132551. 2, 121,
  132552. _vq_lengthlist__44c6_s_p5_1,
  132553. 1, -531365888, 1611661312, 4, 0,
  132554. _vq_quantlist__44c6_s_p5_1,
  132555. NULL,
  132556. &_vq_auxt__44c6_s_p5_1,
  132557. NULL,
  132558. 0
  132559. };
  132560. static long _vq_quantlist__44c6_s_p6_0[] = {
  132561. 6,
  132562. 5,
  132563. 7,
  132564. 4,
  132565. 8,
  132566. 3,
  132567. 9,
  132568. 2,
  132569. 10,
  132570. 1,
  132571. 11,
  132572. 0,
  132573. 12,
  132574. };
  132575. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132576. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132577. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132578. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132579. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132580. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132581. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132586. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132587. };
  132588. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132589. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132590. 12.5, 17.5, 22.5, 27.5,
  132591. };
  132592. static long _vq_quantmap__44c6_s_p6_0[] = {
  132593. 11, 9, 7, 5, 3, 1, 0, 2,
  132594. 4, 6, 8, 10, 12,
  132595. };
  132596. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132597. _vq_quantthresh__44c6_s_p6_0,
  132598. _vq_quantmap__44c6_s_p6_0,
  132599. 13,
  132600. 13
  132601. };
  132602. static static_codebook _44c6_s_p6_0 = {
  132603. 2, 169,
  132604. _vq_lengthlist__44c6_s_p6_0,
  132605. 1, -526516224, 1616117760, 4, 0,
  132606. _vq_quantlist__44c6_s_p6_0,
  132607. NULL,
  132608. &_vq_auxt__44c6_s_p6_0,
  132609. NULL,
  132610. 0
  132611. };
  132612. static long _vq_quantlist__44c6_s_p6_1[] = {
  132613. 2,
  132614. 1,
  132615. 3,
  132616. 0,
  132617. 4,
  132618. };
  132619. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132620. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132621. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132622. };
  132623. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132624. -1.5, -0.5, 0.5, 1.5,
  132625. };
  132626. static long _vq_quantmap__44c6_s_p6_1[] = {
  132627. 3, 1, 0, 2, 4,
  132628. };
  132629. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132630. _vq_quantthresh__44c6_s_p6_1,
  132631. _vq_quantmap__44c6_s_p6_1,
  132632. 5,
  132633. 5
  132634. };
  132635. static static_codebook _44c6_s_p6_1 = {
  132636. 2, 25,
  132637. _vq_lengthlist__44c6_s_p6_1,
  132638. 1, -533725184, 1611661312, 3, 0,
  132639. _vq_quantlist__44c6_s_p6_1,
  132640. NULL,
  132641. &_vq_auxt__44c6_s_p6_1,
  132642. NULL,
  132643. 0
  132644. };
  132645. static long _vq_quantlist__44c6_s_p7_0[] = {
  132646. 6,
  132647. 5,
  132648. 7,
  132649. 4,
  132650. 8,
  132651. 3,
  132652. 9,
  132653. 2,
  132654. 10,
  132655. 1,
  132656. 11,
  132657. 0,
  132658. 12,
  132659. };
  132660. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132661. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132662. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132663. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132664. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132665. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132666. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132667. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132668. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132669. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132670. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132671. 20,13,13,13,13,13,13,14,14,
  132672. };
  132673. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132674. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132675. 27.5, 38.5, 49.5, 60.5,
  132676. };
  132677. static long _vq_quantmap__44c6_s_p7_0[] = {
  132678. 11, 9, 7, 5, 3, 1, 0, 2,
  132679. 4, 6, 8, 10, 12,
  132680. };
  132681. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132682. _vq_quantthresh__44c6_s_p7_0,
  132683. _vq_quantmap__44c6_s_p7_0,
  132684. 13,
  132685. 13
  132686. };
  132687. static static_codebook _44c6_s_p7_0 = {
  132688. 2, 169,
  132689. _vq_lengthlist__44c6_s_p7_0,
  132690. 1, -523206656, 1618345984, 4, 0,
  132691. _vq_quantlist__44c6_s_p7_0,
  132692. NULL,
  132693. &_vq_auxt__44c6_s_p7_0,
  132694. NULL,
  132695. 0
  132696. };
  132697. static long _vq_quantlist__44c6_s_p7_1[] = {
  132698. 5,
  132699. 4,
  132700. 6,
  132701. 3,
  132702. 7,
  132703. 2,
  132704. 8,
  132705. 1,
  132706. 9,
  132707. 0,
  132708. 10,
  132709. };
  132710. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132711. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132712. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132713. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132714. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132715. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132716. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132717. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132718. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132719. };
  132720. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132721. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132722. 3.5, 4.5,
  132723. };
  132724. static long _vq_quantmap__44c6_s_p7_1[] = {
  132725. 9, 7, 5, 3, 1, 0, 2, 4,
  132726. 6, 8, 10,
  132727. };
  132728. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132729. _vq_quantthresh__44c6_s_p7_1,
  132730. _vq_quantmap__44c6_s_p7_1,
  132731. 11,
  132732. 11
  132733. };
  132734. static static_codebook _44c6_s_p7_1 = {
  132735. 2, 121,
  132736. _vq_lengthlist__44c6_s_p7_1,
  132737. 1, -531365888, 1611661312, 4, 0,
  132738. _vq_quantlist__44c6_s_p7_1,
  132739. NULL,
  132740. &_vq_auxt__44c6_s_p7_1,
  132741. NULL,
  132742. 0
  132743. };
  132744. static long _vq_quantlist__44c6_s_p8_0[] = {
  132745. 7,
  132746. 6,
  132747. 8,
  132748. 5,
  132749. 9,
  132750. 4,
  132751. 10,
  132752. 3,
  132753. 11,
  132754. 2,
  132755. 12,
  132756. 1,
  132757. 13,
  132758. 0,
  132759. 14,
  132760. };
  132761. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132762. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132763. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132764. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132765. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132766. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132767. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132768. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132769. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132770. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132771. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132772. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132773. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132774. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132775. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132776. 14,
  132777. };
  132778. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132779. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132780. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132781. };
  132782. static long _vq_quantmap__44c6_s_p8_0[] = {
  132783. 13, 11, 9, 7, 5, 3, 1, 0,
  132784. 2, 4, 6, 8, 10, 12, 14,
  132785. };
  132786. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132787. _vq_quantthresh__44c6_s_p8_0,
  132788. _vq_quantmap__44c6_s_p8_0,
  132789. 15,
  132790. 15
  132791. };
  132792. static static_codebook _44c6_s_p8_0 = {
  132793. 2, 225,
  132794. _vq_lengthlist__44c6_s_p8_0,
  132795. 1, -520986624, 1620377600, 4, 0,
  132796. _vq_quantlist__44c6_s_p8_0,
  132797. NULL,
  132798. &_vq_auxt__44c6_s_p8_0,
  132799. NULL,
  132800. 0
  132801. };
  132802. static long _vq_quantlist__44c6_s_p8_1[] = {
  132803. 10,
  132804. 9,
  132805. 11,
  132806. 8,
  132807. 12,
  132808. 7,
  132809. 13,
  132810. 6,
  132811. 14,
  132812. 5,
  132813. 15,
  132814. 4,
  132815. 16,
  132816. 3,
  132817. 17,
  132818. 2,
  132819. 18,
  132820. 1,
  132821. 19,
  132822. 0,
  132823. 20,
  132824. };
  132825. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132826. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132827. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132828. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132829. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132830. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132831. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132832. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132833. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132834. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132835. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132836. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132837. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132838. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132839. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132840. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132841. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132842. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132843. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132844. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132845. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132846. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132847. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132848. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132849. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132850. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132851. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132852. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132853. 10,10,10,10,10,10,10,10,10,
  132854. };
  132855. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132856. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132857. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132858. 6.5, 7.5, 8.5, 9.5,
  132859. };
  132860. static long _vq_quantmap__44c6_s_p8_1[] = {
  132861. 19, 17, 15, 13, 11, 9, 7, 5,
  132862. 3, 1, 0, 2, 4, 6, 8, 10,
  132863. 12, 14, 16, 18, 20,
  132864. };
  132865. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132866. _vq_quantthresh__44c6_s_p8_1,
  132867. _vq_quantmap__44c6_s_p8_1,
  132868. 21,
  132869. 21
  132870. };
  132871. static static_codebook _44c6_s_p8_1 = {
  132872. 2, 441,
  132873. _vq_lengthlist__44c6_s_p8_1,
  132874. 1, -529268736, 1611661312, 5, 0,
  132875. _vq_quantlist__44c6_s_p8_1,
  132876. NULL,
  132877. &_vq_auxt__44c6_s_p8_1,
  132878. NULL,
  132879. 0
  132880. };
  132881. static long _vq_quantlist__44c6_s_p9_0[] = {
  132882. 6,
  132883. 5,
  132884. 7,
  132885. 4,
  132886. 8,
  132887. 3,
  132888. 9,
  132889. 2,
  132890. 10,
  132891. 1,
  132892. 11,
  132893. 0,
  132894. 12,
  132895. };
  132896. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132897. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132898. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132899. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132900. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132901. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132902. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132903. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132904. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132905. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132906. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132907. 10,10,10,10,10,10,10,10,10,
  132908. };
  132909. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132910. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132911. 1592.5, 2229.5, 2866.5, 3503.5,
  132912. };
  132913. static long _vq_quantmap__44c6_s_p9_0[] = {
  132914. 11, 9, 7, 5, 3, 1, 0, 2,
  132915. 4, 6, 8, 10, 12,
  132916. };
  132917. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132918. _vq_quantthresh__44c6_s_p9_0,
  132919. _vq_quantmap__44c6_s_p9_0,
  132920. 13,
  132921. 13
  132922. };
  132923. static static_codebook _44c6_s_p9_0 = {
  132924. 2, 169,
  132925. _vq_lengthlist__44c6_s_p9_0,
  132926. 1, -511845376, 1630791680, 4, 0,
  132927. _vq_quantlist__44c6_s_p9_0,
  132928. NULL,
  132929. &_vq_auxt__44c6_s_p9_0,
  132930. NULL,
  132931. 0
  132932. };
  132933. static long _vq_quantlist__44c6_s_p9_1[] = {
  132934. 6,
  132935. 5,
  132936. 7,
  132937. 4,
  132938. 8,
  132939. 3,
  132940. 9,
  132941. 2,
  132942. 10,
  132943. 1,
  132944. 11,
  132945. 0,
  132946. 12,
  132947. };
  132948. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132949. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132950. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132951. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132952. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132953. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132954. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132955. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132956. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132957. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132958. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132959. 15,12,10,11,11,13,11,12,13,
  132960. };
  132961. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132962. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132963. 122.5, 171.5, 220.5, 269.5,
  132964. };
  132965. static long _vq_quantmap__44c6_s_p9_1[] = {
  132966. 11, 9, 7, 5, 3, 1, 0, 2,
  132967. 4, 6, 8, 10, 12,
  132968. };
  132969. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132970. _vq_quantthresh__44c6_s_p9_1,
  132971. _vq_quantmap__44c6_s_p9_1,
  132972. 13,
  132973. 13
  132974. };
  132975. static static_codebook _44c6_s_p9_1 = {
  132976. 2, 169,
  132977. _vq_lengthlist__44c6_s_p9_1,
  132978. 1, -518889472, 1622704128, 4, 0,
  132979. _vq_quantlist__44c6_s_p9_1,
  132980. NULL,
  132981. &_vq_auxt__44c6_s_p9_1,
  132982. NULL,
  132983. 0
  132984. };
  132985. static long _vq_quantlist__44c6_s_p9_2[] = {
  132986. 24,
  132987. 23,
  132988. 25,
  132989. 22,
  132990. 26,
  132991. 21,
  132992. 27,
  132993. 20,
  132994. 28,
  132995. 19,
  132996. 29,
  132997. 18,
  132998. 30,
  132999. 17,
  133000. 31,
  133001. 16,
  133002. 32,
  133003. 15,
  133004. 33,
  133005. 14,
  133006. 34,
  133007. 13,
  133008. 35,
  133009. 12,
  133010. 36,
  133011. 11,
  133012. 37,
  133013. 10,
  133014. 38,
  133015. 9,
  133016. 39,
  133017. 8,
  133018. 40,
  133019. 7,
  133020. 41,
  133021. 6,
  133022. 42,
  133023. 5,
  133024. 43,
  133025. 4,
  133026. 44,
  133027. 3,
  133028. 45,
  133029. 2,
  133030. 46,
  133031. 1,
  133032. 47,
  133033. 0,
  133034. 48,
  133035. };
  133036. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133037. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133038. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133039. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133040. 7,
  133041. };
  133042. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133043. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133044. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133045. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133046. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133047. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133048. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133049. };
  133050. static long _vq_quantmap__44c6_s_p9_2[] = {
  133051. 47, 45, 43, 41, 39, 37, 35, 33,
  133052. 31, 29, 27, 25, 23, 21, 19, 17,
  133053. 15, 13, 11, 9, 7, 5, 3, 1,
  133054. 0, 2, 4, 6, 8, 10, 12, 14,
  133055. 16, 18, 20, 22, 24, 26, 28, 30,
  133056. 32, 34, 36, 38, 40, 42, 44, 46,
  133057. 48,
  133058. };
  133059. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133060. _vq_quantthresh__44c6_s_p9_2,
  133061. _vq_quantmap__44c6_s_p9_2,
  133062. 49,
  133063. 49
  133064. };
  133065. static static_codebook _44c6_s_p9_2 = {
  133066. 1, 49,
  133067. _vq_lengthlist__44c6_s_p9_2,
  133068. 1, -526909440, 1611661312, 6, 0,
  133069. _vq_quantlist__44c6_s_p9_2,
  133070. NULL,
  133071. &_vq_auxt__44c6_s_p9_2,
  133072. NULL,
  133073. 0
  133074. };
  133075. static long _huff_lengthlist__44c6_s_short[] = {
  133076. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133077. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133078. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133079. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133080. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133081. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133082. 9,10,17,18,
  133083. };
  133084. static static_codebook _huff_book__44c6_s_short = {
  133085. 2, 100,
  133086. _huff_lengthlist__44c6_s_short,
  133087. 0, 0, 0, 0, 0,
  133088. NULL,
  133089. NULL,
  133090. NULL,
  133091. NULL,
  133092. 0
  133093. };
  133094. static long _huff_lengthlist__44c7_s_long[] = {
  133095. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133096. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133097. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133098. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133099. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133100. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133101. 11,10,10,12,
  133102. };
  133103. static static_codebook _huff_book__44c7_s_long = {
  133104. 2, 100,
  133105. _huff_lengthlist__44c7_s_long,
  133106. 0, 0, 0, 0, 0,
  133107. NULL,
  133108. NULL,
  133109. NULL,
  133110. NULL,
  133111. 0
  133112. };
  133113. static long _vq_quantlist__44c7_s_p1_0[] = {
  133114. 1,
  133115. 0,
  133116. 2,
  133117. };
  133118. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133119. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133120. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133121. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133122. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133123. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133124. 8,
  133125. };
  133126. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133127. -0.5, 0.5,
  133128. };
  133129. static long _vq_quantmap__44c7_s_p1_0[] = {
  133130. 1, 0, 2,
  133131. };
  133132. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133133. _vq_quantthresh__44c7_s_p1_0,
  133134. _vq_quantmap__44c7_s_p1_0,
  133135. 3,
  133136. 3
  133137. };
  133138. static static_codebook _44c7_s_p1_0 = {
  133139. 4, 81,
  133140. _vq_lengthlist__44c7_s_p1_0,
  133141. 1, -535822336, 1611661312, 2, 0,
  133142. _vq_quantlist__44c7_s_p1_0,
  133143. NULL,
  133144. &_vq_auxt__44c7_s_p1_0,
  133145. NULL,
  133146. 0
  133147. };
  133148. static long _vq_quantlist__44c7_s_p2_0[] = {
  133149. 2,
  133150. 1,
  133151. 3,
  133152. 0,
  133153. 4,
  133154. };
  133155. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133156. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133157. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133158. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133159. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133160. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133161. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133162. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133163. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133165. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133166. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133167. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133168. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133169. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133170. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133171. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133173. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133174. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133175. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133176. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133177. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133178. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133179. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133181. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133182. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133183. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133184. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133185. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133186. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133187. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133192. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133193. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133194. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133195. 13,
  133196. };
  133197. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133198. -1.5, -0.5, 0.5, 1.5,
  133199. };
  133200. static long _vq_quantmap__44c7_s_p2_0[] = {
  133201. 3, 1, 0, 2, 4,
  133202. };
  133203. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133204. _vq_quantthresh__44c7_s_p2_0,
  133205. _vq_quantmap__44c7_s_p2_0,
  133206. 5,
  133207. 5
  133208. };
  133209. static static_codebook _44c7_s_p2_0 = {
  133210. 4, 625,
  133211. _vq_lengthlist__44c7_s_p2_0,
  133212. 1, -533725184, 1611661312, 3, 0,
  133213. _vq_quantlist__44c7_s_p2_0,
  133214. NULL,
  133215. &_vq_auxt__44c7_s_p2_0,
  133216. NULL,
  133217. 0
  133218. };
  133219. static long _vq_quantlist__44c7_s_p3_0[] = {
  133220. 4,
  133221. 3,
  133222. 5,
  133223. 2,
  133224. 6,
  133225. 1,
  133226. 7,
  133227. 0,
  133228. 8,
  133229. };
  133230. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133231. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133232. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133233. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133234. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133236. 0,
  133237. };
  133238. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133239. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133240. };
  133241. static long _vq_quantmap__44c7_s_p3_0[] = {
  133242. 7, 5, 3, 1, 0, 2, 4, 6,
  133243. 8,
  133244. };
  133245. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133246. _vq_quantthresh__44c7_s_p3_0,
  133247. _vq_quantmap__44c7_s_p3_0,
  133248. 9,
  133249. 9
  133250. };
  133251. static static_codebook _44c7_s_p3_0 = {
  133252. 2, 81,
  133253. _vq_lengthlist__44c7_s_p3_0,
  133254. 1, -531628032, 1611661312, 4, 0,
  133255. _vq_quantlist__44c7_s_p3_0,
  133256. NULL,
  133257. &_vq_auxt__44c7_s_p3_0,
  133258. NULL,
  133259. 0
  133260. };
  133261. static long _vq_quantlist__44c7_s_p4_0[] = {
  133262. 8,
  133263. 7,
  133264. 9,
  133265. 6,
  133266. 10,
  133267. 5,
  133268. 11,
  133269. 4,
  133270. 12,
  133271. 3,
  133272. 13,
  133273. 2,
  133274. 14,
  133275. 1,
  133276. 15,
  133277. 0,
  133278. 16,
  133279. };
  133280. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133281. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133282. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133283. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133284. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133285. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133286. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133287. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133288. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133289. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133290. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133299. 0,
  133300. };
  133301. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133302. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133303. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133304. };
  133305. static long _vq_quantmap__44c7_s_p4_0[] = {
  133306. 15, 13, 11, 9, 7, 5, 3, 1,
  133307. 0, 2, 4, 6, 8, 10, 12, 14,
  133308. 16,
  133309. };
  133310. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133311. _vq_quantthresh__44c7_s_p4_0,
  133312. _vq_quantmap__44c7_s_p4_0,
  133313. 17,
  133314. 17
  133315. };
  133316. static static_codebook _44c7_s_p4_0 = {
  133317. 2, 289,
  133318. _vq_lengthlist__44c7_s_p4_0,
  133319. 1, -529530880, 1611661312, 5, 0,
  133320. _vq_quantlist__44c7_s_p4_0,
  133321. NULL,
  133322. &_vq_auxt__44c7_s_p4_0,
  133323. NULL,
  133324. 0
  133325. };
  133326. static long _vq_quantlist__44c7_s_p5_0[] = {
  133327. 1,
  133328. 0,
  133329. 2,
  133330. };
  133331. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133332. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133333. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133334. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133335. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133336. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133337. 12,
  133338. };
  133339. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133340. -5.5, 5.5,
  133341. };
  133342. static long _vq_quantmap__44c7_s_p5_0[] = {
  133343. 1, 0, 2,
  133344. };
  133345. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133346. _vq_quantthresh__44c7_s_p5_0,
  133347. _vq_quantmap__44c7_s_p5_0,
  133348. 3,
  133349. 3
  133350. };
  133351. static static_codebook _44c7_s_p5_0 = {
  133352. 4, 81,
  133353. _vq_lengthlist__44c7_s_p5_0,
  133354. 1, -529137664, 1618345984, 2, 0,
  133355. _vq_quantlist__44c7_s_p5_0,
  133356. NULL,
  133357. &_vq_auxt__44c7_s_p5_0,
  133358. NULL,
  133359. 0
  133360. };
  133361. static long _vq_quantlist__44c7_s_p5_1[] = {
  133362. 5,
  133363. 4,
  133364. 6,
  133365. 3,
  133366. 7,
  133367. 2,
  133368. 8,
  133369. 1,
  133370. 9,
  133371. 0,
  133372. 10,
  133373. };
  133374. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133375. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133376. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133377. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133378. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133379. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133380. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133381. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133382. 11,11,11, 7, 7, 8, 8, 8, 8,
  133383. };
  133384. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133385. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133386. 3.5, 4.5,
  133387. };
  133388. static long _vq_quantmap__44c7_s_p5_1[] = {
  133389. 9, 7, 5, 3, 1, 0, 2, 4,
  133390. 6, 8, 10,
  133391. };
  133392. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133393. _vq_quantthresh__44c7_s_p5_1,
  133394. _vq_quantmap__44c7_s_p5_1,
  133395. 11,
  133396. 11
  133397. };
  133398. static static_codebook _44c7_s_p5_1 = {
  133399. 2, 121,
  133400. _vq_lengthlist__44c7_s_p5_1,
  133401. 1, -531365888, 1611661312, 4, 0,
  133402. _vq_quantlist__44c7_s_p5_1,
  133403. NULL,
  133404. &_vq_auxt__44c7_s_p5_1,
  133405. NULL,
  133406. 0
  133407. };
  133408. static long _vq_quantlist__44c7_s_p6_0[] = {
  133409. 6,
  133410. 5,
  133411. 7,
  133412. 4,
  133413. 8,
  133414. 3,
  133415. 9,
  133416. 2,
  133417. 10,
  133418. 1,
  133419. 11,
  133420. 0,
  133421. 12,
  133422. };
  133423. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133424. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133425. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133426. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133427. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133428. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133429. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133434. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133435. };
  133436. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133437. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133438. 12.5, 17.5, 22.5, 27.5,
  133439. };
  133440. static long _vq_quantmap__44c7_s_p6_0[] = {
  133441. 11, 9, 7, 5, 3, 1, 0, 2,
  133442. 4, 6, 8, 10, 12,
  133443. };
  133444. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133445. _vq_quantthresh__44c7_s_p6_0,
  133446. _vq_quantmap__44c7_s_p6_0,
  133447. 13,
  133448. 13
  133449. };
  133450. static static_codebook _44c7_s_p6_0 = {
  133451. 2, 169,
  133452. _vq_lengthlist__44c7_s_p6_0,
  133453. 1, -526516224, 1616117760, 4, 0,
  133454. _vq_quantlist__44c7_s_p6_0,
  133455. NULL,
  133456. &_vq_auxt__44c7_s_p6_0,
  133457. NULL,
  133458. 0
  133459. };
  133460. static long _vq_quantlist__44c7_s_p6_1[] = {
  133461. 2,
  133462. 1,
  133463. 3,
  133464. 0,
  133465. 4,
  133466. };
  133467. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133468. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133469. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133470. };
  133471. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133472. -1.5, -0.5, 0.5, 1.5,
  133473. };
  133474. static long _vq_quantmap__44c7_s_p6_1[] = {
  133475. 3, 1, 0, 2, 4,
  133476. };
  133477. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133478. _vq_quantthresh__44c7_s_p6_1,
  133479. _vq_quantmap__44c7_s_p6_1,
  133480. 5,
  133481. 5
  133482. };
  133483. static static_codebook _44c7_s_p6_1 = {
  133484. 2, 25,
  133485. _vq_lengthlist__44c7_s_p6_1,
  133486. 1, -533725184, 1611661312, 3, 0,
  133487. _vq_quantlist__44c7_s_p6_1,
  133488. NULL,
  133489. &_vq_auxt__44c7_s_p6_1,
  133490. NULL,
  133491. 0
  133492. };
  133493. static long _vq_quantlist__44c7_s_p7_0[] = {
  133494. 6,
  133495. 5,
  133496. 7,
  133497. 4,
  133498. 8,
  133499. 3,
  133500. 9,
  133501. 2,
  133502. 10,
  133503. 1,
  133504. 11,
  133505. 0,
  133506. 12,
  133507. };
  133508. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133509. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133510. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133511. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133512. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133513. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133514. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133515. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133516. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133517. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133518. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133519. 19,13,13,13,13,14,14,15,15,
  133520. };
  133521. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133522. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133523. 27.5, 38.5, 49.5, 60.5,
  133524. };
  133525. static long _vq_quantmap__44c7_s_p7_0[] = {
  133526. 11, 9, 7, 5, 3, 1, 0, 2,
  133527. 4, 6, 8, 10, 12,
  133528. };
  133529. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133530. _vq_quantthresh__44c7_s_p7_0,
  133531. _vq_quantmap__44c7_s_p7_0,
  133532. 13,
  133533. 13
  133534. };
  133535. static static_codebook _44c7_s_p7_0 = {
  133536. 2, 169,
  133537. _vq_lengthlist__44c7_s_p7_0,
  133538. 1, -523206656, 1618345984, 4, 0,
  133539. _vq_quantlist__44c7_s_p7_0,
  133540. NULL,
  133541. &_vq_auxt__44c7_s_p7_0,
  133542. NULL,
  133543. 0
  133544. };
  133545. static long _vq_quantlist__44c7_s_p7_1[] = {
  133546. 5,
  133547. 4,
  133548. 6,
  133549. 3,
  133550. 7,
  133551. 2,
  133552. 8,
  133553. 1,
  133554. 9,
  133555. 0,
  133556. 10,
  133557. };
  133558. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133559. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133560. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133561. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133562. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133563. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133564. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133565. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133566. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133567. };
  133568. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133569. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133570. 3.5, 4.5,
  133571. };
  133572. static long _vq_quantmap__44c7_s_p7_1[] = {
  133573. 9, 7, 5, 3, 1, 0, 2, 4,
  133574. 6, 8, 10,
  133575. };
  133576. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133577. _vq_quantthresh__44c7_s_p7_1,
  133578. _vq_quantmap__44c7_s_p7_1,
  133579. 11,
  133580. 11
  133581. };
  133582. static static_codebook _44c7_s_p7_1 = {
  133583. 2, 121,
  133584. _vq_lengthlist__44c7_s_p7_1,
  133585. 1, -531365888, 1611661312, 4, 0,
  133586. _vq_quantlist__44c7_s_p7_1,
  133587. NULL,
  133588. &_vq_auxt__44c7_s_p7_1,
  133589. NULL,
  133590. 0
  133591. };
  133592. static long _vq_quantlist__44c7_s_p8_0[] = {
  133593. 7,
  133594. 6,
  133595. 8,
  133596. 5,
  133597. 9,
  133598. 4,
  133599. 10,
  133600. 3,
  133601. 11,
  133602. 2,
  133603. 12,
  133604. 1,
  133605. 13,
  133606. 0,
  133607. 14,
  133608. };
  133609. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133610. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133611. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133612. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133613. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133614. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133615. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133616. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133617. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133618. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133619. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133620. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133621. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133622. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133623. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133624. 14,
  133625. };
  133626. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133627. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133628. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133629. };
  133630. static long _vq_quantmap__44c7_s_p8_0[] = {
  133631. 13, 11, 9, 7, 5, 3, 1, 0,
  133632. 2, 4, 6, 8, 10, 12, 14,
  133633. };
  133634. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133635. _vq_quantthresh__44c7_s_p8_0,
  133636. _vq_quantmap__44c7_s_p8_0,
  133637. 15,
  133638. 15
  133639. };
  133640. static static_codebook _44c7_s_p8_0 = {
  133641. 2, 225,
  133642. _vq_lengthlist__44c7_s_p8_0,
  133643. 1, -520986624, 1620377600, 4, 0,
  133644. _vq_quantlist__44c7_s_p8_0,
  133645. NULL,
  133646. &_vq_auxt__44c7_s_p8_0,
  133647. NULL,
  133648. 0
  133649. };
  133650. static long _vq_quantlist__44c7_s_p8_1[] = {
  133651. 10,
  133652. 9,
  133653. 11,
  133654. 8,
  133655. 12,
  133656. 7,
  133657. 13,
  133658. 6,
  133659. 14,
  133660. 5,
  133661. 15,
  133662. 4,
  133663. 16,
  133664. 3,
  133665. 17,
  133666. 2,
  133667. 18,
  133668. 1,
  133669. 19,
  133670. 0,
  133671. 20,
  133672. };
  133673. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133674. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133675. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133676. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133677. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133678. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133679. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133680. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133681. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133682. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133683. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133684. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133685. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133686. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133687. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133688. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133689. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133690. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133691. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133692. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133693. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133694. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133695. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133696. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133697. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133698. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133699. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133700. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133701. 10,10,10,10,10,10,10,10,10,
  133702. };
  133703. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133704. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133705. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133706. 6.5, 7.5, 8.5, 9.5,
  133707. };
  133708. static long _vq_quantmap__44c7_s_p8_1[] = {
  133709. 19, 17, 15, 13, 11, 9, 7, 5,
  133710. 3, 1, 0, 2, 4, 6, 8, 10,
  133711. 12, 14, 16, 18, 20,
  133712. };
  133713. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133714. _vq_quantthresh__44c7_s_p8_1,
  133715. _vq_quantmap__44c7_s_p8_1,
  133716. 21,
  133717. 21
  133718. };
  133719. static static_codebook _44c7_s_p8_1 = {
  133720. 2, 441,
  133721. _vq_lengthlist__44c7_s_p8_1,
  133722. 1, -529268736, 1611661312, 5, 0,
  133723. _vq_quantlist__44c7_s_p8_1,
  133724. NULL,
  133725. &_vq_auxt__44c7_s_p8_1,
  133726. NULL,
  133727. 0
  133728. };
  133729. static long _vq_quantlist__44c7_s_p9_0[] = {
  133730. 6,
  133731. 5,
  133732. 7,
  133733. 4,
  133734. 8,
  133735. 3,
  133736. 9,
  133737. 2,
  133738. 10,
  133739. 1,
  133740. 11,
  133741. 0,
  133742. 12,
  133743. };
  133744. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133745. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133746. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133755. 11,11,11,11,11,11,11,11,11,
  133756. };
  133757. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133758. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133759. 1592.5, 2229.5, 2866.5, 3503.5,
  133760. };
  133761. static long _vq_quantmap__44c7_s_p9_0[] = {
  133762. 11, 9, 7, 5, 3, 1, 0, 2,
  133763. 4, 6, 8, 10, 12,
  133764. };
  133765. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133766. _vq_quantthresh__44c7_s_p9_0,
  133767. _vq_quantmap__44c7_s_p9_0,
  133768. 13,
  133769. 13
  133770. };
  133771. static static_codebook _44c7_s_p9_0 = {
  133772. 2, 169,
  133773. _vq_lengthlist__44c7_s_p9_0,
  133774. 1, -511845376, 1630791680, 4, 0,
  133775. _vq_quantlist__44c7_s_p9_0,
  133776. NULL,
  133777. &_vq_auxt__44c7_s_p9_0,
  133778. NULL,
  133779. 0
  133780. };
  133781. static long _vq_quantlist__44c7_s_p9_1[] = {
  133782. 6,
  133783. 5,
  133784. 7,
  133785. 4,
  133786. 8,
  133787. 3,
  133788. 9,
  133789. 2,
  133790. 10,
  133791. 1,
  133792. 11,
  133793. 0,
  133794. 12,
  133795. };
  133796. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133797. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133798. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133799. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133800. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133801. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133802. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133803. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133804. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133805. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133806. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133807. 15,11,11,10,10,12,12,12,12,
  133808. };
  133809. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133810. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133811. 122.5, 171.5, 220.5, 269.5,
  133812. };
  133813. static long _vq_quantmap__44c7_s_p9_1[] = {
  133814. 11, 9, 7, 5, 3, 1, 0, 2,
  133815. 4, 6, 8, 10, 12,
  133816. };
  133817. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133818. _vq_quantthresh__44c7_s_p9_1,
  133819. _vq_quantmap__44c7_s_p9_1,
  133820. 13,
  133821. 13
  133822. };
  133823. static static_codebook _44c7_s_p9_1 = {
  133824. 2, 169,
  133825. _vq_lengthlist__44c7_s_p9_1,
  133826. 1, -518889472, 1622704128, 4, 0,
  133827. _vq_quantlist__44c7_s_p9_1,
  133828. NULL,
  133829. &_vq_auxt__44c7_s_p9_1,
  133830. NULL,
  133831. 0
  133832. };
  133833. static long _vq_quantlist__44c7_s_p9_2[] = {
  133834. 24,
  133835. 23,
  133836. 25,
  133837. 22,
  133838. 26,
  133839. 21,
  133840. 27,
  133841. 20,
  133842. 28,
  133843. 19,
  133844. 29,
  133845. 18,
  133846. 30,
  133847. 17,
  133848. 31,
  133849. 16,
  133850. 32,
  133851. 15,
  133852. 33,
  133853. 14,
  133854. 34,
  133855. 13,
  133856. 35,
  133857. 12,
  133858. 36,
  133859. 11,
  133860. 37,
  133861. 10,
  133862. 38,
  133863. 9,
  133864. 39,
  133865. 8,
  133866. 40,
  133867. 7,
  133868. 41,
  133869. 6,
  133870. 42,
  133871. 5,
  133872. 43,
  133873. 4,
  133874. 44,
  133875. 3,
  133876. 45,
  133877. 2,
  133878. 46,
  133879. 1,
  133880. 47,
  133881. 0,
  133882. 48,
  133883. };
  133884. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133885. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133886. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133887. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133888. 7,
  133889. };
  133890. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133891. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133892. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133893. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133894. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133895. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133896. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133897. };
  133898. static long _vq_quantmap__44c7_s_p9_2[] = {
  133899. 47, 45, 43, 41, 39, 37, 35, 33,
  133900. 31, 29, 27, 25, 23, 21, 19, 17,
  133901. 15, 13, 11, 9, 7, 5, 3, 1,
  133902. 0, 2, 4, 6, 8, 10, 12, 14,
  133903. 16, 18, 20, 22, 24, 26, 28, 30,
  133904. 32, 34, 36, 38, 40, 42, 44, 46,
  133905. 48,
  133906. };
  133907. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133908. _vq_quantthresh__44c7_s_p9_2,
  133909. _vq_quantmap__44c7_s_p9_2,
  133910. 49,
  133911. 49
  133912. };
  133913. static static_codebook _44c7_s_p9_2 = {
  133914. 1, 49,
  133915. _vq_lengthlist__44c7_s_p9_2,
  133916. 1, -526909440, 1611661312, 6, 0,
  133917. _vq_quantlist__44c7_s_p9_2,
  133918. NULL,
  133919. &_vq_auxt__44c7_s_p9_2,
  133920. NULL,
  133921. 0
  133922. };
  133923. static long _huff_lengthlist__44c7_s_short[] = {
  133924. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133925. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133926. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133927. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133928. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133929. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133930. 10, 9,11,14,
  133931. };
  133932. static static_codebook _huff_book__44c7_s_short = {
  133933. 2, 100,
  133934. _huff_lengthlist__44c7_s_short,
  133935. 0, 0, 0, 0, 0,
  133936. NULL,
  133937. NULL,
  133938. NULL,
  133939. NULL,
  133940. 0
  133941. };
  133942. static long _huff_lengthlist__44c8_s_long[] = {
  133943. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133944. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133945. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133946. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133947. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133948. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133949. 11, 9, 9,10,
  133950. };
  133951. static static_codebook _huff_book__44c8_s_long = {
  133952. 2, 100,
  133953. _huff_lengthlist__44c8_s_long,
  133954. 0, 0, 0, 0, 0,
  133955. NULL,
  133956. NULL,
  133957. NULL,
  133958. NULL,
  133959. 0
  133960. };
  133961. static long _vq_quantlist__44c8_s_p1_0[] = {
  133962. 1,
  133963. 0,
  133964. 2,
  133965. };
  133966. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133967. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133968. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133969. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133970. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133971. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133972. 8,
  133973. };
  133974. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133975. -0.5, 0.5,
  133976. };
  133977. static long _vq_quantmap__44c8_s_p1_0[] = {
  133978. 1, 0, 2,
  133979. };
  133980. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133981. _vq_quantthresh__44c8_s_p1_0,
  133982. _vq_quantmap__44c8_s_p1_0,
  133983. 3,
  133984. 3
  133985. };
  133986. static static_codebook _44c8_s_p1_0 = {
  133987. 4, 81,
  133988. _vq_lengthlist__44c8_s_p1_0,
  133989. 1, -535822336, 1611661312, 2, 0,
  133990. _vq_quantlist__44c8_s_p1_0,
  133991. NULL,
  133992. &_vq_auxt__44c8_s_p1_0,
  133993. NULL,
  133994. 0
  133995. };
  133996. static long _vq_quantlist__44c8_s_p2_0[] = {
  133997. 2,
  133998. 1,
  133999. 3,
  134000. 0,
  134001. 4,
  134002. };
  134003. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134004. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134005. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134006. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134007. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134008. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134009. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134010. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134011. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134013. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134014. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134015. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134016. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134017. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134018. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134019. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134021. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134022. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134023. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134024. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134025. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134026. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134027. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134029. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134030. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134031. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134032. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134033. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134034. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134035. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134040. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134041. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134042. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134043. 13,
  134044. };
  134045. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134046. -1.5, -0.5, 0.5, 1.5,
  134047. };
  134048. static long _vq_quantmap__44c8_s_p2_0[] = {
  134049. 3, 1, 0, 2, 4,
  134050. };
  134051. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134052. _vq_quantthresh__44c8_s_p2_0,
  134053. _vq_quantmap__44c8_s_p2_0,
  134054. 5,
  134055. 5
  134056. };
  134057. static static_codebook _44c8_s_p2_0 = {
  134058. 4, 625,
  134059. _vq_lengthlist__44c8_s_p2_0,
  134060. 1, -533725184, 1611661312, 3, 0,
  134061. _vq_quantlist__44c8_s_p2_0,
  134062. NULL,
  134063. &_vq_auxt__44c8_s_p2_0,
  134064. NULL,
  134065. 0
  134066. };
  134067. static long _vq_quantlist__44c8_s_p3_0[] = {
  134068. 4,
  134069. 3,
  134070. 5,
  134071. 2,
  134072. 6,
  134073. 1,
  134074. 7,
  134075. 0,
  134076. 8,
  134077. };
  134078. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134079. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134080. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134081. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134082. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134084. 0,
  134085. };
  134086. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134087. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134088. };
  134089. static long _vq_quantmap__44c8_s_p3_0[] = {
  134090. 7, 5, 3, 1, 0, 2, 4, 6,
  134091. 8,
  134092. };
  134093. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134094. _vq_quantthresh__44c8_s_p3_0,
  134095. _vq_quantmap__44c8_s_p3_0,
  134096. 9,
  134097. 9
  134098. };
  134099. static static_codebook _44c8_s_p3_0 = {
  134100. 2, 81,
  134101. _vq_lengthlist__44c8_s_p3_0,
  134102. 1, -531628032, 1611661312, 4, 0,
  134103. _vq_quantlist__44c8_s_p3_0,
  134104. NULL,
  134105. &_vq_auxt__44c8_s_p3_0,
  134106. NULL,
  134107. 0
  134108. };
  134109. static long _vq_quantlist__44c8_s_p4_0[] = {
  134110. 8,
  134111. 7,
  134112. 9,
  134113. 6,
  134114. 10,
  134115. 5,
  134116. 11,
  134117. 4,
  134118. 12,
  134119. 3,
  134120. 13,
  134121. 2,
  134122. 14,
  134123. 1,
  134124. 15,
  134125. 0,
  134126. 16,
  134127. };
  134128. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134129. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134130. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134131. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134132. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134133. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134134. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134135. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134136. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134137. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134138. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134147. 0,
  134148. };
  134149. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134150. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134151. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134152. };
  134153. static long _vq_quantmap__44c8_s_p4_0[] = {
  134154. 15, 13, 11, 9, 7, 5, 3, 1,
  134155. 0, 2, 4, 6, 8, 10, 12, 14,
  134156. 16,
  134157. };
  134158. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134159. _vq_quantthresh__44c8_s_p4_0,
  134160. _vq_quantmap__44c8_s_p4_0,
  134161. 17,
  134162. 17
  134163. };
  134164. static static_codebook _44c8_s_p4_0 = {
  134165. 2, 289,
  134166. _vq_lengthlist__44c8_s_p4_0,
  134167. 1, -529530880, 1611661312, 5, 0,
  134168. _vq_quantlist__44c8_s_p4_0,
  134169. NULL,
  134170. &_vq_auxt__44c8_s_p4_0,
  134171. NULL,
  134172. 0
  134173. };
  134174. static long _vq_quantlist__44c8_s_p5_0[] = {
  134175. 1,
  134176. 0,
  134177. 2,
  134178. };
  134179. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134180. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134181. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134182. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134183. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134184. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134185. 12,
  134186. };
  134187. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134188. -5.5, 5.5,
  134189. };
  134190. static long _vq_quantmap__44c8_s_p5_0[] = {
  134191. 1, 0, 2,
  134192. };
  134193. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134194. _vq_quantthresh__44c8_s_p5_0,
  134195. _vq_quantmap__44c8_s_p5_0,
  134196. 3,
  134197. 3
  134198. };
  134199. static static_codebook _44c8_s_p5_0 = {
  134200. 4, 81,
  134201. _vq_lengthlist__44c8_s_p5_0,
  134202. 1, -529137664, 1618345984, 2, 0,
  134203. _vq_quantlist__44c8_s_p5_0,
  134204. NULL,
  134205. &_vq_auxt__44c8_s_p5_0,
  134206. NULL,
  134207. 0
  134208. };
  134209. static long _vq_quantlist__44c8_s_p5_1[] = {
  134210. 5,
  134211. 4,
  134212. 6,
  134213. 3,
  134214. 7,
  134215. 2,
  134216. 8,
  134217. 1,
  134218. 9,
  134219. 0,
  134220. 10,
  134221. };
  134222. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134223. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134224. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134225. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134226. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134227. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134228. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134229. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134230. 11,11,11, 7, 7, 7, 7, 8, 8,
  134231. };
  134232. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134233. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134234. 3.5, 4.5,
  134235. };
  134236. static long _vq_quantmap__44c8_s_p5_1[] = {
  134237. 9, 7, 5, 3, 1, 0, 2, 4,
  134238. 6, 8, 10,
  134239. };
  134240. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134241. _vq_quantthresh__44c8_s_p5_1,
  134242. _vq_quantmap__44c8_s_p5_1,
  134243. 11,
  134244. 11
  134245. };
  134246. static static_codebook _44c8_s_p5_1 = {
  134247. 2, 121,
  134248. _vq_lengthlist__44c8_s_p5_1,
  134249. 1, -531365888, 1611661312, 4, 0,
  134250. _vq_quantlist__44c8_s_p5_1,
  134251. NULL,
  134252. &_vq_auxt__44c8_s_p5_1,
  134253. NULL,
  134254. 0
  134255. };
  134256. static long _vq_quantlist__44c8_s_p6_0[] = {
  134257. 6,
  134258. 5,
  134259. 7,
  134260. 4,
  134261. 8,
  134262. 3,
  134263. 9,
  134264. 2,
  134265. 10,
  134266. 1,
  134267. 11,
  134268. 0,
  134269. 12,
  134270. };
  134271. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134272. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134273. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134274. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134275. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134276. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134277. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134282. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134283. };
  134284. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134285. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134286. 12.5, 17.5, 22.5, 27.5,
  134287. };
  134288. static long _vq_quantmap__44c8_s_p6_0[] = {
  134289. 11, 9, 7, 5, 3, 1, 0, 2,
  134290. 4, 6, 8, 10, 12,
  134291. };
  134292. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134293. _vq_quantthresh__44c8_s_p6_0,
  134294. _vq_quantmap__44c8_s_p6_0,
  134295. 13,
  134296. 13
  134297. };
  134298. static static_codebook _44c8_s_p6_0 = {
  134299. 2, 169,
  134300. _vq_lengthlist__44c8_s_p6_0,
  134301. 1, -526516224, 1616117760, 4, 0,
  134302. _vq_quantlist__44c8_s_p6_0,
  134303. NULL,
  134304. &_vq_auxt__44c8_s_p6_0,
  134305. NULL,
  134306. 0
  134307. };
  134308. static long _vq_quantlist__44c8_s_p6_1[] = {
  134309. 2,
  134310. 1,
  134311. 3,
  134312. 0,
  134313. 4,
  134314. };
  134315. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134316. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134317. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134318. };
  134319. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134320. -1.5, -0.5, 0.5, 1.5,
  134321. };
  134322. static long _vq_quantmap__44c8_s_p6_1[] = {
  134323. 3, 1, 0, 2, 4,
  134324. };
  134325. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134326. _vq_quantthresh__44c8_s_p6_1,
  134327. _vq_quantmap__44c8_s_p6_1,
  134328. 5,
  134329. 5
  134330. };
  134331. static static_codebook _44c8_s_p6_1 = {
  134332. 2, 25,
  134333. _vq_lengthlist__44c8_s_p6_1,
  134334. 1, -533725184, 1611661312, 3, 0,
  134335. _vq_quantlist__44c8_s_p6_1,
  134336. NULL,
  134337. &_vq_auxt__44c8_s_p6_1,
  134338. NULL,
  134339. 0
  134340. };
  134341. static long _vq_quantlist__44c8_s_p7_0[] = {
  134342. 6,
  134343. 5,
  134344. 7,
  134345. 4,
  134346. 8,
  134347. 3,
  134348. 9,
  134349. 2,
  134350. 10,
  134351. 1,
  134352. 11,
  134353. 0,
  134354. 12,
  134355. };
  134356. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134357. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134358. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134359. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134360. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134361. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134362. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134363. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134364. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134365. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134366. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134367. 20,13,13,13,13,14,13,15,15,
  134368. };
  134369. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134370. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134371. 27.5, 38.5, 49.5, 60.5,
  134372. };
  134373. static long _vq_quantmap__44c8_s_p7_0[] = {
  134374. 11, 9, 7, 5, 3, 1, 0, 2,
  134375. 4, 6, 8, 10, 12,
  134376. };
  134377. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134378. _vq_quantthresh__44c8_s_p7_0,
  134379. _vq_quantmap__44c8_s_p7_0,
  134380. 13,
  134381. 13
  134382. };
  134383. static static_codebook _44c8_s_p7_0 = {
  134384. 2, 169,
  134385. _vq_lengthlist__44c8_s_p7_0,
  134386. 1, -523206656, 1618345984, 4, 0,
  134387. _vq_quantlist__44c8_s_p7_0,
  134388. NULL,
  134389. &_vq_auxt__44c8_s_p7_0,
  134390. NULL,
  134391. 0
  134392. };
  134393. static long _vq_quantlist__44c8_s_p7_1[] = {
  134394. 5,
  134395. 4,
  134396. 6,
  134397. 3,
  134398. 7,
  134399. 2,
  134400. 8,
  134401. 1,
  134402. 9,
  134403. 0,
  134404. 10,
  134405. };
  134406. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134407. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134408. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134409. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134410. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134411. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134412. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134413. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134414. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134415. };
  134416. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134417. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134418. 3.5, 4.5,
  134419. };
  134420. static long _vq_quantmap__44c8_s_p7_1[] = {
  134421. 9, 7, 5, 3, 1, 0, 2, 4,
  134422. 6, 8, 10,
  134423. };
  134424. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134425. _vq_quantthresh__44c8_s_p7_1,
  134426. _vq_quantmap__44c8_s_p7_1,
  134427. 11,
  134428. 11
  134429. };
  134430. static static_codebook _44c8_s_p7_1 = {
  134431. 2, 121,
  134432. _vq_lengthlist__44c8_s_p7_1,
  134433. 1, -531365888, 1611661312, 4, 0,
  134434. _vq_quantlist__44c8_s_p7_1,
  134435. NULL,
  134436. &_vq_auxt__44c8_s_p7_1,
  134437. NULL,
  134438. 0
  134439. };
  134440. static long _vq_quantlist__44c8_s_p8_0[] = {
  134441. 7,
  134442. 6,
  134443. 8,
  134444. 5,
  134445. 9,
  134446. 4,
  134447. 10,
  134448. 3,
  134449. 11,
  134450. 2,
  134451. 12,
  134452. 1,
  134453. 13,
  134454. 0,
  134455. 14,
  134456. };
  134457. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134458. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134459. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134460. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134461. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134462. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134463. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134464. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134465. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134466. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134467. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134468. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134469. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134470. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134471. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134472. 15,
  134473. };
  134474. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134475. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134476. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134477. };
  134478. static long _vq_quantmap__44c8_s_p8_0[] = {
  134479. 13, 11, 9, 7, 5, 3, 1, 0,
  134480. 2, 4, 6, 8, 10, 12, 14,
  134481. };
  134482. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134483. _vq_quantthresh__44c8_s_p8_0,
  134484. _vq_quantmap__44c8_s_p8_0,
  134485. 15,
  134486. 15
  134487. };
  134488. static static_codebook _44c8_s_p8_0 = {
  134489. 2, 225,
  134490. _vq_lengthlist__44c8_s_p8_0,
  134491. 1, -520986624, 1620377600, 4, 0,
  134492. _vq_quantlist__44c8_s_p8_0,
  134493. NULL,
  134494. &_vq_auxt__44c8_s_p8_0,
  134495. NULL,
  134496. 0
  134497. };
  134498. static long _vq_quantlist__44c8_s_p8_1[] = {
  134499. 10,
  134500. 9,
  134501. 11,
  134502. 8,
  134503. 12,
  134504. 7,
  134505. 13,
  134506. 6,
  134507. 14,
  134508. 5,
  134509. 15,
  134510. 4,
  134511. 16,
  134512. 3,
  134513. 17,
  134514. 2,
  134515. 18,
  134516. 1,
  134517. 19,
  134518. 0,
  134519. 20,
  134520. };
  134521. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134522. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134523. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134524. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134525. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134526. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134527. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134528. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134529. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134530. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134531. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134532. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134533. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134534. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134535. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134536. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134537. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134538. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134539. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134540. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134541. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134542. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134543. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134544. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134545. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134546. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134547. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134548. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134549. 10, 9, 9,10,10, 9,10, 9, 9,
  134550. };
  134551. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134552. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134553. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134554. 6.5, 7.5, 8.5, 9.5,
  134555. };
  134556. static long _vq_quantmap__44c8_s_p8_1[] = {
  134557. 19, 17, 15, 13, 11, 9, 7, 5,
  134558. 3, 1, 0, 2, 4, 6, 8, 10,
  134559. 12, 14, 16, 18, 20,
  134560. };
  134561. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134562. _vq_quantthresh__44c8_s_p8_1,
  134563. _vq_quantmap__44c8_s_p8_1,
  134564. 21,
  134565. 21
  134566. };
  134567. static static_codebook _44c8_s_p8_1 = {
  134568. 2, 441,
  134569. _vq_lengthlist__44c8_s_p8_1,
  134570. 1, -529268736, 1611661312, 5, 0,
  134571. _vq_quantlist__44c8_s_p8_1,
  134572. NULL,
  134573. &_vq_auxt__44c8_s_p8_1,
  134574. NULL,
  134575. 0
  134576. };
  134577. static long _vq_quantlist__44c8_s_p9_0[] = {
  134578. 8,
  134579. 7,
  134580. 9,
  134581. 6,
  134582. 10,
  134583. 5,
  134584. 11,
  134585. 4,
  134586. 12,
  134587. 3,
  134588. 13,
  134589. 2,
  134590. 14,
  134591. 1,
  134592. 15,
  134593. 0,
  134594. 16,
  134595. };
  134596. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134597. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134598. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134599. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134604. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134611. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134612. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134613. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134614. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134615. 10,
  134616. };
  134617. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134618. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134619. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134620. };
  134621. static long _vq_quantmap__44c8_s_p9_0[] = {
  134622. 15, 13, 11, 9, 7, 5, 3, 1,
  134623. 0, 2, 4, 6, 8, 10, 12, 14,
  134624. 16,
  134625. };
  134626. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134627. _vq_quantthresh__44c8_s_p9_0,
  134628. _vq_quantmap__44c8_s_p9_0,
  134629. 17,
  134630. 17
  134631. };
  134632. static static_codebook _44c8_s_p9_0 = {
  134633. 2, 289,
  134634. _vq_lengthlist__44c8_s_p9_0,
  134635. 1, -509798400, 1631393792, 5, 0,
  134636. _vq_quantlist__44c8_s_p9_0,
  134637. NULL,
  134638. &_vq_auxt__44c8_s_p9_0,
  134639. NULL,
  134640. 0
  134641. };
  134642. static long _vq_quantlist__44c8_s_p9_1[] = {
  134643. 9,
  134644. 8,
  134645. 10,
  134646. 7,
  134647. 11,
  134648. 6,
  134649. 12,
  134650. 5,
  134651. 13,
  134652. 4,
  134653. 14,
  134654. 3,
  134655. 15,
  134656. 2,
  134657. 16,
  134658. 1,
  134659. 17,
  134660. 0,
  134661. 18,
  134662. };
  134663. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134664. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134665. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134666. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134667. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134668. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134669. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134670. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134671. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134672. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134673. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134674. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134675. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134676. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134677. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134678. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134679. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134680. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134681. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134682. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134683. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134684. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134685. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134686. 14,13,13,14,14,15,14,15,14,
  134687. };
  134688. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134689. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134690. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134691. 367.5, 416.5,
  134692. };
  134693. static long _vq_quantmap__44c8_s_p9_1[] = {
  134694. 17, 15, 13, 11, 9, 7, 5, 3,
  134695. 1, 0, 2, 4, 6, 8, 10, 12,
  134696. 14, 16, 18,
  134697. };
  134698. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134699. _vq_quantthresh__44c8_s_p9_1,
  134700. _vq_quantmap__44c8_s_p9_1,
  134701. 19,
  134702. 19
  134703. };
  134704. static static_codebook _44c8_s_p9_1 = {
  134705. 2, 361,
  134706. _vq_lengthlist__44c8_s_p9_1,
  134707. 1, -518287360, 1622704128, 5, 0,
  134708. _vq_quantlist__44c8_s_p9_1,
  134709. NULL,
  134710. &_vq_auxt__44c8_s_p9_1,
  134711. NULL,
  134712. 0
  134713. };
  134714. static long _vq_quantlist__44c8_s_p9_2[] = {
  134715. 24,
  134716. 23,
  134717. 25,
  134718. 22,
  134719. 26,
  134720. 21,
  134721. 27,
  134722. 20,
  134723. 28,
  134724. 19,
  134725. 29,
  134726. 18,
  134727. 30,
  134728. 17,
  134729. 31,
  134730. 16,
  134731. 32,
  134732. 15,
  134733. 33,
  134734. 14,
  134735. 34,
  134736. 13,
  134737. 35,
  134738. 12,
  134739. 36,
  134740. 11,
  134741. 37,
  134742. 10,
  134743. 38,
  134744. 9,
  134745. 39,
  134746. 8,
  134747. 40,
  134748. 7,
  134749. 41,
  134750. 6,
  134751. 42,
  134752. 5,
  134753. 43,
  134754. 4,
  134755. 44,
  134756. 3,
  134757. 45,
  134758. 2,
  134759. 46,
  134760. 1,
  134761. 47,
  134762. 0,
  134763. 48,
  134764. };
  134765. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134766. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134767. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134768. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134769. 7,
  134770. };
  134771. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134772. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134773. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134774. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134775. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134776. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134777. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134778. };
  134779. static long _vq_quantmap__44c8_s_p9_2[] = {
  134780. 47, 45, 43, 41, 39, 37, 35, 33,
  134781. 31, 29, 27, 25, 23, 21, 19, 17,
  134782. 15, 13, 11, 9, 7, 5, 3, 1,
  134783. 0, 2, 4, 6, 8, 10, 12, 14,
  134784. 16, 18, 20, 22, 24, 26, 28, 30,
  134785. 32, 34, 36, 38, 40, 42, 44, 46,
  134786. 48,
  134787. };
  134788. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134789. _vq_quantthresh__44c8_s_p9_2,
  134790. _vq_quantmap__44c8_s_p9_2,
  134791. 49,
  134792. 49
  134793. };
  134794. static static_codebook _44c8_s_p9_2 = {
  134795. 1, 49,
  134796. _vq_lengthlist__44c8_s_p9_2,
  134797. 1, -526909440, 1611661312, 6, 0,
  134798. _vq_quantlist__44c8_s_p9_2,
  134799. NULL,
  134800. &_vq_auxt__44c8_s_p9_2,
  134801. NULL,
  134802. 0
  134803. };
  134804. static long _huff_lengthlist__44c8_s_short[] = {
  134805. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134806. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134807. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134808. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134809. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134810. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134811. 10, 9,11,14,
  134812. };
  134813. static static_codebook _huff_book__44c8_s_short = {
  134814. 2, 100,
  134815. _huff_lengthlist__44c8_s_short,
  134816. 0, 0, 0, 0, 0,
  134817. NULL,
  134818. NULL,
  134819. NULL,
  134820. NULL,
  134821. 0
  134822. };
  134823. static long _huff_lengthlist__44c9_s_long[] = {
  134824. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134825. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134826. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134827. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134828. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134829. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134830. 10, 9, 8, 9,
  134831. };
  134832. static static_codebook _huff_book__44c9_s_long = {
  134833. 2, 100,
  134834. _huff_lengthlist__44c9_s_long,
  134835. 0, 0, 0, 0, 0,
  134836. NULL,
  134837. NULL,
  134838. NULL,
  134839. NULL,
  134840. 0
  134841. };
  134842. static long _vq_quantlist__44c9_s_p1_0[] = {
  134843. 1,
  134844. 0,
  134845. 2,
  134846. };
  134847. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134848. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134849. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134850. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134851. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134852. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134853. 7,
  134854. };
  134855. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134856. -0.5, 0.5,
  134857. };
  134858. static long _vq_quantmap__44c9_s_p1_0[] = {
  134859. 1, 0, 2,
  134860. };
  134861. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134862. _vq_quantthresh__44c9_s_p1_0,
  134863. _vq_quantmap__44c9_s_p1_0,
  134864. 3,
  134865. 3
  134866. };
  134867. static static_codebook _44c9_s_p1_0 = {
  134868. 4, 81,
  134869. _vq_lengthlist__44c9_s_p1_0,
  134870. 1, -535822336, 1611661312, 2, 0,
  134871. _vq_quantlist__44c9_s_p1_0,
  134872. NULL,
  134873. &_vq_auxt__44c9_s_p1_0,
  134874. NULL,
  134875. 0
  134876. };
  134877. static long _vq_quantlist__44c9_s_p2_0[] = {
  134878. 2,
  134879. 1,
  134880. 3,
  134881. 0,
  134882. 4,
  134883. };
  134884. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134885. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134886. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134887. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134888. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134889. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134890. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134891. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134892. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134894. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134895. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134896. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134897. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134898. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134899. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134900. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134902. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134903. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134904. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134905. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134906. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134907. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134908. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134910. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134911. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134912. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134913. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134914. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134915. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134916. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134921. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134922. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134923. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134924. 12,
  134925. };
  134926. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134927. -1.5, -0.5, 0.5, 1.5,
  134928. };
  134929. static long _vq_quantmap__44c9_s_p2_0[] = {
  134930. 3, 1, 0, 2, 4,
  134931. };
  134932. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134933. _vq_quantthresh__44c9_s_p2_0,
  134934. _vq_quantmap__44c9_s_p2_0,
  134935. 5,
  134936. 5
  134937. };
  134938. static static_codebook _44c9_s_p2_0 = {
  134939. 4, 625,
  134940. _vq_lengthlist__44c9_s_p2_0,
  134941. 1, -533725184, 1611661312, 3, 0,
  134942. _vq_quantlist__44c9_s_p2_0,
  134943. NULL,
  134944. &_vq_auxt__44c9_s_p2_0,
  134945. NULL,
  134946. 0
  134947. };
  134948. static long _vq_quantlist__44c9_s_p3_0[] = {
  134949. 4,
  134950. 3,
  134951. 5,
  134952. 2,
  134953. 6,
  134954. 1,
  134955. 7,
  134956. 0,
  134957. 8,
  134958. };
  134959. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134960. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134961. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134962. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134963. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134965. 0,
  134966. };
  134967. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134968. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134969. };
  134970. static long _vq_quantmap__44c9_s_p3_0[] = {
  134971. 7, 5, 3, 1, 0, 2, 4, 6,
  134972. 8,
  134973. };
  134974. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134975. _vq_quantthresh__44c9_s_p3_0,
  134976. _vq_quantmap__44c9_s_p3_0,
  134977. 9,
  134978. 9
  134979. };
  134980. static static_codebook _44c9_s_p3_0 = {
  134981. 2, 81,
  134982. _vq_lengthlist__44c9_s_p3_0,
  134983. 1, -531628032, 1611661312, 4, 0,
  134984. _vq_quantlist__44c9_s_p3_0,
  134985. NULL,
  134986. &_vq_auxt__44c9_s_p3_0,
  134987. NULL,
  134988. 0
  134989. };
  134990. static long _vq_quantlist__44c9_s_p4_0[] = {
  134991. 8,
  134992. 7,
  134993. 9,
  134994. 6,
  134995. 10,
  134996. 5,
  134997. 11,
  134998. 4,
  134999. 12,
  135000. 3,
  135001. 13,
  135002. 2,
  135003. 14,
  135004. 1,
  135005. 15,
  135006. 0,
  135007. 16,
  135008. };
  135009. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135010. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135011. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135012. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135013. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135014. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135015. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135016. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135017. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135018. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135019. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0,
  135029. };
  135030. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135031. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135032. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135033. };
  135034. static long _vq_quantmap__44c9_s_p4_0[] = {
  135035. 15, 13, 11, 9, 7, 5, 3, 1,
  135036. 0, 2, 4, 6, 8, 10, 12, 14,
  135037. 16,
  135038. };
  135039. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135040. _vq_quantthresh__44c9_s_p4_0,
  135041. _vq_quantmap__44c9_s_p4_0,
  135042. 17,
  135043. 17
  135044. };
  135045. static static_codebook _44c9_s_p4_0 = {
  135046. 2, 289,
  135047. _vq_lengthlist__44c9_s_p4_0,
  135048. 1, -529530880, 1611661312, 5, 0,
  135049. _vq_quantlist__44c9_s_p4_0,
  135050. NULL,
  135051. &_vq_auxt__44c9_s_p4_0,
  135052. NULL,
  135053. 0
  135054. };
  135055. static long _vq_quantlist__44c9_s_p5_0[] = {
  135056. 1,
  135057. 0,
  135058. 2,
  135059. };
  135060. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135061. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135062. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135063. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135064. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135065. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135066. 12,
  135067. };
  135068. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135069. -5.5, 5.5,
  135070. };
  135071. static long _vq_quantmap__44c9_s_p5_0[] = {
  135072. 1, 0, 2,
  135073. };
  135074. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135075. _vq_quantthresh__44c9_s_p5_0,
  135076. _vq_quantmap__44c9_s_p5_0,
  135077. 3,
  135078. 3
  135079. };
  135080. static static_codebook _44c9_s_p5_0 = {
  135081. 4, 81,
  135082. _vq_lengthlist__44c9_s_p5_0,
  135083. 1, -529137664, 1618345984, 2, 0,
  135084. _vq_quantlist__44c9_s_p5_0,
  135085. NULL,
  135086. &_vq_auxt__44c9_s_p5_0,
  135087. NULL,
  135088. 0
  135089. };
  135090. static long _vq_quantlist__44c9_s_p5_1[] = {
  135091. 5,
  135092. 4,
  135093. 6,
  135094. 3,
  135095. 7,
  135096. 2,
  135097. 8,
  135098. 1,
  135099. 9,
  135100. 0,
  135101. 10,
  135102. };
  135103. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135104. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135105. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135106. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135107. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135108. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135109. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135110. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135111. 11,11,11, 7, 7, 7, 7, 7, 7,
  135112. };
  135113. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135114. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135115. 3.5, 4.5,
  135116. };
  135117. static long _vq_quantmap__44c9_s_p5_1[] = {
  135118. 9, 7, 5, 3, 1, 0, 2, 4,
  135119. 6, 8, 10,
  135120. };
  135121. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135122. _vq_quantthresh__44c9_s_p5_1,
  135123. _vq_quantmap__44c9_s_p5_1,
  135124. 11,
  135125. 11
  135126. };
  135127. static static_codebook _44c9_s_p5_1 = {
  135128. 2, 121,
  135129. _vq_lengthlist__44c9_s_p5_1,
  135130. 1, -531365888, 1611661312, 4, 0,
  135131. _vq_quantlist__44c9_s_p5_1,
  135132. NULL,
  135133. &_vq_auxt__44c9_s_p5_1,
  135134. NULL,
  135135. 0
  135136. };
  135137. static long _vq_quantlist__44c9_s_p6_0[] = {
  135138. 6,
  135139. 5,
  135140. 7,
  135141. 4,
  135142. 8,
  135143. 3,
  135144. 9,
  135145. 2,
  135146. 10,
  135147. 1,
  135148. 11,
  135149. 0,
  135150. 12,
  135151. };
  135152. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135153. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135154. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135155. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135156. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135157. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135158. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135163. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135164. };
  135165. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135166. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135167. 12.5, 17.5, 22.5, 27.5,
  135168. };
  135169. static long _vq_quantmap__44c9_s_p6_0[] = {
  135170. 11, 9, 7, 5, 3, 1, 0, 2,
  135171. 4, 6, 8, 10, 12,
  135172. };
  135173. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135174. _vq_quantthresh__44c9_s_p6_0,
  135175. _vq_quantmap__44c9_s_p6_0,
  135176. 13,
  135177. 13
  135178. };
  135179. static static_codebook _44c9_s_p6_0 = {
  135180. 2, 169,
  135181. _vq_lengthlist__44c9_s_p6_0,
  135182. 1, -526516224, 1616117760, 4, 0,
  135183. _vq_quantlist__44c9_s_p6_0,
  135184. NULL,
  135185. &_vq_auxt__44c9_s_p6_0,
  135186. NULL,
  135187. 0
  135188. };
  135189. static long _vq_quantlist__44c9_s_p6_1[] = {
  135190. 2,
  135191. 1,
  135192. 3,
  135193. 0,
  135194. 4,
  135195. };
  135196. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135197. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135198. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135199. };
  135200. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135201. -1.5, -0.5, 0.5, 1.5,
  135202. };
  135203. static long _vq_quantmap__44c9_s_p6_1[] = {
  135204. 3, 1, 0, 2, 4,
  135205. };
  135206. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135207. _vq_quantthresh__44c9_s_p6_1,
  135208. _vq_quantmap__44c9_s_p6_1,
  135209. 5,
  135210. 5
  135211. };
  135212. static static_codebook _44c9_s_p6_1 = {
  135213. 2, 25,
  135214. _vq_lengthlist__44c9_s_p6_1,
  135215. 1, -533725184, 1611661312, 3, 0,
  135216. _vq_quantlist__44c9_s_p6_1,
  135217. NULL,
  135218. &_vq_auxt__44c9_s_p6_1,
  135219. NULL,
  135220. 0
  135221. };
  135222. static long _vq_quantlist__44c9_s_p7_0[] = {
  135223. 6,
  135224. 5,
  135225. 7,
  135226. 4,
  135227. 8,
  135228. 3,
  135229. 9,
  135230. 2,
  135231. 10,
  135232. 1,
  135233. 11,
  135234. 0,
  135235. 12,
  135236. };
  135237. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135238. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135239. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135240. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135241. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135242. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135243. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135244. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135245. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135246. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135247. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135248. 19,12,12,12,12,13,13,14,14,
  135249. };
  135250. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135251. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135252. 27.5, 38.5, 49.5, 60.5,
  135253. };
  135254. static long _vq_quantmap__44c9_s_p7_0[] = {
  135255. 11, 9, 7, 5, 3, 1, 0, 2,
  135256. 4, 6, 8, 10, 12,
  135257. };
  135258. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135259. _vq_quantthresh__44c9_s_p7_0,
  135260. _vq_quantmap__44c9_s_p7_0,
  135261. 13,
  135262. 13
  135263. };
  135264. static static_codebook _44c9_s_p7_0 = {
  135265. 2, 169,
  135266. _vq_lengthlist__44c9_s_p7_0,
  135267. 1, -523206656, 1618345984, 4, 0,
  135268. _vq_quantlist__44c9_s_p7_0,
  135269. NULL,
  135270. &_vq_auxt__44c9_s_p7_0,
  135271. NULL,
  135272. 0
  135273. };
  135274. static long _vq_quantlist__44c9_s_p7_1[] = {
  135275. 5,
  135276. 4,
  135277. 6,
  135278. 3,
  135279. 7,
  135280. 2,
  135281. 8,
  135282. 1,
  135283. 9,
  135284. 0,
  135285. 10,
  135286. };
  135287. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135288. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135289. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135290. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135291. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135292. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135293. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135294. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135295. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135296. };
  135297. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135298. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135299. 3.5, 4.5,
  135300. };
  135301. static long _vq_quantmap__44c9_s_p7_1[] = {
  135302. 9, 7, 5, 3, 1, 0, 2, 4,
  135303. 6, 8, 10,
  135304. };
  135305. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135306. _vq_quantthresh__44c9_s_p7_1,
  135307. _vq_quantmap__44c9_s_p7_1,
  135308. 11,
  135309. 11
  135310. };
  135311. static static_codebook _44c9_s_p7_1 = {
  135312. 2, 121,
  135313. _vq_lengthlist__44c9_s_p7_1,
  135314. 1, -531365888, 1611661312, 4, 0,
  135315. _vq_quantlist__44c9_s_p7_1,
  135316. NULL,
  135317. &_vq_auxt__44c9_s_p7_1,
  135318. NULL,
  135319. 0
  135320. };
  135321. static long _vq_quantlist__44c9_s_p8_0[] = {
  135322. 7,
  135323. 6,
  135324. 8,
  135325. 5,
  135326. 9,
  135327. 4,
  135328. 10,
  135329. 3,
  135330. 11,
  135331. 2,
  135332. 12,
  135333. 1,
  135334. 13,
  135335. 0,
  135336. 14,
  135337. };
  135338. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135339. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135340. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135341. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135342. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135343. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135344. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135345. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135346. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135347. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135348. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135349. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135350. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135351. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135352. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135353. 14,
  135354. };
  135355. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135356. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135357. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135358. };
  135359. static long _vq_quantmap__44c9_s_p8_0[] = {
  135360. 13, 11, 9, 7, 5, 3, 1, 0,
  135361. 2, 4, 6, 8, 10, 12, 14,
  135362. };
  135363. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135364. _vq_quantthresh__44c9_s_p8_0,
  135365. _vq_quantmap__44c9_s_p8_0,
  135366. 15,
  135367. 15
  135368. };
  135369. static static_codebook _44c9_s_p8_0 = {
  135370. 2, 225,
  135371. _vq_lengthlist__44c9_s_p8_0,
  135372. 1, -520986624, 1620377600, 4, 0,
  135373. _vq_quantlist__44c9_s_p8_0,
  135374. NULL,
  135375. &_vq_auxt__44c9_s_p8_0,
  135376. NULL,
  135377. 0
  135378. };
  135379. static long _vq_quantlist__44c9_s_p8_1[] = {
  135380. 10,
  135381. 9,
  135382. 11,
  135383. 8,
  135384. 12,
  135385. 7,
  135386. 13,
  135387. 6,
  135388. 14,
  135389. 5,
  135390. 15,
  135391. 4,
  135392. 16,
  135393. 3,
  135394. 17,
  135395. 2,
  135396. 18,
  135397. 1,
  135398. 19,
  135399. 0,
  135400. 20,
  135401. };
  135402. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135403. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135404. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135405. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135406. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135407. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135408. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135409. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135410. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135411. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135412. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135413. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135414. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135415. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135416. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135417. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135418. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135419. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135420. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135421. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135422. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135423. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135424. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135425. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135426. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135427. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135428. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135429. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135430. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135431. };
  135432. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135433. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135434. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135435. 6.5, 7.5, 8.5, 9.5,
  135436. };
  135437. static long _vq_quantmap__44c9_s_p8_1[] = {
  135438. 19, 17, 15, 13, 11, 9, 7, 5,
  135439. 3, 1, 0, 2, 4, 6, 8, 10,
  135440. 12, 14, 16, 18, 20,
  135441. };
  135442. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135443. _vq_quantthresh__44c9_s_p8_1,
  135444. _vq_quantmap__44c9_s_p8_1,
  135445. 21,
  135446. 21
  135447. };
  135448. static static_codebook _44c9_s_p8_1 = {
  135449. 2, 441,
  135450. _vq_lengthlist__44c9_s_p8_1,
  135451. 1, -529268736, 1611661312, 5, 0,
  135452. _vq_quantlist__44c9_s_p8_1,
  135453. NULL,
  135454. &_vq_auxt__44c9_s_p8_1,
  135455. NULL,
  135456. 0
  135457. };
  135458. static long _vq_quantlist__44c9_s_p9_0[] = {
  135459. 9,
  135460. 8,
  135461. 10,
  135462. 7,
  135463. 11,
  135464. 6,
  135465. 12,
  135466. 5,
  135467. 13,
  135468. 4,
  135469. 14,
  135470. 3,
  135471. 15,
  135472. 2,
  135473. 16,
  135474. 1,
  135475. 17,
  135476. 0,
  135477. 18,
  135478. };
  135479. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135480. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135481. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135482. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135483. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135484. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135485. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135486. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135487. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135488. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135489. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135490. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135491. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135492. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135493. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135494. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135495. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135496. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135502. 11,11,11,11,11,11,11,11,11,
  135503. };
  135504. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135505. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135506. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135507. 6982.5, 7913.5,
  135508. };
  135509. static long _vq_quantmap__44c9_s_p9_0[] = {
  135510. 17, 15, 13, 11, 9, 7, 5, 3,
  135511. 1, 0, 2, 4, 6, 8, 10, 12,
  135512. 14, 16, 18,
  135513. };
  135514. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135515. _vq_quantthresh__44c9_s_p9_0,
  135516. _vq_quantmap__44c9_s_p9_0,
  135517. 19,
  135518. 19
  135519. };
  135520. static static_codebook _44c9_s_p9_0 = {
  135521. 2, 361,
  135522. _vq_lengthlist__44c9_s_p9_0,
  135523. 1, -508535424, 1631393792, 5, 0,
  135524. _vq_quantlist__44c9_s_p9_0,
  135525. NULL,
  135526. &_vq_auxt__44c9_s_p9_0,
  135527. NULL,
  135528. 0
  135529. };
  135530. static long _vq_quantlist__44c9_s_p9_1[] = {
  135531. 9,
  135532. 8,
  135533. 10,
  135534. 7,
  135535. 11,
  135536. 6,
  135537. 12,
  135538. 5,
  135539. 13,
  135540. 4,
  135541. 14,
  135542. 3,
  135543. 15,
  135544. 2,
  135545. 16,
  135546. 1,
  135547. 17,
  135548. 0,
  135549. 18,
  135550. };
  135551. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135552. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135553. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135554. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135555. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135556. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135557. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135558. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135559. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135560. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135561. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135562. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135563. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135564. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135565. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135566. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135567. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135568. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135569. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135570. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135571. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135572. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135573. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135574. 13,13,13,14,13,14,15,15,15,
  135575. };
  135576. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135577. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135578. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135579. 367.5, 416.5,
  135580. };
  135581. static long _vq_quantmap__44c9_s_p9_1[] = {
  135582. 17, 15, 13, 11, 9, 7, 5, 3,
  135583. 1, 0, 2, 4, 6, 8, 10, 12,
  135584. 14, 16, 18,
  135585. };
  135586. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135587. _vq_quantthresh__44c9_s_p9_1,
  135588. _vq_quantmap__44c9_s_p9_1,
  135589. 19,
  135590. 19
  135591. };
  135592. static static_codebook _44c9_s_p9_1 = {
  135593. 2, 361,
  135594. _vq_lengthlist__44c9_s_p9_1,
  135595. 1, -518287360, 1622704128, 5, 0,
  135596. _vq_quantlist__44c9_s_p9_1,
  135597. NULL,
  135598. &_vq_auxt__44c9_s_p9_1,
  135599. NULL,
  135600. 0
  135601. };
  135602. static long _vq_quantlist__44c9_s_p9_2[] = {
  135603. 24,
  135604. 23,
  135605. 25,
  135606. 22,
  135607. 26,
  135608. 21,
  135609. 27,
  135610. 20,
  135611. 28,
  135612. 19,
  135613. 29,
  135614. 18,
  135615. 30,
  135616. 17,
  135617. 31,
  135618. 16,
  135619. 32,
  135620. 15,
  135621. 33,
  135622. 14,
  135623. 34,
  135624. 13,
  135625. 35,
  135626. 12,
  135627. 36,
  135628. 11,
  135629. 37,
  135630. 10,
  135631. 38,
  135632. 9,
  135633. 39,
  135634. 8,
  135635. 40,
  135636. 7,
  135637. 41,
  135638. 6,
  135639. 42,
  135640. 5,
  135641. 43,
  135642. 4,
  135643. 44,
  135644. 3,
  135645. 45,
  135646. 2,
  135647. 46,
  135648. 1,
  135649. 47,
  135650. 0,
  135651. 48,
  135652. };
  135653. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135654. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135655. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135656. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135657. 7,
  135658. };
  135659. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135660. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135661. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135662. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135663. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135664. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135665. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135666. };
  135667. static long _vq_quantmap__44c9_s_p9_2[] = {
  135668. 47, 45, 43, 41, 39, 37, 35, 33,
  135669. 31, 29, 27, 25, 23, 21, 19, 17,
  135670. 15, 13, 11, 9, 7, 5, 3, 1,
  135671. 0, 2, 4, 6, 8, 10, 12, 14,
  135672. 16, 18, 20, 22, 24, 26, 28, 30,
  135673. 32, 34, 36, 38, 40, 42, 44, 46,
  135674. 48,
  135675. };
  135676. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135677. _vq_quantthresh__44c9_s_p9_2,
  135678. _vq_quantmap__44c9_s_p9_2,
  135679. 49,
  135680. 49
  135681. };
  135682. static static_codebook _44c9_s_p9_2 = {
  135683. 1, 49,
  135684. _vq_lengthlist__44c9_s_p9_2,
  135685. 1, -526909440, 1611661312, 6, 0,
  135686. _vq_quantlist__44c9_s_p9_2,
  135687. NULL,
  135688. &_vq_auxt__44c9_s_p9_2,
  135689. NULL,
  135690. 0
  135691. };
  135692. static long _huff_lengthlist__44c9_s_short[] = {
  135693. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135694. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135695. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135696. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135697. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135698. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135699. 9, 8,10,13,
  135700. };
  135701. static static_codebook _huff_book__44c9_s_short = {
  135702. 2, 100,
  135703. _huff_lengthlist__44c9_s_short,
  135704. 0, 0, 0, 0, 0,
  135705. NULL,
  135706. NULL,
  135707. NULL,
  135708. NULL,
  135709. 0
  135710. };
  135711. static long _huff_lengthlist__44c0_s_long[] = {
  135712. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135713. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135714. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135715. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135716. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135717. 12,
  135718. };
  135719. static static_codebook _huff_book__44c0_s_long = {
  135720. 2, 81,
  135721. _huff_lengthlist__44c0_s_long,
  135722. 0, 0, 0, 0, 0,
  135723. NULL,
  135724. NULL,
  135725. NULL,
  135726. NULL,
  135727. 0
  135728. };
  135729. static long _vq_quantlist__44c0_s_p1_0[] = {
  135730. 1,
  135731. 0,
  135732. 2,
  135733. };
  135734. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135735. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135736. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135740. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135741. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135745. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135746. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135781. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135786. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135791. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135827. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135832. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135837. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0,
  136146. };
  136147. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136148. -0.5, 0.5,
  136149. };
  136150. static long _vq_quantmap__44c0_s_p1_0[] = {
  136151. 1, 0, 2,
  136152. };
  136153. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136154. _vq_quantthresh__44c0_s_p1_0,
  136155. _vq_quantmap__44c0_s_p1_0,
  136156. 3,
  136157. 3
  136158. };
  136159. static static_codebook _44c0_s_p1_0 = {
  136160. 8, 6561,
  136161. _vq_lengthlist__44c0_s_p1_0,
  136162. 1, -535822336, 1611661312, 2, 0,
  136163. _vq_quantlist__44c0_s_p1_0,
  136164. NULL,
  136165. &_vq_auxt__44c0_s_p1_0,
  136166. NULL,
  136167. 0
  136168. };
  136169. static long _vq_quantlist__44c0_s_p2_0[] = {
  136170. 2,
  136171. 1,
  136172. 3,
  136173. 0,
  136174. 4,
  136175. };
  136176. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136177. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  136217. };
  136218. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136219. -1.5, -0.5, 0.5, 1.5,
  136220. };
  136221. static long _vq_quantmap__44c0_s_p2_0[] = {
  136222. 3, 1, 0, 2, 4,
  136223. };
  136224. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136225. _vq_quantthresh__44c0_s_p2_0,
  136226. _vq_quantmap__44c0_s_p2_0,
  136227. 5,
  136228. 5
  136229. };
  136230. static static_codebook _44c0_s_p2_0 = {
  136231. 4, 625,
  136232. _vq_lengthlist__44c0_s_p2_0,
  136233. 1, -533725184, 1611661312, 3, 0,
  136234. _vq_quantlist__44c0_s_p2_0,
  136235. NULL,
  136236. &_vq_auxt__44c0_s_p2_0,
  136237. NULL,
  136238. 0
  136239. };
  136240. static long _vq_quantlist__44c0_s_p3_0[] = {
  136241. 4,
  136242. 3,
  136243. 5,
  136244. 2,
  136245. 6,
  136246. 1,
  136247. 7,
  136248. 0,
  136249. 8,
  136250. };
  136251. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136252. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136253. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136254. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136255. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136256. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0,
  136258. };
  136259. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136260. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136261. };
  136262. static long _vq_quantmap__44c0_s_p3_0[] = {
  136263. 7, 5, 3, 1, 0, 2, 4, 6,
  136264. 8,
  136265. };
  136266. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136267. _vq_quantthresh__44c0_s_p3_0,
  136268. _vq_quantmap__44c0_s_p3_0,
  136269. 9,
  136270. 9
  136271. };
  136272. static static_codebook _44c0_s_p3_0 = {
  136273. 2, 81,
  136274. _vq_lengthlist__44c0_s_p3_0,
  136275. 1, -531628032, 1611661312, 4, 0,
  136276. _vq_quantlist__44c0_s_p3_0,
  136277. NULL,
  136278. &_vq_auxt__44c0_s_p3_0,
  136279. NULL,
  136280. 0
  136281. };
  136282. static long _vq_quantlist__44c0_s_p4_0[] = {
  136283. 4,
  136284. 3,
  136285. 5,
  136286. 2,
  136287. 6,
  136288. 1,
  136289. 7,
  136290. 0,
  136291. 8,
  136292. };
  136293. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136294. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136295. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136296. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136297. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136298. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136299. 10,
  136300. };
  136301. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136302. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136303. };
  136304. static long _vq_quantmap__44c0_s_p4_0[] = {
  136305. 7, 5, 3, 1, 0, 2, 4, 6,
  136306. 8,
  136307. };
  136308. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136309. _vq_quantthresh__44c0_s_p4_0,
  136310. _vq_quantmap__44c0_s_p4_0,
  136311. 9,
  136312. 9
  136313. };
  136314. static static_codebook _44c0_s_p4_0 = {
  136315. 2, 81,
  136316. _vq_lengthlist__44c0_s_p4_0,
  136317. 1, -531628032, 1611661312, 4, 0,
  136318. _vq_quantlist__44c0_s_p4_0,
  136319. NULL,
  136320. &_vq_auxt__44c0_s_p4_0,
  136321. NULL,
  136322. 0
  136323. };
  136324. static long _vq_quantlist__44c0_s_p5_0[] = {
  136325. 8,
  136326. 7,
  136327. 9,
  136328. 6,
  136329. 10,
  136330. 5,
  136331. 11,
  136332. 4,
  136333. 12,
  136334. 3,
  136335. 13,
  136336. 2,
  136337. 14,
  136338. 1,
  136339. 15,
  136340. 0,
  136341. 16,
  136342. };
  136343. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136344. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136345. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136346. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136347. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136348. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136349. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136350. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136351. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136352. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136353. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136354. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136355. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136356. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136357. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136358. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136359. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136360. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136362. 14,
  136363. };
  136364. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136365. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136366. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136367. };
  136368. static long _vq_quantmap__44c0_s_p5_0[] = {
  136369. 15, 13, 11, 9, 7, 5, 3, 1,
  136370. 0, 2, 4, 6, 8, 10, 12, 14,
  136371. 16,
  136372. };
  136373. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136374. _vq_quantthresh__44c0_s_p5_0,
  136375. _vq_quantmap__44c0_s_p5_0,
  136376. 17,
  136377. 17
  136378. };
  136379. static static_codebook _44c0_s_p5_0 = {
  136380. 2, 289,
  136381. _vq_lengthlist__44c0_s_p5_0,
  136382. 1, -529530880, 1611661312, 5, 0,
  136383. _vq_quantlist__44c0_s_p5_0,
  136384. NULL,
  136385. &_vq_auxt__44c0_s_p5_0,
  136386. NULL,
  136387. 0
  136388. };
  136389. static long _vq_quantlist__44c0_s_p6_0[] = {
  136390. 1,
  136391. 0,
  136392. 2,
  136393. };
  136394. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136395. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136396. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136397. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136398. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136399. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136400. 10,
  136401. };
  136402. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136403. -5.5, 5.5,
  136404. };
  136405. static long _vq_quantmap__44c0_s_p6_0[] = {
  136406. 1, 0, 2,
  136407. };
  136408. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136409. _vq_quantthresh__44c0_s_p6_0,
  136410. _vq_quantmap__44c0_s_p6_0,
  136411. 3,
  136412. 3
  136413. };
  136414. static static_codebook _44c0_s_p6_0 = {
  136415. 4, 81,
  136416. _vq_lengthlist__44c0_s_p6_0,
  136417. 1, -529137664, 1618345984, 2, 0,
  136418. _vq_quantlist__44c0_s_p6_0,
  136419. NULL,
  136420. &_vq_auxt__44c0_s_p6_0,
  136421. NULL,
  136422. 0
  136423. };
  136424. static long _vq_quantlist__44c0_s_p6_1[] = {
  136425. 5,
  136426. 4,
  136427. 6,
  136428. 3,
  136429. 7,
  136430. 2,
  136431. 8,
  136432. 1,
  136433. 9,
  136434. 0,
  136435. 10,
  136436. };
  136437. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136438. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136439. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136440. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136441. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136442. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136443. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136444. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136445. 10,10,10, 8, 8, 8, 8, 8, 8,
  136446. };
  136447. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136448. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136449. 3.5, 4.5,
  136450. };
  136451. static long _vq_quantmap__44c0_s_p6_1[] = {
  136452. 9, 7, 5, 3, 1, 0, 2, 4,
  136453. 6, 8, 10,
  136454. };
  136455. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136456. _vq_quantthresh__44c0_s_p6_1,
  136457. _vq_quantmap__44c0_s_p6_1,
  136458. 11,
  136459. 11
  136460. };
  136461. static static_codebook _44c0_s_p6_1 = {
  136462. 2, 121,
  136463. _vq_lengthlist__44c0_s_p6_1,
  136464. 1, -531365888, 1611661312, 4, 0,
  136465. _vq_quantlist__44c0_s_p6_1,
  136466. NULL,
  136467. &_vq_auxt__44c0_s_p6_1,
  136468. NULL,
  136469. 0
  136470. };
  136471. static long _vq_quantlist__44c0_s_p7_0[] = {
  136472. 6,
  136473. 5,
  136474. 7,
  136475. 4,
  136476. 8,
  136477. 3,
  136478. 9,
  136479. 2,
  136480. 10,
  136481. 1,
  136482. 11,
  136483. 0,
  136484. 12,
  136485. };
  136486. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136487. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136488. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136489. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136490. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136491. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136492. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136493. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136494. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136495. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136496. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136497. 0,12,12,11,11,12,12,13,13,
  136498. };
  136499. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136500. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136501. 12.5, 17.5, 22.5, 27.5,
  136502. };
  136503. static long _vq_quantmap__44c0_s_p7_0[] = {
  136504. 11, 9, 7, 5, 3, 1, 0, 2,
  136505. 4, 6, 8, 10, 12,
  136506. };
  136507. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136508. _vq_quantthresh__44c0_s_p7_0,
  136509. _vq_quantmap__44c0_s_p7_0,
  136510. 13,
  136511. 13
  136512. };
  136513. static static_codebook _44c0_s_p7_0 = {
  136514. 2, 169,
  136515. _vq_lengthlist__44c0_s_p7_0,
  136516. 1, -526516224, 1616117760, 4, 0,
  136517. _vq_quantlist__44c0_s_p7_0,
  136518. NULL,
  136519. &_vq_auxt__44c0_s_p7_0,
  136520. NULL,
  136521. 0
  136522. };
  136523. static long _vq_quantlist__44c0_s_p7_1[] = {
  136524. 2,
  136525. 1,
  136526. 3,
  136527. 0,
  136528. 4,
  136529. };
  136530. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136531. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136532. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136533. };
  136534. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136535. -1.5, -0.5, 0.5, 1.5,
  136536. };
  136537. static long _vq_quantmap__44c0_s_p7_1[] = {
  136538. 3, 1, 0, 2, 4,
  136539. };
  136540. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136541. _vq_quantthresh__44c0_s_p7_1,
  136542. _vq_quantmap__44c0_s_p7_1,
  136543. 5,
  136544. 5
  136545. };
  136546. static static_codebook _44c0_s_p7_1 = {
  136547. 2, 25,
  136548. _vq_lengthlist__44c0_s_p7_1,
  136549. 1, -533725184, 1611661312, 3, 0,
  136550. _vq_quantlist__44c0_s_p7_1,
  136551. NULL,
  136552. &_vq_auxt__44c0_s_p7_1,
  136553. NULL,
  136554. 0
  136555. };
  136556. static long _vq_quantlist__44c0_s_p8_0[] = {
  136557. 2,
  136558. 1,
  136559. 3,
  136560. 0,
  136561. 4,
  136562. };
  136563. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136564. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136565. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136566. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136567. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136568. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136569. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136570. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136571. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136572. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136573. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136574. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136575. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136576. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136577. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136578. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136579. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136580. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136581. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136582. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136583. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136584. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136585. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136586. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136587. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136588. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136589. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136590. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136592. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136596. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136603. 11,
  136604. };
  136605. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136606. -331.5, -110.5, 110.5, 331.5,
  136607. };
  136608. static long _vq_quantmap__44c0_s_p8_0[] = {
  136609. 3, 1, 0, 2, 4,
  136610. };
  136611. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136612. _vq_quantthresh__44c0_s_p8_0,
  136613. _vq_quantmap__44c0_s_p8_0,
  136614. 5,
  136615. 5
  136616. };
  136617. static static_codebook _44c0_s_p8_0 = {
  136618. 4, 625,
  136619. _vq_lengthlist__44c0_s_p8_0,
  136620. 1, -518283264, 1627103232, 3, 0,
  136621. _vq_quantlist__44c0_s_p8_0,
  136622. NULL,
  136623. &_vq_auxt__44c0_s_p8_0,
  136624. NULL,
  136625. 0
  136626. };
  136627. static long _vq_quantlist__44c0_s_p8_1[] = {
  136628. 6,
  136629. 5,
  136630. 7,
  136631. 4,
  136632. 8,
  136633. 3,
  136634. 9,
  136635. 2,
  136636. 10,
  136637. 1,
  136638. 11,
  136639. 0,
  136640. 12,
  136641. };
  136642. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136643. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136644. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136645. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136646. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136647. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136648. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136649. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136650. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136651. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136652. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136653. 16,13,13,12,12,14,14,15,13,
  136654. };
  136655. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136656. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136657. 42.5, 59.5, 76.5, 93.5,
  136658. };
  136659. static long _vq_quantmap__44c0_s_p8_1[] = {
  136660. 11, 9, 7, 5, 3, 1, 0, 2,
  136661. 4, 6, 8, 10, 12,
  136662. };
  136663. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136664. _vq_quantthresh__44c0_s_p8_1,
  136665. _vq_quantmap__44c0_s_p8_1,
  136666. 13,
  136667. 13
  136668. };
  136669. static static_codebook _44c0_s_p8_1 = {
  136670. 2, 169,
  136671. _vq_lengthlist__44c0_s_p8_1,
  136672. 1, -522616832, 1620115456, 4, 0,
  136673. _vq_quantlist__44c0_s_p8_1,
  136674. NULL,
  136675. &_vq_auxt__44c0_s_p8_1,
  136676. NULL,
  136677. 0
  136678. };
  136679. static long _vq_quantlist__44c0_s_p8_2[] = {
  136680. 8,
  136681. 7,
  136682. 9,
  136683. 6,
  136684. 10,
  136685. 5,
  136686. 11,
  136687. 4,
  136688. 12,
  136689. 3,
  136690. 13,
  136691. 2,
  136692. 14,
  136693. 1,
  136694. 15,
  136695. 0,
  136696. 16,
  136697. };
  136698. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136699. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136700. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136701. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136702. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136703. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136704. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136705. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136706. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136707. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136708. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136709. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136710. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136711. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136712. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136713. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136714. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136715. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136716. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136717. 10,
  136718. };
  136719. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136720. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136721. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136722. };
  136723. static long _vq_quantmap__44c0_s_p8_2[] = {
  136724. 15, 13, 11, 9, 7, 5, 3, 1,
  136725. 0, 2, 4, 6, 8, 10, 12, 14,
  136726. 16,
  136727. };
  136728. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136729. _vq_quantthresh__44c0_s_p8_2,
  136730. _vq_quantmap__44c0_s_p8_2,
  136731. 17,
  136732. 17
  136733. };
  136734. static static_codebook _44c0_s_p8_2 = {
  136735. 2, 289,
  136736. _vq_lengthlist__44c0_s_p8_2,
  136737. 1, -529530880, 1611661312, 5, 0,
  136738. _vq_quantlist__44c0_s_p8_2,
  136739. NULL,
  136740. &_vq_auxt__44c0_s_p8_2,
  136741. NULL,
  136742. 0
  136743. };
  136744. static long _huff_lengthlist__44c0_s_short[] = {
  136745. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136746. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136747. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136748. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136749. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136750. 12,
  136751. };
  136752. static static_codebook _huff_book__44c0_s_short = {
  136753. 2, 81,
  136754. _huff_lengthlist__44c0_s_short,
  136755. 0, 0, 0, 0, 0,
  136756. NULL,
  136757. NULL,
  136758. NULL,
  136759. NULL,
  136760. 0
  136761. };
  136762. static long _huff_lengthlist__44c0_sm_long[] = {
  136763. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136764. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136765. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136766. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136767. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136768. 13,
  136769. };
  136770. static static_codebook _huff_book__44c0_sm_long = {
  136771. 2, 81,
  136772. _huff_lengthlist__44c0_sm_long,
  136773. 0, 0, 0, 0, 0,
  136774. NULL,
  136775. NULL,
  136776. NULL,
  136777. NULL,
  136778. 0
  136779. };
  136780. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136781. 1,
  136782. 0,
  136783. 2,
  136784. };
  136785. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136786. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136787. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136791. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136792. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136797. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136832. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136837. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136842. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136878. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136883. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136888. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0,
  137197. };
  137198. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137199. -0.5, 0.5,
  137200. };
  137201. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137202. 1, 0, 2,
  137203. };
  137204. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137205. _vq_quantthresh__44c0_sm_p1_0,
  137206. _vq_quantmap__44c0_sm_p1_0,
  137207. 3,
  137208. 3
  137209. };
  137210. static static_codebook _44c0_sm_p1_0 = {
  137211. 8, 6561,
  137212. _vq_lengthlist__44c0_sm_p1_0,
  137213. 1, -535822336, 1611661312, 2, 0,
  137214. _vq_quantlist__44c0_sm_p1_0,
  137215. NULL,
  137216. &_vq_auxt__44c0_sm_p1_0,
  137217. NULL,
  137218. 0
  137219. };
  137220. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137221. 2,
  137222. 1,
  137223. 3,
  137224. 0,
  137225. 4,
  137226. };
  137227. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137228. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  137268. };
  137269. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137270. -1.5, -0.5, 0.5, 1.5,
  137271. };
  137272. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137273. 3, 1, 0, 2, 4,
  137274. };
  137275. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137276. _vq_quantthresh__44c0_sm_p2_0,
  137277. _vq_quantmap__44c0_sm_p2_0,
  137278. 5,
  137279. 5
  137280. };
  137281. static static_codebook _44c0_sm_p2_0 = {
  137282. 4, 625,
  137283. _vq_lengthlist__44c0_sm_p2_0,
  137284. 1, -533725184, 1611661312, 3, 0,
  137285. _vq_quantlist__44c0_sm_p2_0,
  137286. NULL,
  137287. &_vq_auxt__44c0_sm_p2_0,
  137288. NULL,
  137289. 0
  137290. };
  137291. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137292. 4,
  137293. 3,
  137294. 5,
  137295. 2,
  137296. 6,
  137297. 1,
  137298. 7,
  137299. 0,
  137300. 8,
  137301. };
  137302. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137303. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137304. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137305. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137306. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137307. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0,
  137309. };
  137310. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137311. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137312. };
  137313. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137314. 7, 5, 3, 1, 0, 2, 4, 6,
  137315. 8,
  137316. };
  137317. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137318. _vq_quantthresh__44c0_sm_p3_0,
  137319. _vq_quantmap__44c0_sm_p3_0,
  137320. 9,
  137321. 9
  137322. };
  137323. static static_codebook _44c0_sm_p3_0 = {
  137324. 2, 81,
  137325. _vq_lengthlist__44c0_sm_p3_0,
  137326. 1, -531628032, 1611661312, 4, 0,
  137327. _vq_quantlist__44c0_sm_p3_0,
  137328. NULL,
  137329. &_vq_auxt__44c0_sm_p3_0,
  137330. NULL,
  137331. 0
  137332. };
  137333. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137334. 4,
  137335. 3,
  137336. 5,
  137337. 2,
  137338. 6,
  137339. 1,
  137340. 7,
  137341. 0,
  137342. 8,
  137343. };
  137344. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137345. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137346. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137347. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137348. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137349. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137350. 11,
  137351. };
  137352. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137353. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137354. };
  137355. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137356. 7, 5, 3, 1, 0, 2, 4, 6,
  137357. 8,
  137358. };
  137359. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137360. _vq_quantthresh__44c0_sm_p4_0,
  137361. _vq_quantmap__44c0_sm_p4_0,
  137362. 9,
  137363. 9
  137364. };
  137365. static static_codebook _44c0_sm_p4_0 = {
  137366. 2, 81,
  137367. _vq_lengthlist__44c0_sm_p4_0,
  137368. 1, -531628032, 1611661312, 4, 0,
  137369. _vq_quantlist__44c0_sm_p4_0,
  137370. NULL,
  137371. &_vq_auxt__44c0_sm_p4_0,
  137372. NULL,
  137373. 0
  137374. };
  137375. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137376. 8,
  137377. 7,
  137378. 9,
  137379. 6,
  137380. 10,
  137381. 5,
  137382. 11,
  137383. 4,
  137384. 12,
  137385. 3,
  137386. 13,
  137387. 2,
  137388. 14,
  137389. 1,
  137390. 15,
  137391. 0,
  137392. 16,
  137393. };
  137394. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137395. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137396. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137397. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137398. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137399. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137400. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137401. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137402. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137403. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137404. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137405. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137406. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137407. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137408. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137409. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137410. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137411. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137413. 14,
  137414. };
  137415. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137416. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137417. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137418. };
  137419. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137420. 15, 13, 11, 9, 7, 5, 3, 1,
  137421. 0, 2, 4, 6, 8, 10, 12, 14,
  137422. 16,
  137423. };
  137424. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137425. _vq_quantthresh__44c0_sm_p5_0,
  137426. _vq_quantmap__44c0_sm_p5_0,
  137427. 17,
  137428. 17
  137429. };
  137430. static static_codebook _44c0_sm_p5_0 = {
  137431. 2, 289,
  137432. _vq_lengthlist__44c0_sm_p5_0,
  137433. 1, -529530880, 1611661312, 5, 0,
  137434. _vq_quantlist__44c0_sm_p5_0,
  137435. NULL,
  137436. &_vq_auxt__44c0_sm_p5_0,
  137437. NULL,
  137438. 0
  137439. };
  137440. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137441. 1,
  137442. 0,
  137443. 2,
  137444. };
  137445. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137446. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137447. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137448. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137449. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137450. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137451. 11,
  137452. };
  137453. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137454. -5.5, 5.5,
  137455. };
  137456. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137457. 1, 0, 2,
  137458. };
  137459. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137460. _vq_quantthresh__44c0_sm_p6_0,
  137461. _vq_quantmap__44c0_sm_p6_0,
  137462. 3,
  137463. 3
  137464. };
  137465. static static_codebook _44c0_sm_p6_0 = {
  137466. 4, 81,
  137467. _vq_lengthlist__44c0_sm_p6_0,
  137468. 1, -529137664, 1618345984, 2, 0,
  137469. _vq_quantlist__44c0_sm_p6_0,
  137470. NULL,
  137471. &_vq_auxt__44c0_sm_p6_0,
  137472. NULL,
  137473. 0
  137474. };
  137475. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137476. 5,
  137477. 4,
  137478. 6,
  137479. 3,
  137480. 7,
  137481. 2,
  137482. 8,
  137483. 1,
  137484. 9,
  137485. 0,
  137486. 10,
  137487. };
  137488. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137489. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137490. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137491. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137492. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137493. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137494. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137495. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137496. 10,10,10, 8, 8, 8, 8, 8, 8,
  137497. };
  137498. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137499. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137500. 3.5, 4.5,
  137501. };
  137502. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137503. 9, 7, 5, 3, 1, 0, 2, 4,
  137504. 6, 8, 10,
  137505. };
  137506. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137507. _vq_quantthresh__44c0_sm_p6_1,
  137508. _vq_quantmap__44c0_sm_p6_1,
  137509. 11,
  137510. 11
  137511. };
  137512. static static_codebook _44c0_sm_p6_1 = {
  137513. 2, 121,
  137514. _vq_lengthlist__44c0_sm_p6_1,
  137515. 1, -531365888, 1611661312, 4, 0,
  137516. _vq_quantlist__44c0_sm_p6_1,
  137517. NULL,
  137518. &_vq_auxt__44c0_sm_p6_1,
  137519. NULL,
  137520. 0
  137521. };
  137522. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137523. 6,
  137524. 5,
  137525. 7,
  137526. 4,
  137527. 8,
  137528. 3,
  137529. 9,
  137530. 2,
  137531. 10,
  137532. 1,
  137533. 11,
  137534. 0,
  137535. 12,
  137536. };
  137537. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137538. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137539. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137540. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137541. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137542. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137543. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137544. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137545. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137546. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137547. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137548. 0,12,12,11,11,13,12,14,14,
  137549. };
  137550. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137551. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137552. 12.5, 17.5, 22.5, 27.5,
  137553. };
  137554. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137555. 11, 9, 7, 5, 3, 1, 0, 2,
  137556. 4, 6, 8, 10, 12,
  137557. };
  137558. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137559. _vq_quantthresh__44c0_sm_p7_0,
  137560. _vq_quantmap__44c0_sm_p7_0,
  137561. 13,
  137562. 13
  137563. };
  137564. static static_codebook _44c0_sm_p7_0 = {
  137565. 2, 169,
  137566. _vq_lengthlist__44c0_sm_p7_0,
  137567. 1, -526516224, 1616117760, 4, 0,
  137568. _vq_quantlist__44c0_sm_p7_0,
  137569. NULL,
  137570. &_vq_auxt__44c0_sm_p7_0,
  137571. NULL,
  137572. 0
  137573. };
  137574. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137575. 2,
  137576. 1,
  137577. 3,
  137578. 0,
  137579. 4,
  137580. };
  137581. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137582. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137583. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137584. };
  137585. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137586. -1.5, -0.5, 0.5, 1.5,
  137587. };
  137588. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137589. 3, 1, 0, 2, 4,
  137590. };
  137591. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137592. _vq_quantthresh__44c0_sm_p7_1,
  137593. _vq_quantmap__44c0_sm_p7_1,
  137594. 5,
  137595. 5
  137596. };
  137597. static static_codebook _44c0_sm_p7_1 = {
  137598. 2, 25,
  137599. _vq_lengthlist__44c0_sm_p7_1,
  137600. 1, -533725184, 1611661312, 3, 0,
  137601. _vq_quantlist__44c0_sm_p7_1,
  137602. NULL,
  137603. &_vq_auxt__44c0_sm_p7_1,
  137604. NULL,
  137605. 0
  137606. };
  137607. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137608. 4,
  137609. 3,
  137610. 5,
  137611. 2,
  137612. 6,
  137613. 1,
  137614. 7,
  137615. 0,
  137616. 8,
  137617. };
  137618. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137619. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137620. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137621. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137622. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137623. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137624. 12,
  137625. };
  137626. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137627. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137628. };
  137629. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137630. 7, 5, 3, 1, 0, 2, 4, 6,
  137631. 8,
  137632. };
  137633. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137634. _vq_quantthresh__44c0_sm_p8_0,
  137635. _vq_quantmap__44c0_sm_p8_0,
  137636. 9,
  137637. 9
  137638. };
  137639. static static_codebook _44c0_sm_p8_0 = {
  137640. 2, 81,
  137641. _vq_lengthlist__44c0_sm_p8_0,
  137642. 1, -516186112, 1627103232, 4, 0,
  137643. _vq_quantlist__44c0_sm_p8_0,
  137644. NULL,
  137645. &_vq_auxt__44c0_sm_p8_0,
  137646. NULL,
  137647. 0
  137648. };
  137649. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137650. 6,
  137651. 5,
  137652. 7,
  137653. 4,
  137654. 8,
  137655. 3,
  137656. 9,
  137657. 2,
  137658. 10,
  137659. 1,
  137660. 11,
  137661. 0,
  137662. 12,
  137663. };
  137664. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137665. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137666. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137667. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137668. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137669. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137670. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137671. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137672. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137673. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137674. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137675. 20,13,13,12,12,16,13,15,13,
  137676. };
  137677. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137678. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137679. 42.5, 59.5, 76.5, 93.5,
  137680. };
  137681. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137682. 11, 9, 7, 5, 3, 1, 0, 2,
  137683. 4, 6, 8, 10, 12,
  137684. };
  137685. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137686. _vq_quantthresh__44c0_sm_p8_1,
  137687. _vq_quantmap__44c0_sm_p8_1,
  137688. 13,
  137689. 13
  137690. };
  137691. static static_codebook _44c0_sm_p8_1 = {
  137692. 2, 169,
  137693. _vq_lengthlist__44c0_sm_p8_1,
  137694. 1, -522616832, 1620115456, 4, 0,
  137695. _vq_quantlist__44c0_sm_p8_1,
  137696. NULL,
  137697. &_vq_auxt__44c0_sm_p8_1,
  137698. NULL,
  137699. 0
  137700. };
  137701. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137702. 8,
  137703. 7,
  137704. 9,
  137705. 6,
  137706. 10,
  137707. 5,
  137708. 11,
  137709. 4,
  137710. 12,
  137711. 3,
  137712. 13,
  137713. 2,
  137714. 14,
  137715. 1,
  137716. 15,
  137717. 0,
  137718. 16,
  137719. };
  137720. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137721. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137722. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137723. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137724. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137725. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137726. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137727. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137728. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137729. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137730. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137731. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137732. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137733. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137734. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137735. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137736. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137737. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137738. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137739. 9,
  137740. };
  137741. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137742. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137743. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137744. };
  137745. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137746. 15, 13, 11, 9, 7, 5, 3, 1,
  137747. 0, 2, 4, 6, 8, 10, 12, 14,
  137748. 16,
  137749. };
  137750. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137751. _vq_quantthresh__44c0_sm_p8_2,
  137752. _vq_quantmap__44c0_sm_p8_2,
  137753. 17,
  137754. 17
  137755. };
  137756. static static_codebook _44c0_sm_p8_2 = {
  137757. 2, 289,
  137758. _vq_lengthlist__44c0_sm_p8_2,
  137759. 1, -529530880, 1611661312, 5, 0,
  137760. _vq_quantlist__44c0_sm_p8_2,
  137761. NULL,
  137762. &_vq_auxt__44c0_sm_p8_2,
  137763. NULL,
  137764. 0
  137765. };
  137766. static long _huff_lengthlist__44c0_sm_short[] = {
  137767. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137768. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137769. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137770. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137771. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137772. 12,
  137773. };
  137774. static static_codebook _huff_book__44c0_sm_short = {
  137775. 2, 81,
  137776. _huff_lengthlist__44c0_sm_short,
  137777. 0, 0, 0, 0, 0,
  137778. NULL,
  137779. NULL,
  137780. NULL,
  137781. NULL,
  137782. 0
  137783. };
  137784. static long _huff_lengthlist__44c1_s_long[] = {
  137785. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137786. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137787. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137788. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137789. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137790. 11,
  137791. };
  137792. static static_codebook _huff_book__44c1_s_long = {
  137793. 2, 81,
  137794. _huff_lengthlist__44c1_s_long,
  137795. 0, 0, 0, 0, 0,
  137796. NULL,
  137797. NULL,
  137798. NULL,
  137799. NULL,
  137800. 0
  137801. };
  137802. static long _vq_quantlist__44c1_s_p1_0[] = {
  137803. 1,
  137804. 0,
  137805. 2,
  137806. };
  137807. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137808. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137809. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137813. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137814. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137818. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137819. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137854. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137859. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137864. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137900. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137905. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137910. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0,
  138219. };
  138220. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138221. -0.5, 0.5,
  138222. };
  138223. static long _vq_quantmap__44c1_s_p1_0[] = {
  138224. 1, 0, 2,
  138225. };
  138226. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138227. _vq_quantthresh__44c1_s_p1_0,
  138228. _vq_quantmap__44c1_s_p1_0,
  138229. 3,
  138230. 3
  138231. };
  138232. static static_codebook _44c1_s_p1_0 = {
  138233. 8, 6561,
  138234. _vq_lengthlist__44c1_s_p1_0,
  138235. 1, -535822336, 1611661312, 2, 0,
  138236. _vq_quantlist__44c1_s_p1_0,
  138237. NULL,
  138238. &_vq_auxt__44c1_s_p1_0,
  138239. NULL,
  138240. 0
  138241. };
  138242. static long _vq_quantlist__44c1_s_p2_0[] = {
  138243. 2,
  138244. 1,
  138245. 3,
  138246. 0,
  138247. 4,
  138248. };
  138249. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138250. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  138290. };
  138291. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138292. -1.5, -0.5, 0.5, 1.5,
  138293. };
  138294. static long _vq_quantmap__44c1_s_p2_0[] = {
  138295. 3, 1, 0, 2, 4,
  138296. };
  138297. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138298. _vq_quantthresh__44c1_s_p2_0,
  138299. _vq_quantmap__44c1_s_p2_0,
  138300. 5,
  138301. 5
  138302. };
  138303. static static_codebook _44c1_s_p2_0 = {
  138304. 4, 625,
  138305. _vq_lengthlist__44c1_s_p2_0,
  138306. 1, -533725184, 1611661312, 3, 0,
  138307. _vq_quantlist__44c1_s_p2_0,
  138308. NULL,
  138309. &_vq_auxt__44c1_s_p2_0,
  138310. NULL,
  138311. 0
  138312. };
  138313. static long _vq_quantlist__44c1_s_p3_0[] = {
  138314. 4,
  138315. 3,
  138316. 5,
  138317. 2,
  138318. 6,
  138319. 1,
  138320. 7,
  138321. 0,
  138322. 8,
  138323. };
  138324. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138325. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138326. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138327. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138328. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138329. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0,
  138331. };
  138332. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138333. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138334. };
  138335. static long _vq_quantmap__44c1_s_p3_0[] = {
  138336. 7, 5, 3, 1, 0, 2, 4, 6,
  138337. 8,
  138338. };
  138339. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138340. _vq_quantthresh__44c1_s_p3_0,
  138341. _vq_quantmap__44c1_s_p3_0,
  138342. 9,
  138343. 9
  138344. };
  138345. static static_codebook _44c1_s_p3_0 = {
  138346. 2, 81,
  138347. _vq_lengthlist__44c1_s_p3_0,
  138348. 1, -531628032, 1611661312, 4, 0,
  138349. _vq_quantlist__44c1_s_p3_0,
  138350. NULL,
  138351. &_vq_auxt__44c1_s_p3_0,
  138352. NULL,
  138353. 0
  138354. };
  138355. static long _vq_quantlist__44c1_s_p4_0[] = {
  138356. 4,
  138357. 3,
  138358. 5,
  138359. 2,
  138360. 6,
  138361. 1,
  138362. 7,
  138363. 0,
  138364. 8,
  138365. };
  138366. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138367. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138368. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138369. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138370. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138371. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138372. 11,
  138373. };
  138374. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138375. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138376. };
  138377. static long _vq_quantmap__44c1_s_p4_0[] = {
  138378. 7, 5, 3, 1, 0, 2, 4, 6,
  138379. 8,
  138380. };
  138381. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138382. _vq_quantthresh__44c1_s_p4_0,
  138383. _vq_quantmap__44c1_s_p4_0,
  138384. 9,
  138385. 9
  138386. };
  138387. static static_codebook _44c1_s_p4_0 = {
  138388. 2, 81,
  138389. _vq_lengthlist__44c1_s_p4_0,
  138390. 1, -531628032, 1611661312, 4, 0,
  138391. _vq_quantlist__44c1_s_p4_0,
  138392. NULL,
  138393. &_vq_auxt__44c1_s_p4_0,
  138394. NULL,
  138395. 0
  138396. };
  138397. static long _vq_quantlist__44c1_s_p5_0[] = {
  138398. 8,
  138399. 7,
  138400. 9,
  138401. 6,
  138402. 10,
  138403. 5,
  138404. 11,
  138405. 4,
  138406. 12,
  138407. 3,
  138408. 13,
  138409. 2,
  138410. 14,
  138411. 1,
  138412. 15,
  138413. 0,
  138414. 16,
  138415. };
  138416. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138417. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138418. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138419. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138420. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138421. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138422. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138423. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138424. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138425. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138426. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138427. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138428. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138429. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138430. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138431. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138432. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138433. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138435. 14,
  138436. };
  138437. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138438. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138439. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138440. };
  138441. static long _vq_quantmap__44c1_s_p5_0[] = {
  138442. 15, 13, 11, 9, 7, 5, 3, 1,
  138443. 0, 2, 4, 6, 8, 10, 12, 14,
  138444. 16,
  138445. };
  138446. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138447. _vq_quantthresh__44c1_s_p5_0,
  138448. _vq_quantmap__44c1_s_p5_0,
  138449. 17,
  138450. 17
  138451. };
  138452. static static_codebook _44c1_s_p5_0 = {
  138453. 2, 289,
  138454. _vq_lengthlist__44c1_s_p5_0,
  138455. 1, -529530880, 1611661312, 5, 0,
  138456. _vq_quantlist__44c1_s_p5_0,
  138457. NULL,
  138458. &_vq_auxt__44c1_s_p5_0,
  138459. NULL,
  138460. 0
  138461. };
  138462. static long _vq_quantlist__44c1_s_p6_0[] = {
  138463. 1,
  138464. 0,
  138465. 2,
  138466. };
  138467. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138468. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138469. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138470. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138471. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138472. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138473. 11,
  138474. };
  138475. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138476. -5.5, 5.5,
  138477. };
  138478. static long _vq_quantmap__44c1_s_p6_0[] = {
  138479. 1, 0, 2,
  138480. };
  138481. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138482. _vq_quantthresh__44c1_s_p6_0,
  138483. _vq_quantmap__44c1_s_p6_0,
  138484. 3,
  138485. 3
  138486. };
  138487. static static_codebook _44c1_s_p6_0 = {
  138488. 4, 81,
  138489. _vq_lengthlist__44c1_s_p6_0,
  138490. 1, -529137664, 1618345984, 2, 0,
  138491. _vq_quantlist__44c1_s_p6_0,
  138492. NULL,
  138493. &_vq_auxt__44c1_s_p6_0,
  138494. NULL,
  138495. 0
  138496. };
  138497. static long _vq_quantlist__44c1_s_p6_1[] = {
  138498. 5,
  138499. 4,
  138500. 6,
  138501. 3,
  138502. 7,
  138503. 2,
  138504. 8,
  138505. 1,
  138506. 9,
  138507. 0,
  138508. 10,
  138509. };
  138510. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138511. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138512. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138513. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138514. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138515. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138516. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138517. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138518. 10,10,10, 8, 8, 8, 8, 8, 8,
  138519. };
  138520. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138521. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138522. 3.5, 4.5,
  138523. };
  138524. static long _vq_quantmap__44c1_s_p6_1[] = {
  138525. 9, 7, 5, 3, 1, 0, 2, 4,
  138526. 6, 8, 10,
  138527. };
  138528. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138529. _vq_quantthresh__44c1_s_p6_1,
  138530. _vq_quantmap__44c1_s_p6_1,
  138531. 11,
  138532. 11
  138533. };
  138534. static static_codebook _44c1_s_p6_1 = {
  138535. 2, 121,
  138536. _vq_lengthlist__44c1_s_p6_1,
  138537. 1, -531365888, 1611661312, 4, 0,
  138538. _vq_quantlist__44c1_s_p6_1,
  138539. NULL,
  138540. &_vq_auxt__44c1_s_p6_1,
  138541. NULL,
  138542. 0
  138543. };
  138544. static long _vq_quantlist__44c1_s_p7_0[] = {
  138545. 6,
  138546. 5,
  138547. 7,
  138548. 4,
  138549. 8,
  138550. 3,
  138551. 9,
  138552. 2,
  138553. 10,
  138554. 1,
  138555. 11,
  138556. 0,
  138557. 12,
  138558. };
  138559. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138560. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138561. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138562. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138563. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138564. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138565. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138566. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138567. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138568. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138569. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138570. 0,12,11,11,11,13,10,14,13,
  138571. };
  138572. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138573. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138574. 12.5, 17.5, 22.5, 27.5,
  138575. };
  138576. static long _vq_quantmap__44c1_s_p7_0[] = {
  138577. 11, 9, 7, 5, 3, 1, 0, 2,
  138578. 4, 6, 8, 10, 12,
  138579. };
  138580. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138581. _vq_quantthresh__44c1_s_p7_0,
  138582. _vq_quantmap__44c1_s_p7_0,
  138583. 13,
  138584. 13
  138585. };
  138586. static static_codebook _44c1_s_p7_0 = {
  138587. 2, 169,
  138588. _vq_lengthlist__44c1_s_p7_0,
  138589. 1, -526516224, 1616117760, 4, 0,
  138590. _vq_quantlist__44c1_s_p7_0,
  138591. NULL,
  138592. &_vq_auxt__44c1_s_p7_0,
  138593. NULL,
  138594. 0
  138595. };
  138596. static long _vq_quantlist__44c1_s_p7_1[] = {
  138597. 2,
  138598. 1,
  138599. 3,
  138600. 0,
  138601. 4,
  138602. };
  138603. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138604. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138605. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138606. };
  138607. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138608. -1.5, -0.5, 0.5, 1.5,
  138609. };
  138610. static long _vq_quantmap__44c1_s_p7_1[] = {
  138611. 3, 1, 0, 2, 4,
  138612. };
  138613. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138614. _vq_quantthresh__44c1_s_p7_1,
  138615. _vq_quantmap__44c1_s_p7_1,
  138616. 5,
  138617. 5
  138618. };
  138619. static static_codebook _44c1_s_p7_1 = {
  138620. 2, 25,
  138621. _vq_lengthlist__44c1_s_p7_1,
  138622. 1, -533725184, 1611661312, 3, 0,
  138623. _vq_quantlist__44c1_s_p7_1,
  138624. NULL,
  138625. &_vq_auxt__44c1_s_p7_1,
  138626. NULL,
  138627. 0
  138628. };
  138629. static long _vq_quantlist__44c1_s_p8_0[] = {
  138630. 6,
  138631. 5,
  138632. 7,
  138633. 4,
  138634. 8,
  138635. 3,
  138636. 9,
  138637. 2,
  138638. 10,
  138639. 1,
  138640. 11,
  138641. 0,
  138642. 12,
  138643. };
  138644. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138645. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138646. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138647. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138648. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138649. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138650. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138651. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138652. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138653. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138654. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138655. 10,10,10,10,10,10,10,10,10,
  138656. };
  138657. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138658. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138659. 552.5, 773.5, 994.5, 1215.5,
  138660. };
  138661. static long _vq_quantmap__44c1_s_p8_0[] = {
  138662. 11, 9, 7, 5, 3, 1, 0, 2,
  138663. 4, 6, 8, 10, 12,
  138664. };
  138665. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138666. _vq_quantthresh__44c1_s_p8_0,
  138667. _vq_quantmap__44c1_s_p8_0,
  138668. 13,
  138669. 13
  138670. };
  138671. static static_codebook _44c1_s_p8_0 = {
  138672. 2, 169,
  138673. _vq_lengthlist__44c1_s_p8_0,
  138674. 1, -514541568, 1627103232, 4, 0,
  138675. _vq_quantlist__44c1_s_p8_0,
  138676. NULL,
  138677. &_vq_auxt__44c1_s_p8_0,
  138678. NULL,
  138679. 0
  138680. };
  138681. static long _vq_quantlist__44c1_s_p8_1[] = {
  138682. 6,
  138683. 5,
  138684. 7,
  138685. 4,
  138686. 8,
  138687. 3,
  138688. 9,
  138689. 2,
  138690. 10,
  138691. 1,
  138692. 11,
  138693. 0,
  138694. 12,
  138695. };
  138696. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138697. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138698. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138699. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138700. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138701. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138702. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138703. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138704. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138705. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138706. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138707. 16,13,12,12,11,14,12,15,13,
  138708. };
  138709. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138710. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138711. 42.5, 59.5, 76.5, 93.5,
  138712. };
  138713. static long _vq_quantmap__44c1_s_p8_1[] = {
  138714. 11, 9, 7, 5, 3, 1, 0, 2,
  138715. 4, 6, 8, 10, 12,
  138716. };
  138717. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138718. _vq_quantthresh__44c1_s_p8_1,
  138719. _vq_quantmap__44c1_s_p8_1,
  138720. 13,
  138721. 13
  138722. };
  138723. static static_codebook _44c1_s_p8_1 = {
  138724. 2, 169,
  138725. _vq_lengthlist__44c1_s_p8_1,
  138726. 1, -522616832, 1620115456, 4, 0,
  138727. _vq_quantlist__44c1_s_p8_1,
  138728. NULL,
  138729. &_vq_auxt__44c1_s_p8_1,
  138730. NULL,
  138731. 0
  138732. };
  138733. static long _vq_quantlist__44c1_s_p8_2[] = {
  138734. 8,
  138735. 7,
  138736. 9,
  138737. 6,
  138738. 10,
  138739. 5,
  138740. 11,
  138741. 4,
  138742. 12,
  138743. 3,
  138744. 13,
  138745. 2,
  138746. 14,
  138747. 1,
  138748. 15,
  138749. 0,
  138750. 16,
  138751. };
  138752. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138753. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138754. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138755. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138756. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138757. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138758. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138759. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138760. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138761. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138762. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138763. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138764. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138765. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138766. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138767. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138768. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138769. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138770. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138771. 9,
  138772. };
  138773. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138774. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138775. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138776. };
  138777. static long _vq_quantmap__44c1_s_p8_2[] = {
  138778. 15, 13, 11, 9, 7, 5, 3, 1,
  138779. 0, 2, 4, 6, 8, 10, 12, 14,
  138780. 16,
  138781. };
  138782. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138783. _vq_quantthresh__44c1_s_p8_2,
  138784. _vq_quantmap__44c1_s_p8_2,
  138785. 17,
  138786. 17
  138787. };
  138788. static static_codebook _44c1_s_p8_2 = {
  138789. 2, 289,
  138790. _vq_lengthlist__44c1_s_p8_2,
  138791. 1, -529530880, 1611661312, 5, 0,
  138792. _vq_quantlist__44c1_s_p8_2,
  138793. NULL,
  138794. &_vq_auxt__44c1_s_p8_2,
  138795. NULL,
  138796. 0
  138797. };
  138798. static long _huff_lengthlist__44c1_s_short[] = {
  138799. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138800. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138801. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138802. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138803. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138804. 11,
  138805. };
  138806. static static_codebook _huff_book__44c1_s_short = {
  138807. 2, 81,
  138808. _huff_lengthlist__44c1_s_short,
  138809. 0, 0, 0, 0, 0,
  138810. NULL,
  138811. NULL,
  138812. NULL,
  138813. NULL,
  138814. 0
  138815. };
  138816. static long _huff_lengthlist__44c1_sm_long[] = {
  138817. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138818. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138819. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138820. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138821. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138822. 11,
  138823. };
  138824. static static_codebook _huff_book__44c1_sm_long = {
  138825. 2, 81,
  138826. _huff_lengthlist__44c1_sm_long,
  138827. 0, 0, 0, 0, 0,
  138828. NULL,
  138829. NULL,
  138830. NULL,
  138831. NULL,
  138832. 0
  138833. };
  138834. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138835. 1,
  138836. 0,
  138837. 2,
  138838. };
  138839. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138840. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138841. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138845. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138846. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138850. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138851. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138886. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138891. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138896. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138932. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138937. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138942. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0,
  139251. };
  139252. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139253. -0.5, 0.5,
  139254. };
  139255. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139256. 1, 0, 2,
  139257. };
  139258. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139259. _vq_quantthresh__44c1_sm_p1_0,
  139260. _vq_quantmap__44c1_sm_p1_0,
  139261. 3,
  139262. 3
  139263. };
  139264. static static_codebook _44c1_sm_p1_0 = {
  139265. 8, 6561,
  139266. _vq_lengthlist__44c1_sm_p1_0,
  139267. 1, -535822336, 1611661312, 2, 0,
  139268. _vq_quantlist__44c1_sm_p1_0,
  139269. NULL,
  139270. &_vq_auxt__44c1_sm_p1_0,
  139271. NULL,
  139272. 0
  139273. };
  139274. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139275. 2,
  139276. 1,
  139277. 3,
  139278. 0,
  139279. 4,
  139280. };
  139281. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139282. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  139322. };
  139323. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139324. -1.5, -0.5, 0.5, 1.5,
  139325. };
  139326. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139327. 3, 1, 0, 2, 4,
  139328. };
  139329. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139330. _vq_quantthresh__44c1_sm_p2_0,
  139331. _vq_quantmap__44c1_sm_p2_0,
  139332. 5,
  139333. 5
  139334. };
  139335. static static_codebook _44c1_sm_p2_0 = {
  139336. 4, 625,
  139337. _vq_lengthlist__44c1_sm_p2_0,
  139338. 1, -533725184, 1611661312, 3, 0,
  139339. _vq_quantlist__44c1_sm_p2_0,
  139340. NULL,
  139341. &_vq_auxt__44c1_sm_p2_0,
  139342. NULL,
  139343. 0
  139344. };
  139345. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139346. 4,
  139347. 3,
  139348. 5,
  139349. 2,
  139350. 6,
  139351. 1,
  139352. 7,
  139353. 0,
  139354. 8,
  139355. };
  139356. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139357. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139358. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139359. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139360. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139361. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0,
  139363. };
  139364. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139365. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139366. };
  139367. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139368. 7, 5, 3, 1, 0, 2, 4, 6,
  139369. 8,
  139370. };
  139371. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139372. _vq_quantthresh__44c1_sm_p3_0,
  139373. _vq_quantmap__44c1_sm_p3_0,
  139374. 9,
  139375. 9
  139376. };
  139377. static static_codebook _44c1_sm_p3_0 = {
  139378. 2, 81,
  139379. _vq_lengthlist__44c1_sm_p3_0,
  139380. 1, -531628032, 1611661312, 4, 0,
  139381. _vq_quantlist__44c1_sm_p3_0,
  139382. NULL,
  139383. &_vq_auxt__44c1_sm_p3_0,
  139384. NULL,
  139385. 0
  139386. };
  139387. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139388. 4,
  139389. 3,
  139390. 5,
  139391. 2,
  139392. 6,
  139393. 1,
  139394. 7,
  139395. 0,
  139396. 8,
  139397. };
  139398. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139399. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139400. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139401. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139402. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139403. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139404. 11,
  139405. };
  139406. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139407. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139408. };
  139409. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139410. 7, 5, 3, 1, 0, 2, 4, 6,
  139411. 8,
  139412. };
  139413. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139414. _vq_quantthresh__44c1_sm_p4_0,
  139415. _vq_quantmap__44c1_sm_p4_0,
  139416. 9,
  139417. 9
  139418. };
  139419. static static_codebook _44c1_sm_p4_0 = {
  139420. 2, 81,
  139421. _vq_lengthlist__44c1_sm_p4_0,
  139422. 1, -531628032, 1611661312, 4, 0,
  139423. _vq_quantlist__44c1_sm_p4_0,
  139424. NULL,
  139425. &_vq_auxt__44c1_sm_p4_0,
  139426. NULL,
  139427. 0
  139428. };
  139429. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139430. 8,
  139431. 7,
  139432. 9,
  139433. 6,
  139434. 10,
  139435. 5,
  139436. 11,
  139437. 4,
  139438. 12,
  139439. 3,
  139440. 13,
  139441. 2,
  139442. 14,
  139443. 1,
  139444. 15,
  139445. 0,
  139446. 16,
  139447. };
  139448. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139449. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139450. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139451. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139452. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139453. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139454. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139455. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139456. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139457. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139458. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139459. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139460. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139461. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139462. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139463. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139464. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139465. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139467. 14,
  139468. };
  139469. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139470. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139471. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139472. };
  139473. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139474. 15, 13, 11, 9, 7, 5, 3, 1,
  139475. 0, 2, 4, 6, 8, 10, 12, 14,
  139476. 16,
  139477. };
  139478. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139479. _vq_quantthresh__44c1_sm_p5_0,
  139480. _vq_quantmap__44c1_sm_p5_0,
  139481. 17,
  139482. 17
  139483. };
  139484. static static_codebook _44c1_sm_p5_0 = {
  139485. 2, 289,
  139486. _vq_lengthlist__44c1_sm_p5_0,
  139487. 1, -529530880, 1611661312, 5, 0,
  139488. _vq_quantlist__44c1_sm_p5_0,
  139489. NULL,
  139490. &_vq_auxt__44c1_sm_p5_0,
  139491. NULL,
  139492. 0
  139493. };
  139494. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139495. 1,
  139496. 0,
  139497. 2,
  139498. };
  139499. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139500. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139501. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139502. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139503. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139504. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139505. 11,
  139506. };
  139507. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139508. -5.5, 5.5,
  139509. };
  139510. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139511. 1, 0, 2,
  139512. };
  139513. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139514. _vq_quantthresh__44c1_sm_p6_0,
  139515. _vq_quantmap__44c1_sm_p6_0,
  139516. 3,
  139517. 3
  139518. };
  139519. static static_codebook _44c1_sm_p6_0 = {
  139520. 4, 81,
  139521. _vq_lengthlist__44c1_sm_p6_0,
  139522. 1, -529137664, 1618345984, 2, 0,
  139523. _vq_quantlist__44c1_sm_p6_0,
  139524. NULL,
  139525. &_vq_auxt__44c1_sm_p6_0,
  139526. NULL,
  139527. 0
  139528. };
  139529. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139530. 5,
  139531. 4,
  139532. 6,
  139533. 3,
  139534. 7,
  139535. 2,
  139536. 8,
  139537. 1,
  139538. 9,
  139539. 0,
  139540. 10,
  139541. };
  139542. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139543. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139544. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139545. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139546. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139547. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139548. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139549. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139550. 10,10,10, 8, 8, 8, 8, 8, 8,
  139551. };
  139552. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139553. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139554. 3.5, 4.5,
  139555. };
  139556. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139557. 9, 7, 5, 3, 1, 0, 2, 4,
  139558. 6, 8, 10,
  139559. };
  139560. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139561. _vq_quantthresh__44c1_sm_p6_1,
  139562. _vq_quantmap__44c1_sm_p6_1,
  139563. 11,
  139564. 11
  139565. };
  139566. static static_codebook _44c1_sm_p6_1 = {
  139567. 2, 121,
  139568. _vq_lengthlist__44c1_sm_p6_1,
  139569. 1, -531365888, 1611661312, 4, 0,
  139570. _vq_quantlist__44c1_sm_p6_1,
  139571. NULL,
  139572. &_vq_auxt__44c1_sm_p6_1,
  139573. NULL,
  139574. 0
  139575. };
  139576. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139577. 6,
  139578. 5,
  139579. 7,
  139580. 4,
  139581. 8,
  139582. 3,
  139583. 9,
  139584. 2,
  139585. 10,
  139586. 1,
  139587. 11,
  139588. 0,
  139589. 12,
  139590. };
  139591. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139592. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139593. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139594. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139595. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139596. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139597. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139598. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139599. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139600. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139601. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139602. 0,12,12,11,11,13,12,14,13,
  139603. };
  139604. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139605. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139606. 12.5, 17.5, 22.5, 27.5,
  139607. };
  139608. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139609. 11, 9, 7, 5, 3, 1, 0, 2,
  139610. 4, 6, 8, 10, 12,
  139611. };
  139612. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139613. _vq_quantthresh__44c1_sm_p7_0,
  139614. _vq_quantmap__44c1_sm_p7_0,
  139615. 13,
  139616. 13
  139617. };
  139618. static static_codebook _44c1_sm_p7_0 = {
  139619. 2, 169,
  139620. _vq_lengthlist__44c1_sm_p7_0,
  139621. 1, -526516224, 1616117760, 4, 0,
  139622. _vq_quantlist__44c1_sm_p7_0,
  139623. NULL,
  139624. &_vq_auxt__44c1_sm_p7_0,
  139625. NULL,
  139626. 0
  139627. };
  139628. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139629. 2,
  139630. 1,
  139631. 3,
  139632. 0,
  139633. 4,
  139634. };
  139635. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139636. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139637. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139638. };
  139639. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139640. -1.5, -0.5, 0.5, 1.5,
  139641. };
  139642. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139643. 3, 1, 0, 2, 4,
  139644. };
  139645. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139646. _vq_quantthresh__44c1_sm_p7_1,
  139647. _vq_quantmap__44c1_sm_p7_1,
  139648. 5,
  139649. 5
  139650. };
  139651. static static_codebook _44c1_sm_p7_1 = {
  139652. 2, 25,
  139653. _vq_lengthlist__44c1_sm_p7_1,
  139654. 1, -533725184, 1611661312, 3, 0,
  139655. _vq_quantlist__44c1_sm_p7_1,
  139656. NULL,
  139657. &_vq_auxt__44c1_sm_p7_1,
  139658. NULL,
  139659. 0
  139660. };
  139661. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139662. 6,
  139663. 5,
  139664. 7,
  139665. 4,
  139666. 8,
  139667. 3,
  139668. 9,
  139669. 2,
  139670. 10,
  139671. 1,
  139672. 11,
  139673. 0,
  139674. 12,
  139675. };
  139676. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139677. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139678. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139679. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139680. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139681. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139682. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139683. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139684. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139685. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139686. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139687. 13,13,13,13,13,13,13,13,13,
  139688. };
  139689. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139690. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139691. 552.5, 773.5, 994.5, 1215.5,
  139692. };
  139693. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139694. 11, 9, 7, 5, 3, 1, 0, 2,
  139695. 4, 6, 8, 10, 12,
  139696. };
  139697. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139698. _vq_quantthresh__44c1_sm_p8_0,
  139699. _vq_quantmap__44c1_sm_p8_0,
  139700. 13,
  139701. 13
  139702. };
  139703. static static_codebook _44c1_sm_p8_0 = {
  139704. 2, 169,
  139705. _vq_lengthlist__44c1_sm_p8_0,
  139706. 1, -514541568, 1627103232, 4, 0,
  139707. _vq_quantlist__44c1_sm_p8_0,
  139708. NULL,
  139709. &_vq_auxt__44c1_sm_p8_0,
  139710. NULL,
  139711. 0
  139712. };
  139713. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139714. 6,
  139715. 5,
  139716. 7,
  139717. 4,
  139718. 8,
  139719. 3,
  139720. 9,
  139721. 2,
  139722. 10,
  139723. 1,
  139724. 11,
  139725. 0,
  139726. 12,
  139727. };
  139728. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139729. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139730. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139731. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139732. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139733. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139734. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139735. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139736. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139737. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139738. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139739. 20,13,12,12,12,14,12,14,13,
  139740. };
  139741. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139742. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139743. 42.5, 59.5, 76.5, 93.5,
  139744. };
  139745. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139746. 11, 9, 7, 5, 3, 1, 0, 2,
  139747. 4, 6, 8, 10, 12,
  139748. };
  139749. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139750. _vq_quantthresh__44c1_sm_p8_1,
  139751. _vq_quantmap__44c1_sm_p8_1,
  139752. 13,
  139753. 13
  139754. };
  139755. static static_codebook _44c1_sm_p8_1 = {
  139756. 2, 169,
  139757. _vq_lengthlist__44c1_sm_p8_1,
  139758. 1, -522616832, 1620115456, 4, 0,
  139759. _vq_quantlist__44c1_sm_p8_1,
  139760. NULL,
  139761. &_vq_auxt__44c1_sm_p8_1,
  139762. NULL,
  139763. 0
  139764. };
  139765. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139766. 8,
  139767. 7,
  139768. 9,
  139769. 6,
  139770. 10,
  139771. 5,
  139772. 11,
  139773. 4,
  139774. 12,
  139775. 3,
  139776. 13,
  139777. 2,
  139778. 14,
  139779. 1,
  139780. 15,
  139781. 0,
  139782. 16,
  139783. };
  139784. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139785. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139786. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139787. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139788. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139789. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139790. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139791. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139792. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139793. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139794. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139795. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139796. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139797. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139798. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139799. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139800. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139801. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139802. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139803. 9,
  139804. };
  139805. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139806. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139807. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139808. };
  139809. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139810. 15, 13, 11, 9, 7, 5, 3, 1,
  139811. 0, 2, 4, 6, 8, 10, 12, 14,
  139812. 16,
  139813. };
  139814. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139815. _vq_quantthresh__44c1_sm_p8_2,
  139816. _vq_quantmap__44c1_sm_p8_2,
  139817. 17,
  139818. 17
  139819. };
  139820. static static_codebook _44c1_sm_p8_2 = {
  139821. 2, 289,
  139822. _vq_lengthlist__44c1_sm_p8_2,
  139823. 1, -529530880, 1611661312, 5, 0,
  139824. _vq_quantlist__44c1_sm_p8_2,
  139825. NULL,
  139826. &_vq_auxt__44c1_sm_p8_2,
  139827. NULL,
  139828. 0
  139829. };
  139830. static long _huff_lengthlist__44c1_sm_short[] = {
  139831. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139832. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139833. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139834. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139835. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139836. 11,
  139837. };
  139838. static static_codebook _huff_book__44c1_sm_short = {
  139839. 2, 81,
  139840. _huff_lengthlist__44c1_sm_short,
  139841. 0, 0, 0, 0, 0,
  139842. NULL,
  139843. NULL,
  139844. NULL,
  139845. NULL,
  139846. 0
  139847. };
  139848. static long _huff_lengthlist__44cn1_s_long[] = {
  139849. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139850. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139851. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139852. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139853. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139854. 20,
  139855. };
  139856. static static_codebook _huff_book__44cn1_s_long = {
  139857. 2, 81,
  139858. _huff_lengthlist__44cn1_s_long,
  139859. 0, 0, 0, 0, 0,
  139860. NULL,
  139861. NULL,
  139862. NULL,
  139863. NULL,
  139864. 0
  139865. };
  139866. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139867. 1,
  139868. 0,
  139869. 2,
  139870. };
  139871. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139872. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139873. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139877. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139878. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139882. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139883. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139918. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139923. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139928. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139964. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139969. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139974. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0,
  140283. };
  140284. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140285. -0.5, 0.5,
  140286. };
  140287. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140288. 1, 0, 2,
  140289. };
  140290. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140291. _vq_quantthresh__44cn1_s_p1_0,
  140292. _vq_quantmap__44cn1_s_p1_0,
  140293. 3,
  140294. 3
  140295. };
  140296. static static_codebook _44cn1_s_p1_0 = {
  140297. 8, 6561,
  140298. _vq_lengthlist__44cn1_s_p1_0,
  140299. 1, -535822336, 1611661312, 2, 0,
  140300. _vq_quantlist__44cn1_s_p1_0,
  140301. NULL,
  140302. &_vq_auxt__44cn1_s_p1_0,
  140303. NULL,
  140304. 0
  140305. };
  140306. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140307. 2,
  140308. 1,
  140309. 3,
  140310. 0,
  140311. 4,
  140312. };
  140313. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140314. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  140354. };
  140355. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140356. -1.5, -0.5, 0.5, 1.5,
  140357. };
  140358. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140359. 3, 1, 0, 2, 4,
  140360. };
  140361. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140362. _vq_quantthresh__44cn1_s_p2_0,
  140363. _vq_quantmap__44cn1_s_p2_0,
  140364. 5,
  140365. 5
  140366. };
  140367. static static_codebook _44cn1_s_p2_0 = {
  140368. 4, 625,
  140369. _vq_lengthlist__44cn1_s_p2_0,
  140370. 1, -533725184, 1611661312, 3, 0,
  140371. _vq_quantlist__44cn1_s_p2_0,
  140372. NULL,
  140373. &_vq_auxt__44cn1_s_p2_0,
  140374. NULL,
  140375. 0
  140376. };
  140377. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140378. 4,
  140379. 3,
  140380. 5,
  140381. 2,
  140382. 6,
  140383. 1,
  140384. 7,
  140385. 0,
  140386. 8,
  140387. };
  140388. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140389. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140390. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140391. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140392. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140393. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0,
  140395. };
  140396. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140397. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140398. };
  140399. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140400. 7, 5, 3, 1, 0, 2, 4, 6,
  140401. 8,
  140402. };
  140403. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140404. _vq_quantthresh__44cn1_s_p3_0,
  140405. _vq_quantmap__44cn1_s_p3_0,
  140406. 9,
  140407. 9
  140408. };
  140409. static static_codebook _44cn1_s_p3_0 = {
  140410. 2, 81,
  140411. _vq_lengthlist__44cn1_s_p3_0,
  140412. 1, -531628032, 1611661312, 4, 0,
  140413. _vq_quantlist__44cn1_s_p3_0,
  140414. NULL,
  140415. &_vq_auxt__44cn1_s_p3_0,
  140416. NULL,
  140417. 0
  140418. };
  140419. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140420. 4,
  140421. 3,
  140422. 5,
  140423. 2,
  140424. 6,
  140425. 1,
  140426. 7,
  140427. 0,
  140428. 8,
  140429. };
  140430. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140431. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140432. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140433. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140434. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140435. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140436. 11,
  140437. };
  140438. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140439. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140440. };
  140441. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140442. 7, 5, 3, 1, 0, 2, 4, 6,
  140443. 8,
  140444. };
  140445. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140446. _vq_quantthresh__44cn1_s_p4_0,
  140447. _vq_quantmap__44cn1_s_p4_0,
  140448. 9,
  140449. 9
  140450. };
  140451. static static_codebook _44cn1_s_p4_0 = {
  140452. 2, 81,
  140453. _vq_lengthlist__44cn1_s_p4_0,
  140454. 1, -531628032, 1611661312, 4, 0,
  140455. _vq_quantlist__44cn1_s_p4_0,
  140456. NULL,
  140457. &_vq_auxt__44cn1_s_p4_0,
  140458. NULL,
  140459. 0
  140460. };
  140461. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140462. 8,
  140463. 7,
  140464. 9,
  140465. 6,
  140466. 10,
  140467. 5,
  140468. 11,
  140469. 4,
  140470. 12,
  140471. 3,
  140472. 13,
  140473. 2,
  140474. 14,
  140475. 1,
  140476. 15,
  140477. 0,
  140478. 16,
  140479. };
  140480. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140481. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140482. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140483. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140484. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140485. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140486. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140487. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140488. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140489. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140490. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140491. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140492. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140493. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140494. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140495. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140496. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140497. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140499. 14,
  140500. };
  140501. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140502. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140503. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140504. };
  140505. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140506. 15, 13, 11, 9, 7, 5, 3, 1,
  140507. 0, 2, 4, 6, 8, 10, 12, 14,
  140508. 16,
  140509. };
  140510. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140511. _vq_quantthresh__44cn1_s_p5_0,
  140512. _vq_quantmap__44cn1_s_p5_0,
  140513. 17,
  140514. 17
  140515. };
  140516. static static_codebook _44cn1_s_p5_0 = {
  140517. 2, 289,
  140518. _vq_lengthlist__44cn1_s_p5_0,
  140519. 1, -529530880, 1611661312, 5, 0,
  140520. _vq_quantlist__44cn1_s_p5_0,
  140521. NULL,
  140522. &_vq_auxt__44cn1_s_p5_0,
  140523. NULL,
  140524. 0
  140525. };
  140526. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140527. 1,
  140528. 0,
  140529. 2,
  140530. };
  140531. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140532. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140533. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140534. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140535. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140536. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140537. 10,
  140538. };
  140539. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140540. -5.5, 5.5,
  140541. };
  140542. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140543. 1, 0, 2,
  140544. };
  140545. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140546. _vq_quantthresh__44cn1_s_p6_0,
  140547. _vq_quantmap__44cn1_s_p6_0,
  140548. 3,
  140549. 3
  140550. };
  140551. static static_codebook _44cn1_s_p6_0 = {
  140552. 4, 81,
  140553. _vq_lengthlist__44cn1_s_p6_0,
  140554. 1, -529137664, 1618345984, 2, 0,
  140555. _vq_quantlist__44cn1_s_p6_0,
  140556. NULL,
  140557. &_vq_auxt__44cn1_s_p6_0,
  140558. NULL,
  140559. 0
  140560. };
  140561. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140562. 5,
  140563. 4,
  140564. 6,
  140565. 3,
  140566. 7,
  140567. 2,
  140568. 8,
  140569. 1,
  140570. 9,
  140571. 0,
  140572. 10,
  140573. };
  140574. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140575. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140576. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140577. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140578. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140579. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140580. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140581. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140582. 10,10,10, 9, 9, 9, 9, 9, 9,
  140583. };
  140584. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140585. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140586. 3.5, 4.5,
  140587. };
  140588. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140589. 9, 7, 5, 3, 1, 0, 2, 4,
  140590. 6, 8, 10,
  140591. };
  140592. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140593. _vq_quantthresh__44cn1_s_p6_1,
  140594. _vq_quantmap__44cn1_s_p6_1,
  140595. 11,
  140596. 11
  140597. };
  140598. static static_codebook _44cn1_s_p6_1 = {
  140599. 2, 121,
  140600. _vq_lengthlist__44cn1_s_p6_1,
  140601. 1, -531365888, 1611661312, 4, 0,
  140602. _vq_quantlist__44cn1_s_p6_1,
  140603. NULL,
  140604. &_vq_auxt__44cn1_s_p6_1,
  140605. NULL,
  140606. 0
  140607. };
  140608. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140609. 6,
  140610. 5,
  140611. 7,
  140612. 4,
  140613. 8,
  140614. 3,
  140615. 9,
  140616. 2,
  140617. 10,
  140618. 1,
  140619. 11,
  140620. 0,
  140621. 12,
  140622. };
  140623. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140624. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140625. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140626. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140627. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140628. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140629. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140630. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140631. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140632. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140633. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140634. 0,13,13,12,12,13,13,13,14,
  140635. };
  140636. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140637. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140638. 12.5, 17.5, 22.5, 27.5,
  140639. };
  140640. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140641. 11, 9, 7, 5, 3, 1, 0, 2,
  140642. 4, 6, 8, 10, 12,
  140643. };
  140644. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140645. _vq_quantthresh__44cn1_s_p7_0,
  140646. _vq_quantmap__44cn1_s_p7_0,
  140647. 13,
  140648. 13
  140649. };
  140650. static static_codebook _44cn1_s_p7_0 = {
  140651. 2, 169,
  140652. _vq_lengthlist__44cn1_s_p7_0,
  140653. 1, -526516224, 1616117760, 4, 0,
  140654. _vq_quantlist__44cn1_s_p7_0,
  140655. NULL,
  140656. &_vq_auxt__44cn1_s_p7_0,
  140657. NULL,
  140658. 0
  140659. };
  140660. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140661. 2,
  140662. 1,
  140663. 3,
  140664. 0,
  140665. 4,
  140666. };
  140667. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140668. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140669. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140670. };
  140671. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140672. -1.5, -0.5, 0.5, 1.5,
  140673. };
  140674. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140675. 3, 1, 0, 2, 4,
  140676. };
  140677. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140678. _vq_quantthresh__44cn1_s_p7_1,
  140679. _vq_quantmap__44cn1_s_p7_1,
  140680. 5,
  140681. 5
  140682. };
  140683. static static_codebook _44cn1_s_p7_1 = {
  140684. 2, 25,
  140685. _vq_lengthlist__44cn1_s_p7_1,
  140686. 1, -533725184, 1611661312, 3, 0,
  140687. _vq_quantlist__44cn1_s_p7_1,
  140688. NULL,
  140689. &_vq_auxt__44cn1_s_p7_1,
  140690. NULL,
  140691. 0
  140692. };
  140693. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140694. 2,
  140695. 1,
  140696. 3,
  140697. 0,
  140698. 4,
  140699. };
  140700. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140701. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140702. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140704. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140708. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140710. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140716. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140734. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140735. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140736. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140737. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140738. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140739. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140740. 12,
  140741. };
  140742. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140743. -331.5, -110.5, 110.5, 331.5,
  140744. };
  140745. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140746. 3, 1, 0, 2, 4,
  140747. };
  140748. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140749. _vq_quantthresh__44cn1_s_p8_0,
  140750. _vq_quantmap__44cn1_s_p8_0,
  140751. 5,
  140752. 5
  140753. };
  140754. static static_codebook _44cn1_s_p8_0 = {
  140755. 4, 625,
  140756. _vq_lengthlist__44cn1_s_p8_0,
  140757. 1, -518283264, 1627103232, 3, 0,
  140758. _vq_quantlist__44cn1_s_p8_0,
  140759. NULL,
  140760. &_vq_auxt__44cn1_s_p8_0,
  140761. NULL,
  140762. 0
  140763. };
  140764. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140765. 6,
  140766. 5,
  140767. 7,
  140768. 4,
  140769. 8,
  140770. 3,
  140771. 9,
  140772. 2,
  140773. 10,
  140774. 1,
  140775. 11,
  140776. 0,
  140777. 12,
  140778. };
  140779. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140780. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140781. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140782. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140783. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140784. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140785. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140786. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140787. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140788. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140789. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140790. 15,12,12,11,11,14,12,13,14,
  140791. };
  140792. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140793. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140794. 42.5, 59.5, 76.5, 93.5,
  140795. };
  140796. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140797. 11, 9, 7, 5, 3, 1, 0, 2,
  140798. 4, 6, 8, 10, 12,
  140799. };
  140800. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140801. _vq_quantthresh__44cn1_s_p8_1,
  140802. _vq_quantmap__44cn1_s_p8_1,
  140803. 13,
  140804. 13
  140805. };
  140806. static static_codebook _44cn1_s_p8_1 = {
  140807. 2, 169,
  140808. _vq_lengthlist__44cn1_s_p8_1,
  140809. 1, -522616832, 1620115456, 4, 0,
  140810. _vq_quantlist__44cn1_s_p8_1,
  140811. NULL,
  140812. &_vq_auxt__44cn1_s_p8_1,
  140813. NULL,
  140814. 0
  140815. };
  140816. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140817. 8,
  140818. 7,
  140819. 9,
  140820. 6,
  140821. 10,
  140822. 5,
  140823. 11,
  140824. 4,
  140825. 12,
  140826. 3,
  140827. 13,
  140828. 2,
  140829. 14,
  140830. 1,
  140831. 15,
  140832. 0,
  140833. 16,
  140834. };
  140835. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140836. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140837. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140838. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140839. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140840. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140841. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140842. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140843. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140844. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140845. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140846. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140847. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140848. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140849. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140850. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140851. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140852. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140853. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140854. 9,
  140855. };
  140856. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140857. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140858. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140859. };
  140860. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140861. 15, 13, 11, 9, 7, 5, 3, 1,
  140862. 0, 2, 4, 6, 8, 10, 12, 14,
  140863. 16,
  140864. };
  140865. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140866. _vq_quantthresh__44cn1_s_p8_2,
  140867. _vq_quantmap__44cn1_s_p8_2,
  140868. 17,
  140869. 17
  140870. };
  140871. static static_codebook _44cn1_s_p8_2 = {
  140872. 2, 289,
  140873. _vq_lengthlist__44cn1_s_p8_2,
  140874. 1, -529530880, 1611661312, 5, 0,
  140875. _vq_quantlist__44cn1_s_p8_2,
  140876. NULL,
  140877. &_vq_auxt__44cn1_s_p8_2,
  140878. NULL,
  140879. 0
  140880. };
  140881. static long _huff_lengthlist__44cn1_s_short[] = {
  140882. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140883. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140884. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140885. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140886. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140887. 10,
  140888. };
  140889. static static_codebook _huff_book__44cn1_s_short = {
  140890. 2, 81,
  140891. _huff_lengthlist__44cn1_s_short,
  140892. 0, 0, 0, 0, 0,
  140893. NULL,
  140894. NULL,
  140895. NULL,
  140896. NULL,
  140897. 0
  140898. };
  140899. static long _huff_lengthlist__44cn1_sm_long[] = {
  140900. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140901. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140902. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140903. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140904. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140905. 17,
  140906. };
  140907. static static_codebook _huff_book__44cn1_sm_long = {
  140908. 2, 81,
  140909. _huff_lengthlist__44cn1_sm_long,
  140910. 0, 0, 0, 0, 0,
  140911. NULL,
  140912. NULL,
  140913. NULL,
  140914. NULL,
  140915. 0
  140916. };
  140917. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140918. 1,
  140919. 0,
  140920. 2,
  140921. };
  140922. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140923. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140924. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140928. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140929. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140933. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140934. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140969. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140974. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140979. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141014. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141015. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141019. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141020. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141024. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141025. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  141334. };
  141335. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141336. -0.5, 0.5,
  141337. };
  141338. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141339. 1, 0, 2,
  141340. };
  141341. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141342. _vq_quantthresh__44cn1_sm_p1_0,
  141343. _vq_quantmap__44cn1_sm_p1_0,
  141344. 3,
  141345. 3
  141346. };
  141347. static static_codebook _44cn1_sm_p1_0 = {
  141348. 8, 6561,
  141349. _vq_lengthlist__44cn1_sm_p1_0,
  141350. 1, -535822336, 1611661312, 2, 0,
  141351. _vq_quantlist__44cn1_sm_p1_0,
  141352. NULL,
  141353. &_vq_auxt__44cn1_sm_p1_0,
  141354. NULL,
  141355. 0
  141356. };
  141357. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141358. 2,
  141359. 1,
  141360. 3,
  141361. 0,
  141362. 4,
  141363. };
  141364. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141365. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  141405. };
  141406. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141407. -1.5, -0.5, 0.5, 1.5,
  141408. };
  141409. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141410. 3, 1, 0, 2, 4,
  141411. };
  141412. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141413. _vq_quantthresh__44cn1_sm_p2_0,
  141414. _vq_quantmap__44cn1_sm_p2_0,
  141415. 5,
  141416. 5
  141417. };
  141418. static static_codebook _44cn1_sm_p2_0 = {
  141419. 4, 625,
  141420. _vq_lengthlist__44cn1_sm_p2_0,
  141421. 1, -533725184, 1611661312, 3, 0,
  141422. _vq_quantlist__44cn1_sm_p2_0,
  141423. NULL,
  141424. &_vq_auxt__44cn1_sm_p2_0,
  141425. NULL,
  141426. 0
  141427. };
  141428. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141429. 4,
  141430. 3,
  141431. 5,
  141432. 2,
  141433. 6,
  141434. 1,
  141435. 7,
  141436. 0,
  141437. 8,
  141438. };
  141439. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141440. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141441. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141442. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141443. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141444. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0,
  141446. };
  141447. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141448. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141449. };
  141450. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141451. 7, 5, 3, 1, 0, 2, 4, 6,
  141452. 8,
  141453. };
  141454. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141455. _vq_quantthresh__44cn1_sm_p3_0,
  141456. _vq_quantmap__44cn1_sm_p3_0,
  141457. 9,
  141458. 9
  141459. };
  141460. static static_codebook _44cn1_sm_p3_0 = {
  141461. 2, 81,
  141462. _vq_lengthlist__44cn1_sm_p3_0,
  141463. 1, -531628032, 1611661312, 4, 0,
  141464. _vq_quantlist__44cn1_sm_p3_0,
  141465. NULL,
  141466. &_vq_auxt__44cn1_sm_p3_0,
  141467. NULL,
  141468. 0
  141469. };
  141470. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141471. 4,
  141472. 3,
  141473. 5,
  141474. 2,
  141475. 6,
  141476. 1,
  141477. 7,
  141478. 0,
  141479. 8,
  141480. };
  141481. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141482. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141483. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141484. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141485. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141486. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141487. 11,
  141488. };
  141489. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141490. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141491. };
  141492. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141493. 7, 5, 3, 1, 0, 2, 4, 6,
  141494. 8,
  141495. };
  141496. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141497. _vq_quantthresh__44cn1_sm_p4_0,
  141498. _vq_quantmap__44cn1_sm_p4_0,
  141499. 9,
  141500. 9
  141501. };
  141502. static static_codebook _44cn1_sm_p4_0 = {
  141503. 2, 81,
  141504. _vq_lengthlist__44cn1_sm_p4_0,
  141505. 1, -531628032, 1611661312, 4, 0,
  141506. _vq_quantlist__44cn1_sm_p4_0,
  141507. NULL,
  141508. &_vq_auxt__44cn1_sm_p4_0,
  141509. NULL,
  141510. 0
  141511. };
  141512. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141513. 8,
  141514. 7,
  141515. 9,
  141516. 6,
  141517. 10,
  141518. 5,
  141519. 11,
  141520. 4,
  141521. 12,
  141522. 3,
  141523. 13,
  141524. 2,
  141525. 14,
  141526. 1,
  141527. 15,
  141528. 0,
  141529. 16,
  141530. };
  141531. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141532. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141533. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141534. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141535. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141536. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141537. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141538. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141539. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141540. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141541. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141542. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141543. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141544. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141545. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141546. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141547. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141548. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141549. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141550. 14,
  141551. };
  141552. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141553. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141554. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141555. };
  141556. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141557. 15, 13, 11, 9, 7, 5, 3, 1,
  141558. 0, 2, 4, 6, 8, 10, 12, 14,
  141559. 16,
  141560. };
  141561. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141562. _vq_quantthresh__44cn1_sm_p5_0,
  141563. _vq_quantmap__44cn1_sm_p5_0,
  141564. 17,
  141565. 17
  141566. };
  141567. static static_codebook _44cn1_sm_p5_0 = {
  141568. 2, 289,
  141569. _vq_lengthlist__44cn1_sm_p5_0,
  141570. 1, -529530880, 1611661312, 5, 0,
  141571. _vq_quantlist__44cn1_sm_p5_0,
  141572. NULL,
  141573. &_vq_auxt__44cn1_sm_p5_0,
  141574. NULL,
  141575. 0
  141576. };
  141577. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141578. 1,
  141579. 0,
  141580. 2,
  141581. };
  141582. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141583. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141584. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141585. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141586. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141587. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141588. 10,
  141589. };
  141590. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141591. -5.5, 5.5,
  141592. };
  141593. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141594. 1, 0, 2,
  141595. };
  141596. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141597. _vq_quantthresh__44cn1_sm_p6_0,
  141598. _vq_quantmap__44cn1_sm_p6_0,
  141599. 3,
  141600. 3
  141601. };
  141602. static static_codebook _44cn1_sm_p6_0 = {
  141603. 4, 81,
  141604. _vq_lengthlist__44cn1_sm_p6_0,
  141605. 1, -529137664, 1618345984, 2, 0,
  141606. _vq_quantlist__44cn1_sm_p6_0,
  141607. NULL,
  141608. &_vq_auxt__44cn1_sm_p6_0,
  141609. NULL,
  141610. 0
  141611. };
  141612. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141613. 5,
  141614. 4,
  141615. 6,
  141616. 3,
  141617. 7,
  141618. 2,
  141619. 8,
  141620. 1,
  141621. 9,
  141622. 0,
  141623. 10,
  141624. };
  141625. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141626. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141627. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141628. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141629. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141630. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141631. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141632. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141633. 10,10,10, 8, 9, 8, 8, 9, 8,
  141634. };
  141635. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141636. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141637. 3.5, 4.5,
  141638. };
  141639. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141640. 9, 7, 5, 3, 1, 0, 2, 4,
  141641. 6, 8, 10,
  141642. };
  141643. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141644. _vq_quantthresh__44cn1_sm_p6_1,
  141645. _vq_quantmap__44cn1_sm_p6_1,
  141646. 11,
  141647. 11
  141648. };
  141649. static static_codebook _44cn1_sm_p6_1 = {
  141650. 2, 121,
  141651. _vq_lengthlist__44cn1_sm_p6_1,
  141652. 1, -531365888, 1611661312, 4, 0,
  141653. _vq_quantlist__44cn1_sm_p6_1,
  141654. NULL,
  141655. &_vq_auxt__44cn1_sm_p6_1,
  141656. NULL,
  141657. 0
  141658. };
  141659. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141660. 6,
  141661. 5,
  141662. 7,
  141663. 4,
  141664. 8,
  141665. 3,
  141666. 9,
  141667. 2,
  141668. 10,
  141669. 1,
  141670. 11,
  141671. 0,
  141672. 12,
  141673. };
  141674. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141675. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141676. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141677. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141678. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141679. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141680. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141681. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141682. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141683. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141684. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141685. 0,13,12,12,12,13,13,13,14,
  141686. };
  141687. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141688. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141689. 12.5, 17.5, 22.5, 27.5,
  141690. };
  141691. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141692. 11, 9, 7, 5, 3, 1, 0, 2,
  141693. 4, 6, 8, 10, 12,
  141694. };
  141695. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141696. _vq_quantthresh__44cn1_sm_p7_0,
  141697. _vq_quantmap__44cn1_sm_p7_0,
  141698. 13,
  141699. 13
  141700. };
  141701. static static_codebook _44cn1_sm_p7_0 = {
  141702. 2, 169,
  141703. _vq_lengthlist__44cn1_sm_p7_0,
  141704. 1, -526516224, 1616117760, 4, 0,
  141705. _vq_quantlist__44cn1_sm_p7_0,
  141706. NULL,
  141707. &_vq_auxt__44cn1_sm_p7_0,
  141708. NULL,
  141709. 0
  141710. };
  141711. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141712. 2,
  141713. 1,
  141714. 3,
  141715. 0,
  141716. 4,
  141717. };
  141718. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141719. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141720. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141721. };
  141722. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141723. -1.5, -0.5, 0.5, 1.5,
  141724. };
  141725. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141726. 3, 1, 0, 2, 4,
  141727. };
  141728. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141729. _vq_quantthresh__44cn1_sm_p7_1,
  141730. _vq_quantmap__44cn1_sm_p7_1,
  141731. 5,
  141732. 5
  141733. };
  141734. static static_codebook _44cn1_sm_p7_1 = {
  141735. 2, 25,
  141736. _vq_lengthlist__44cn1_sm_p7_1,
  141737. 1, -533725184, 1611661312, 3, 0,
  141738. _vq_quantlist__44cn1_sm_p7_1,
  141739. NULL,
  141740. &_vq_auxt__44cn1_sm_p7_1,
  141741. NULL,
  141742. 0
  141743. };
  141744. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141745. 4,
  141746. 3,
  141747. 5,
  141748. 2,
  141749. 6,
  141750. 1,
  141751. 7,
  141752. 0,
  141753. 8,
  141754. };
  141755. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141756. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141757. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141758. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141759. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141760. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141761. 14,
  141762. };
  141763. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141764. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141765. };
  141766. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141767. 7, 5, 3, 1, 0, 2, 4, 6,
  141768. 8,
  141769. };
  141770. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141771. _vq_quantthresh__44cn1_sm_p8_0,
  141772. _vq_quantmap__44cn1_sm_p8_0,
  141773. 9,
  141774. 9
  141775. };
  141776. static static_codebook _44cn1_sm_p8_0 = {
  141777. 2, 81,
  141778. _vq_lengthlist__44cn1_sm_p8_0,
  141779. 1, -516186112, 1627103232, 4, 0,
  141780. _vq_quantlist__44cn1_sm_p8_0,
  141781. NULL,
  141782. &_vq_auxt__44cn1_sm_p8_0,
  141783. NULL,
  141784. 0
  141785. };
  141786. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141787. 6,
  141788. 5,
  141789. 7,
  141790. 4,
  141791. 8,
  141792. 3,
  141793. 9,
  141794. 2,
  141795. 10,
  141796. 1,
  141797. 11,
  141798. 0,
  141799. 12,
  141800. };
  141801. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141802. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141803. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141804. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141805. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141806. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141807. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141808. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141809. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141810. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141811. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141812. 17,12,12,11,10,13,11,13,13,
  141813. };
  141814. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141815. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141816. 42.5, 59.5, 76.5, 93.5,
  141817. };
  141818. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141819. 11, 9, 7, 5, 3, 1, 0, 2,
  141820. 4, 6, 8, 10, 12,
  141821. };
  141822. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141823. _vq_quantthresh__44cn1_sm_p8_1,
  141824. _vq_quantmap__44cn1_sm_p8_1,
  141825. 13,
  141826. 13
  141827. };
  141828. static static_codebook _44cn1_sm_p8_1 = {
  141829. 2, 169,
  141830. _vq_lengthlist__44cn1_sm_p8_1,
  141831. 1, -522616832, 1620115456, 4, 0,
  141832. _vq_quantlist__44cn1_sm_p8_1,
  141833. NULL,
  141834. &_vq_auxt__44cn1_sm_p8_1,
  141835. NULL,
  141836. 0
  141837. };
  141838. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141839. 8,
  141840. 7,
  141841. 9,
  141842. 6,
  141843. 10,
  141844. 5,
  141845. 11,
  141846. 4,
  141847. 12,
  141848. 3,
  141849. 13,
  141850. 2,
  141851. 14,
  141852. 1,
  141853. 15,
  141854. 0,
  141855. 16,
  141856. };
  141857. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141858. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141859. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141860. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141861. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141862. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141863. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141864. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141865. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141866. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141867. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141868. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141869. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141870. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141871. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141872. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141873. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141874. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141875. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141876. 9,
  141877. };
  141878. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141879. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141880. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141881. };
  141882. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141883. 15, 13, 11, 9, 7, 5, 3, 1,
  141884. 0, 2, 4, 6, 8, 10, 12, 14,
  141885. 16,
  141886. };
  141887. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141888. _vq_quantthresh__44cn1_sm_p8_2,
  141889. _vq_quantmap__44cn1_sm_p8_2,
  141890. 17,
  141891. 17
  141892. };
  141893. static static_codebook _44cn1_sm_p8_2 = {
  141894. 2, 289,
  141895. _vq_lengthlist__44cn1_sm_p8_2,
  141896. 1, -529530880, 1611661312, 5, 0,
  141897. _vq_quantlist__44cn1_sm_p8_2,
  141898. NULL,
  141899. &_vq_auxt__44cn1_sm_p8_2,
  141900. NULL,
  141901. 0
  141902. };
  141903. static long _huff_lengthlist__44cn1_sm_short[] = {
  141904. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141905. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141906. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141907. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141908. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141909. 9,
  141910. };
  141911. static static_codebook _huff_book__44cn1_sm_short = {
  141912. 2, 81,
  141913. _huff_lengthlist__44cn1_sm_short,
  141914. 0, 0, 0, 0, 0,
  141915. NULL,
  141916. NULL,
  141917. NULL,
  141918. NULL,
  141919. 0
  141920. };
  141921. /*** End of inlined file: res_books_stereo.h ***/
  141922. /***** residue backends *********************************************/
  141923. static vorbis_info_residue0 _residue_44_low={
  141924. 0,-1, -1, 9,-1,
  141925. /* 0 1 2 3 4 5 6 7 */
  141926. {0},
  141927. {-1},
  141928. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141929. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141930. };
  141931. static vorbis_info_residue0 _residue_44_mid={
  141932. 0,-1, -1, 10,-1,
  141933. /* 0 1 2 3 4 5 6 7 8 */
  141934. {0},
  141935. {-1},
  141936. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141937. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141938. };
  141939. static vorbis_info_residue0 _residue_44_high={
  141940. 0,-1, -1, 10,-1,
  141941. /* 0 1 2 3 4 5 6 7 8 */
  141942. {0},
  141943. {-1},
  141944. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141945. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141946. };
  141947. static static_bookblock _resbook_44s_n1={
  141948. {
  141949. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141950. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141951. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141952. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141953. }
  141954. };
  141955. static static_bookblock _resbook_44sm_n1={
  141956. {
  141957. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141958. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141959. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141960. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141961. }
  141962. };
  141963. static static_bookblock _resbook_44s_0={
  141964. {
  141965. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141966. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141967. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141968. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141969. }
  141970. };
  141971. static static_bookblock _resbook_44sm_0={
  141972. {
  141973. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141974. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141975. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141976. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141977. }
  141978. };
  141979. static static_bookblock _resbook_44s_1={
  141980. {
  141981. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141982. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141983. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141984. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141985. }
  141986. };
  141987. static static_bookblock _resbook_44sm_1={
  141988. {
  141989. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141990. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141991. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141992. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141993. }
  141994. };
  141995. static static_bookblock _resbook_44s_2={
  141996. {
  141997. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141998. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141999. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142000. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142001. }
  142002. };
  142003. static static_bookblock _resbook_44s_3={
  142004. {
  142005. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142006. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142007. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142008. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142009. }
  142010. };
  142011. static static_bookblock _resbook_44s_4={
  142012. {
  142013. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142014. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142015. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142016. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142017. }
  142018. };
  142019. static static_bookblock _resbook_44s_5={
  142020. {
  142021. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142022. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142023. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142024. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142025. }
  142026. };
  142027. static static_bookblock _resbook_44s_6={
  142028. {
  142029. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142030. {0,0,&_44c6_s_p4_0},
  142031. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142032. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142033. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142034. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142035. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142036. }
  142037. };
  142038. static static_bookblock _resbook_44s_7={
  142039. {
  142040. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142041. {0,0,&_44c7_s_p4_0},
  142042. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142043. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142044. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142045. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142046. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142047. }
  142048. };
  142049. static static_bookblock _resbook_44s_8={
  142050. {
  142051. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142052. {0,0,&_44c8_s_p4_0},
  142053. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142054. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142055. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142056. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142057. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142058. }
  142059. };
  142060. static static_bookblock _resbook_44s_9={
  142061. {
  142062. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142063. {0,0,&_44c9_s_p4_0},
  142064. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142065. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142066. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142067. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142068. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142069. }
  142070. };
  142071. static vorbis_residue_template _res_44s_n1[]={
  142072. {2,0, &_residue_44_low,
  142073. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142074. &_resbook_44s_n1,&_resbook_44sm_n1},
  142075. {2,0, &_residue_44_low,
  142076. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142077. &_resbook_44s_n1,&_resbook_44sm_n1}
  142078. };
  142079. static vorbis_residue_template _res_44s_0[]={
  142080. {2,0, &_residue_44_low,
  142081. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142082. &_resbook_44s_0,&_resbook_44sm_0},
  142083. {2,0, &_residue_44_low,
  142084. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142085. &_resbook_44s_0,&_resbook_44sm_0}
  142086. };
  142087. static vorbis_residue_template _res_44s_1[]={
  142088. {2,0, &_residue_44_low,
  142089. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142090. &_resbook_44s_1,&_resbook_44sm_1},
  142091. {2,0, &_residue_44_low,
  142092. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142093. &_resbook_44s_1,&_resbook_44sm_1}
  142094. };
  142095. static vorbis_residue_template _res_44s_2[]={
  142096. {2,0, &_residue_44_mid,
  142097. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142098. &_resbook_44s_2,&_resbook_44s_2},
  142099. {2,0, &_residue_44_mid,
  142100. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142101. &_resbook_44s_2,&_resbook_44s_2}
  142102. };
  142103. static vorbis_residue_template _res_44s_3[]={
  142104. {2,0, &_residue_44_mid,
  142105. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142106. &_resbook_44s_3,&_resbook_44s_3},
  142107. {2,0, &_residue_44_mid,
  142108. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142109. &_resbook_44s_3,&_resbook_44s_3}
  142110. };
  142111. static vorbis_residue_template _res_44s_4[]={
  142112. {2,0, &_residue_44_mid,
  142113. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142114. &_resbook_44s_4,&_resbook_44s_4},
  142115. {2,0, &_residue_44_mid,
  142116. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142117. &_resbook_44s_4,&_resbook_44s_4}
  142118. };
  142119. static vorbis_residue_template _res_44s_5[]={
  142120. {2,0, &_residue_44_mid,
  142121. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142122. &_resbook_44s_5,&_resbook_44s_5},
  142123. {2,0, &_residue_44_mid,
  142124. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142125. &_resbook_44s_5,&_resbook_44s_5}
  142126. };
  142127. static vorbis_residue_template _res_44s_6[]={
  142128. {2,0, &_residue_44_high,
  142129. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142130. &_resbook_44s_6,&_resbook_44s_6},
  142131. {2,0, &_residue_44_high,
  142132. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142133. &_resbook_44s_6,&_resbook_44s_6}
  142134. };
  142135. static vorbis_residue_template _res_44s_7[]={
  142136. {2,0, &_residue_44_high,
  142137. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142138. &_resbook_44s_7,&_resbook_44s_7},
  142139. {2,0, &_residue_44_high,
  142140. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142141. &_resbook_44s_7,&_resbook_44s_7}
  142142. };
  142143. static vorbis_residue_template _res_44s_8[]={
  142144. {2,0, &_residue_44_high,
  142145. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142146. &_resbook_44s_8,&_resbook_44s_8},
  142147. {2,0, &_residue_44_high,
  142148. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142149. &_resbook_44s_8,&_resbook_44s_8}
  142150. };
  142151. static vorbis_residue_template _res_44s_9[]={
  142152. {2,0, &_residue_44_high,
  142153. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142154. &_resbook_44s_9,&_resbook_44s_9},
  142155. {2,0, &_residue_44_high,
  142156. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142157. &_resbook_44s_9,&_resbook_44s_9}
  142158. };
  142159. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142160. { _map_nominal, _res_44s_n1 }, /* -1 */
  142161. { _map_nominal, _res_44s_0 }, /* 0 */
  142162. { _map_nominal, _res_44s_1 }, /* 1 */
  142163. { _map_nominal, _res_44s_2 }, /* 2 */
  142164. { _map_nominal, _res_44s_3 }, /* 3 */
  142165. { _map_nominal, _res_44s_4 }, /* 4 */
  142166. { _map_nominal, _res_44s_5 }, /* 5 */
  142167. { _map_nominal, _res_44s_6 }, /* 6 */
  142168. { _map_nominal, _res_44s_7 }, /* 7 */
  142169. { _map_nominal, _res_44s_8 }, /* 8 */
  142170. { _map_nominal, _res_44s_9 }, /* 9 */
  142171. };
  142172. /*** End of inlined file: residue_44.h ***/
  142173. /*** Start of inlined file: psych_44.h ***/
  142174. /* preecho trigger settings *****************************************/
  142175. static vorbis_info_psy_global _psy_global_44[5]={
  142176. {8, /* lines per eighth octave */
  142177. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142178. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142179. -6.f,
  142180. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142181. },
  142182. {8, /* lines per eighth octave */
  142183. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142184. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142185. -6.f,
  142186. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142187. },
  142188. {8, /* lines per eighth octave */
  142189. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142190. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142191. -6.f,
  142192. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142193. },
  142194. {8, /* lines per eighth octave */
  142195. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142196. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142197. -6.f,
  142198. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142199. },
  142200. {8, /* lines per eighth octave */
  142201. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142202. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142203. -6.f,
  142204. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142205. },
  142206. };
  142207. /* noise compander lookups * low, mid, high quality ****************/
  142208. static compandblock _psy_compand_44[6]={
  142209. /* sub-mode Z short */
  142210. {{
  142211. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142212. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142213. 16,17,18,19,20,21,22, 23, /* 23dB */
  142214. 24,25,26,27,28,29,30, 31, /* 31dB */
  142215. 32,33,34,35,36,37,38, 39, /* 39dB */
  142216. }},
  142217. /* mode_Z nominal short */
  142218. {{
  142219. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142220. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142221. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142222. 15,16,17,17,17,18,18, 19, /* 31dB */
  142223. 19,19,20,21,22,23,24, 25, /* 39dB */
  142224. }},
  142225. /* mode A short */
  142226. {{
  142227. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142228. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142229. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142230. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142231. 11,12,13,14,15,16,17, 18, /* 39dB */
  142232. }},
  142233. /* sub-mode Z long */
  142234. {{
  142235. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142236. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142237. 16,17,18,19,20,21,22, 23, /* 23dB */
  142238. 24,25,26,27,28,29,30, 31, /* 31dB */
  142239. 32,33,34,35,36,37,38, 39, /* 39dB */
  142240. }},
  142241. /* mode_Z nominal long */
  142242. {{
  142243. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142244. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142245. 13,14,14,14,15,15,15, 15, /* 23dB */
  142246. 16,16,17,17,17,18,18, 19, /* 31dB */
  142247. 19,19,20,21,22,23,24, 25, /* 39dB */
  142248. }},
  142249. /* mode A long */
  142250. {{
  142251. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142252. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142253. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142254. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142255. 11,12,13,14,15,16,17, 18, /* 39dB */
  142256. }}
  142257. };
  142258. /* tonal masking curve level adjustments *************************/
  142259. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142260. /* 63 125 250 500 1 2 4 8 16 */
  142261. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142262. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142263. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142264. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142265. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142266. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142267. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142268. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142269. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142270. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142271. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142272. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142273. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142274. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142275. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142276. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142277. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142278. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142279. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142280. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142281. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142282. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142283. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142284. };
  142285. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142286. /* 63 125 250 500 1 2 4 8 16 */
  142287. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142288. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142289. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142290. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142291. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142292. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142293. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142294. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142295. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142296. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142297. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142298. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142299. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142300. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142301. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142302. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142303. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142304. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142305. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142306. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142307. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142308. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142309. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142310. };
  142311. /* noise bias (transition block) */
  142312. static noise3 _psy_noisebias_trans[12]={
  142313. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142314. /* -1 */
  142315. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142316. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142317. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142318. /* 0
  142319. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142320. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142321. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142322. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142323. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142324. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142325. /* 1
  142326. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142327. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142328. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142329. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142330. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142331. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142332. /* 2
  142333. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142334. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142335. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142336. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142337. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142338. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142339. /* 3
  142340. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142341. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142342. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142343. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142344. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142345. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142346. /* 4
  142347. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142348. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142349. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142350. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142351. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142352. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142353. /* 5
  142354. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142355. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142356. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142357. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142358. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142359. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142360. /* 6
  142361. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142362. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142363. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142364. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142365. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142366. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142367. /* 7
  142368. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142369. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142370. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142371. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142372. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142373. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142374. /* 8
  142375. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142376. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142377. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142378. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142379. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142380. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142381. /* 9
  142382. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142383. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142384. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142385. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142386. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142387. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142388. /* 10 */
  142389. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142390. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142391. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142392. };
  142393. /* noise bias (long block) */
  142394. static noise3 _psy_noisebias_long[12]={
  142395. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142396. /* -1 */
  142397. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142398. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142399. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142400. /* 0 */
  142401. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142402. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142403. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142404. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142405. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142406. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142407. /* 1 */
  142408. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142409. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142410. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142411. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142412. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142413. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142414. /* 2 */
  142415. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142416. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142417. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142418. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142419. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142420. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142421. /* 3 */
  142422. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142423. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142424. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142425. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142426. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142427. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142428. /* 4 */
  142429. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142430. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142431. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142432. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142433. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142434. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142435. /* 5 */
  142436. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142437. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142438. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142439. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142440. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142441. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142442. /* 6 */
  142443. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142444. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142445. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142446. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142447. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142448. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142449. /* 7 */
  142450. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142451. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142452. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142453. /* 8 */
  142454. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142455. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142456. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142457. /* 9 */
  142458. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142459. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142460. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142461. /* 10 */
  142462. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142463. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142464. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142465. };
  142466. /* noise bias (impulse block) */
  142467. static noise3 _psy_noisebias_impulse[12]={
  142468. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142469. /* -1 */
  142470. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142471. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142472. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142473. /* 0 */
  142474. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142475. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142476. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142477. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142478. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142479. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142480. /* 1 */
  142481. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142482. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142483. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142484. /* 2 */
  142485. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142486. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142487. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142488. /* 3 */
  142489. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142490. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142491. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142492. /* 4 */
  142493. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142494. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142495. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142496. /* 5 */
  142497. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142498. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142499. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142500. /* 6
  142501. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142502. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142503. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142504. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142505. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142506. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142507. /* 7 */
  142508. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142509. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142510. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142511. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142512. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142513. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142514. /* 8 */
  142515. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142516. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142517. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142518. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142519. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142520. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142521. /* 9 */
  142522. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142523. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142524. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142525. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142526. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142527. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142528. /* 10 */
  142529. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142530. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142531. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142532. };
  142533. /* noise bias (padding block) */
  142534. static noise3 _psy_noisebias_padding[12]={
  142535. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142536. /* -1 */
  142537. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142538. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142539. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142540. /* 0 */
  142541. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142542. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142543. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142544. /* 1 */
  142545. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142546. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142547. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142548. /* 2 */
  142549. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142550. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142551. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142552. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142553. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142554. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142555. /* 3 */
  142556. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142557. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142558. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142559. /* 4 */
  142560. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142561. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142562. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142563. /* 5 */
  142564. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142565. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142566. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142567. /* 6 */
  142568. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142569. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142570. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142571. /* 7 */
  142572. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142573. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142574. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142575. /* 8 */
  142576. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142577. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142578. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142579. /* 9 */
  142580. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142581. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142582. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142583. /* 10 */
  142584. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142585. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142586. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142587. };
  142588. static noiseguard _psy_noiseguards_44[4]={
  142589. {3,3,15},
  142590. {3,3,15},
  142591. {10,10,100},
  142592. {10,10,100},
  142593. };
  142594. static int _psy_tone_suppress[12]={
  142595. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142596. };
  142597. static int _psy_tone_0dB[12]={
  142598. 90,90,95,95,95,95,105,105,105,105,105,105,
  142599. };
  142600. static int _psy_noise_suppress[12]={
  142601. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142602. };
  142603. static vorbis_info_psy _psy_info_template={
  142604. /* blockflag */
  142605. -1,
  142606. /* ath_adjatt, ath_maxatt */
  142607. -140.,-140.,
  142608. /* tonemask att boost/decay,suppr,curves */
  142609. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142610. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142611. 1, -0.f, .5f, .5f, 0,0,0,
  142612. /* noiseoffset*3, noisecompand, max_curve_dB */
  142613. {{-1},{-1},{-1}},{-1},105.f,
  142614. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142615. 0,0,-1,-1,0.,
  142616. };
  142617. /* ath ****************/
  142618. static int _psy_ath_floater[12]={
  142619. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142620. };
  142621. static int _psy_ath_abs[12]={
  142622. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142623. };
  142624. /* stereo setup. These don't map directly to quality level, there's
  142625. an additional indirection as several of the below may be used in a
  142626. single bitmanaged stream
  142627. ****************/
  142628. /* various stereo possibilities */
  142629. /* stereo mode by base quality level */
  142630. static adj_stereo _psy_stereo_modes_44[12]={
  142631. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142632. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142633. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142634. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142635. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142636. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142637. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142638. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142639. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142640. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142641. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142642. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142643. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142644. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142645. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142646. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142647. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142648. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142649. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142650. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142651. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142652. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142653. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142654. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142655. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142656. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142657. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142658. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142659. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142660. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142661. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142662. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142663. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142664. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142665. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142666. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142667. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142668. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142669. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142670. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142671. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142672. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142673. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142674. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142675. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142676. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142677. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142678. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142679. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142680. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142681. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142682. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142683. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142684. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142685. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142686. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142687. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142688. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142689. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142690. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142691. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142692. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142693. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142694. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142695. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142696. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142697. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142698. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142699. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142700. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142701. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142702. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142703. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142704. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142705. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142706. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142707. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142708. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142709. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142710. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142711. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142712. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142713. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142714. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142715. };
  142716. /* tone master attenuation by base quality mode and bitrate tweak */
  142717. static att3 _psy_tone_masteratt_44[12]={
  142718. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142719. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142720. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142721. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142722. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142723. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142724. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142725. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142726. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142727. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142728. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142729. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142730. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142731. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142732. };
  142733. /* lowpass by mode **************/
  142734. static double _psy_lowpass_44[12]={
  142735. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142736. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142737. };
  142738. /* noise normalization **********/
  142739. static int _noise_start_short_44[11]={
  142740. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142741. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142742. };
  142743. static int _noise_start_long_44[11]={
  142744. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142745. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142746. };
  142747. static int _noise_part_short_44[11]={
  142748. 8,8,8,8,8,8,8,8,8,8,8
  142749. };
  142750. static int _noise_part_long_44[11]={
  142751. 32,32,32,32,32,32,32,32,32,32,32
  142752. };
  142753. static double _noise_thresh_44[11]={
  142754. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142755. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142756. };
  142757. static double _noise_thresh_5only[2]={
  142758. .5,.5,
  142759. };
  142760. /*** End of inlined file: psych_44.h ***/
  142761. static double rate_mapping_44_stereo[12]={
  142762. 22500.,32000.,40000.,48000.,56000.,64000.,
  142763. 80000.,96000.,112000.,128000.,160000.,250001.
  142764. };
  142765. static double quality_mapping_44[12]={
  142766. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142767. };
  142768. static int blocksize_short_44[11]={
  142769. 512,256,256,256,256,256,256,256,256,256,256
  142770. };
  142771. static int blocksize_long_44[11]={
  142772. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142773. };
  142774. static double _psy_compand_short_mapping[12]={
  142775. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142776. };
  142777. static double _psy_compand_long_mapping[12]={
  142778. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142779. };
  142780. static double _global_mapping_44[12]={
  142781. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142782. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142783. };
  142784. static int _floor_short_mapping_44[11]={
  142785. 1,0,0,2,2,4,5,5,5,5,5
  142786. };
  142787. static int _floor_long_mapping_44[11]={
  142788. 8,7,7,7,7,7,7,7,7,7,7
  142789. };
  142790. ve_setup_data_template ve_setup_44_stereo={
  142791. 11,
  142792. rate_mapping_44_stereo,
  142793. quality_mapping_44,
  142794. 2,
  142795. 40000,
  142796. 50000,
  142797. blocksize_short_44,
  142798. blocksize_long_44,
  142799. _psy_tone_masteratt_44,
  142800. _psy_tone_0dB,
  142801. _psy_tone_suppress,
  142802. _vp_tonemask_adj_otherblock,
  142803. _vp_tonemask_adj_longblock,
  142804. _vp_tonemask_adj_otherblock,
  142805. _psy_noiseguards_44,
  142806. _psy_noisebias_impulse,
  142807. _psy_noisebias_padding,
  142808. _psy_noisebias_trans,
  142809. _psy_noisebias_long,
  142810. _psy_noise_suppress,
  142811. _psy_compand_44,
  142812. _psy_compand_short_mapping,
  142813. _psy_compand_long_mapping,
  142814. {_noise_start_short_44,_noise_start_long_44},
  142815. {_noise_part_short_44,_noise_part_long_44},
  142816. _noise_thresh_44,
  142817. _psy_ath_floater,
  142818. _psy_ath_abs,
  142819. _psy_lowpass_44,
  142820. _psy_global_44,
  142821. _global_mapping_44,
  142822. _psy_stereo_modes_44,
  142823. _floor_books,
  142824. _floor,
  142825. _floor_short_mapping_44,
  142826. _floor_long_mapping_44,
  142827. _mapres_template_44_stereo
  142828. };
  142829. /*** End of inlined file: setup_44.h ***/
  142830. /*** Start of inlined file: setup_44u.h ***/
  142831. /*** Start of inlined file: residue_44u.h ***/
  142832. /*** Start of inlined file: res_books_uncoupled.h ***/
  142833. static long _vq_quantlist__16u0__p1_0[] = {
  142834. 1,
  142835. 0,
  142836. 2,
  142837. };
  142838. static long _vq_lengthlist__16u0__p1_0[] = {
  142839. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142840. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142841. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142842. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142843. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142844. 12,
  142845. };
  142846. static float _vq_quantthresh__16u0__p1_0[] = {
  142847. -0.5, 0.5,
  142848. };
  142849. static long _vq_quantmap__16u0__p1_0[] = {
  142850. 1, 0, 2,
  142851. };
  142852. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142853. _vq_quantthresh__16u0__p1_0,
  142854. _vq_quantmap__16u0__p1_0,
  142855. 3,
  142856. 3
  142857. };
  142858. static static_codebook _16u0__p1_0 = {
  142859. 4, 81,
  142860. _vq_lengthlist__16u0__p1_0,
  142861. 1, -535822336, 1611661312, 2, 0,
  142862. _vq_quantlist__16u0__p1_0,
  142863. NULL,
  142864. &_vq_auxt__16u0__p1_0,
  142865. NULL,
  142866. 0
  142867. };
  142868. static long _vq_quantlist__16u0__p2_0[] = {
  142869. 1,
  142870. 0,
  142871. 2,
  142872. };
  142873. static long _vq_lengthlist__16u0__p2_0[] = {
  142874. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142875. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142876. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142877. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142878. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142879. 8,
  142880. };
  142881. static float _vq_quantthresh__16u0__p2_0[] = {
  142882. -0.5, 0.5,
  142883. };
  142884. static long _vq_quantmap__16u0__p2_0[] = {
  142885. 1, 0, 2,
  142886. };
  142887. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142888. _vq_quantthresh__16u0__p2_0,
  142889. _vq_quantmap__16u0__p2_0,
  142890. 3,
  142891. 3
  142892. };
  142893. static static_codebook _16u0__p2_0 = {
  142894. 4, 81,
  142895. _vq_lengthlist__16u0__p2_0,
  142896. 1, -535822336, 1611661312, 2, 0,
  142897. _vq_quantlist__16u0__p2_0,
  142898. NULL,
  142899. &_vq_auxt__16u0__p2_0,
  142900. NULL,
  142901. 0
  142902. };
  142903. static long _vq_quantlist__16u0__p3_0[] = {
  142904. 2,
  142905. 1,
  142906. 3,
  142907. 0,
  142908. 4,
  142909. };
  142910. static long _vq_lengthlist__16u0__p3_0[] = {
  142911. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142912. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142913. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142914. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142915. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142916. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142917. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142918. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142919. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142920. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142921. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142922. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142923. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142924. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142925. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142926. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142927. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142928. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142929. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142930. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142931. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142932. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142933. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142934. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142935. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142936. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142937. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142938. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142939. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142940. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142941. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142942. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142943. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142944. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142945. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142946. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142947. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142948. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142949. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142950. 18,
  142951. };
  142952. static float _vq_quantthresh__16u0__p3_0[] = {
  142953. -1.5, -0.5, 0.5, 1.5,
  142954. };
  142955. static long _vq_quantmap__16u0__p3_0[] = {
  142956. 3, 1, 0, 2, 4,
  142957. };
  142958. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142959. _vq_quantthresh__16u0__p3_0,
  142960. _vq_quantmap__16u0__p3_0,
  142961. 5,
  142962. 5
  142963. };
  142964. static static_codebook _16u0__p3_0 = {
  142965. 4, 625,
  142966. _vq_lengthlist__16u0__p3_0,
  142967. 1, -533725184, 1611661312, 3, 0,
  142968. _vq_quantlist__16u0__p3_0,
  142969. NULL,
  142970. &_vq_auxt__16u0__p3_0,
  142971. NULL,
  142972. 0
  142973. };
  142974. static long _vq_quantlist__16u0__p4_0[] = {
  142975. 2,
  142976. 1,
  142977. 3,
  142978. 0,
  142979. 4,
  142980. };
  142981. static long _vq_lengthlist__16u0__p4_0[] = {
  142982. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142983. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142984. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142985. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142986. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142987. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142988. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142989. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142990. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142991. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142992. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142993. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142994. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142995. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142996. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142997. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142998. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142999. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143000. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143001. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143002. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143003. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143004. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143005. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143006. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143007. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143008. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143009. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143010. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143011. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143012. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143013. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143014. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143015. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143016. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143017. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143018. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143019. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143020. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143021. 11,
  143022. };
  143023. static float _vq_quantthresh__16u0__p4_0[] = {
  143024. -1.5, -0.5, 0.5, 1.5,
  143025. };
  143026. static long _vq_quantmap__16u0__p4_0[] = {
  143027. 3, 1, 0, 2, 4,
  143028. };
  143029. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143030. _vq_quantthresh__16u0__p4_0,
  143031. _vq_quantmap__16u0__p4_0,
  143032. 5,
  143033. 5
  143034. };
  143035. static static_codebook _16u0__p4_0 = {
  143036. 4, 625,
  143037. _vq_lengthlist__16u0__p4_0,
  143038. 1, -533725184, 1611661312, 3, 0,
  143039. _vq_quantlist__16u0__p4_0,
  143040. NULL,
  143041. &_vq_auxt__16u0__p4_0,
  143042. NULL,
  143043. 0
  143044. };
  143045. static long _vq_quantlist__16u0__p5_0[] = {
  143046. 4,
  143047. 3,
  143048. 5,
  143049. 2,
  143050. 6,
  143051. 1,
  143052. 7,
  143053. 0,
  143054. 8,
  143055. };
  143056. static long _vq_lengthlist__16u0__p5_0[] = {
  143057. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143058. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143059. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143060. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143061. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143062. 12,
  143063. };
  143064. static float _vq_quantthresh__16u0__p5_0[] = {
  143065. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143066. };
  143067. static long _vq_quantmap__16u0__p5_0[] = {
  143068. 7, 5, 3, 1, 0, 2, 4, 6,
  143069. 8,
  143070. };
  143071. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143072. _vq_quantthresh__16u0__p5_0,
  143073. _vq_quantmap__16u0__p5_0,
  143074. 9,
  143075. 9
  143076. };
  143077. static static_codebook _16u0__p5_0 = {
  143078. 2, 81,
  143079. _vq_lengthlist__16u0__p5_0,
  143080. 1, -531628032, 1611661312, 4, 0,
  143081. _vq_quantlist__16u0__p5_0,
  143082. NULL,
  143083. &_vq_auxt__16u0__p5_0,
  143084. NULL,
  143085. 0
  143086. };
  143087. static long _vq_quantlist__16u0__p6_0[] = {
  143088. 6,
  143089. 5,
  143090. 7,
  143091. 4,
  143092. 8,
  143093. 3,
  143094. 9,
  143095. 2,
  143096. 10,
  143097. 1,
  143098. 11,
  143099. 0,
  143100. 12,
  143101. };
  143102. static long _vq_lengthlist__16u0__p6_0[] = {
  143103. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143104. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143105. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143106. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143107. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143108. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143109. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143110. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143111. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143112. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143113. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143114. };
  143115. static float _vq_quantthresh__16u0__p6_0[] = {
  143116. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143117. 12.5, 17.5, 22.5, 27.5,
  143118. };
  143119. static long _vq_quantmap__16u0__p6_0[] = {
  143120. 11, 9, 7, 5, 3, 1, 0, 2,
  143121. 4, 6, 8, 10, 12,
  143122. };
  143123. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143124. _vq_quantthresh__16u0__p6_0,
  143125. _vq_quantmap__16u0__p6_0,
  143126. 13,
  143127. 13
  143128. };
  143129. static static_codebook _16u0__p6_0 = {
  143130. 2, 169,
  143131. _vq_lengthlist__16u0__p6_0,
  143132. 1, -526516224, 1616117760, 4, 0,
  143133. _vq_quantlist__16u0__p6_0,
  143134. NULL,
  143135. &_vq_auxt__16u0__p6_0,
  143136. NULL,
  143137. 0
  143138. };
  143139. static long _vq_quantlist__16u0__p6_1[] = {
  143140. 2,
  143141. 1,
  143142. 3,
  143143. 0,
  143144. 4,
  143145. };
  143146. static long _vq_lengthlist__16u0__p6_1[] = {
  143147. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143148. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143149. };
  143150. static float _vq_quantthresh__16u0__p6_1[] = {
  143151. -1.5, -0.5, 0.5, 1.5,
  143152. };
  143153. static long _vq_quantmap__16u0__p6_1[] = {
  143154. 3, 1, 0, 2, 4,
  143155. };
  143156. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143157. _vq_quantthresh__16u0__p6_1,
  143158. _vq_quantmap__16u0__p6_1,
  143159. 5,
  143160. 5
  143161. };
  143162. static static_codebook _16u0__p6_1 = {
  143163. 2, 25,
  143164. _vq_lengthlist__16u0__p6_1,
  143165. 1, -533725184, 1611661312, 3, 0,
  143166. _vq_quantlist__16u0__p6_1,
  143167. NULL,
  143168. &_vq_auxt__16u0__p6_1,
  143169. NULL,
  143170. 0
  143171. };
  143172. static long _vq_quantlist__16u0__p7_0[] = {
  143173. 1,
  143174. 0,
  143175. 2,
  143176. };
  143177. static long _vq_lengthlist__16u0__p7_0[] = {
  143178. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143179. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143180. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143181. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143182. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143183. 7,
  143184. };
  143185. static float _vq_quantthresh__16u0__p7_0[] = {
  143186. -157.5, 157.5,
  143187. };
  143188. static long _vq_quantmap__16u0__p7_0[] = {
  143189. 1, 0, 2,
  143190. };
  143191. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143192. _vq_quantthresh__16u0__p7_0,
  143193. _vq_quantmap__16u0__p7_0,
  143194. 3,
  143195. 3
  143196. };
  143197. static static_codebook _16u0__p7_0 = {
  143198. 4, 81,
  143199. _vq_lengthlist__16u0__p7_0,
  143200. 1, -518803456, 1628680192, 2, 0,
  143201. _vq_quantlist__16u0__p7_0,
  143202. NULL,
  143203. &_vq_auxt__16u0__p7_0,
  143204. NULL,
  143205. 0
  143206. };
  143207. static long _vq_quantlist__16u0__p7_1[] = {
  143208. 7,
  143209. 6,
  143210. 8,
  143211. 5,
  143212. 9,
  143213. 4,
  143214. 10,
  143215. 3,
  143216. 11,
  143217. 2,
  143218. 12,
  143219. 1,
  143220. 13,
  143221. 0,
  143222. 14,
  143223. };
  143224. static long _vq_lengthlist__16u0__p7_1[] = {
  143225. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143226. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143227. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143228. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143229. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143230. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143231. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143232. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143233. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143234. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143235. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143236. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143237. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143238. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143239. 10,
  143240. };
  143241. static float _vq_quantthresh__16u0__p7_1[] = {
  143242. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143243. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143244. };
  143245. static long _vq_quantmap__16u0__p7_1[] = {
  143246. 13, 11, 9, 7, 5, 3, 1, 0,
  143247. 2, 4, 6, 8, 10, 12, 14,
  143248. };
  143249. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143250. _vq_quantthresh__16u0__p7_1,
  143251. _vq_quantmap__16u0__p7_1,
  143252. 15,
  143253. 15
  143254. };
  143255. static static_codebook _16u0__p7_1 = {
  143256. 2, 225,
  143257. _vq_lengthlist__16u0__p7_1,
  143258. 1, -520986624, 1620377600, 4, 0,
  143259. _vq_quantlist__16u0__p7_1,
  143260. NULL,
  143261. &_vq_auxt__16u0__p7_1,
  143262. NULL,
  143263. 0
  143264. };
  143265. static long _vq_quantlist__16u0__p7_2[] = {
  143266. 10,
  143267. 9,
  143268. 11,
  143269. 8,
  143270. 12,
  143271. 7,
  143272. 13,
  143273. 6,
  143274. 14,
  143275. 5,
  143276. 15,
  143277. 4,
  143278. 16,
  143279. 3,
  143280. 17,
  143281. 2,
  143282. 18,
  143283. 1,
  143284. 19,
  143285. 0,
  143286. 20,
  143287. };
  143288. static long _vq_lengthlist__16u0__p7_2[] = {
  143289. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143290. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143291. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143292. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143293. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143294. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143295. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143296. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143297. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143298. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143299. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143300. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143301. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143302. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143303. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143304. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143305. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143306. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143307. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143308. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143309. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143310. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143311. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143312. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143313. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143314. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143315. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143316. 10,10,12,11,10,11,11,11,10,
  143317. };
  143318. static float _vq_quantthresh__16u0__p7_2[] = {
  143319. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143320. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143321. 6.5, 7.5, 8.5, 9.5,
  143322. };
  143323. static long _vq_quantmap__16u0__p7_2[] = {
  143324. 19, 17, 15, 13, 11, 9, 7, 5,
  143325. 3, 1, 0, 2, 4, 6, 8, 10,
  143326. 12, 14, 16, 18, 20,
  143327. };
  143328. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143329. _vq_quantthresh__16u0__p7_2,
  143330. _vq_quantmap__16u0__p7_2,
  143331. 21,
  143332. 21
  143333. };
  143334. static static_codebook _16u0__p7_2 = {
  143335. 2, 441,
  143336. _vq_lengthlist__16u0__p7_2,
  143337. 1, -529268736, 1611661312, 5, 0,
  143338. _vq_quantlist__16u0__p7_2,
  143339. NULL,
  143340. &_vq_auxt__16u0__p7_2,
  143341. NULL,
  143342. 0
  143343. };
  143344. static long _huff_lengthlist__16u0__single[] = {
  143345. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143346. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143347. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143348. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143349. };
  143350. static static_codebook _huff_book__16u0__single = {
  143351. 2, 64,
  143352. _huff_lengthlist__16u0__single,
  143353. 0, 0, 0, 0, 0,
  143354. NULL,
  143355. NULL,
  143356. NULL,
  143357. NULL,
  143358. 0
  143359. };
  143360. static long _huff_lengthlist__16u1__long[] = {
  143361. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143362. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143363. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143364. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143365. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143366. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143367. 16,13,16,18,
  143368. };
  143369. static static_codebook _huff_book__16u1__long = {
  143370. 2, 100,
  143371. _huff_lengthlist__16u1__long,
  143372. 0, 0, 0, 0, 0,
  143373. NULL,
  143374. NULL,
  143375. NULL,
  143376. NULL,
  143377. 0
  143378. };
  143379. static long _vq_quantlist__16u1__p1_0[] = {
  143380. 1,
  143381. 0,
  143382. 2,
  143383. };
  143384. static long _vq_lengthlist__16u1__p1_0[] = {
  143385. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143386. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143387. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143388. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143389. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143390. 11,
  143391. };
  143392. static float _vq_quantthresh__16u1__p1_0[] = {
  143393. -0.5, 0.5,
  143394. };
  143395. static long _vq_quantmap__16u1__p1_0[] = {
  143396. 1, 0, 2,
  143397. };
  143398. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143399. _vq_quantthresh__16u1__p1_0,
  143400. _vq_quantmap__16u1__p1_0,
  143401. 3,
  143402. 3
  143403. };
  143404. static static_codebook _16u1__p1_0 = {
  143405. 4, 81,
  143406. _vq_lengthlist__16u1__p1_0,
  143407. 1, -535822336, 1611661312, 2, 0,
  143408. _vq_quantlist__16u1__p1_0,
  143409. NULL,
  143410. &_vq_auxt__16u1__p1_0,
  143411. NULL,
  143412. 0
  143413. };
  143414. static long _vq_quantlist__16u1__p2_0[] = {
  143415. 1,
  143416. 0,
  143417. 2,
  143418. };
  143419. static long _vq_lengthlist__16u1__p2_0[] = {
  143420. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143421. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143422. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143423. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143424. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143425. 8,
  143426. };
  143427. static float _vq_quantthresh__16u1__p2_0[] = {
  143428. -0.5, 0.5,
  143429. };
  143430. static long _vq_quantmap__16u1__p2_0[] = {
  143431. 1, 0, 2,
  143432. };
  143433. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143434. _vq_quantthresh__16u1__p2_0,
  143435. _vq_quantmap__16u1__p2_0,
  143436. 3,
  143437. 3
  143438. };
  143439. static static_codebook _16u1__p2_0 = {
  143440. 4, 81,
  143441. _vq_lengthlist__16u1__p2_0,
  143442. 1, -535822336, 1611661312, 2, 0,
  143443. _vq_quantlist__16u1__p2_0,
  143444. NULL,
  143445. &_vq_auxt__16u1__p2_0,
  143446. NULL,
  143447. 0
  143448. };
  143449. static long _vq_quantlist__16u1__p3_0[] = {
  143450. 2,
  143451. 1,
  143452. 3,
  143453. 0,
  143454. 4,
  143455. };
  143456. static long _vq_lengthlist__16u1__p3_0[] = {
  143457. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143458. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143459. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143460. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143461. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143462. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143463. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143464. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143465. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143466. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143467. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143468. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143469. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143470. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143471. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143472. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143473. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143474. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143475. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143476. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143477. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143478. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143479. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143480. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143481. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143482. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143483. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143484. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143485. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143486. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143487. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143488. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143489. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143490. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143491. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143492. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143493. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143494. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143495. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143496. 16,
  143497. };
  143498. static float _vq_quantthresh__16u1__p3_0[] = {
  143499. -1.5, -0.5, 0.5, 1.5,
  143500. };
  143501. static long _vq_quantmap__16u1__p3_0[] = {
  143502. 3, 1, 0, 2, 4,
  143503. };
  143504. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143505. _vq_quantthresh__16u1__p3_0,
  143506. _vq_quantmap__16u1__p3_0,
  143507. 5,
  143508. 5
  143509. };
  143510. static static_codebook _16u1__p3_0 = {
  143511. 4, 625,
  143512. _vq_lengthlist__16u1__p3_0,
  143513. 1, -533725184, 1611661312, 3, 0,
  143514. _vq_quantlist__16u1__p3_0,
  143515. NULL,
  143516. &_vq_auxt__16u1__p3_0,
  143517. NULL,
  143518. 0
  143519. };
  143520. static long _vq_quantlist__16u1__p4_0[] = {
  143521. 2,
  143522. 1,
  143523. 3,
  143524. 0,
  143525. 4,
  143526. };
  143527. static long _vq_lengthlist__16u1__p4_0[] = {
  143528. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143529. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143530. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143531. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143532. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143533. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143534. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143535. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143536. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143537. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143538. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143539. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143540. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143541. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143542. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143543. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143544. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143545. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143546. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143547. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143548. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143549. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143550. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143551. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143552. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143553. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143554. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143555. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143556. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143557. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143558. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143559. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143560. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143561. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143562. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143563. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143564. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143565. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143566. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143567. 11,
  143568. };
  143569. static float _vq_quantthresh__16u1__p4_0[] = {
  143570. -1.5, -0.5, 0.5, 1.5,
  143571. };
  143572. static long _vq_quantmap__16u1__p4_0[] = {
  143573. 3, 1, 0, 2, 4,
  143574. };
  143575. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143576. _vq_quantthresh__16u1__p4_0,
  143577. _vq_quantmap__16u1__p4_0,
  143578. 5,
  143579. 5
  143580. };
  143581. static static_codebook _16u1__p4_0 = {
  143582. 4, 625,
  143583. _vq_lengthlist__16u1__p4_0,
  143584. 1, -533725184, 1611661312, 3, 0,
  143585. _vq_quantlist__16u1__p4_0,
  143586. NULL,
  143587. &_vq_auxt__16u1__p4_0,
  143588. NULL,
  143589. 0
  143590. };
  143591. static long _vq_quantlist__16u1__p5_0[] = {
  143592. 4,
  143593. 3,
  143594. 5,
  143595. 2,
  143596. 6,
  143597. 1,
  143598. 7,
  143599. 0,
  143600. 8,
  143601. };
  143602. static long _vq_lengthlist__16u1__p5_0[] = {
  143603. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143604. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143605. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143606. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143607. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143608. 13,
  143609. };
  143610. static float _vq_quantthresh__16u1__p5_0[] = {
  143611. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143612. };
  143613. static long _vq_quantmap__16u1__p5_0[] = {
  143614. 7, 5, 3, 1, 0, 2, 4, 6,
  143615. 8,
  143616. };
  143617. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143618. _vq_quantthresh__16u1__p5_0,
  143619. _vq_quantmap__16u1__p5_0,
  143620. 9,
  143621. 9
  143622. };
  143623. static static_codebook _16u1__p5_0 = {
  143624. 2, 81,
  143625. _vq_lengthlist__16u1__p5_0,
  143626. 1, -531628032, 1611661312, 4, 0,
  143627. _vq_quantlist__16u1__p5_0,
  143628. NULL,
  143629. &_vq_auxt__16u1__p5_0,
  143630. NULL,
  143631. 0
  143632. };
  143633. static long _vq_quantlist__16u1__p6_0[] = {
  143634. 4,
  143635. 3,
  143636. 5,
  143637. 2,
  143638. 6,
  143639. 1,
  143640. 7,
  143641. 0,
  143642. 8,
  143643. };
  143644. static long _vq_lengthlist__16u1__p6_0[] = {
  143645. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143646. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143647. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143648. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143649. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143650. 11,
  143651. };
  143652. static float _vq_quantthresh__16u1__p6_0[] = {
  143653. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143654. };
  143655. static long _vq_quantmap__16u1__p6_0[] = {
  143656. 7, 5, 3, 1, 0, 2, 4, 6,
  143657. 8,
  143658. };
  143659. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143660. _vq_quantthresh__16u1__p6_0,
  143661. _vq_quantmap__16u1__p6_0,
  143662. 9,
  143663. 9
  143664. };
  143665. static static_codebook _16u1__p6_0 = {
  143666. 2, 81,
  143667. _vq_lengthlist__16u1__p6_0,
  143668. 1, -531628032, 1611661312, 4, 0,
  143669. _vq_quantlist__16u1__p6_0,
  143670. NULL,
  143671. &_vq_auxt__16u1__p6_0,
  143672. NULL,
  143673. 0
  143674. };
  143675. static long _vq_quantlist__16u1__p7_0[] = {
  143676. 1,
  143677. 0,
  143678. 2,
  143679. };
  143680. static long _vq_lengthlist__16u1__p7_0[] = {
  143681. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143682. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143683. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143684. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143685. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143686. 13,
  143687. };
  143688. static float _vq_quantthresh__16u1__p7_0[] = {
  143689. -5.5, 5.5,
  143690. };
  143691. static long _vq_quantmap__16u1__p7_0[] = {
  143692. 1, 0, 2,
  143693. };
  143694. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143695. _vq_quantthresh__16u1__p7_0,
  143696. _vq_quantmap__16u1__p7_0,
  143697. 3,
  143698. 3
  143699. };
  143700. static static_codebook _16u1__p7_0 = {
  143701. 4, 81,
  143702. _vq_lengthlist__16u1__p7_0,
  143703. 1, -529137664, 1618345984, 2, 0,
  143704. _vq_quantlist__16u1__p7_0,
  143705. NULL,
  143706. &_vq_auxt__16u1__p7_0,
  143707. NULL,
  143708. 0
  143709. };
  143710. static long _vq_quantlist__16u1__p7_1[] = {
  143711. 5,
  143712. 4,
  143713. 6,
  143714. 3,
  143715. 7,
  143716. 2,
  143717. 8,
  143718. 1,
  143719. 9,
  143720. 0,
  143721. 10,
  143722. };
  143723. static long _vq_lengthlist__16u1__p7_1[] = {
  143724. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143725. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143726. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143727. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143728. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143729. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143730. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143731. 8, 9, 9,10,10,10,10,10,10,
  143732. };
  143733. static float _vq_quantthresh__16u1__p7_1[] = {
  143734. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143735. 3.5, 4.5,
  143736. };
  143737. static long _vq_quantmap__16u1__p7_1[] = {
  143738. 9, 7, 5, 3, 1, 0, 2, 4,
  143739. 6, 8, 10,
  143740. };
  143741. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143742. _vq_quantthresh__16u1__p7_1,
  143743. _vq_quantmap__16u1__p7_1,
  143744. 11,
  143745. 11
  143746. };
  143747. static static_codebook _16u1__p7_1 = {
  143748. 2, 121,
  143749. _vq_lengthlist__16u1__p7_1,
  143750. 1, -531365888, 1611661312, 4, 0,
  143751. _vq_quantlist__16u1__p7_1,
  143752. NULL,
  143753. &_vq_auxt__16u1__p7_1,
  143754. NULL,
  143755. 0
  143756. };
  143757. static long _vq_quantlist__16u1__p8_0[] = {
  143758. 5,
  143759. 4,
  143760. 6,
  143761. 3,
  143762. 7,
  143763. 2,
  143764. 8,
  143765. 1,
  143766. 9,
  143767. 0,
  143768. 10,
  143769. };
  143770. static long _vq_lengthlist__16u1__p8_0[] = {
  143771. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143772. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143773. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143774. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143775. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143776. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143777. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143778. 13,14,14,15,15,16,16,15,16,
  143779. };
  143780. static float _vq_quantthresh__16u1__p8_0[] = {
  143781. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143782. 38.5, 49.5,
  143783. };
  143784. static long _vq_quantmap__16u1__p8_0[] = {
  143785. 9, 7, 5, 3, 1, 0, 2, 4,
  143786. 6, 8, 10,
  143787. };
  143788. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143789. _vq_quantthresh__16u1__p8_0,
  143790. _vq_quantmap__16u1__p8_0,
  143791. 11,
  143792. 11
  143793. };
  143794. static static_codebook _16u1__p8_0 = {
  143795. 2, 121,
  143796. _vq_lengthlist__16u1__p8_0,
  143797. 1, -524582912, 1618345984, 4, 0,
  143798. _vq_quantlist__16u1__p8_0,
  143799. NULL,
  143800. &_vq_auxt__16u1__p8_0,
  143801. NULL,
  143802. 0
  143803. };
  143804. static long _vq_quantlist__16u1__p8_1[] = {
  143805. 5,
  143806. 4,
  143807. 6,
  143808. 3,
  143809. 7,
  143810. 2,
  143811. 8,
  143812. 1,
  143813. 9,
  143814. 0,
  143815. 10,
  143816. };
  143817. static long _vq_lengthlist__16u1__p8_1[] = {
  143818. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143819. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143820. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143821. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143822. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143823. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143824. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143825. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143826. };
  143827. static float _vq_quantthresh__16u1__p8_1[] = {
  143828. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143829. 3.5, 4.5,
  143830. };
  143831. static long _vq_quantmap__16u1__p8_1[] = {
  143832. 9, 7, 5, 3, 1, 0, 2, 4,
  143833. 6, 8, 10,
  143834. };
  143835. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143836. _vq_quantthresh__16u1__p8_1,
  143837. _vq_quantmap__16u1__p8_1,
  143838. 11,
  143839. 11
  143840. };
  143841. static static_codebook _16u1__p8_1 = {
  143842. 2, 121,
  143843. _vq_lengthlist__16u1__p8_1,
  143844. 1, -531365888, 1611661312, 4, 0,
  143845. _vq_quantlist__16u1__p8_1,
  143846. NULL,
  143847. &_vq_auxt__16u1__p8_1,
  143848. NULL,
  143849. 0
  143850. };
  143851. static long _vq_quantlist__16u1__p9_0[] = {
  143852. 7,
  143853. 6,
  143854. 8,
  143855. 5,
  143856. 9,
  143857. 4,
  143858. 10,
  143859. 3,
  143860. 11,
  143861. 2,
  143862. 12,
  143863. 1,
  143864. 13,
  143865. 0,
  143866. 14,
  143867. };
  143868. static long _vq_lengthlist__16u1__p9_0[] = {
  143869. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143870. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143871. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143872. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143873. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143874. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143875. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143876. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143877. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143878. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143879. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143880. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143881. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143882. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143883. 8,
  143884. };
  143885. static float _vq_quantthresh__16u1__p9_0[] = {
  143886. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143887. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143888. };
  143889. static long _vq_quantmap__16u1__p9_0[] = {
  143890. 13, 11, 9, 7, 5, 3, 1, 0,
  143891. 2, 4, 6, 8, 10, 12, 14,
  143892. };
  143893. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143894. _vq_quantthresh__16u1__p9_0,
  143895. _vq_quantmap__16u1__p9_0,
  143896. 15,
  143897. 15
  143898. };
  143899. static static_codebook _16u1__p9_0 = {
  143900. 2, 225,
  143901. _vq_lengthlist__16u1__p9_0,
  143902. 1, -514071552, 1627381760, 4, 0,
  143903. _vq_quantlist__16u1__p9_0,
  143904. NULL,
  143905. &_vq_auxt__16u1__p9_0,
  143906. NULL,
  143907. 0
  143908. };
  143909. static long _vq_quantlist__16u1__p9_1[] = {
  143910. 7,
  143911. 6,
  143912. 8,
  143913. 5,
  143914. 9,
  143915. 4,
  143916. 10,
  143917. 3,
  143918. 11,
  143919. 2,
  143920. 12,
  143921. 1,
  143922. 13,
  143923. 0,
  143924. 14,
  143925. };
  143926. static long _vq_lengthlist__16u1__p9_1[] = {
  143927. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143928. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143929. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143930. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143931. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143932. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143933. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143934. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143935. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143936. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143937. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143938. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143939. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143940. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143941. 9,
  143942. };
  143943. static float _vq_quantthresh__16u1__p9_1[] = {
  143944. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143945. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143946. };
  143947. static long _vq_quantmap__16u1__p9_1[] = {
  143948. 13, 11, 9, 7, 5, 3, 1, 0,
  143949. 2, 4, 6, 8, 10, 12, 14,
  143950. };
  143951. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143952. _vq_quantthresh__16u1__p9_1,
  143953. _vq_quantmap__16u1__p9_1,
  143954. 15,
  143955. 15
  143956. };
  143957. static static_codebook _16u1__p9_1 = {
  143958. 2, 225,
  143959. _vq_lengthlist__16u1__p9_1,
  143960. 1, -522338304, 1620115456, 4, 0,
  143961. _vq_quantlist__16u1__p9_1,
  143962. NULL,
  143963. &_vq_auxt__16u1__p9_1,
  143964. NULL,
  143965. 0
  143966. };
  143967. static long _vq_quantlist__16u1__p9_2[] = {
  143968. 8,
  143969. 7,
  143970. 9,
  143971. 6,
  143972. 10,
  143973. 5,
  143974. 11,
  143975. 4,
  143976. 12,
  143977. 3,
  143978. 13,
  143979. 2,
  143980. 14,
  143981. 1,
  143982. 15,
  143983. 0,
  143984. 16,
  143985. };
  143986. static long _vq_lengthlist__16u1__p9_2[] = {
  143987. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143988. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143989. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143990. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143991. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143992. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143993. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143994. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143995. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143996. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143997. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143998. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143999. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144000. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144001. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144002. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144003. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144004. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144005. 10,
  144006. };
  144007. static float _vq_quantthresh__16u1__p9_2[] = {
  144008. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144009. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144010. };
  144011. static long _vq_quantmap__16u1__p9_2[] = {
  144012. 15, 13, 11, 9, 7, 5, 3, 1,
  144013. 0, 2, 4, 6, 8, 10, 12, 14,
  144014. 16,
  144015. };
  144016. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144017. _vq_quantthresh__16u1__p9_2,
  144018. _vq_quantmap__16u1__p9_2,
  144019. 17,
  144020. 17
  144021. };
  144022. static static_codebook _16u1__p9_2 = {
  144023. 2, 289,
  144024. _vq_lengthlist__16u1__p9_2,
  144025. 1, -529530880, 1611661312, 5, 0,
  144026. _vq_quantlist__16u1__p9_2,
  144027. NULL,
  144028. &_vq_auxt__16u1__p9_2,
  144029. NULL,
  144030. 0
  144031. };
  144032. static long _huff_lengthlist__16u1__short[] = {
  144033. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144034. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144035. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144036. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144037. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144038. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144039. 16,16,16,16,
  144040. };
  144041. static static_codebook _huff_book__16u1__short = {
  144042. 2, 100,
  144043. _huff_lengthlist__16u1__short,
  144044. 0, 0, 0, 0, 0,
  144045. NULL,
  144046. NULL,
  144047. NULL,
  144048. NULL,
  144049. 0
  144050. };
  144051. static long _huff_lengthlist__16u2__long[] = {
  144052. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144053. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144054. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144055. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144056. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144057. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144058. 13,14,18,18,
  144059. };
  144060. static static_codebook _huff_book__16u2__long = {
  144061. 2, 100,
  144062. _huff_lengthlist__16u2__long,
  144063. 0, 0, 0, 0, 0,
  144064. NULL,
  144065. NULL,
  144066. NULL,
  144067. NULL,
  144068. 0
  144069. };
  144070. static long _huff_lengthlist__16u2__short[] = {
  144071. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144072. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144073. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144074. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144075. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144076. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144077. 16,16,16,16,
  144078. };
  144079. static static_codebook _huff_book__16u2__short = {
  144080. 2, 100,
  144081. _huff_lengthlist__16u2__short,
  144082. 0, 0, 0, 0, 0,
  144083. NULL,
  144084. NULL,
  144085. NULL,
  144086. NULL,
  144087. 0
  144088. };
  144089. static long _vq_quantlist__16u2_p1_0[] = {
  144090. 1,
  144091. 0,
  144092. 2,
  144093. };
  144094. static long _vq_lengthlist__16u2_p1_0[] = {
  144095. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144096. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144097. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144098. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144099. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144100. 10,
  144101. };
  144102. static float _vq_quantthresh__16u2_p1_0[] = {
  144103. -0.5, 0.5,
  144104. };
  144105. static long _vq_quantmap__16u2_p1_0[] = {
  144106. 1, 0, 2,
  144107. };
  144108. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144109. _vq_quantthresh__16u2_p1_0,
  144110. _vq_quantmap__16u2_p1_0,
  144111. 3,
  144112. 3
  144113. };
  144114. static static_codebook _16u2_p1_0 = {
  144115. 4, 81,
  144116. _vq_lengthlist__16u2_p1_0,
  144117. 1, -535822336, 1611661312, 2, 0,
  144118. _vq_quantlist__16u2_p1_0,
  144119. NULL,
  144120. &_vq_auxt__16u2_p1_0,
  144121. NULL,
  144122. 0
  144123. };
  144124. static long _vq_quantlist__16u2_p2_0[] = {
  144125. 2,
  144126. 1,
  144127. 3,
  144128. 0,
  144129. 4,
  144130. };
  144131. static long _vq_lengthlist__16u2_p2_0[] = {
  144132. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144133. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144134. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144135. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144136. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144137. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144138. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144139. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144140. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144141. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144142. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144143. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144144. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144145. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144146. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144147. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144148. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144149. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144150. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144151. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144152. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144153. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144154. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144155. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144156. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144157. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144158. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144159. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144160. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144161. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144162. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144163. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144164. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144165. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144166. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144167. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144168. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144169. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144170. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144171. 13,
  144172. };
  144173. static float _vq_quantthresh__16u2_p2_0[] = {
  144174. -1.5, -0.5, 0.5, 1.5,
  144175. };
  144176. static long _vq_quantmap__16u2_p2_0[] = {
  144177. 3, 1, 0, 2, 4,
  144178. };
  144179. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144180. _vq_quantthresh__16u2_p2_0,
  144181. _vq_quantmap__16u2_p2_0,
  144182. 5,
  144183. 5
  144184. };
  144185. static static_codebook _16u2_p2_0 = {
  144186. 4, 625,
  144187. _vq_lengthlist__16u2_p2_0,
  144188. 1, -533725184, 1611661312, 3, 0,
  144189. _vq_quantlist__16u2_p2_0,
  144190. NULL,
  144191. &_vq_auxt__16u2_p2_0,
  144192. NULL,
  144193. 0
  144194. };
  144195. static long _vq_quantlist__16u2_p3_0[] = {
  144196. 4,
  144197. 3,
  144198. 5,
  144199. 2,
  144200. 6,
  144201. 1,
  144202. 7,
  144203. 0,
  144204. 8,
  144205. };
  144206. static long _vq_lengthlist__16u2_p3_0[] = {
  144207. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144208. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144209. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144210. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144211. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144212. 11,
  144213. };
  144214. static float _vq_quantthresh__16u2_p3_0[] = {
  144215. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144216. };
  144217. static long _vq_quantmap__16u2_p3_0[] = {
  144218. 7, 5, 3, 1, 0, 2, 4, 6,
  144219. 8,
  144220. };
  144221. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144222. _vq_quantthresh__16u2_p3_0,
  144223. _vq_quantmap__16u2_p3_0,
  144224. 9,
  144225. 9
  144226. };
  144227. static static_codebook _16u2_p3_0 = {
  144228. 2, 81,
  144229. _vq_lengthlist__16u2_p3_0,
  144230. 1, -531628032, 1611661312, 4, 0,
  144231. _vq_quantlist__16u2_p3_0,
  144232. NULL,
  144233. &_vq_auxt__16u2_p3_0,
  144234. NULL,
  144235. 0
  144236. };
  144237. static long _vq_quantlist__16u2_p4_0[] = {
  144238. 8,
  144239. 7,
  144240. 9,
  144241. 6,
  144242. 10,
  144243. 5,
  144244. 11,
  144245. 4,
  144246. 12,
  144247. 3,
  144248. 13,
  144249. 2,
  144250. 14,
  144251. 1,
  144252. 15,
  144253. 0,
  144254. 16,
  144255. };
  144256. static long _vq_lengthlist__16u2_p4_0[] = {
  144257. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144258. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144259. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144260. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144261. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144262. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144263. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144264. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144265. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144266. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144267. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144268. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144269. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144270. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144271. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144272. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144273. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144274. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144275. 14,
  144276. };
  144277. static float _vq_quantthresh__16u2_p4_0[] = {
  144278. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144279. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144280. };
  144281. static long _vq_quantmap__16u2_p4_0[] = {
  144282. 15, 13, 11, 9, 7, 5, 3, 1,
  144283. 0, 2, 4, 6, 8, 10, 12, 14,
  144284. 16,
  144285. };
  144286. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144287. _vq_quantthresh__16u2_p4_0,
  144288. _vq_quantmap__16u2_p4_0,
  144289. 17,
  144290. 17
  144291. };
  144292. static static_codebook _16u2_p4_0 = {
  144293. 2, 289,
  144294. _vq_lengthlist__16u2_p4_0,
  144295. 1, -529530880, 1611661312, 5, 0,
  144296. _vq_quantlist__16u2_p4_0,
  144297. NULL,
  144298. &_vq_auxt__16u2_p4_0,
  144299. NULL,
  144300. 0
  144301. };
  144302. static long _vq_quantlist__16u2_p5_0[] = {
  144303. 1,
  144304. 0,
  144305. 2,
  144306. };
  144307. static long _vq_lengthlist__16u2_p5_0[] = {
  144308. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144309. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144310. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144311. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144312. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144313. 10,
  144314. };
  144315. static float _vq_quantthresh__16u2_p5_0[] = {
  144316. -5.5, 5.5,
  144317. };
  144318. static long _vq_quantmap__16u2_p5_0[] = {
  144319. 1, 0, 2,
  144320. };
  144321. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144322. _vq_quantthresh__16u2_p5_0,
  144323. _vq_quantmap__16u2_p5_0,
  144324. 3,
  144325. 3
  144326. };
  144327. static static_codebook _16u2_p5_0 = {
  144328. 4, 81,
  144329. _vq_lengthlist__16u2_p5_0,
  144330. 1, -529137664, 1618345984, 2, 0,
  144331. _vq_quantlist__16u2_p5_0,
  144332. NULL,
  144333. &_vq_auxt__16u2_p5_0,
  144334. NULL,
  144335. 0
  144336. };
  144337. static long _vq_quantlist__16u2_p5_1[] = {
  144338. 5,
  144339. 4,
  144340. 6,
  144341. 3,
  144342. 7,
  144343. 2,
  144344. 8,
  144345. 1,
  144346. 9,
  144347. 0,
  144348. 10,
  144349. };
  144350. static long _vq_lengthlist__16u2_p5_1[] = {
  144351. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144352. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144353. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144354. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144355. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144356. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144357. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144358. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144359. };
  144360. static float _vq_quantthresh__16u2_p5_1[] = {
  144361. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144362. 3.5, 4.5,
  144363. };
  144364. static long _vq_quantmap__16u2_p5_1[] = {
  144365. 9, 7, 5, 3, 1, 0, 2, 4,
  144366. 6, 8, 10,
  144367. };
  144368. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144369. _vq_quantthresh__16u2_p5_1,
  144370. _vq_quantmap__16u2_p5_1,
  144371. 11,
  144372. 11
  144373. };
  144374. static static_codebook _16u2_p5_1 = {
  144375. 2, 121,
  144376. _vq_lengthlist__16u2_p5_1,
  144377. 1, -531365888, 1611661312, 4, 0,
  144378. _vq_quantlist__16u2_p5_1,
  144379. NULL,
  144380. &_vq_auxt__16u2_p5_1,
  144381. NULL,
  144382. 0
  144383. };
  144384. static long _vq_quantlist__16u2_p6_0[] = {
  144385. 6,
  144386. 5,
  144387. 7,
  144388. 4,
  144389. 8,
  144390. 3,
  144391. 9,
  144392. 2,
  144393. 10,
  144394. 1,
  144395. 11,
  144396. 0,
  144397. 12,
  144398. };
  144399. static long _vq_lengthlist__16u2_p6_0[] = {
  144400. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144401. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144402. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144403. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144404. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144405. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144406. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144407. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144408. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144409. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144410. 12,13,13,14,14,14,14,15,15,
  144411. };
  144412. static float _vq_quantthresh__16u2_p6_0[] = {
  144413. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144414. 12.5, 17.5, 22.5, 27.5,
  144415. };
  144416. static long _vq_quantmap__16u2_p6_0[] = {
  144417. 11, 9, 7, 5, 3, 1, 0, 2,
  144418. 4, 6, 8, 10, 12,
  144419. };
  144420. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144421. _vq_quantthresh__16u2_p6_0,
  144422. _vq_quantmap__16u2_p6_0,
  144423. 13,
  144424. 13
  144425. };
  144426. static static_codebook _16u2_p6_0 = {
  144427. 2, 169,
  144428. _vq_lengthlist__16u2_p6_0,
  144429. 1, -526516224, 1616117760, 4, 0,
  144430. _vq_quantlist__16u2_p6_0,
  144431. NULL,
  144432. &_vq_auxt__16u2_p6_0,
  144433. NULL,
  144434. 0
  144435. };
  144436. static long _vq_quantlist__16u2_p6_1[] = {
  144437. 2,
  144438. 1,
  144439. 3,
  144440. 0,
  144441. 4,
  144442. };
  144443. static long _vq_lengthlist__16u2_p6_1[] = {
  144444. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144445. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144446. };
  144447. static float _vq_quantthresh__16u2_p6_1[] = {
  144448. -1.5, -0.5, 0.5, 1.5,
  144449. };
  144450. static long _vq_quantmap__16u2_p6_1[] = {
  144451. 3, 1, 0, 2, 4,
  144452. };
  144453. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144454. _vq_quantthresh__16u2_p6_1,
  144455. _vq_quantmap__16u2_p6_1,
  144456. 5,
  144457. 5
  144458. };
  144459. static static_codebook _16u2_p6_1 = {
  144460. 2, 25,
  144461. _vq_lengthlist__16u2_p6_1,
  144462. 1, -533725184, 1611661312, 3, 0,
  144463. _vq_quantlist__16u2_p6_1,
  144464. NULL,
  144465. &_vq_auxt__16u2_p6_1,
  144466. NULL,
  144467. 0
  144468. };
  144469. static long _vq_quantlist__16u2_p7_0[] = {
  144470. 6,
  144471. 5,
  144472. 7,
  144473. 4,
  144474. 8,
  144475. 3,
  144476. 9,
  144477. 2,
  144478. 10,
  144479. 1,
  144480. 11,
  144481. 0,
  144482. 12,
  144483. };
  144484. static long _vq_lengthlist__16u2_p7_0[] = {
  144485. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144486. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144487. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144488. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144489. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144490. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144491. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144492. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144493. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144494. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144495. 12,13,13,13,14,14,14,15,14,
  144496. };
  144497. static float _vq_quantthresh__16u2_p7_0[] = {
  144498. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144499. 27.5, 38.5, 49.5, 60.5,
  144500. };
  144501. static long _vq_quantmap__16u2_p7_0[] = {
  144502. 11, 9, 7, 5, 3, 1, 0, 2,
  144503. 4, 6, 8, 10, 12,
  144504. };
  144505. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144506. _vq_quantthresh__16u2_p7_0,
  144507. _vq_quantmap__16u2_p7_0,
  144508. 13,
  144509. 13
  144510. };
  144511. static static_codebook _16u2_p7_0 = {
  144512. 2, 169,
  144513. _vq_lengthlist__16u2_p7_0,
  144514. 1, -523206656, 1618345984, 4, 0,
  144515. _vq_quantlist__16u2_p7_0,
  144516. NULL,
  144517. &_vq_auxt__16u2_p7_0,
  144518. NULL,
  144519. 0
  144520. };
  144521. static long _vq_quantlist__16u2_p7_1[] = {
  144522. 5,
  144523. 4,
  144524. 6,
  144525. 3,
  144526. 7,
  144527. 2,
  144528. 8,
  144529. 1,
  144530. 9,
  144531. 0,
  144532. 10,
  144533. };
  144534. static long _vq_lengthlist__16u2_p7_1[] = {
  144535. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144536. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144537. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144538. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144539. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144540. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144541. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144542. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144543. };
  144544. static float _vq_quantthresh__16u2_p7_1[] = {
  144545. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144546. 3.5, 4.5,
  144547. };
  144548. static long _vq_quantmap__16u2_p7_1[] = {
  144549. 9, 7, 5, 3, 1, 0, 2, 4,
  144550. 6, 8, 10,
  144551. };
  144552. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144553. _vq_quantthresh__16u2_p7_1,
  144554. _vq_quantmap__16u2_p7_1,
  144555. 11,
  144556. 11
  144557. };
  144558. static static_codebook _16u2_p7_1 = {
  144559. 2, 121,
  144560. _vq_lengthlist__16u2_p7_1,
  144561. 1, -531365888, 1611661312, 4, 0,
  144562. _vq_quantlist__16u2_p7_1,
  144563. NULL,
  144564. &_vq_auxt__16u2_p7_1,
  144565. NULL,
  144566. 0
  144567. };
  144568. static long _vq_quantlist__16u2_p8_0[] = {
  144569. 7,
  144570. 6,
  144571. 8,
  144572. 5,
  144573. 9,
  144574. 4,
  144575. 10,
  144576. 3,
  144577. 11,
  144578. 2,
  144579. 12,
  144580. 1,
  144581. 13,
  144582. 0,
  144583. 14,
  144584. };
  144585. static long _vq_lengthlist__16u2_p8_0[] = {
  144586. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144587. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144588. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144589. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144590. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144591. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144592. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144593. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144594. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144595. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144596. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144597. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144598. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144599. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144600. 14,
  144601. };
  144602. static float _vq_quantthresh__16u2_p8_0[] = {
  144603. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144604. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144605. };
  144606. static long _vq_quantmap__16u2_p8_0[] = {
  144607. 13, 11, 9, 7, 5, 3, 1, 0,
  144608. 2, 4, 6, 8, 10, 12, 14,
  144609. };
  144610. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144611. _vq_quantthresh__16u2_p8_0,
  144612. _vq_quantmap__16u2_p8_0,
  144613. 15,
  144614. 15
  144615. };
  144616. static static_codebook _16u2_p8_0 = {
  144617. 2, 225,
  144618. _vq_lengthlist__16u2_p8_0,
  144619. 1, -520986624, 1620377600, 4, 0,
  144620. _vq_quantlist__16u2_p8_0,
  144621. NULL,
  144622. &_vq_auxt__16u2_p8_0,
  144623. NULL,
  144624. 0
  144625. };
  144626. static long _vq_quantlist__16u2_p8_1[] = {
  144627. 10,
  144628. 9,
  144629. 11,
  144630. 8,
  144631. 12,
  144632. 7,
  144633. 13,
  144634. 6,
  144635. 14,
  144636. 5,
  144637. 15,
  144638. 4,
  144639. 16,
  144640. 3,
  144641. 17,
  144642. 2,
  144643. 18,
  144644. 1,
  144645. 19,
  144646. 0,
  144647. 20,
  144648. };
  144649. static long _vq_lengthlist__16u2_p8_1[] = {
  144650. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144651. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144652. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144653. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144654. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144655. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144656. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144657. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144658. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144659. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144660. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144661. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144662. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144663. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144664. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144665. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144666. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144667. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144668. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144669. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144670. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144671. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144672. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144673. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144674. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144675. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144676. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144677. 11,11,10,11,11,11,10,11,11,
  144678. };
  144679. static float _vq_quantthresh__16u2_p8_1[] = {
  144680. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144681. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144682. 6.5, 7.5, 8.5, 9.5,
  144683. };
  144684. static long _vq_quantmap__16u2_p8_1[] = {
  144685. 19, 17, 15, 13, 11, 9, 7, 5,
  144686. 3, 1, 0, 2, 4, 6, 8, 10,
  144687. 12, 14, 16, 18, 20,
  144688. };
  144689. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144690. _vq_quantthresh__16u2_p8_1,
  144691. _vq_quantmap__16u2_p8_1,
  144692. 21,
  144693. 21
  144694. };
  144695. static static_codebook _16u2_p8_1 = {
  144696. 2, 441,
  144697. _vq_lengthlist__16u2_p8_1,
  144698. 1, -529268736, 1611661312, 5, 0,
  144699. _vq_quantlist__16u2_p8_1,
  144700. NULL,
  144701. &_vq_auxt__16u2_p8_1,
  144702. NULL,
  144703. 0
  144704. };
  144705. static long _vq_quantlist__16u2_p9_0[] = {
  144706. 5586,
  144707. 4655,
  144708. 6517,
  144709. 3724,
  144710. 7448,
  144711. 2793,
  144712. 8379,
  144713. 1862,
  144714. 9310,
  144715. 931,
  144716. 10241,
  144717. 0,
  144718. 11172,
  144719. 5521,
  144720. 5651,
  144721. };
  144722. static long _vq_lengthlist__16u2_p9_0[] = {
  144723. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144724. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144725. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144726. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144727. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144728. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144729. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144730. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144731. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144732. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144733. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144735. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144736. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144737. 5,
  144738. };
  144739. static float _vq_quantthresh__16u2_p9_0[] = {
  144740. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144741. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144742. };
  144743. static long _vq_quantmap__16u2_p9_0[] = {
  144744. 11, 9, 7, 5, 3, 1, 13, 0,
  144745. 14, 2, 4, 6, 8, 10, 12,
  144746. };
  144747. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144748. _vq_quantthresh__16u2_p9_0,
  144749. _vq_quantmap__16u2_p9_0,
  144750. 15,
  144751. 15
  144752. };
  144753. static static_codebook _16u2_p9_0 = {
  144754. 2, 225,
  144755. _vq_lengthlist__16u2_p9_0,
  144756. 1, -510275072, 1611661312, 14, 0,
  144757. _vq_quantlist__16u2_p9_0,
  144758. NULL,
  144759. &_vq_auxt__16u2_p9_0,
  144760. NULL,
  144761. 0
  144762. };
  144763. static long _vq_quantlist__16u2_p9_1[] = {
  144764. 392,
  144765. 343,
  144766. 441,
  144767. 294,
  144768. 490,
  144769. 245,
  144770. 539,
  144771. 196,
  144772. 588,
  144773. 147,
  144774. 637,
  144775. 98,
  144776. 686,
  144777. 49,
  144778. 735,
  144779. 0,
  144780. 784,
  144781. 388,
  144782. 396,
  144783. };
  144784. static long _vq_lengthlist__16u2_p9_1[] = {
  144785. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144786. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144787. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144788. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144789. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144790. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144791. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144792. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144793. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144794. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144795. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144796. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144797. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144798. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144799. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144804. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144805. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144806. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144807. 11,11,11,11,11,11,11, 5, 4,
  144808. };
  144809. static float _vq_quantthresh__16u2_p9_1[] = {
  144810. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144811. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144812. 318.5, 367.5,
  144813. };
  144814. static long _vq_quantmap__16u2_p9_1[] = {
  144815. 15, 13, 11, 9, 7, 5, 3, 1,
  144816. 17, 0, 18, 2, 4, 6, 8, 10,
  144817. 12, 14, 16,
  144818. };
  144819. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144820. _vq_quantthresh__16u2_p9_1,
  144821. _vq_quantmap__16u2_p9_1,
  144822. 19,
  144823. 19
  144824. };
  144825. static static_codebook _16u2_p9_1 = {
  144826. 2, 361,
  144827. _vq_lengthlist__16u2_p9_1,
  144828. 1, -518488064, 1611661312, 10, 0,
  144829. _vq_quantlist__16u2_p9_1,
  144830. NULL,
  144831. &_vq_auxt__16u2_p9_1,
  144832. NULL,
  144833. 0
  144834. };
  144835. static long _vq_quantlist__16u2_p9_2[] = {
  144836. 24,
  144837. 23,
  144838. 25,
  144839. 22,
  144840. 26,
  144841. 21,
  144842. 27,
  144843. 20,
  144844. 28,
  144845. 19,
  144846. 29,
  144847. 18,
  144848. 30,
  144849. 17,
  144850. 31,
  144851. 16,
  144852. 32,
  144853. 15,
  144854. 33,
  144855. 14,
  144856. 34,
  144857. 13,
  144858. 35,
  144859. 12,
  144860. 36,
  144861. 11,
  144862. 37,
  144863. 10,
  144864. 38,
  144865. 9,
  144866. 39,
  144867. 8,
  144868. 40,
  144869. 7,
  144870. 41,
  144871. 6,
  144872. 42,
  144873. 5,
  144874. 43,
  144875. 4,
  144876. 44,
  144877. 3,
  144878. 45,
  144879. 2,
  144880. 46,
  144881. 1,
  144882. 47,
  144883. 0,
  144884. 48,
  144885. };
  144886. static long _vq_lengthlist__16u2_p9_2[] = {
  144887. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144888. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144889. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144890. 11,
  144891. };
  144892. static float _vq_quantthresh__16u2_p9_2[] = {
  144893. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144894. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144895. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144896. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144897. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144898. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144899. };
  144900. static long _vq_quantmap__16u2_p9_2[] = {
  144901. 47, 45, 43, 41, 39, 37, 35, 33,
  144902. 31, 29, 27, 25, 23, 21, 19, 17,
  144903. 15, 13, 11, 9, 7, 5, 3, 1,
  144904. 0, 2, 4, 6, 8, 10, 12, 14,
  144905. 16, 18, 20, 22, 24, 26, 28, 30,
  144906. 32, 34, 36, 38, 40, 42, 44, 46,
  144907. 48,
  144908. };
  144909. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144910. _vq_quantthresh__16u2_p9_2,
  144911. _vq_quantmap__16u2_p9_2,
  144912. 49,
  144913. 49
  144914. };
  144915. static static_codebook _16u2_p9_2 = {
  144916. 1, 49,
  144917. _vq_lengthlist__16u2_p9_2,
  144918. 1, -526909440, 1611661312, 6, 0,
  144919. _vq_quantlist__16u2_p9_2,
  144920. NULL,
  144921. &_vq_auxt__16u2_p9_2,
  144922. NULL,
  144923. 0
  144924. };
  144925. static long _vq_quantlist__8u0__p1_0[] = {
  144926. 1,
  144927. 0,
  144928. 2,
  144929. };
  144930. static long _vq_lengthlist__8u0__p1_0[] = {
  144931. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144932. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144933. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144934. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144935. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144936. 11,
  144937. };
  144938. static float _vq_quantthresh__8u0__p1_0[] = {
  144939. -0.5, 0.5,
  144940. };
  144941. static long _vq_quantmap__8u0__p1_0[] = {
  144942. 1, 0, 2,
  144943. };
  144944. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144945. _vq_quantthresh__8u0__p1_0,
  144946. _vq_quantmap__8u0__p1_0,
  144947. 3,
  144948. 3
  144949. };
  144950. static static_codebook _8u0__p1_0 = {
  144951. 4, 81,
  144952. _vq_lengthlist__8u0__p1_0,
  144953. 1, -535822336, 1611661312, 2, 0,
  144954. _vq_quantlist__8u0__p1_0,
  144955. NULL,
  144956. &_vq_auxt__8u0__p1_0,
  144957. NULL,
  144958. 0
  144959. };
  144960. static long _vq_quantlist__8u0__p2_0[] = {
  144961. 1,
  144962. 0,
  144963. 2,
  144964. };
  144965. static long _vq_lengthlist__8u0__p2_0[] = {
  144966. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144967. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144968. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144969. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144970. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144971. 8,
  144972. };
  144973. static float _vq_quantthresh__8u0__p2_0[] = {
  144974. -0.5, 0.5,
  144975. };
  144976. static long _vq_quantmap__8u0__p2_0[] = {
  144977. 1, 0, 2,
  144978. };
  144979. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144980. _vq_quantthresh__8u0__p2_0,
  144981. _vq_quantmap__8u0__p2_0,
  144982. 3,
  144983. 3
  144984. };
  144985. static static_codebook _8u0__p2_0 = {
  144986. 4, 81,
  144987. _vq_lengthlist__8u0__p2_0,
  144988. 1, -535822336, 1611661312, 2, 0,
  144989. _vq_quantlist__8u0__p2_0,
  144990. NULL,
  144991. &_vq_auxt__8u0__p2_0,
  144992. NULL,
  144993. 0
  144994. };
  144995. static long _vq_quantlist__8u0__p3_0[] = {
  144996. 2,
  144997. 1,
  144998. 3,
  144999. 0,
  145000. 4,
  145001. };
  145002. static long _vq_lengthlist__8u0__p3_0[] = {
  145003. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145004. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145005. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145006. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145007. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145008. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145009. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145010. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145011. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145012. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145013. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145014. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145015. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145016. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145017. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145018. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145019. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145020. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145021. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145022. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145023. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145024. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145025. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145026. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145027. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145028. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145029. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145030. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145031. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145032. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145033. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145034. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145035. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145036. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145037. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145038. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145039. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145040. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145041. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145042. 16,
  145043. };
  145044. static float _vq_quantthresh__8u0__p3_0[] = {
  145045. -1.5, -0.5, 0.5, 1.5,
  145046. };
  145047. static long _vq_quantmap__8u0__p3_0[] = {
  145048. 3, 1, 0, 2, 4,
  145049. };
  145050. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145051. _vq_quantthresh__8u0__p3_0,
  145052. _vq_quantmap__8u0__p3_0,
  145053. 5,
  145054. 5
  145055. };
  145056. static static_codebook _8u0__p3_0 = {
  145057. 4, 625,
  145058. _vq_lengthlist__8u0__p3_0,
  145059. 1, -533725184, 1611661312, 3, 0,
  145060. _vq_quantlist__8u0__p3_0,
  145061. NULL,
  145062. &_vq_auxt__8u0__p3_0,
  145063. NULL,
  145064. 0
  145065. };
  145066. static long _vq_quantlist__8u0__p4_0[] = {
  145067. 2,
  145068. 1,
  145069. 3,
  145070. 0,
  145071. 4,
  145072. };
  145073. static long _vq_lengthlist__8u0__p4_0[] = {
  145074. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145075. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145076. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145077. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145078. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145079. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145080. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145081. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145082. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145083. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145084. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145085. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145086. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145087. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145088. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145089. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145090. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145091. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145092. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145093. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145094. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145095. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145096. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145097. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145098. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145099. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145100. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145101. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145102. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145103. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145104. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145105. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145106. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145107. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145108. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145109. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145110. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145111. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145112. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145113. 12,
  145114. };
  145115. static float _vq_quantthresh__8u0__p4_0[] = {
  145116. -1.5, -0.5, 0.5, 1.5,
  145117. };
  145118. static long _vq_quantmap__8u0__p4_0[] = {
  145119. 3, 1, 0, 2, 4,
  145120. };
  145121. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145122. _vq_quantthresh__8u0__p4_0,
  145123. _vq_quantmap__8u0__p4_0,
  145124. 5,
  145125. 5
  145126. };
  145127. static static_codebook _8u0__p4_0 = {
  145128. 4, 625,
  145129. _vq_lengthlist__8u0__p4_0,
  145130. 1, -533725184, 1611661312, 3, 0,
  145131. _vq_quantlist__8u0__p4_0,
  145132. NULL,
  145133. &_vq_auxt__8u0__p4_0,
  145134. NULL,
  145135. 0
  145136. };
  145137. static long _vq_quantlist__8u0__p5_0[] = {
  145138. 4,
  145139. 3,
  145140. 5,
  145141. 2,
  145142. 6,
  145143. 1,
  145144. 7,
  145145. 0,
  145146. 8,
  145147. };
  145148. static long _vq_lengthlist__8u0__p5_0[] = {
  145149. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145150. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145151. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145152. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145153. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145154. 12,
  145155. };
  145156. static float _vq_quantthresh__8u0__p5_0[] = {
  145157. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145158. };
  145159. static long _vq_quantmap__8u0__p5_0[] = {
  145160. 7, 5, 3, 1, 0, 2, 4, 6,
  145161. 8,
  145162. };
  145163. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145164. _vq_quantthresh__8u0__p5_0,
  145165. _vq_quantmap__8u0__p5_0,
  145166. 9,
  145167. 9
  145168. };
  145169. static static_codebook _8u0__p5_0 = {
  145170. 2, 81,
  145171. _vq_lengthlist__8u0__p5_0,
  145172. 1, -531628032, 1611661312, 4, 0,
  145173. _vq_quantlist__8u0__p5_0,
  145174. NULL,
  145175. &_vq_auxt__8u0__p5_0,
  145176. NULL,
  145177. 0
  145178. };
  145179. static long _vq_quantlist__8u0__p6_0[] = {
  145180. 6,
  145181. 5,
  145182. 7,
  145183. 4,
  145184. 8,
  145185. 3,
  145186. 9,
  145187. 2,
  145188. 10,
  145189. 1,
  145190. 11,
  145191. 0,
  145192. 12,
  145193. };
  145194. static long _vq_lengthlist__8u0__p6_0[] = {
  145195. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145196. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145197. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145198. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145199. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145200. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145201. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145202. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145203. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145204. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145205. 16, 0,15, 0,17, 0, 0, 0, 0,
  145206. };
  145207. static float _vq_quantthresh__8u0__p6_0[] = {
  145208. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145209. 12.5, 17.5, 22.5, 27.5,
  145210. };
  145211. static long _vq_quantmap__8u0__p6_0[] = {
  145212. 11, 9, 7, 5, 3, 1, 0, 2,
  145213. 4, 6, 8, 10, 12,
  145214. };
  145215. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145216. _vq_quantthresh__8u0__p6_0,
  145217. _vq_quantmap__8u0__p6_0,
  145218. 13,
  145219. 13
  145220. };
  145221. static static_codebook _8u0__p6_0 = {
  145222. 2, 169,
  145223. _vq_lengthlist__8u0__p6_0,
  145224. 1, -526516224, 1616117760, 4, 0,
  145225. _vq_quantlist__8u0__p6_0,
  145226. NULL,
  145227. &_vq_auxt__8u0__p6_0,
  145228. NULL,
  145229. 0
  145230. };
  145231. static long _vq_quantlist__8u0__p6_1[] = {
  145232. 2,
  145233. 1,
  145234. 3,
  145235. 0,
  145236. 4,
  145237. };
  145238. static long _vq_lengthlist__8u0__p6_1[] = {
  145239. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145240. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145241. };
  145242. static float _vq_quantthresh__8u0__p6_1[] = {
  145243. -1.5, -0.5, 0.5, 1.5,
  145244. };
  145245. static long _vq_quantmap__8u0__p6_1[] = {
  145246. 3, 1, 0, 2, 4,
  145247. };
  145248. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145249. _vq_quantthresh__8u0__p6_1,
  145250. _vq_quantmap__8u0__p6_1,
  145251. 5,
  145252. 5
  145253. };
  145254. static static_codebook _8u0__p6_1 = {
  145255. 2, 25,
  145256. _vq_lengthlist__8u0__p6_1,
  145257. 1, -533725184, 1611661312, 3, 0,
  145258. _vq_quantlist__8u0__p6_1,
  145259. NULL,
  145260. &_vq_auxt__8u0__p6_1,
  145261. NULL,
  145262. 0
  145263. };
  145264. static long _vq_quantlist__8u0__p7_0[] = {
  145265. 1,
  145266. 0,
  145267. 2,
  145268. };
  145269. static long _vq_lengthlist__8u0__p7_0[] = {
  145270. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145271. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145272. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145273. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145274. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145275. 7,
  145276. };
  145277. static float _vq_quantthresh__8u0__p7_0[] = {
  145278. -157.5, 157.5,
  145279. };
  145280. static long _vq_quantmap__8u0__p7_0[] = {
  145281. 1, 0, 2,
  145282. };
  145283. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145284. _vq_quantthresh__8u0__p7_0,
  145285. _vq_quantmap__8u0__p7_0,
  145286. 3,
  145287. 3
  145288. };
  145289. static static_codebook _8u0__p7_0 = {
  145290. 4, 81,
  145291. _vq_lengthlist__8u0__p7_0,
  145292. 1, -518803456, 1628680192, 2, 0,
  145293. _vq_quantlist__8u0__p7_0,
  145294. NULL,
  145295. &_vq_auxt__8u0__p7_0,
  145296. NULL,
  145297. 0
  145298. };
  145299. static long _vq_quantlist__8u0__p7_1[] = {
  145300. 7,
  145301. 6,
  145302. 8,
  145303. 5,
  145304. 9,
  145305. 4,
  145306. 10,
  145307. 3,
  145308. 11,
  145309. 2,
  145310. 12,
  145311. 1,
  145312. 13,
  145313. 0,
  145314. 14,
  145315. };
  145316. static long _vq_lengthlist__8u0__p7_1[] = {
  145317. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145318. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145319. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145320. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145321. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145322. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145323. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145324. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145325. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145326. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145327. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145328. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145329. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145330. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145331. 10,
  145332. };
  145333. static float _vq_quantthresh__8u0__p7_1[] = {
  145334. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145335. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145336. };
  145337. static long _vq_quantmap__8u0__p7_1[] = {
  145338. 13, 11, 9, 7, 5, 3, 1, 0,
  145339. 2, 4, 6, 8, 10, 12, 14,
  145340. };
  145341. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145342. _vq_quantthresh__8u0__p7_1,
  145343. _vq_quantmap__8u0__p7_1,
  145344. 15,
  145345. 15
  145346. };
  145347. static static_codebook _8u0__p7_1 = {
  145348. 2, 225,
  145349. _vq_lengthlist__8u0__p7_1,
  145350. 1, -520986624, 1620377600, 4, 0,
  145351. _vq_quantlist__8u0__p7_1,
  145352. NULL,
  145353. &_vq_auxt__8u0__p7_1,
  145354. NULL,
  145355. 0
  145356. };
  145357. static long _vq_quantlist__8u0__p7_2[] = {
  145358. 10,
  145359. 9,
  145360. 11,
  145361. 8,
  145362. 12,
  145363. 7,
  145364. 13,
  145365. 6,
  145366. 14,
  145367. 5,
  145368. 15,
  145369. 4,
  145370. 16,
  145371. 3,
  145372. 17,
  145373. 2,
  145374. 18,
  145375. 1,
  145376. 19,
  145377. 0,
  145378. 20,
  145379. };
  145380. static long _vq_lengthlist__8u0__p7_2[] = {
  145381. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145382. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145383. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145384. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145385. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145386. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145387. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145388. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145389. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145390. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145391. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145392. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145393. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145394. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145395. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145396. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145397. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145398. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145399. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145400. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145401. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145402. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145403. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145404. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145405. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145406. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145407. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145408. 11,12,11,11,11,10,10,11,11,
  145409. };
  145410. static float _vq_quantthresh__8u0__p7_2[] = {
  145411. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145412. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145413. 6.5, 7.5, 8.5, 9.5,
  145414. };
  145415. static long _vq_quantmap__8u0__p7_2[] = {
  145416. 19, 17, 15, 13, 11, 9, 7, 5,
  145417. 3, 1, 0, 2, 4, 6, 8, 10,
  145418. 12, 14, 16, 18, 20,
  145419. };
  145420. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145421. _vq_quantthresh__8u0__p7_2,
  145422. _vq_quantmap__8u0__p7_2,
  145423. 21,
  145424. 21
  145425. };
  145426. static static_codebook _8u0__p7_2 = {
  145427. 2, 441,
  145428. _vq_lengthlist__8u0__p7_2,
  145429. 1, -529268736, 1611661312, 5, 0,
  145430. _vq_quantlist__8u0__p7_2,
  145431. NULL,
  145432. &_vq_auxt__8u0__p7_2,
  145433. NULL,
  145434. 0
  145435. };
  145436. static long _huff_lengthlist__8u0__single[] = {
  145437. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145438. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145439. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145440. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145441. };
  145442. static static_codebook _huff_book__8u0__single = {
  145443. 2, 64,
  145444. _huff_lengthlist__8u0__single,
  145445. 0, 0, 0, 0, 0,
  145446. NULL,
  145447. NULL,
  145448. NULL,
  145449. NULL,
  145450. 0
  145451. };
  145452. static long _vq_quantlist__8u1__p1_0[] = {
  145453. 1,
  145454. 0,
  145455. 2,
  145456. };
  145457. static long _vq_lengthlist__8u1__p1_0[] = {
  145458. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145459. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145460. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145461. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145462. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145463. 10,
  145464. };
  145465. static float _vq_quantthresh__8u1__p1_0[] = {
  145466. -0.5, 0.5,
  145467. };
  145468. static long _vq_quantmap__8u1__p1_0[] = {
  145469. 1, 0, 2,
  145470. };
  145471. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145472. _vq_quantthresh__8u1__p1_0,
  145473. _vq_quantmap__8u1__p1_0,
  145474. 3,
  145475. 3
  145476. };
  145477. static static_codebook _8u1__p1_0 = {
  145478. 4, 81,
  145479. _vq_lengthlist__8u1__p1_0,
  145480. 1, -535822336, 1611661312, 2, 0,
  145481. _vq_quantlist__8u1__p1_0,
  145482. NULL,
  145483. &_vq_auxt__8u1__p1_0,
  145484. NULL,
  145485. 0
  145486. };
  145487. static long _vq_quantlist__8u1__p2_0[] = {
  145488. 1,
  145489. 0,
  145490. 2,
  145491. };
  145492. static long _vq_lengthlist__8u1__p2_0[] = {
  145493. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145494. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145495. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145496. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145497. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145498. 7,
  145499. };
  145500. static float _vq_quantthresh__8u1__p2_0[] = {
  145501. -0.5, 0.5,
  145502. };
  145503. static long _vq_quantmap__8u1__p2_0[] = {
  145504. 1, 0, 2,
  145505. };
  145506. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145507. _vq_quantthresh__8u1__p2_0,
  145508. _vq_quantmap__8u1__p2_0,
  145509. 3,
  145510. 3
  145511. };
  145512. static static_codebook _8u1__p2_0 = {
  145513. 4, 81,
  145514. _vq_lengthlist__8u1__p2_0,
  145515. 1, -535822336, 1611661312, 2, 0,
  145516. _vq_quantlist__8u1__p2_0,
  145517. NULL,
  145518. &_vq_auxt__8u1__p2_0,
  145519. NULL,
  145520. 0
  145521. };
  145522. static long _vq_quantlist__8u1__p3_0[] = {
  145523. 2,
  145524. 1,
  145525. 3,
  145526. 0,
  145527. 4,
  145528. };
  145529. static long _vq_lengthlist__8u1__p3_0[] = {
  145530. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145531. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145532. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145533. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145534. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145535. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145536. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145537. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145538. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145539. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145540. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145541. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145542. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145543. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145544. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145545. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145546. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145547. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145548. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145549. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145550. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145551. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145552. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145553. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145554. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145555. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145556. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145557. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145558. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145559. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145560. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145561. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145562. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145563. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145564. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145565. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145566. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145567. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145568. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145569. 16,
  145570. };
  145571. static float _vq_quantthresh__8u1__p3_0[] = {
  145572. -1.5, -0.5, 0.5, 1.5,
  145573. };
  145574. static long _vq_quantmap__8u1__p3_0[] = {
  145575. 3, 1, 0, 2, 4,
  145576. };
  145577. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145578. _vq_quantthresh__8u1__p3_0,
  145579. _vq_quantmap__8u1__p3_0,
  145580. 5,
  145581. 5
  145582. };
  145583. static static_codebook _8u1__p3_0 = {
  145584. 4, 625,
  145585. _vq_lengthlist__8u1__p3_0,
  145586. 1, -533725184, 1611661312, 3, 0,
  145587. _vq_quantlist__8u1__p3_0,
  145588. NULL,
  145589. &_vq_auxt__8u1__p3_0,
  145590. NULL,
  145591. 0
  145592. };
  145593. static long _vq_quantlist__8u1__p4_0[] = {
  145594. 2,
  145595. 1,
  145596. 3,
  145597. 0,
  145598. 4,
  145599. };
  145600. static long _vq_lengthlist__8u1__p4_0[] = {
  145601. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145602. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145603. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145604. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145605. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145606. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145607. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145608. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145609. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145610. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145611. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145612. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145613. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145614. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145615. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145616. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145617. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145618. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145619. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145620. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145621. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145622. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145623. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145624. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145625. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145626. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145627. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145628. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145629. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145630. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145631. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145632. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145633. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145634. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145635. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145636. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145637. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145638. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145639. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145640. 10,
  145641. };
  145642. static float _vq_quantthresh__8u1__p4_0[] = {
  145643. -1.5, -0.5, 0.5, 1.5,
  145644. };
  145645. static long _vq_quantmap__8u1__p4_0[] = {
  145646. 3, 1, 0, 2, 4,
  145647. };
  145648. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145649. _vq_quantthresh__8u1__p4_0,
  145650. _vq_quantmap__8u1__p4_0,
  145651. 5,
  145652. 5
  145653. };
  145654. static static_codebook _8u1__p4_0 = {
  145655. 4, 625,
  145656. _vq_lengthlist__8u1__p4_0,
  145657. 1, -533725184, 1611661312, 3, 0,
  145658. _vq_quantlist__8u1__p4_0,
  145659. NULL,
  145660. &_vq_auxt__8u1__p4_0,
  145661. NULL,
  145662. 0
  145663. };
  145664. static long _vq_quantlist__8u1__p5_0[] = {
  145665. 4,
  145666. 3,
  145667. 5,
  145668. 2,
  145669. 6,
  145670. 1,
  145671. 7,
  145672. 0,
  145673. 8,
  145674. };
  145675. static long _vq_lengthlist__8u1__p5_0[] = {
  145676. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145677. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145678. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145679. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145680. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145681. 13,
  145682. };
  145683. static float _vq_quantthresh__8u1__p5_0[] = {
  145684. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145685. };
  145686. static long _vq_quantmap__8u1__p5_0[] = {
  145687. 7, 5, 3, 1, 0, 2, 4, 6,
  145688. 8,
  145689. };
  145690. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145691. _vq_quantthresh__8u1__p5_0,
  145692. _vq_quantmap__8u1__p5_0,
  145693. 9,
  145694. 9
  145695. };
  145696. static static_codebook _8u1__p5_0 = {
  145697. 2, 81,
  145698. _vq_lengthlist__8u1__p5_0,
  145699. 1, -531628032, 1611661312, 4, 0,
  145700. _vq_quantlist__8u1__p5_0,
  145701. NULL,
  145702. &_vq_auxt__8u1__p5_0,
  145703. NULL,
  145704. 0
  145705. };
  145706. static long _vq_quantlist__8u1__p6_0[] = {
  145707. 4,
  145708. 3,
  145709. 5,
  145710. 2,
  145711. 6,
  145712. 1,
  145713. 7,
  145714. 0,
  145715. 8,
  145716. };
  145717. static long _vq_lengthlist__8u1__p6_0[] = {
  145718. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145719. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145720. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145721. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145722. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145723. 10,
  145724. };
  145725. static float _vq_quantthresh__8u1__p6_0[] = {
  145726. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145727. };
  145728. static long _vq_quantmap__8u1__p6_0[] = {
  145729. 7, 5, 3, 1, 0, 2, 4, 6,
  145730. 8,
  145731. };
  145732. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145733. _vq_quantthresh__8u1__p6_0,
  145734. _vq_quantmap__8u1__p6_0,
  145735. 9,
  145736. 9
  145737. };
  145738. static static_codebook _8u1__p6_0 = {
  145739. 2, 81,
  145740. _vq_lengthlist__8u1__p6_0,
  145741. 1, -531628032, 1611661312, 4, 0,
  145742. _vq_quantlist__8u1__p6_0,
  145743. NULL,
  145744. &_vq_auxt__8u1__p6_0,
  145745. NULL,
  145746. 0
  145747. };
  145748. static long _vq_quantlist__8u1__p7_0[] = {
  145749. 1,
  145750. 0,
  145751. 2,
  145752. };
  145753. static long _vq_lengthlist__8u1__p7_0[] = {
  145754. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145755. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145756. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145757. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145758. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145759. 11,
  145760. };
  145761. static float _vq_quantthresh__8u1__p7_0[] = {
  145762. -5.5, 5.5,
  145763. };
  145764. static long _vq_quantmap__8u1__p7_0[] = {
  145765. 1, 0, 2,
  145766. };
  145767. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145768. _vq_quantthresh__8u1__p7_0,
  145769. _vq_quantmap__8u1__p7_0,
  145770. 3,
  145771. 3
  145772. };
  145773. static static_codebook _8u1__p7_0 = {
  145774. 4, 81,
  145775. _vq_lengthlist__8u1__p7_0,
  145776. 1, -529137664, 1618345984, 2, 0,
  145777. _vq_quantlist__8u1__p7_0,
  145778. NULL,
  145779. &_vq_auxt__8u1__p7_0,
  145780. NULL,
  145781. 0
  145782. };
  145783. static long _vq_quantlist__8u1__p7_1[] = {
  145784. 5,
  145785. 4,
  145786. 6,
  145787. 3,
  145788. 7,
  145789. 2,
  145790. 8,
  145791. 1,
  145792. 9,
  145793. 0,
  145794. 10,
  145795. };
  145796. static long _vq_lengthlist__8u1__p7_1[] = {
  145797. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145798. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145799. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145800. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145801. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145802. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145803. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145804. 9, 9, 9, 9, 9,10,10,10,10,
  145805. };
  145806. static float _vq_quantthresh__8u1__p7_1[] = {
  145807. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145808. 3.5, 4.5,
  145809. };
  145810. static long _vq_quantmap__8u1__p7_1[] = {
  145811. 9, 7, 5, 3, 1, 0, 2, 4,
  145812. 6, 8, 10,
  145813. };
  145814. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145815. _vq_quantthresh__8u1__p7_1,
  145816. _vq_quantmap__8u1__p7_1,
  145817. 11,
  145818. 11
  145819. };
  145820. static static_codebook _8u1__p7_1 = {
  145821. 2, 121,
  145822. _vq_lengthlist__8u1__p7_1,
  145823. 1, -531365888, 1611661312, 4, 0,
  145824. _vq_quantlist__8u1__p7_1,
  145825. NULL,
  145826. &_vq_auxt__8u1__p7_1,
  145827. NULL,
  145828. 0
  145829. };
  145830. static long _vq_quantlist__8u1__p8_0[] = {
  145831. 5,
  145832. 4,
  145833. 6,
  145834. 3,
  145835. 7,
  145836. 2,
  145837. 8,
  145838. 1,
  145839. 9,
  145840. 0,
  145841. 10,
  145842. };
  145843. static long _vq_lengthlist__8u1__p8_0[] = {
  145844. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145845. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145846. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145847. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145848. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145849. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145850. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145851. 12,13,13,14,14,15,15,15,15,
  145852. };
  145853. static float _vq_quantthresh__8u1__p8_0[] = {
  145854. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145855. 38.5, 49.5,
  145856. };
  145857. static long _vq_quantmap__8u1__p8_0[] = {
  145858. 9, 7, 5, 3, 1, 0, 2, 4,
  145859. 6, 8, 10,
  145860. };
  145861. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145862. _vq_quantthresh__8u1__p8_0,
  145863. _vq_quantmap__8u1__p8_0,
  145864. 11,
  145865. 11
  145866. };
  145867. static static_codebook _8u1__p8_0 = {
  145868. 2, 121,
  145869. _vq_lengthlist__8u1__p8_0,
  145870. 1, -524582912, 1618345984, 4, 0,
  145871. _vq_quantlist__8u1__p8_0,
  145872. NULL,
  145873. &_vq_auxt__8u1__p8_0,
  145874. NULL,
  145875. 0
  145876. };
  145877. static long _vq_quantlist__8u1__p8_1[] = {
  145878. 5,
  145879. 4,
  145880. 6,
  145881. 3,
  145882. 7,
  145883. 2,
  145884. 8,
  145885. 1,
  145886. 9,
  145887. 0,
  145888. 10,
  145889. };
  145890. static long _vq_lengthlist__8u1__p8_1[] = {
  145891. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145892. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145893. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145894. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145895. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145896. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145897. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145898. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145899. };
  145900. static float _vq_quantthresh__8u1__p8_1[] = {
  145901. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145902. 3.5, 4.5,
  145903. };
  145904. static long _vq_quantmap__8u1__p8_1[] = {
  145905. 9, 7, 5, 3, 1, 0, 2, 4,
  145906. 6, 8, 10,
  145907. };
  145908. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145909. _vq_quantthresh__8u1__p8_1,
  145910. _vq_quantmap__8u1__p8_1,
  145911. 11,
  145912. 11
  145913. };
  145914. static static_codebook _8u1__p8_1 = {
  145915. 2, 121,
  145916. _vq_lengthlist__8u1__p8_1,
  145917. 1, -531365888, 1611661312, 4, 0,
  145918. _vq_quantlist__8u1__p8_1,
  145919. NULL,
  145920. &_vq_auxt__8u1__p8_1,
  145921. NULL,
  145922. 0
  145923. };
  145924. static long _vq_quantlist__8u1__p9_0[] = {
  145925. 7,
  145926. 6,
  145927. 8,
  145928. 5,
  145929. 9,
  145930. 4,
  145931. 10,
  145932. 3,
  145933. 11,
  145934. 2,
  145935. 12,
  145936. 1,
  145937. 13,
  145938. 0,
  145939. 14,
  145940. };
  145941. static long _vq_lengthlist__8u1__p9_0[] = {
  145942. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145943. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145944. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145945. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145946. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145947. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145948. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145949. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145950. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145951. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145952. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145954. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145955. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145956. 10,
  145957. };
  145958. static float _vq_quantthresh__8u1__p9_0[] = {
  145959. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145960. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145961. };
  145962. static long _vq_quantmap__8u1__p9_0[] = {
  145963. 13, 11, 9, 7, 5, 3, 1, 0,
  145964. 2, 4, 6, 8, 10, 12, 14,
  145965. };
  145966. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145967. _vq_quantthresh__8u1__p9_0,
  145968. _vq_quantmap__8u1__p9_0,
  145969. 15,
  145970. 15
  145971. };
  145972. static static_codebook _8u1__p9_0 = {
  145973. 2, 225,
  145974. _vq_lengthlist__8u1__p9_0,
  145975. 1, -514071552, 1627381760, 4, 0,
  145976. _vq_quantlist__8u1__p9_0,
  145977. NULL,
  145978. &_vq_auxt__8u1__p9_0,
  145979. NULL,
  145980. 0
  145981. };
  145982. static long _vq_quantlist__8u1__p9_1[] = {
  145983. 7,
  145984. 6,
  145985. 8,
  145986. 5,
  145987. 9,
  145988. 4,
  145989. 10,
  145990. 3,
  145991. 11,
  145992. 2,
  145993. 12,
  145994. 1,
  145995. 13,
  145996. 0,
  145997. 14,
  145998. };
  145999. static long _vq_lengthlist__8u1__p9_1[] = {
  146000. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146001. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146002. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146003. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146004. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146005. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146006. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146007. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146008. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146009. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146010. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146011. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146012. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146013. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146014. 13,
  146015. };
  146016. static float _vq_quantthresh__8u1__p9_1[] = {
  146017. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146018. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146019. };
  146020. static long _vq_quantmap__8u1__p9_1[] = {
  146021. 13, 11, 9, 7, 5, 3, 1, 0,
  146022. 2, 4, 6, 8, 10, 12, 14,
  146023. };
  146024. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146025. _vq_quantthresh__8u1__p9_1,
  146026. _vq_quantmap__8u1__p9_1,
  146027. 15,
  146028. 15
  146029. };
  146030. static static_codebook _8u1__p9_1 = {
  146031. 2, 225,
  146032. _vq_lengthlist__8u1__p9_1,
  146033. 1, -522338304, 1620115456, 4, 0,
  146034. _vq_quantlist__8u1__p9_1,
  146035. NULL,
  146036. &_vq_auxt__8u1__p9_1,
  146037. NULL,
  146038. 0
  146039. };
  146040. static long _vq_quantlist__8u1__p9_2[] = {
  146041. 8,
  146042. 7,
  146043. 9,
  146044. 6,
  146045. 10,
  146046. 5,
  146047. 11,
  146048. 4,
  146049. 12,
  146050. 3,
  146051. 13,
  146052. 2,
  146053. 14,
  146054. 1,
  146055. 15,
  146056. 0,
  146057. 16,
  146058. };
  146059. static long _vq_lengthlist__8u1__p9_2[] = {
  146060. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146061. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146062. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146063. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146064. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146065. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146066. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146067. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146068. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146069. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146070. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146071. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146072. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146073. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146074. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146075. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146076. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146077. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146078. 10,
  146079. };
  146080. static float _vq_quantthresh__8u1__p9_2[] = {
  146081. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146082. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146083. };
  146084. static long _vq_quantmap__8u1__p9_2[] = {
  146085. 15, 13, 11, 9, 7, 5, 3, 1,
  146086. 0, 2, 4, 6, 8, 10, 12, 14,
  146087. 16,
  146088. };
  146089. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146090. _vq_quantthresh__8u1__p9_2,
  146091. _vq_quantmap__8u1__p9_2,
  146092. 17,
  146093. 17
  146094. };
  146095. static static_codebook _8u1__p9_2 = {
  146096. 2, 289,
  146097. _vq_lengthlist__8u1__p9_2,
  146098. 1, -529530880, 1611661312, 5, 0,
  146099. _vq_quantlist__8u1__p9_2,
  146100. NULL,
  146101. &_vq_auxt__8u1__p9_2,
  146102. NULL,
  146103. 0
  146104. };
  146105. static long _huff_lengthlist__8u1__single[] = {
  146106. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146107. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146108. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146109. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146110. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146111. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146112. 13, 8, 8,15,
  146113. };
  146114. static static_codebook _huff_book__8u1__single = {
  146115. 2, 100,
  146116. _huff_lengthlist__8u1__single,
  146117. 0, 0, 0, 0, 0,
  146118. NULL,
  146119. NULL,
  146120. NULL,
  146121. NULL,
  146122. 0
  146123. };
  146124. static long _huff_lengthlist__44u0__long[] = {
  146125. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146126. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146127. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146128. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146129. };
  146130. static static_codebook _huff_book__44u0__long = {
  146131. 2, 64,
  146132. _huff_lengthlist__44u0__long,
  146133. 0, 0, 0, 0, 0,
  146134. NULL,
  146135. NULL,
  146136. NULL,
  146137. NULL,
  146138. 0
  146139. };
  146140. static long _vq_quantlist__44u0__p1_0[] = {
  146141. 1,
  146142. 0,
  146143. 2,
  146144. };
  146145. static long _vq_lengthlist__44u0__p1_0[] = {
  146146. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146147. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146148. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146149. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146150. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146151. 13,
  146152. };
  146153. static float _vq_quantthresh__44u0__p1_0[] = {
  146154. -0.5, 0.5,
  146155. };
  146156. static long _vq_quantmap__44u0__p1_0[] = {
  146157. 1, 0, 2,
  146158. };
  146159. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146160. _vq_quantthresh__44u0__p1_0,
  146161. _vq_quantmap__44u0__p1_0,
  146162. 3,
  146163. 3
  146164. };
  146165. static static_codebook _44u0__p1_0 = {
  146166. 4, 81,
  146167. _vq_lengthlist__44u0__p1_0,
  146168. 1, -535822336, 1611661312, 2, 0,
  146169. _vq_quantlist__44u0__p1_0,
  146170. NULL,
  146171. &_vq_auxt__44u0__p1_0,
  146172. NULL,
  146173. 0
  146174. };
  146175. static long _vq_quantlist__44u0__p2_0[] = {
  146176. 1,
  146177. 0,
  146178. 2,
  146179. };
  146180. static long _vq_lengthlist__44u0__p2_0[] = {
  146181. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146182. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146183. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146184. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146185. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146186. 9,
  146187. };
  146188. static float _vq_quantthresh__44u0__p2_0[] = {
  146189. -0.5, 0.5,
  146190. };
  146191. static long _vq_quantmap__44u0__p2_0[] = {
  146192. 1, 0, 2,
  146193. };
  146194. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146195. _vq_quantthresh__44u0__p2_0,
  146196. _vq_quantmap__44u0__p2_0,
  146197. 3,
  146198. 3
  146199. };
  146200. static static_codebook _44u0__p2_0 = {
  146201. 4, 81,
  146202. _vq_lengthlist__44u0__p2_0,
  146203. 1, -535822336, 1611661312, 2, 0,
  146204. _vq_quantlist__44u0__p2_0,
  146205. NULL,
  146206. &_vq_auxt__44u0__p2_0,
  146207. NULL,
  146208. 0
  146209. };
  146210. static long _vq_quantlist__44u0__p3_0[] = {
  146211. 2,
  146212. 1,
  146213. 3,
  146214. 0,
  146215. 4,
  146216. };
  146217. static long _vq_lengthlist__44u0__p3_0[] = {
  146218. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146219. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146220. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146221. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146222. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146223. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146224. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146225. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146226. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146227. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146228. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146229. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146230. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146231. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146232. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146233. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146234. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146235. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146236. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146237. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146238. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146239. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146240. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146241. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146242. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146243. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146244. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146245. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146246. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146247. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146248. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146249. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146250. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146251. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146252. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146253. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146254. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146255. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146256. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146257. 19,
  146258. };
  146259. static float _vq_quantthresh__44u0__p3_0[] = {
  146260. -1.5, -0.5, 0.5, 1.5,
  146261. };
  146262. static long _vq_quantmap__44u0__p3_0[] = {
  146263. 3, 1, 0, 2, 4,
  146264. };
  146265. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146266. _vq_quantthresh__44u0__p3_0,
  146267. _vq_quantmap__44u0__p3_0,
  146268. 5,
  146269. 5
  146270. };
  146271. static static_codebook _44u0__p3_0 = {
  146272. 4, 625,
  146273. _vq_lengthlist__44u0__p3_0,
  146274. 1, -533725184, 1611661312, 3, 0,
  146275. _vq_quantlist__44u0__p3_0,
  146276. NULL,
  146277. &_vq_auxt__44u0__p3_0,
  146278. NULL,
  146279. 0
  146280. };
  146281. static long _vq_quantlist__44u0__p4_0[] = {
  146282. 2,
  146283. 1,
  146284. 3,
  146285. 0,
  146286. 4,
  146287. };
  146288. static long _vq_lengthlist__44u0__p4_0[] = {
  146289. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146290. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146291. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146292. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146293. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146294. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146295. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146296. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146297. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146298. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146299. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146300. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146301. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146302. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146303. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146304. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146305. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146306. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146307. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146308. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146309. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146310. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146311. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146312. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146313. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146314. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146315. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146316. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146317. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146318. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146319. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146320. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146321. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146322. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146323. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146324. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146325. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146326. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146327. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146328. 12,
  146329. };
  146330. static float _vq_quantthresh__44u0__p4_0[] = {
  146331. -1.5, -0.5, 0.5, 1.5,
  146332. };
  146333. static long _vq_quantmap__44u0__p4_0[] = {
  146334. 3, 1, 0, 2, 4,
  146335. };
  146336. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146337. _vq_quantthresh__44u0__p4_0,
  146338. _vq_quantmap__44u0__p4_0,
  146339. 5,
  146340. 5
  146341. };
  146342. static static_codebook _44u0__p4_0 = {
  146343. 4, 625,
  146344. _vq_lengthlist__44u0__p4_0,
  146345. 1, -533725184, 1611661312, 3, 0,
  146346. _vq_quantlist__44u0__p4_0,
  146347. NULL,
  146348. &_vq_auxt__44u0__p4_0,
  146349. NULL,
  146350. 0
  146351. };
  146352. static long _vq_quantlist__44u0__p5_0[] = {
  146353. 4,
  146354. 3,
  146355. 5,
  146356. 2,
  146357. 6,
  146358. 1,
  146359. 7,
  146360. 0,
  146361. 8,
  146362. };
  146363. static long _vq_lengthlist__44u0__p5_0[] = {
  146364. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146365. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146366. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146367. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146368. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146369. 12,
  146370. };
  146371. static float _vq_quantthresh__44u0__p5_0[] = {
  146372. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146373. };
  146374. static long _vq_quantmap__44u0__p5_0[] = {
  146375. 7, 5, 3, 1, 0, 2, 4, 6,
  146376. 8,
  146377. };
  146378. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146379. _vq_quantthresh__44u0__p5_0,
  146380. _vq_quantmap__44u0__p5_0,
  146381. 9,
  146382. 9
  146383. };
  146384. static static_codebook _44u0__p5_0 = {
  146385. 2, 81,
  146386. _vq_lengthlist__44u0__p5_0,
  146387. 1, -531628032, 1611661312, 4, 0,
  146388. _vq_quantlist__44u0__p5_0,
  146389. NULL,
  146390. &_vq_auxt__44u0__p5_0,
  146391. NULL,
  146392. 0
  146393. };
  146394. static long _vq_quantlist__44u0__p6_0[] = {
  146395. 6,
  146396. 5,
  146397. 7,
  146398. 4,
  146399. 8,
  146400. 3,
  146401. 9,
  146402. 2,
  146403. 10,
  146404. 1,
  146405. 11,
  146406. 0,
  146407. 12,
  146408. };
  146409. static long _vq_lengthlist__44u0__p6_0[] = {
  146410. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146411. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146412. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146413. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146414. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146415. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146416. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146417. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146418. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146419. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146420. 15,17,16,17,18,17,17,18, 0,
  146421. };
  146422. static float _vq_quantthresh__44u0__p6_0[] = {
  146423. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146424. 12.5, 17.5, 22.5, 27.5,
  146425. };
  146426. static long _vq_quantmap__44u0__p6_0[] = {
  146427. 11, 9, 7, 5, 3, 1, 0, 2,
  146428. 4, 6, 8, 10, 12,
  146429. };
  146430. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146431. _vq_quantthresh__44u0__p6_0,
  146432. _vq_quantmap__44u0__p6_0,
  146433. 13,
  146434. 13
  146435. };
  146436. static static_codebook _44u0__p6_0 = {
  146437. 2, 169,
  146438. _vq_lengthlist__44u0__p6_0,
  146439. 1, -526516224, 1616117760, 4, 0,
  146440. _vq_quantlist__44u0__p6_0,
  146441. NULL,
  146442. &_vq_auxt__44u0__p6_0,
  146443. NULL,
  146444. 0
  146445. };
  146446. static long _vq_quantlist__44u0__p6_1[] = {
  146447. 2,
  146448. 1,
  146449. 3,
  146450. 0,
  146451. 4,
  146452. };
  146453. static long _vq_lengthlist__44u0__p6_1[] = {
  146454. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146455. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146456. };
  146457. static float _vq_quantthresh__44u0__p6_1[] = {
  146458. -1.5, -0.5, 0.5, 1.5,
  146459. };
  146460. static long _vq_quantmap__44u0__p6_1[] = {
  146461. 3, 1, 0, 2, 4,
  146462. };
  146463. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146464. _vq_quantthresh__44u0__p6_1,
  146465. _vq_quantmap__44u0__p6_1,
  146466. 5,
  146467. 5
  146468. };
  146469. static static_codebook _44u0__p6_1 = {
  146470. 2, 25,
  146471. _vq_lengthlist__44u0__p6_1,
  146472. 1, -533725184, 1611661312, 3, 0,
  146473. _vq_quantlist__44u0__p6_1,
  146474. NULL,
  146475. &_vq_auxt__44u0__p6_1,
  146476. NULL,
  146477. 0
  146478. };
  146479. static long _vq_quantlist__44u0__p7_0[] = {
  146480. 2,
  146481. 1,
  146482. 3,
  146483. 0,
  146484. 4,
  146485. };
  146486. static long _vq_lengthlist__44u0__p7_0[] = {
  146487. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146490. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146494. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146514. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146515. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146516. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146517. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146518. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146519. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146520. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146521. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146522. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146523. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146526. 10,
  146527. };
  146528. static float _vq_quantthresh__44u0__p7_0[] = {
  146529. -253.5, -84.5, 84.5, 253.5,
  146530. };
  146531. static long _vq_quantmap__44u0__p7_0[] = {
  146532. 3, 1, 0, 2, 4,
  146533. };
  146534. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146535. _vq_quantthresh__44u0__p7_0,
  146536. _vq_quantmap__44u0__p7_0,
  146537. 5,
  146538. 5
  146539. };
  146540. static static_codebook _44u0__p7_0 = {
  146541. 4, 625,
  146542. _vq_lengthlist__44u0__p7_0,
  146543. 1, -518709248, 1626677248, 3, 0,
  146544. _vq_quantlist__44u0__p7_0,
  146545. NULL,
  146546. &_vq_auxt__44u0__p7_0,
  146547. NULL,
  146548. 0
  146549. };
  146550. static long _vq_quantlist__44u0__p7_1[] = {
  146551. 6,
  146552. 5,
  146553. 7,
  146554. 4,
  146555. 8,
  146556. 3,
  146557. 9,
  146558. 2,
  146559. 10,
  146560. 1,
  146561. 11,
  146562. 0,
  146563. 12,
  146564. };
  146565. static long _vq_lengthlist__44u0__p7_1[] = {
  146566. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146567. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146568. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146569. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146570. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146571. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146572. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146573. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146574. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146575. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146576. 15,15,15,15,15,15,15,15,15,
  146577. };
  146578. static float _vq_quantthresh__44u0__p7_1[] = {
  146579. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146580. 32.5, 45.5, 58.5, 71.5,
  146581. };
  146582. static long _vq_quantmap__44u0__p7_1[] = {
  146583. 11, 9, 7, 5, 3, 1, 0, 2,
  146584. 4, 6, 8, 10, 12,
  146585. };
  146586. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146587. _vq_quantthresh__44u0__p7_1,
  146588. _vq_quantmap__44u0__p7_1,
  146589. 13,
  146590. 13
  146591. };
  146592. static static_codebook _44u0__p7_1 = {
  146593. 2, 169,
  146594. _vq_lengthlist__44u0__p7_1,
  146595. 1, -523010048, 1618608128, 4, 0,
  146596. _vq_quantlist__44u0__p7_1,
  146597. NULL,
  146598. &_vq_auxt__44u0__p7_1,
  146599. NULL,
  146600. 0
  146601. };
  146602. static long _vq_quantlist__44u0__p7_2[] = {
  146603. 6,
  146604. 5,
  146605. 7,
  146606. 4,
  146607. 8,
  146608. 3,
  146609. 9,
  146610. 2,
  146611. 10,
  146612. 1,
  146613. 11,
  146614. 0,
  146615. 12,
  146616. };
  146617. static long _vq_lengthlist__44u0__p7_2[] = {
  146618. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146619. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146620. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146621. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146622. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146623. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146624. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146625. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146626. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146627. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146628. 9, 9, 9,10, 9, 9,10,10, 9,
  146629. };
  146630. static float _vq_quantthresh__44u0__p7_2[] = {
  146631. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146632. 2.5, 3.5, 4.5, 5.5,
  146633. };
  146634. static long _vq_quantmap__44u0__p7_2[] = {
  146635. 11, 9, 7, 5, 3, 1, 0, 2,
  146636. 4, 6, 8, 10, 12,
  146637. };
  146638. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146639. _vq_quantthresh__44u0__p7_2,
  146640. _vq_quantmap__44u0__p7_2,
  146641. 13,
  146642. 13
  146643. };
  146644. static static_codebook _44u0__p7_2 = {
  146645. 2, 169,
  146646. _vq_lengthlist__44u0__p7_2,
  146647. 1, -531103744, 1611661312, 4, 0,
  146648. _vq_quantlist__44u0__p7_2,
  146649. NULL,
  146650. &_vq_auxt__44u0__p7_2,
  146651. NULL,
  146652. 0
  146653. };
  146654. static long _huff_lengthlist__44u0__short[] = {
  146655. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146656. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146657. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146658. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146659. };
  146660. static static_codebook _huff_book__44u0__short = {
  146661. 2, 64,
  146662. _huff_lengthlist__44u0__short,
  146663. 0, 0, 0, 0, 0,
  146664. NULL,
  146665. NULL,
  146666. NULL,
  146667. NULL,
  146668. 0
  146669. };
  146670. static long _huff_lengthlist__44u1__long[] = {
  146671. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146672. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146673. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146674. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146675. };
  146676. static static_codebook _huff_book__44u1__long = {
  146677. 2, 64,
  146678. _huff_lengthlist__44u1__long,
  146679. 0, 0, 0, 0, 0,
  146680. NULL,
  146681. NULL,
  146682. NULL,
  146683. NULL,
  146684. 0
  146685. };
  146686. static long _vq_quantlist__44u1__p1_0[] = {
  146687. 1,
  146688. 0,
  146689. 2,
  146690. };
  146691. static long _vq_lengthlist__44u1__p1_0[] = {
  146692. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146693. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146694. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146695. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146696. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146697. 13,
  146698. };
  146699. static float _vq_quantthresh__44u1__p1_0[] = {
  146700. -0.5, 0.5,
  146701. };
  146702. static long _vq_quantmap__44u1__p1_0[] = {
  146703. 1, 0, 2,
  146704. };
  146705. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146706. _vq_quantthresh__44u1__p1_0,
  146707. _vq_quantmap__44u1__p1_0,
  146708. 3,
  146709. 3
  146710. };
  146711. static static_codebook _44u1__p1_0 = {
  146712. 4, 81,
  146713. _vq_lengthlist__44u1__p1_0,
  146714. 1, -535822336, 1611661312, 2, 0,
  146715. _vq_quantlist__44u1__p1_0,
  146716. NULL,
  146717. &_vq_auxt__44u1__p1_0,
  146718. NULL,
  146719. 0
  146720. };
  146721. static long _vq_quantlist__44u1__p2_0[] = {
  146722. 1,
  146723. 0,
  146724. 2,
  146725. };
  146726. static long _vq_lengthlist__44u1__p2_0[] = {
  146727. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146728. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146729. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146730. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146731. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146732. 9,
  146733. };
  146734. static float _vq_quantthresh__44u1__p2_0[] = {
  146735. -0.5, 0.5,
  146736. };
  146737. static long _vq_quantmap__44u1__p2_0[] = {
  146738. 1, 0, 2,
  146739. };
  146740. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146741. _vq_quantthresh__44u1__p2_0,
  146742. _vq_quantmap__44u1__p2_0,
  146743. 3,
  146744. 3
  146745. };
  146746. static static_codebook _44u1__p2_0 = {
  146747. 4, 81,
  146748. _vq_lengthlist__44u1__p2_0,
  146749. 1, -535822336, 1611661312, 2, 0,
  146750. _vq_quantlist__44u1__p2_0,
  146751. NULL,
  146752. &_vq_auxt__44u1__p2_0,
  146753. NULL,
  146754. 0
  146755. };
  146756. static long _vq_quantlist__44u1__p3_0[] = {
  146757. 2,
  146758. 1,
  146759. 3,
  146760. 0,
  146761. 4,
  146762. };
  146763. static long _vq_lengthlist__44u1__p3_0[] = {
  146764. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146765. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146766. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146767. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146768. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146769. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146770. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146771. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146772. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146773. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146774. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146775. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146776. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146777. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146778. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146779. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146780. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146781. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146782. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146783. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146784. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146785. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146786. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146787. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146788. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146789. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146790. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146791. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146792. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146793. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146794. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146795. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146796. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146797. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146798. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146799. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146800. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146801. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146802. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146803. 19,
  146804. };
  146805. static float _vq_quantthresh__44u1__p3_0[] = {
  146806. -1.5, -0.5, 0.5, 1.5,
  146807. };
  146808. static long _vq_quantmap__44u1__p3_0[] = {
  146809. 3, 1, 0, 2, 4,
  146810. };
  146811. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146812. _vq_quantthresh__44u1__p3_0,
  146813. _vq_quantmap__44u1__p3_0,
  146814. 5,
  146815. 5
  146816. };
  146817. static static_codebook _44u1__p3_0 = {
  146818. 4, 625,
  146819. _vq_lengthlist__44u1__p3_0,
  146820. 1, -533725184, 1611661312, 3, 0,
  146821. _vq_quantlist__44u1__p3_0,
  146822. NULL,
  146823. &_vq_auxt__44u1__p3_0,
  146824. NULL,
  146825. 0
  146826. };
  146827. static long _vq_quantlist__44u1__p4_0[] = {
  146828. 2,
  146829. 1,
  146830. 3,
  146831. 0,
  146832. 4,
  146833. };
  146834. static long _vq_lengthlist__44u1__p4_0[] = {
  146835. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146836. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146837. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146838. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146839. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146840. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146841. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146842. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146843. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146844. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146845. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146846. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146847. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146848. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146849. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146850. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146851. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146852. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146853. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146854. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146855. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146856. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146857. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146858. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146859. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146860. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146861. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146862. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146863. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146864. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146865. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146866. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146867. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146868. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146869. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146870. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146871. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146872. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146873. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146874. 12,
  146875. };
  146876. static float _vq_quantthresh__44u1__p4_0[] = {
  146877. -1.5, -0.5, 0.5, 1.5,
  146878. };
  146879. static long _vq_quantmap__44u1__p4_0[] = {
  146880. 3, 1, 0, 2, 4,
  146881. };
  146882. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146883. _vq_quantthresh__44u1__p4_0,
  146884. _vq_quantmap__44u1__p4_0,
  146885. 5,
  146886. 5
  146887. };
  146888. static static_codebook _44u1__p4_0 = {
  146889. 4, 625,
  146890. _vq_lengthlist__44u1__p4_0,
  146891. 1, -533725184, 1611661312, 3, 0,
  146892. _vq_quantlist__44u1__p4_0,
  146893. NULL,
  146894. &_vq_auxt__44u1__p4_0,
  146895. NULL,
  146896. 0
  146897. };
  146898. static long _vq_quantlist__44u1__p5_0[] = {
  146899. 4,
  146900. 3,
  146901. 5,
  146902. 2,
  146903. 6,
  146904. 1,
  146905. 7,
  146906. 0,
  146907. 8,
  146908. };
  146909. static long _vq_lengthlist__44u1__p5_0[] = {
  146910. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146911. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146912. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146913. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146914. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146915. 12,
  146916. };
  146917. static float _vq_quantthresh__44u1__p5_0[] = {
  146918. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146919. };
  146920. static long _vq_quantmap__44u1__p5_0[] = {
  146921. 7, 5, 3, 1, 0, 2, 4, 6,
  146922. 8,
  146923. };
  146924. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146925. _vq_quantthresh__44u1__p5_0,
  146926. _vq_quantmap__44u1__p5_0,
  146927. 9,
  146928. 9
  146929. };
  146930. static static_codebook _44u1__p5_0 = {
  146931. 2, 81,
  146932. _vq_lengthlist__44u1__p5_0,
  146933. 1, -531628032, 1611661312, 4, 0,
  146934. _vq_quantlist__44u1__p5_0,
  146935. NULL,
  146936. &_vq_auxt__44u1__p5_0,
  146937. NULL,
  146938. 0
  146939. };
  146940. static long _vq_quantlist__44u1__p6_0[] = {
  146941. 6,
  146942. 5,
  146943. 7,
  146944. 4,
  146945. 8,
  146946. 3,
  146947. 9,
  146948. 2,
  146949. 10,
  146950. 1,
  146951. 11,
  146952. 0,
  146953. 12,
  146954. };
  146955. static long _vq_lengthlist__44u1__p6_0[] = {
  146956. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146957. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146958. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146959. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146960. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146961. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146962. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146963. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146964. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146965. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146966. 15,17,16,17,18,17,17,18, 0,
  146967. };
  146968. static float _vq_quantthresh__44u1__p6_0[] = {
  146969. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146970. 12.5, 17.5, 22.5, 27.5,
  146971. };
  146972. static long _vq_quantmap__44u1__p6_0[] = {
  146973. 11, 9, 7, 5, 3, 1, 0, 2,
  146974. 4, 6, 8, 10, 12,
  146975. };
  146976. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146977. _vq_quantthresh__44u1__p6_0,
  146978. _vq_quantmap__44u1__p6_0,
  146979. 13,
  146980. 13
  146981. };
  146982. static static_codebook _44u1__p6_0 = {
  146983. 2, 169,
  146984. _vq_lengthlist__44u1__p6_0,
  146985. 1, -526516224, 1616117760, 4, 0,
  146986. _vq_quantlist__44u1__p6_0,
  146987. NULL,
  146988. &_vq_auxt__44u1__p6_0,
  146989. NULL,
  146990. 0
  146991. };
  146992. static long _vq_quantlist__44u1__p6_1[] = {
  146993. 2,
  146994. 1,
  146995. 3,
  146996. 0,
  146997. 4,
  146998. };
  146999. static long _vq_lengthlist__44u1__p6_1[] = {
  147000. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147001. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147002. };
  147003. static float _vq_quantthresh__44u1__p6_1[] = {
  147004. -1.5, -0.5, 0.5, 1.5,
  147005. };
  147006. static long _vq_quantmap__44u1__p6_1[] = {
  147007. 3, 1, 0, 2, 4,
  147008. };
  147009. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147010. _vq_quantthresh__44u1__p6_1,
  147011. _vq_quantmap__44u1__p6_1,
  147012. 5,
  147013. 5
  147014. };
  147015. static static_codebook _44u1__p6_1 = {
  147016. 2, 25,
  147017. _vq_lengthlist__44u1__p6_1,
  147018. 1, -533725184, 1611661312, 3, 0,
  147019. _vq_quantlist__44u1__p6_1,
  147020. NULL,
  147021. &_vq_auxt__44u1__p6_1,
  147022. NULL,
  147023. 0
  147024. };
  147025. static long _vq_quantlist__44u1__p7_0[] = {
  147026. 3,
  147027. 2,
  147028. 4,
  147029. 1,
  147030. 5,
  147031. 0,
  147032. 6,
  147033. };
  147034. static long _vq_lengthlist__44u1__p7_0[] = {
  147035. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147036. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147037. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147038. 8,
  147039. };
  147040. static float _vq_quantthresh__44u1__p7_0[] = {
  147041. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147042. };
  147043. static long _vq_quantmap__44u1__p7_0[] = {
  147044. 5, 3, 1, 0, 2, 4, 6,
  147045. };
  147046. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147047. _vq_quantthresh__44u1__p7_0,
  147048. _vq_quantmap__44u1__p7_0,
  147049. 7,
  147050. 7
  147051. };
  147052. static static_codebook _44u1__p7_0 = {
  147053. 2, 49,
  147054. _vq_lengthlist__44u1__p7_0,
  147055. 1, -518017024, 1626677248, 3, 0,
  147056. _vq_quantlist__44u1__p7_0,
  147057. NULL,
  147058. &_vq_auxt__44u1__p7_0,
  147059. NULL,
  147060. 0
  147061. };
  147062. static long _vq_quantlist__44u1__p7_1[] = {
  147063. 6,
  147064. 5,
  147065. 7,
  147066. 4,
  147067. 8,
  147068. 3,
  147069. 9,
  147070. 2,
  147071. 10,
  147072. 1,
  147073. 11,
  147074. 0,
  147075. 12,
  147076. };
  147077. static long _vq_lengthlist__44u1__p7_1[] = {
  147078. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147079. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147080. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147081. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147082. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147083. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147084. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147085. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147086. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147087. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147088. 15,15,15,15,15,15,15,15,15,
  147089. };
  147090. static float _vq_quantthresh__44u1__p7_1[] = {
  147091. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147092. 32.5, 45.5, 58.5, 71.5,
  147093. };
  147094. static long _vq_quantmap__44u1__p7_1[] = {
  147095. 11, 9, 7, 5, 3, 1, 0, 2,
  147096. 4, 6, 8, 10, 12,
  147097. };
  147098. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147099. _vq_quantthresh__44u1__p7_1,
  147100. _vq_quantmap__44u1__p7_1,
  147101. 13,
  147102. 13
  147103. };
  147104. static static_codebook _44u1__p7_1 = {
  147105. 2, 169,
  147106. _vq_lengthlist__44u1__p7_1,
  147107. 1, -523010048, 1618608128, 4, 0,
  147108. _vq_quantlist__44u1__p7_1,
  147109. NULL,
  147110. &_vq_auxt__44u1__p7_1,
  147111. NULL,
  147112. 0
  147113. };
  147114. static long _vq_quantlist__44u1__p7_2[] = {
  147115. 6,
  147116. 5,
  147117. 7,
  147118. 4,
  147119. 8,
  147120. 3,
  147121. 9,
  147122. 2,
  147123. 10,
  147124. 1,
  147125. 11,
  147126. 0,
  147127. 12,
  147128. };
  147129. static long _vq_lengthlist__44u1__p7_2[] = {
  147130. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147131. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147132. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147133. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147134. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147135. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147136. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147137. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147138. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147139. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147140. 9, 9, 9,10, 9, 9,10,10, 9,
  147141. };
  147142. static float _vq_quantthresh__44u1__p7_2[] = {
  147143. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147144. 2.5, 3.5, 4.5, 5.5,
  147145. };
  147146. static long _vq_quantmap__44u1__p7_2[] = {
  147147. 11, 9, 7, 5, 3, 1, 0, 2,
  147148. 4, 6, 8, 10, 12,
  147149. };
  147150. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147151. _vq_quantthresh__44u1__p7_2,
  147152. _vq_quantmap__44u1__p7_2,
  147153. 13,
  147154. 13
  147155. };
  147156. static static_codebook _44u1__p7_2 = {
  147157. 2, 169,
  147158. _vq_lengthlist__44u1__p7_2,
  147159. 1, -531103744, 1611661312, 4, 0,
  147160. _vq_quantlist__44u1__p7_2,
  147161. NULL,
  147162. &_vq_auxt__44u1__p7_2,
  147163. NULL,
  147164. 0
  147165. };
  147166. static long _huff_lengthlist__44u1__short[] = {
  147167. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147168. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147169. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147170. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147171. };
  147172. static static_codebook _huff_book__44u1__short = {
  147173. 2, 64,
  147174. _huff_lengthlist__44u1__short,
  147175. 0, 0, 0, 0, 0,
  147176. NULL,
  147177. NULL,
  147178. NULL,
  147179. NULL,
  147180. 0
  147181. };
  147182. static long _huff_lengthlist__44u2__long[] = {
  147183. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147184. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147185. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147186. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147187. };
  147188. static static_codebook _huff_book__44u2__long = {
  147189. 2, 64,
  147190. _huff_lengthlist__44u2__long,
  147191. 0, 0, 0, 0, 0,
  147192. NULL,
  147193. NULL,
  147194. NULL,
  147195. NULL,
  147196. 0
  147197. };
  147198. static long _vq_quantlist__44u2__p1_0[] = {
  147199. 1,
  147200. 0,
  147201. 2,
  147202. };
  147203. static long _vq_lengthlist__44u2__p1_0[] = {
  147204. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147205. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147206. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147207. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147208. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147209. 13,
  147210. };
  147211. static float _vq_quantthresh__44u2__p1_0[] = {
  147212. -0.5, 0.5,
  147213. };
  147214. static long _vq_quantmap__44u2__p1_0[] = {
  147215. 1, 0, 2,
  147216. };
  147217. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147218. _vq_quantthresh__44u2__p1_0,
  147219. _vq_quantmap__44u2__p1_0,
  147220. 3,
  147221. 3
  147222. };
  147223. static static_codebook _44u2__p1_0 = {
  147224. 4, 81,
  147225. _vq_lengthlist__44u2__p1_0,
  147226. 1, -535822336, 1611661312, 2, 0,
  147227. _vq_quantlist__44u2__p1_0,
  147228. NULL,
  147229. &_vq_auxt__44u2__p1_0,
  147230. NULL,
  147231. 0
  147232. };
  147233. static long _vq_quantlist__44u2__p2_0[] = {
  147234. 1,
  147235. 0,
  147236. 2,
  147237. };
  147238. static long _vq_lengthlist__44u2__p2_0[] = {
  147239. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147240. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147241. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147242. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147243. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147244. 9,
  147245. };
  147246. static float _vq_quantthresh__44u2__p2_0[] = {
  147247. -0.5, 0.5,
  147248. };
  147249. static long _vq_quantmap__44u2__p2_0[] = {
  147250. 1, 0, 2,
  147251. };
  147252. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147253. _vq_quantthresh__44u2__p2_0,
  147254. _vq_quantmap__44u2__p2_0,
  147255. 3,
  147256. 3
  147257. };
  147258. static static_codebook _44u2__p2_0 = {
  147259. 4, 81,
  147260. _vq_lengthlist__44u2__p2_0,
  147261. 1, -535822336, 1611661312, 2, 0,
  147262. _vq_quantlist__44u2__p2_0,
  147263. NULL,
  147264. &_vq_auxt__44u2__p2_0,
  147265. NULL,
  147266. 0
  147267. };
  147268. static long _vq_quantlist__44u2__p3_0[] = {
  147269. 2,
  147270. 1,
  147271. 3,
  147272. 0,
  147273. 4,
  147274. };
  147275. static long _vq_lengthlist__44u2__p3_0[] = {
  147276. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147277. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147278. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147279. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147280. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147281. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147282. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147283. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147284. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147285. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147286. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147287. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147288. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147289. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147290. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147291. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147292. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147293. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147294. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147295. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147296. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147297. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147298. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147299. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147300. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147301. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147302. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147303. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147304. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147305. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147306. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147307. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147308. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147309. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147310. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147311. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147312. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147313. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147314. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147315. 0,
  147316. };
  147317. static float _vq_quantthresh__44u2__p3_0[] = {
  147318. -1.5, -0.5, 0.5, 1.5,
  147319. };
  147320. static long _vq_quantmap__44u2__p3_0[] = {
  147321. 3, 1, 0, 2, 4,
  147322. };
  147323. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147324. _vq_quantthresh__44u2__p3_0,
  147325. _vq_quantmap__44u2__p3_0,
  147326. 5,
  147327. 5
  147328. };
  147329. static static_codebook _44u2__p3_0 = {
  147330. 4, 625,
  147331. _vq_lengthlist__44u2__p3_0,
  147332. 1, -533725184, 1611661312, 3, 0,
  147333. _vq_quantlist__44u2__p3_0,
  147334. NULL,
  147335. &_vq_auxt__44u2__p3_0,
  147336. NULL,
  147337. 0
  147338. };
  147339. static long _vq_quantlist__44u2__p4_0[] = {
  147340. 2,
  147341. 1,
  147342. 3,
  147343. 0,
  147344. 4,
  147345. };
  147346. static long _vq_lengthlist__44u2__p4_0[] = {
  147347. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147348. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147349. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147350. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147351. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147352. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147353. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147354. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147355. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147356. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147357. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147358. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147359. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147360. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147361. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147362. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147363. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147364. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147365. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147366. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147367. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147368. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147369. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147370. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147371. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147372. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147373. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147374. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147375. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147376. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147377. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147378. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147379. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147380. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147381. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147382. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147383. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147384. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147385. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147386. 13,
  147387. };
  147388. static float _vq_quantthresh__44u2__p4_0[] = {
  147389. -1.5, -0.5, 0.5, 1.5,
  147390. };
  147391. static long _vq_quantmap__44u2__p4_0[] = {
  147392. 3, 1, 0, 2, 4,
  147393. };
  147394. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147395. _vq_quantthresh__44u2__p4_0,
  147396. _vq_quantmap__44u2__p4_0,
  147397. 5,
  147398. 5
  147399. };
  147400. static static_codebook _44u2__p4_0 = {
  147401. 4, 625,
  147402. _vq_lengthlist__44u2__p4_0,
  147403. 1, -533725184, 1611661312, 3, 0,
  147404. _vq_quantlist__44u2__p4_0,
  147405. NULL,
  147406. &_vq_auxt__44u2__p4_0,
  147407. NULL,
  147408. 0
  147409. };
  147410. static long _vq_quantlist__44u2__p5_0[] = {
  147411. 4,
  147412. 3,
  147413. 5,
  147414. 2,
  147415. 6,
  147416. 1,
  147417. 7,
  147418. 0,
  147419. 8,
  147420. };
  147421. static long _vq_lengthlist__44u2__p5_0[] = {
  147422. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147423. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147424. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147425. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147426. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147427. 13,
  147428. };
  147429. static float _vq_quantthresh__44u2__p5_0[] = {
  147430. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147431. };
  147432. static long _vq_quantmap__44u2__p5_0[] = {
  147433. 7, 5, 3, 1, 0, 2, 4, 6,
  147434. 8,
  147435. };
  147436. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147437. _vq_quantthresh__44u2__p5_0,
  147438. _vq_quantmap__44u2__p5_0,
  147439. 9,
  147440. 9
  147441. };
  147442. static static_codebook _44u2__p5_0 = {
  147443. 2, 81,
  147444. _vq_lengthlist__44u2__p5_0,
  147445. 1, -531628032, 1611661312, 4, 0,
  147446. _vq_quantlist__44u2__p5_0,
  147447. NULL,
  147448. &_vq_auxt__44u2__p5_0,
  147449. NULL,
  147450. 0
  147451. };
  147452. static long _vq_quantlist__44u2__p6_0[] = {
  147453. 6,
  147454. 5,
  147455. 7,
  147456. 4,
  147457. 8,
  147458. 3,
  147459. 9,
  147460. 2,
  147461. 10,
  147462. 1,
  147463. 11,
  147464. 0,
  147465. 12,
  147466. };
  147467. static long _vq_lengthlist__44u2__p6_0[] = {
  147468. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147469. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147470. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147471. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147472. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147473. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147474. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147475. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147476. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147477. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147478. 15,17,17,16,18,17,18, 0, 0,
  147479. };
  147480. static float _vq_quantthresh__44u2__p6_0[] = {
  147481. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147482. 12.5, 17.5, 22.5, 27.5,
  147483. };
  147484. static long _vq_quantmap__44u2__p6_0[] = {
  147485. 11, 9, 7, 5, 3, 1, 0, 2,
  147486. 4, 6, 8, 10, 12,
  147487. };
  147488. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147489. _vq_quantthresh__44u2__p6_0,
  147490. _vq_quantmap__44u2__p6_0,
  147491. 13,
  147492. 13
  147493. };
  147494. static static_codebook _44u2__p6_0 = {
  147495. 2, 169,
  147496. _vq_lengthlist__44u2__p6_0,
  147497. 1, -526516224, 1616117760, 4, 0,
  147498. _vq_quantlist__44u2__p6_0,
  147499. NULL,
  147500. &_vq_auxt__44u2__p6_0,
  147501. NULL,
  147502. 0
  147503. };
  147504. static long _vq_quantlist__44u2__p6_1[] = {
  147505. 2,
  147506. 1,
  147507. 3,
  147508. 0,
  147509. 4,
  147510. };
  147511. static long _vq_lengthlist__44u2__p6_1[] = {
  147512. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147513. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147514. };
  147515. static float _vq_quantthresh__44u2__p6_1[] = {
  147516. -1.5, -0.5, 0.5, 1.5,
  147517. };
  147518. static long _vq_quantmap__44u2__p6_1[] = {
  147519. 3, 1, 0, 2, 4,
  147520. };
  147521. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147522. _vq_quantthresh__44u2__p6_1,
  147523. _vq_quantmap__44u2__p6_1,
  147524. 5,
  147525. 5
  147526. };
  147527. static static_codebook _44u2__p6_1 = {
  147528. 2, 25,
  147529. _vq_lengthlist__44u2__p6_1,
  147530. 1, -533725184, 1611661312, 3, 0,
  147531. _vq_quantlist__44u2__p6_1,
  147532. NULL,
  147533. &_vq_auxt__44u2__p6_1,
  147534. NULL,
  147535. 0
  147536. };
  147537. static long _vq_quantlist__44u2__p7_0[] = {
  147538. 4,
  147539. 3,
  147540. 5,
  147541. 2,
  147542. 6,
  147543. 1,
  147544. 7,
  147545. 0,
  147546. 8,
  147547. };
  147548. static long _vq_lengthlist__44u2__p7_0[] = {
  147549. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147550. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147551. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147552. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147553. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147554. 11,
  147555. };
  147556. static float _vq_quantthresh__44u2__p7_0[] = {
  147557. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147558. };
  147559. static long _vq_quantmap__44u2__p7_0[] = {
  147560. 7, 5, 3, 1, 0, 2, 4, 6,
  147561. 8,
  147562. };
  147563. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147564. _vq_quantthresh__44u2__p7_0,
  147565. _vq_quantmap__44u2__p7_0,
  147566. 9,
  147567. 9
  147568. };
  147569. static static_codebook _44u2__p7_0 = {
  147570. 2, 81,
  147571. _vq_lengthlist__44u2__p7_0,
  147572. 1, -516612096, 1626677248, 4, 0,
  147573. _vq_quantlist__44u2__p7_0,
  147574. NULL,
  147575. &_vq_auxt__44u2__p7_0,
  147576. NULL,
  147577. 0
  147578. };
  147579. static long _vq_quantlist__44u2__p7_1[] = {
  147580. 6,
  147581. 5,
  147582. 7,
  147583. 4,
  147584. 8,
  147585. 3,
  147586. 9,
  147587. 2,
  147588. 10,
  147589. 1,
  147590. 11,
  147591. 0,
  147592. 12,
  147593. };
  147594. static long _vq_lengthlist__44u2__p7_1[] = {
  147595. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147596. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147597. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147598. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147599. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147600. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147601. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147602. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147603. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147604. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147605. 14,14,14,17,15,17,17,17,17,
  147606. };
  147607. static float _vq_quantthresh__44u2__p7_1[] = {
  147608. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147609. 32.5, 45.5, 58.5, 71.5,
  147610. };
  147611. static long _vq_quantmap__44u2__p7_1[] = {
  147612. 11, 9, 7, 5, 3, 1, 0, 2,
  147613. 4, 6, 8, 10, 12,
  147614. };
  147615. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147616. _vq_quantthresh__44u2__p7_1,
  147617. _vq_quantmap__44u2__p7_1,
  147618. 13,
  147619. 13
  147620. };
  147621. static static_codebook _44u2__p7_1 = {
  147622. 2, 169,
  147623. _vq_lengthlist__44u2__p7_1,
  147624. 1, -523010048, 1618608128, 4, 0,
  147625. _vq_quantlist__44u2__p7_1,
  147626. NULL,
  147627. &_vq_auxt__44u2__p7_1,
  147628. NULL,
  147629. 0
  147630. };
  147631. static long _vq_quantlist__44u2__p7_2[] = {
  147632. 6,
  147633. 5,
  147634. 7,
  147635. 4,
  147636. 8,
  147637. 3,
  147638. 9,
  147639. 2,
  147640. 10,
  147641. 1,
  147642. 11,
  147643. 0,
  147644. 12,
  147645. };
  147646. static long _vq_lengthlist__44u2__p7_2[] = {
  147647. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147648. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147649. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147650. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147651. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147652. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147653. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147654. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147655. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147656. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147657. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147658. };
  147659. static float _vq_quantthresh__44u2__p7_2[] = {
  147660. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147661. 2.5, 3.5, 4.5, 5.5,
  147662. };
  147663. static long _vq_quantmap__44u2__p7_2[] = {
  147664. 11, 9, 7, 5, 3, 1, 0, 2,
  147665. 4, 6, 8, 10, 12,
  147666. };
  147667. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147668. _vq_quantthresh__44u2__p7_2,
  147669. _vq_quantmap__44u2__p7_2,
  147670. 13,
  147671. 13
  147672. };
  147673. static static_codebook _44u2__p7_2 = {
  147674. 2, 169,
  147675. _vq_lengthlist__44u2__p7_2,
  147676. 1, -531103744, 1611661312, 4, 0,
  147677. _vq_quantlist__44u2__p7_2,
  147678. NULL,
  147679. &_vq_auxt__44u2__p7_2,
  147680. NULL,
  147681. 0
  147682. };
  147683. static long _huff_lengthlist__44u2__short[] = {
  147684. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147685. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147686. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147687. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147688. };
  147689. static static_codebook _huff_book__44u2__short = {
  147690. 2, 64,
  147691. _huff_lengthlist__44u2__short,
  147692. 0, 0, 0, 0, 0,
  147693. NULL,
  147694. NULL,
  147695. NULL,
  147696. NULL,
  147697. 0
  147698. };
  147699. static long _huff_lengthlist__44u3__long[] = {
  147700. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147701. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147702. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147703. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147704. };
  147705. static static_codebook _huff_book__44u3__long = {
  147706. 2, 64,
  147707. _huff_lengthlist__44u3__long,
  147708. 0, 0, 0, 0, 0,
  147709. NULL,
  147710. NULL,
  147711. NULL,
  147712. NULL,
  147713. 0
  147714. };
  147715. static long _vq_quantlist__44u3__p1_0[] = {
  147716. 1,
  147717. 0,
  147718. 2,
  147719. };
  147720. static long _vq_lengthlist__44u3__p1_0[] = {
  147721. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147722. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147723. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147724. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147725. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147726. 13,
  147727. };
  147728. static float _vq_quantthresh__44u3__p1_0[] = {
  147729. -0.5, 0.5,
  147730. };
  147731. static long _vq_quantmap__44u3__p1_0[] = {
  147732. 1, 0, 2,
  147733. };
  147734. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147735. _vq_quantthresh__44u3__p1_0,
  147736. _vq_quantmap__44u3__p1_0,
  147737. 3,
  147738. 3
  147739. };
  147740. static static_codebook _44u3__p1_0 = {
  147741. 4, 81,
  147742. _vq_lengthlist__44u3__p1_0,
  147743. 1, -535822336, 1611661312, 2, 0,
  147744. _vq_quantlist__44u3__p1_0,
  147745. NULL,
  147746. &_vq_auxt__44u3__p1_0,
  147747. NULL,
  147748. 0
  147749. };
  147750. static long _vq_quantlist__44u3__p2_0[] = {
  147751. 1,
  147752. 0,
  147753. 2,
  147754. };
  147755. static long _vq_lengthlist__44u3__p2_0[] = {
  147756. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147757. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147758. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147759. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147760. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147761. 9,
  147762. };
  147763. static float _vq_quantthresh__44u3__p2_0[] = {
  147764. -0.5, 0.5,
  147765. };
  147766. static long _vq_quantmap__44u3__p2_0[] = {
  147767. 1, 0, 2,
  147768. };
  147769. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147770. _vq_quantthresh__44u3__p2_0,
  147771. _vq_quantmap__44u3__p2_0,
  147772. 3,
  147773. 3
  147774. };
  147775. static static_codebook _44u3__p2_0 = {
  147776. 4, 81,
  147777. _vq_lengthlist__44u3__p2_0,
  147778. 1, -535822336, 1611661312, 2, 0,
  147779. _vq_quantlist__44u3__p2_0,
  147780. NULL,
  147781. &_vq_auxt__44u3__p2_0,
  147782. NULL,
  147783. 0
  147784. };
  147785. static long _vq_quantlist__44u3__p3_0[] = {
  147786. 2,
  147787. 1,
  147788. 3,
  147789. 0,
  147790. 4,
  147791. };
  147792. static long _vq_lengthlist__44u3__p3_0[] = {
  147793. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147794. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147795. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147796. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147797. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147798. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147799. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147800. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147801. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147802. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147803. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147804. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147805. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147806. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147807. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147808. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147809. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147810. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147811. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147812. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147813. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147814. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147815. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147816. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147817. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147818. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147819. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147820. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147821. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147822. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147823. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147824. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147825. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147826. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147827. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147828. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147829. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147830. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147831. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147832. 0,
  147833. };
  147834. static float _vq_quantthresh__44u3__p3_0[] = {
  147835. -1.5, -0.5, 0.5, 1.5,
  147836. };
  147837. static long _vq_quantmap__44u3__p3_0[] = {
  147838. 3, 1, 0, 2, 4,
  147839. };
  147840. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147841. _vq_quantthresh__44u3__p3_0,
  147842. _vq_quantmap__44u3__p3_0,
  147843. 5,
  147844. 5
  147845. };
  147846. static static_codebook _44u3__p3_0 = {
  147847. 4, 625,
  147848. _vq_lengthlist__44u3__p3_0,
  147849. 1, -533725184, 1611661312, 3, 0,
  147850. _vq_quantlist__44u3__p3_0,
  147851. NULL,
  147852. &_vq_auxt__44u3__p3_0,
  147853. NULL,
  147854. 0
  147855. };
  147856. static long _vq_quantlist__44u3__p4_0[] = {
  147857. 2,
  147858. 1,
  147859. 3,
  147860. 0,
  147861. 4,
  147862. };
  147863. static long _vq_lengthlist__44u3__p4_0[] = {
  147864. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147865. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147866. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147867. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147868. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147869. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147870. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147871. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147872. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147873. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147874. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147875. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147876. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147877. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147878. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147879. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147880. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147881. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147882. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147883. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147884. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147885. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147886. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147887. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147888. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147889. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147890. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147891. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147892. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147893. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147894. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147895. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147896. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147897. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147898. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147899. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147900. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147901. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147902. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147903. 13,
  147904. };
  147905. static float _vq_quantthresh__44u3__p4_0[] = {
  147906. -1.5, -0.5, 0.5, 1.5,
  147907. };
  147908. static long _vq_quantmap__44u3__p4_0[] = {
  147909. 3, 1, 0, 2, 4,
  147910. };
  147911. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147912. _vq_quantthresh__44u3__p4_0,
  147913. _vq_quantmap__44u3__p4_0,
  147914. 5,
  147915. 5
  147916. };
  147917. static static_codebook _44u3__p4_0 = {
  147918. 4, 625,
  147919. _vq_lengthlist__44u3__p4_0,
  147920. 1, -533725184, 1611661312, 3, 0,
  147921. _vq_quantlist__44u3__p4_0,
  147922. NULL,
  147923. &_vq_auxt__44u3__p4_0,
  147924. NULL,
  147925. 0
  147926. };
  147927. static long _vq_quantlist__44u3__p5_0[] = {
  147928. 4,
  147929. 3,
  147930. 5,
  147931. 2,
  147932. 6,
  147933. 1,
  147934. 7,
  147935. 0,
  147936. 8,
  147937. };
  147938. static long _vq_lengthlist__44u3__p5_0[] = {
  147939. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147940. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147941. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147942. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147943. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147944. 12,
  147945. };
  147946. static float _vq_quantthresh__44u3__p5_0[] = {
  147947. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147948. };
  147949. static long _vq_quantmap__44u3__p5_0[] = {
  147950. 7, 5, 3, 1, 0, 2, 4, 6,
  147951. 8,
  147952. };
  147953. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147954. _vq_quantthresh__44u3__p5_0,
  147955. _vq_quantmap__44u3__p5_0,
  147956. 9,
  147957. 9
  147958. };
  147959. static static_codebook _44u3__p5_0 = {
  147960. 2, 81,
  147961. _vq_lengthlist__44u3__p5_0,
  147962. 1, -531628032, 1611661312, 4, 0,
  147963. _vq_quantlist__44u3__p5_0,
  147964. NULL,
  147965. &_vq_auxt__44u3__p5_0,
  147966. NULL,
  147967. 0
  147968. };
  147969. static long _vq_quantlist__44u3__p6_0[] = {
  147970. 6,
  147971. 5,
  147972. 7,
  147973. 4,
  147974. 8,
  147975. 3,
  147976. 9,
  147977. 2,
  147978. 10,
  147979. 1,
  147980. 11,
  147981. 0,
  147982. 12,
  147983. };
  147984. static long _vq_lengthlist__44u3__p6_0[] = {
  147985. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147986. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147987. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147988. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147989. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147990. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147991. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147992. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147993. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147994. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147995. 15,16,16,16,17,18,16,20,18,
  147996. };
  147997. static float _vq_quantthresh__44u3__p6_0[] = {
  147998. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147999. 12.5, 17.5, 22.5, 27.5,
  148000. };
  148001. static long _vq_quantmap__44u3__p6_0[] = {
  148002. 11, 9, 7, 5, 3, 1, 0, 2,
  148003. 4, 6, 8, 10, 12,
  148004. };
  148005. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148006. _vq_quantthresh__44u3__p6_0,
  148007. _vq_quantmap__44u3__p6_0,
  148008. 13,
  148009. 13
  148010. };
  148011. static static_codebook _44u3__p6_0 = {
  148012. 2, 169,
  148013. _vq_lengthlist__44u3__p6_0,
  148014. 1, -526516224, 1616117760, 4, 0,
  148015. _vq_quantlist__44u3__p6_0,
  148016. NULL,
  148017. &_vq_auxt__44u3__p6_0,
  148018. NULL,
  148019. 0
  148020. };
  148021. static long _vq_quantlist__44u3__p6_1[] = {
  148022. 2,
  148023. 1,
  148024. 3,
  148025. 0,
  148026. 4,
  148027. };
  148028. static long _vq_lengthlist__44u3__p6_1[] = {
  148029. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148030. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148031. };
  148032. static float _vq_quantthresh__44u3__p6_1[] = {
  148033. -1.5, -0.5, 0.5, 1.5,
  148034. };
  148035. static long _vq_quantmap__44u3__p6_1[] = {
  148036. 3, 1, 0, 2, 4,
  148037. };
  148038. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148039. _vq_quantthresh__44u3__p6_1,
  148040. _vq_quantmap__44u3__p6_1,
  148041. 5,
  148042. 5
  148043. };
  148044. static static_codebook _44u3__p6_1 = {
  148045. 2, 25,
  148046. _vq_lengthlist__44u3__p6_1,
  148047. 1, -533725184, 1611661312, 3, 0,
  148048. _vq_quantlist__44u3__p6_1,
  148049. NULL,
  148050. &_vq_auxt__44u3__p6_1,
  148051. NULL,
  148052. 0
  148053. };
  148054. static long _vq_quantlist__44u3__p7_0[] = {
  148055. 4,
  148056. 3,
  148057. 5,
  148058. 2,
  148059. 6,
  148060. 1,
  148061. 7,
  148062. 0,
  148063. 8,
  148064. };
  148065. static long _vq_lengthlist__44u3__p7_0[] = {
  148066. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148067. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148068. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148069. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148070. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148071. 9,
  148072. };
  148073. static float _vq_quantthresh__44u3__p7_0[] = {
  148074. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148075. };
  148076. static long _vq_quantmap__44u3__p7_0[] = {
  148077. 7, 5, 3, 1, 0, 2, 4, 6,
  148078. 8,
  148079. };
  148080. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148081. _vq_quantthresh__44u3__p7_0,
  148082. _vq_quantmap__44u3__p7_0,
  148083. 9,
  148084. 9
  148085. };
  148086. static static_codebook _44u3__p7_0 = {
  148087. 2, 81,
  148088. _vq_lengthlist__44u3__p7_0,
  148089. 1, -515907584, 1627381760, 4, 0,
  148090. _vq_quantlist__44u3__p7_0,
  148091. NULL,
  148092. &_vq_auxt__44u3__p7_0,
  148093. NULL,
  148094. 0
  148095. };
  148096. static long _vq_quantlist__44u3__p7_1[] = {
  148097. 7,
  148098. 6,
  148099. 8,
  148100. 5,
  148101. 9,
  148102. 4,
  148103. 10,
  148104. 3,
  148105. 11,
  148106. 2,
  148107. 12,
  148108. 1,
  148109. 13,
  148110. 0,
  148111. 14,
  148112. };
  148113. static long _vq_lengthlist__44u3__p7_1[] = {
  148114. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148115. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148116. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148117. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148118. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148119. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148120. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148121. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148122. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148123. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148124. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148125. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148126. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148127. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148128. 17,
  148129. };
  148130. static float _vq_quantthresh__44u3__p7_1[] = {
  148131. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148132. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148133. };
  148134. static long _vq_quantmap__44u3__p7_1[] = {
  148135. 13, 11, 9, 7, 5, 3, 1, 0,
  148136. 2, 4, 6, 8, 10, 12, 14,
  148137. };
  148138. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148139. _vq_quantthresh__44u3__p7_1,
  148140. _vq_quantmap__44u3__p7_1,
  148141. 15,
  148142. 15
  148143. };
  148144. static static_codebook _44u3__p7_1 = {
  148145. 2, 225,
  148146. _vq_lengthlist__44u3__p7_1,
  148147. 1, -522338304, 1620115456, 4, 0,
  148148. _vq_quantlist__44u3__p7_1,
  148149. NULL,
  148150. &_vq_auxt__44u3__p7_1,
  148151. NULL,
  148152. 0
  148153. };
  148154. static long _vq_quantlist__44u3__p7_2[] = {
  148155. 8,
  148156. 7,
  148157. 9,
  148158. 6,
  148159. 10,
  148160. 5,
  148161. 11,
  148162. 4,
  148163. 12,
  148164. 3,
  148165. 13,
  148166. 2,
  148167. 14,
  148168. 1,
  148169. 15,
  148170. 0,
  148171. 16,
  148172. };
  148173. static long _vq_lengthlist__44u3__p7_2[] = {
  148174. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148175. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148176. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148177. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148178. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148179. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148180. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148181. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148182. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148183. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148184. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148185. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148186. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148187. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148188. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148189. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148190. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148191. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148192. 11,
  148193. };
  148194. static float _vq_quantthresh__44u3__p7_2[] = {
  148195. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148196. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148197. };
  148198. static long _vq_quantmap__44u3__p7_2[] = {
  148199. 15, 13, 11, 9, 7, 5, 3, 1,
  148200. 0, 2, 4, 6, 8, 10, 12, 14,
  148201. 16,
  148202. };
  148203. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148204. _vq_quantthresh__44u3__p7_2,
  148205. _vq_quantmap__44u3__p7_2,
  148206. 17,
  148207. 17
  148208. };
  148209. static static_codebook _44u3__p7_2 = {
  148210. 2, 289,
  148211. _vq_lengthlist__44u3__p7_2,
  148212. 1, -529530880, 1611661312, 5, 0,
  148213. _vq_quantlist__44u3__p7_2,
  148214. NULL,
  148215. &_vq_auxt__44u3__p7_2,
  148216. NULL,
  148217. 0
  148218. };
  148219. static long _huff_lengthlist__44u3__short[] = {
  148220. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148221. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148222. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148223. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148224. };
  148225. static static_codebook _huff_book__44u3__short = {
  148226. 2, 64,
  148227. _huff_lengthlist__44u3__short,
  148228. 0, 0, 0, 0, 0,
  148229. NULL,
  148230. NULL,
  148231. NULL,
  148232. NULL,
  148233. 0
  148234. };
  148235. static long _huff_lengthlist__44u4__long[] = {
  148236. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148237. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148238. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148239. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148240. };
  148241. static static_codebook _huff_book__44u4__long = {
  148242. 2, 64,
  148243. _huff_lengthlist__44u4__long,
  148244. 0, 0, 0, 0, 0,
  148245. NULL,
  148246. NULL,
  148247. NULL,
  148248. NULL,
  148249. 0
  148250. };
  148251. static long _vq_quantlist__44u4__p1_0[] = {
  148252. 1,
  148253. 0,
  148254. 2,
  148255. };
  148256. static long _vq_lengthlist__44u4__p1_0[] = {
  148257. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148258. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148259. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148260. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148261. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148262. 13,
  148263. };
  148264. static float _vq_quantthresh__44u4__p1_0[] = {
  148265. -0.5, 0.5,
  148266. };
  148267. static long _vq_quantmap__44u4__p1_0[] = {
  148268. 1, 0, 2,
  148269. };
  148270. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148271. _vq_quantthresh__44u4__p1_0,
  148272. _vq_quantmap__44u4__p1_0,
  148273. 3,
  148274. 3
  148275. };
  148276. static static_codebook _44u4__p1_0 = {
  148277. 4, 81,
  148278. _vq_lengthlist__44u4__p1_0,
  148279. 1, -535822336, 1611661312, 2, 0,
  148280. _vq_quantlist__44u4__p1_0,
  148281. NULL,
  148282. &_vq_auxt__44u4__p1_0,
  148283. NULL,
  148284. 0
  148285. };
  148286. static long _vq_quantlist__44u4__p2_0[] = {
  148287. 1,
  148288. 0,
  148289. 2,
  148290. };
  148291. static long _vq_lengthlist__44u4__p2_0[] = {
  148292. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148293. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148294. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148295. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148296. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148297. 9,
  148298. };
  148299. static float _vq_quantthresh__44u4__p2_0[] = {
  148300. -0.5, 0.5,
  148301. };
  148302. static long _vq_quantmap__44u4__p2_0[] = {
  148303. 1, 0, 2,
  148304. };
  148305. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148306. _vq_quantthresh__44u4__p2_0,
  148307. _vq_quantmap__44u4__p2_0,
  148308. 3,
  148309. 3
  148310. };
  148311. static static_codebook _44u4__p2_0 = {
  148312. 4, 81,
  148313. _vq_lengthlist__44u4__p2_0,
  148314. 1, -535822336, 1611661312, 2, 0,
  148315. _vq_quantlist__44u4__p2_0,
  148316. NULL,
  148317. &_vq_auxt__44u4__p2_0,
  148318. NULL,
  148319. 0
  148320. };
  148321. static long _vq_quantlist__44u4__p3_0[] = {
  148322. 2,
  148323. 1,
  148324. 3,
  148325. 0,
  148326. 4,
  148327. };
  148328. static long _vq_lengthlist__44u4__p3_0[] = {
  148329. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148330. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148331. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148332. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148333. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148334. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148335. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148336. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148337. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148338. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148339. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148340. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148341. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148342. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148343. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148344. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148345. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148346. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148347. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148348. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148349. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148350. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148351. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148352. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148353. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148354. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148355. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148356. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148357. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148358. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148359. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148360. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148361. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148362. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148363. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148364. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148365. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148366. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148367. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148368. 0,
  148369. };
  148370. static float _vq_quantthresh__44u4__p3_0[] = {
  148371. -1.5, -0.5, 0.5, 1.5,
  148372. };
  148373. static long _vq_quantmap__44u4__p3_0[] = {
  148374. 3, 1, 0, 2, 4,
  148375. };
  148376. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148377. _vq_quantthresh__44u4__p3_0,
  148378. _vq_quantmap__44u4__p3_0,
  148379. 5,
  148380. 5
  148381. };
  148382. static static_codebook _44u4__p3_0 = {
  148383. 4, 625,
  148384. _vq_lengthlist__44u4__p3_0,
  148385. 1, -533725184, 1611661312, 3, 0,
  148386. _vq_quantlist__44u4__p3_0,
  148387. NULL,
  148388. &_vq_auxt__44u4__p3_0,
  148389. NULL,
  148390. 0
  148391. };
  148392. static long _vq_quantlist__44u4__p4_0[] = {
  148393. 2,
  148394. 1,
  148395. 3,
  148396. 0,
  148397. 4,
  148398. };
  148399. static long _vq_lengthlist__44u4__p4_0[] = {
  148400. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148401. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148402. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148403. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148404. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148405. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148406. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148407. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148408. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148409. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148410. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148411. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148412. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148413. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148414. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148415. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148416. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148417. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148418. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148419. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148420. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148421. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148422. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148423. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148424. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148425. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148426. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148427. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148428. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148429. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148430. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148431. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148432. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148433. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148434. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148435. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148436. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148437. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148438. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148439. 13,
  148440. };
  148441. static float _vq_quantthresh__44u4__p4_0[] = {
  148442. -1.5, -0.5, 0.5, 1.5,
  148443. };
  148444. static long _vq_quantmap__44u4__p4_0[] = {
  148445. 3, 1, 0, 2, 4,
  148446. };
  148447. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148448. _vq_quantthresh__44u4__p4_0,
  148449. _vq_quantmap__44u4__p4_0,
  148450. 5,
  148451. 5
  148452. };
  148453. static static_codebook _44u4__p4_0 = {
  148454. 4, 625,
  148455. _vq_lengthlist__44u4__p4_0,
  148456. 1, -533725184, 1611661312, 3, 0,
  148457. _vq_quantlist__44u4__p4_0,
  148458. NULL,
  148459. &_vq_auxt__44u4__p4_0,
  148460. NULL,
  148461. 0
  148462. };
  148463. static long _vq_quantlist__44u4__p5_0[] = {
  148464. 4,
  148465. 3,
  148466. 5,
  148467. 2,
  148468. 6,
  148469. 1,
  148470. 7,
  148471. 0,
  148472. 8,
  148473. };
  148474. static long _vq_lengthlist__44u4__p5_0[] = {
  148475. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148476. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148477. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148478. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148479. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148480. 12,
  148481. };
  148482. static float _vq_quantthresh__44u4__p5_0[] = {
  148483. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148484. };
  148485. static long _vq_quantmap__44u4__p5_0[] = {
  148486. 7, 5, 3, 1, 0, 2, 4, 6,
  148487. 8,
  148488. };
  148489. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148490. _vq_quantthresh__44u4__p5_0,
  148491. _vq_quantmap__44u4__p5_0,
  148492. 9,
  148493. 9
  148494. };
  148495. static static_codebook _44u4__p5_0 = {
  148496. 2, 81,
  148497. _vq_lengthlist__44u4__p5_0,
  148498. 1, -531628032, 1611661312, 4, 0,
  148499. _vq_quantlist__44u4__p5_0,
  148500. NULL,
  148501. &_vq_auxt__44u4__p5_0,
  148502. NULL,
  148503. 0
  148504. };
  148505. static long _vq_quantlist__44u4__p6_0[] = {
  148506. 6,
  148507. 5,
  148508. 7,
  148509. 4,
  148510. 8,
  148511. 3,
  148512. 9,
  148513. 2,
  148514. 10,
  148515. 1,
  148516. 11,
  148517. 0,
  148518. 12,
  148519. };
  148520. static long _vq_lengthlist__44u4__p6_0[] = {
  148521. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148522. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148523. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148524. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148525. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148526. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148527. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148528. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148529. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148530. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148531. 16,16,16,17,17,18,17,20,21,
  148532. };
  148533. static float _vq_quantthresh__44u4__p6_0[] = {
  148534. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148535. 12.5, 17.5, 22.5, 27.5,
  148536. };
  148537. static long _vq_quantmap__44u4__p6_0[] = {
  148538. 11, 9, 7, 5, 3, 1, 0, 2,
  148539. 4, 6, 8, 10, 12,
  148540. };
  148541. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148542. _vq_quantthresh__44u4__p6_0,
  148543. _vq_quantmap__44u4__p6_0,
  148544. 13,
  148545. 13
  148546. };
  148547. static static_codebook _44u4__p6_0 = {
  148548. 2, 169,
  148549. _vq_lengthlist__44u4__p6_0,
  148550. 1, -526516224, 1616117760, 4, 0,
  148551. _vq_quantlist__44u4__p6_0,
  148552. NULL,
  148553. &_vq_auxt__44u4__p6_0,
  148554. NULL,
  148555. 0
  148556. };
  148557. static long _vq_quantlist__44u4__p6_1[] = {
  148558. 2,
  148559. 1,
  148560. 3,
  148561. 0,
  148562. 4,
  148563. };
  148564. static long _vq_lengthlist__44u4__p6_1[] = {
  148565. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148566. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148567. };
  148568. static float _vq_quantthresh__44u4__p6_1[] = {
  148569. -1.5, -0.5, 0.5, 1.5,
  148570. };
  148571. static long _vq_quantmap__44u4__p6_1[] = {
  148572. 3, 1, 0, 2, 4,
  148573. };
  148574. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148575. _vq_quantthresh__44u4__p6_1,
  148576. _vq_quantmap__44u4__p6_1,
  148577. 5,
  148578. 5
  148579. };
  148580. static static_codebook _44u4__p6_1 = {
  148581. 2, 25,
  148582. _vq_lengthlist__44u4__p6_1,
  148583. 1, -533725184, 1611661312, 3, 0,
  148584. _vq_quantlist__44u4__p6_1,
  148585. NULL,
  148586. &_vq_auxt__44u4__p6_1,
  148587. NULL,
  148588. 0
  148589. };
  148590. static long _vq_quantlist__44u4__p7_0[] = {
  148591. 6,
  148592. 5,
  148593. 7,
  148594. 4,
  148595. 8,
  148596. 3,
  148597. 9,
  148598. 2,
  148599. 10,
  148600. 1,
  148601. 11,
  148602. 0,
  148603. 12,
  148604. };
  148605. static long _vq_lengthlist__44u4__p7_0[] = {
  148606. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148607. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148608. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148609. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148610. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148611. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148612. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148613. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148614. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148615. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148616. 11,11,11,11,11,11,11,11,11,
  148617. };
  148618. static float _vq_quantthresh__44u4__p7_0[] = {
  148619. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148620. 637.5, 892.5, 1147.5, 1402.5,
  148621. };
  148622. static long _vq_quantmap__44u4__p7_0[] = {
  148623. 11, 9, 7, 5, 3, 1, 0, 2,
  148624. 4, 6, 8, 10, 12,
  148625. };
  148626. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148627. _vq_quantthresh__44u4__p7_0,
  148628. _vq_quantmap__44u4__p7_0,
  148629. 13,
  148630. 13
  148631. };
  148632. static static_codebook _44u4__p7_0 = {
  148633. 2, 169,
  148634. _vq_lengthlist__44u4__p7_0,
  148635. 1, -514332672, 1627381760, 4, 0,
  148636. _vq_quantlist__44u4__p7_0,
  148637. NULL,
  148638. &_vq_auxt__44u4__p7_0,
  148639. NULL,
  148640. 0
  148641. };
  148642. static long _vq_quantlist__44u4__p7_1[] = {
  148643. 7,
  148644. 6,
  148645. 8,
  148646. 5,
  148647. 9,
  148648. 4,
  148649. 10,
  148650. 3,
  148651. 11,
  148652. 2,
  148653. 12,
  148654. 1,
  148655. 13,
  148656. 0,
  148657. 14,
  148658. };
  148659. static long _vq_lengthlist__44u4__p7_1[] = {
  148660. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148661. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148662. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148663. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148664. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148665. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148666. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148667. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148668. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148669. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148670. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148671. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148672. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148673. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148674. 16,
  148675. };
  148676. static float _vq_quantthresh__44u4__p7_1[] = {
  148677. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148678. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148679. };
  148680. static long _vq_quantmap__44u4__p7_1[] = {
  148681. 13, 11, 9, 7, 5, 3, 1, 0,
  148682. 2, 4, 6, 8, 10, 12, 14,
  148683. };
  148684. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148685. _vq_quantthresh__44u4__p7_1,
  148686. _vq_quantmap__44u4__p7_1,
  148687. 15,
  148688. 15
  148689. };
  148690. static static_codebook _44u4__p7_1 = {
  148691. 2, 225,
  148692. _vq_lengthlist__44u4__p7_1,
  148693. 1, -522338304, 1620115456, 4, 0,
  148694. _vq_quantlist__44u4__p7_1,
  148695. NULL,
  148696. &_vq_auxt__44u4__p7_1,
  148697. NULL,
  148698. 0
  148699. };
  148700. static long _vq_quantlist__44u4__p7_2[] = {
  148701. 8,
  148702. 7,
  148703. 9,
  148704. 6,
  148705. 10,
  148706. 5,
  148707. 11,
  148708. 4,
  148709. 12,
  148710. 3,
  148711. 13,
  148712. 2,
  148713. 14,
  148714. 1,
  148715. 15,
  148716. 0,
  148717. 16,
  148718. };
  148719. static long _vq_lengthlist__44u4__p7_2[] = {
  148720. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148721. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148722. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148723. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148724. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148725. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148726. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148727. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148728. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148729. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148730. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148731. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148732. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148733. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148735. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148736. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148737. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148738. 10,
  148739. };
  148740. static float _vq_quantthresh__44u4__p7_2[] = {
  148741. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148742. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148743. };
  148744. static long _vq_quantmap__44u4__p7_2[] = {
  148745. 15, 13, 11, 9, 7, 5, 3, 1,
  148746. 0, 2, 4, 6, 8, 10, 12, 14,
  148747. 16,
  148748. };
  148749. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148750. _vq_quantthresh__44u4__p7_2,
  148751. _vq_quantmap__44u4__p7_2,
  148752. 17,
  148753. 17
  148754. };
  148755. static static_codebook _44u4__p7_2 = {
  148756. 2, 289,
  148757. _vq_lengthlist__44u4__p7_2,
  148758. 1, -529530880, 1611661312, 5, 0,
  148759. _vq_quantlist__44u4__p7_2,
  148760. NULL,
  148761. &_vq_auxt__44u4__p7_2,
  148762. NULL,
  148763. 0
  148764. };
  148765. static long _huff_lengthlist__44u4__short[] = {
  148766. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148767. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148768. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148769. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148770. };
  148771. static static_codebook _huff_book__44u4__short = {
  148772. 2, 64,
  148773. _huff_lengthlist__44u4__short,
  148774. 0, 0, 0, 0, 0,
  148775. NULL,
  148776. NULL,
  148777. NULL,
  148778. NULL,
  148779. 0
  148780. };
  148781. static long _huff_lengthlist__44u5__long[] = {
  148782. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148783. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148784. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148785. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148786. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148787. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148788. 14, 8, 7, 8,
  148789. };
  148790. static static_codebook _huff_book__44u5__long = {
  148791. 2, 100,
  148792. _huff_lengthlist__44u5__long,
  148793. 0, 0, 0, 0, 0,
  148794. NULL,
  148795. NULL,
  148796. NULL,
  148797. NULL,
  148798. 0
  148799. };
  148800. static long _vq_quantlist__44u5__p1_0[] = {
  148801. 1,
  148802. 0,
  148803. 2,
  148804. };
  148805. static long _vq_lengthlist__44u5__p1_0[] = {
  148806. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148807. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148808. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148809. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148810. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148811. 12,
  148812. };
  148813. static float _vq_quantthresh__44u5__p1_0[] = {
  148814. -0.5, 0.5,
  148815. };
  148816. static long _vq_quantmap__44u5__p1_0[] = {
  148817. 1, 0, 2,
  148818. };
  148819. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148820. _vq_quantthresh__44u5__p1_0,
  148821. _vq_quantmap__44u5__p1_0,
  148822. 3,
  148823. 3
  148824. };
  148825. static static_codebook _44u5__p1_0 = {
  148826. 4, 81,
  148827. _vq_lengthlist__44u5__p1_0,
  148828. 1, -535822336, 1611661312, 2, 0,
  148829. _vq_quantlist__44u5__p1_0,
  148830. NULL,
  148831. &_vq_auxt__44u5__p1_0,
  148832. NULL,
  148833. 0
  148834. };
  148835. static long _vq_quantlist__44u5__p2_0[] = {
  148836. 1,
  148837. 0,
  148838. 2,
  148839. };
  148840. static long _vq_lengthlist__44u5__p2_0[] = {
  148841. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148842. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148843. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148844. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148845. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148846. 9,
  148847. };
  148848. static float _vq_quantthresh__44u5__p2_0[] = {
  148849. -0.5, 0.5,
  148850. };
  148851. static long _vq_quantmap__44u5__p2_0[] = {
  148852. 1, 0, 2,
  148853. };
  148854. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148855. _vq_quantthresh__44u5__p2_0,
  148856. _vq_quantmap__44u5__p2_0,
  148857. 3,
  148858. 3
  148859. };
  148860. static static_codebook _44u5__p2_0 = {
  148861. 4, 81,
  148862. _vq_lengthlist__44u5__p2_0,
  148863. 1, -535822336, 1611661312, 2, 0,
  148864. _vq_quantlist__44u5__p2_0,
  148865. NULL,
  148866. &_vq_auxt__44u5__p2_0,
  148867. NULL,
  148868. 0
  148869. };
  148870. static long _vq_quantlist__44u5__p3_0[] = {
  148871. 2,
  148872. 1,
  148873. 3,
  148874. 0,
  148875. 4,
  148876. };
  148877. static long _vq_lengthlist__44u5__p3_0[] = {
  148878. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148879. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148880. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148881. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148882. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148883. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148884. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148885. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148886. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148887. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148888. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148889. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148890. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148891. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148892. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148893. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148894. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148895. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148896. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148897. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148898. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148899. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148900. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148901. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148902. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148903. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148904. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148905. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148906. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148907. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148908. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148909. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148910. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148911. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148912. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148913. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148914. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148915. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148916. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148917. 0,
  148918. };
  148919. static float _vq_quantthresh__44u5__p3_0[] = {
  148920. -1.5, -0.5, 0.5, 1.5,
  148921. };
  148922. static long _vq_quantmap__44u5__p3_0[] = {
  148923. 3, 1, 0, 2, 4,
  148924. };
  148925. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148926. _vq_quantthresh__44u5__p3_0,
  148927. _vq_quantmap__44u5__p3_0,
  148928. 5,
  148929. 5
  148930. };
  148931. static static_codebook _44u5__p3_0 = {
  148932. 4, 625,
  148933. _vq_lengthlist__44u5__p3_0,
  148934. 1, -533725184, 1611661312, 3, 0,
  148935. _vq_quantlist__44u5__p3_0,
  148936. NULL,
  148937. &_vq_auxt__44u5__p3_0,
  148938. NULL,
  148939. 0
  148940. };
  148941. static long _vq_quantlist__44u5__p4_0[] = {
  148942. 2,
  148943. 1,
  148944. 3,
  148945. 0,
  148946. 4,
  148947. };
  148948. static long _vq_lengthlist__44u5__p4_0[] = {
  148949. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148950. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148951. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148952. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148953. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148954. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148955. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148956. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148957. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148958. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148959. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148960. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148961. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148962. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148963. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148964. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148965. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148966. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148967. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148968. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148969. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148970. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148971. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148972. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148973. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148974. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148975. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148976. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148977. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148978. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148979. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148980. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148981. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148982. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148983. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148984. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148985. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148986. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148987. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148988. 12,
  148989. };
  148990. static float _vq_quantthresh__44u5__p4_0[] = {
  148991. -1.5, -0.5, 0.5, 1.5,
  148992. };
  148993. static long _vq_quantmap__44u5__p4_0[] = {
  148994. 3, 1, 0, 2, 4,
  148995. };
  148996. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148997. _vq_quantthresh__44u5__p4_0,
  148998. _vq_quantmap__44u5__p4_0,
  148999. 5,
  149000. 5
  149001. };
  149002. static static_codebook _44u5__p4_0 = {
  149003. 4, 625,
  149004. _vq_lengthlist__44u5__p4_0,
  149005. 1, -533725184, 1611661312, 3, 0,
  149006. _vq_quantlist__44u5__p4_0,
  149007. NULL,
  149008. &_vq_auxt__44u5__p4_0,
  149009. NULL,
  149010. 0
  149011. };
  149012. static long _vq_quantlist__44u5__p5_0[] = {
  149013. 4,
  149014. 3,
  149015. 5,
  149016. 2,
  149017. 6,
  149018. 1,
  149019. 7,
  149020. 0,
  149021. 8,
  149022. };
  149023. static long _vq_lengthlist__44u5__p5_0[] = {
  149024. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149025. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149026. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149027. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149028. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149029. 14,
  149030. };
  149031. static float _vq_quantthresh__44u5__p5_0[] = {
  149032. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149033. };
  149034. static long _vq_quantmap__44u5__p5_0[] = {
  149035. 7, 5, 3, 1, 0, 2, 4, 6,
  149036. 8,
  149037. };
  149038. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149039. _vq_quantthresh__44u5__p5_0,
  149040. _vq_quantmap__44u5__p5_0,
  149041. 9,
  149042. 9
  149043. };
  149044. static static_codebook _44u5__p5_0 = {
  149045. 2, 81,
  149046. _vq_lengthlist__44u5__p5_0,
  149047. 1, -531628032, 1611661312, 4, 0,
  149048. _vq_quantlist__44u5__p5_0,
  149049. NULL,
  149050. &_vq_auxt__44u5__p5_0,
  149051. NULL,
  149052. 0
  149053. };
  149054. static long _vq_quantlist__44u5__p6_0[] = {
  149055. 4,
  149056. 3,
  149057. 5,
  149058. 2,
  149059. 6,
  149060. 1,
  149061. 7,
  149062. 0,
  149063. 8,
  149064. };
  149065. static long _vq_lengthlist__44u5__p6_0[] = {
  149066. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149067. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149068. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149069. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149070. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149071. 11,
  149072. };
  149073. static float _vq_quantthresh__44u5__p6_0[] = {
  149074. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149075. };
  149076. static long _vq_quantmap__44u5__p6_0[] = {
  149077. 7, 5, 3, 1, 0, 2, 4, 6,
  149078. 8,
  149079. };
  149080. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149081. _vq_quantthresh__44u5__p6_0,
  149082. _vq_quantmap__44u5__p6_0,
  149083. 9,
  149084. 9
  149085. };
  149086. static static_codebook _44u5__p6_0 = {
  149087. 2, 81,
  149088. _vq_lengthlist__44u5__p6_0,
  149089. 1, -531628032, 1611661312, 4, 0,
  149090. _vq_quantlist__44u5__p6_0,
  149091. NULL,
  149092. &_vq_auxt__44u5__p6_0,
  149093. NULL,
  149094. 0
  149095. };
  149096. static long _vq_quantlist__44u5__p7_0[] = {
  149097. 1,
  149098. 0,
  149099. 2,
  149100. };
  149101. static long _vq_lengthlist__44u5__p7_0[] = {
  149102. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149103. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149104. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149105. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149106. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149107. 12,
  149108. };
  149109. static float _vq_quantthresh__44u5__p7_0[] = {
  149110. -5.5, 5.5,
  149111. };
  149112. static long _vq_quantmap__44u5__p7_0[] = {
  149113. 1, 0, 2,
  149114. };
  149115. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149116. _vq_quantthresh__44u5__p7_0,
  149117. _vq_quantmap__44u5__p7_0,
  149118. 3,
  149119. 3
  149120. };
  149121. static static_codebook _44u5__p7_0 = {
  149122. 4, 81,
  149123. _vq_lengthlist__44u5__p7_0,
  149124. 1, -529137664, 1618345984, 2, 0,
  149125. _vq_quantlist__44u5__p7_0,
  149126. NULL,
  149127. &_vq_auxt__44u5__p7_0,
  149128. NULL,
  149129. 0
  149130. };
  149131. static long _vq_quantlist__44u5__p7_1[] = {
  149132. 5,
  149133. 4,
  149134. 6,
  149135. 3,
  149136. 7,
  149137. 2,
  149138. 8,
  149139. 1,
  149140. 9,
  149141. 0,
  149142. 10,
  149143. };
  149144. static long _vq_lengthlist__44u5__p7_1[] = {
  149145. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149146. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149147. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149148. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149149. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149150. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149151. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149152. 9, 9, 9, 9, 9,10,10,10,10,
  149153. };
  149154. static float _vq_quantthresh__44u5__p7_1[] = {
  149155. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149156. 3.5, 4.5,
  149157. };
  149158. static long _vq_quantmap__44u5__p7_1[] = {
  149159. 9, 7, 5, 3, 1, 0, 2, 4,
  149160. 6, 8, 10,
  149161. };
  149162. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149163. _vq_quantthresh__44u5__p7_1,
  149164. _vq_quantmap__44u5__p7_1,
  149165. 11,
  149166. 11
  149167. };
  149168. static static_codebook _44u5__p7_1 = {
  149169. 2, 121,
  149170. _vq_lengthlist__44u5__p7_1,
  149171. 1, -531365888, 1611661312, 4, 0,
  149172. _vq_quantlist__44u5__p7_1,
  149173. NULL,
  149174. &_vq_auxt__44u5__p7_1,
  149175. NULL,
  149176. 0
  149177. };
  149178. static long _vq_quantlist__44u5__p8_0[] = {
  149179. 5,
  149180. 4,
  149181. 6,
  149182. 3,
  149183. 7,
  149184. 2,
  149185. 8,
  149186. 1,
  149187. 9,
  149188. 0,
  149189. 10,
  149190. };
  149191. static long _vq_lengthlist__44u5__p8_0[] = {
  149192. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149193. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149194. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149195. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149196. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149197. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149198. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149199. 12,13,13,14,14,14,14,15,15,
  149200. };
  149201. static float _vq_quantthresh__44u5__p8_0[] = {
  149202. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149203. 38.5, 49.5,
  149204. };
  149205. static long _vq_quantmap__44u5__p8_0[] = {
  149206. 9, 7, 5, 3, 1, 0, 2, 4,
  149207. 6, 8, 10,
  149208. };
  149209. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149210. _vq_quantthresh__44u5__p8_0,
  149211. _vq_quantmap__44u5__p8_0,
  149212. 11,
  149213. 11
  149214. };
  149215. static static_codebook _44u5__p8_0 = {
  149216. 2, 121,
  149217. _vq_lengthlist__44u5__p8_0,
  149218. 1, -524582912, 1618345984, 4, 0,
  149219. _vq_quantlist__44u5__p8_0,
  149220. NULL,
  149221. &_vq_auxt__44u5__p8_0,
  149222. NULL,
  149223. 0
  149224. };
  149225. static long _vq_quantlist__44u5__p8_1[] = {
  149226. 5,
  149227. 4,
  149228. 6,
  149229. 3,
  149230. 7,
  149231. 2,
  149232. 8,
  149233. 1,
  149234. 9,
  149235. 0,
  149236. 10,
  149237. };
  149238. static long _vq_lengthlist__44u5__p8_1[] = {
  149239. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149240. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149241. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149242. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149243. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149244. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149245. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149246. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149247. };
  149248. static float _vq_quantthresh__44u5__p8_1[] = {
  149249. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149250. 3.5, 4.5,
  149251. };
  149252. static long _vq_quantmap__44u5__p8_1[] = {
  149253. 9, 7, 5, 3, 1, 0, 2, 4,
  149254. 6, 8, 10,
  149255. };
  149256. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149257. _vq_quantthresh__44u5__p8_1,
  149258. _vq_quantmap__44u5__p8_1,
  149259. 11,
  149260. 11
  149261. };
  149262. static static_codebook _44u5__p8_1 = {
  149263. 2, 121,
  149264. _vq_lengthlist__44u5__p8_1,
  149265. 1, -531365888, 1611661312, 4, 0,
  149266. _vq_quantlist__44u5__p8_1,
  149267. NULL,
  149268. &_vq_auxt__44u5__p8_1,
  149269. NULL,
  149270. 0
  149271. };
  149272. static long _vq_quantlist__44u5__p9_0[] = {
  149273. 6,
  149274. 5,
  149275. 7,
  149276. 4,
  149277. 8,
  149278. 3,
  149279. 9,
  149280. 2,
  149281. 10,
  149282. 1,
  149283. 11,
  149284. 0,
  149285. 12,
  149286. };
  149287. static long _vq_lengthlist__44u5__p9_0[] = {
  149288. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149289. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149290. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149291. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149292. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149293. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149294. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149295. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149296. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149297. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149298. 12,12,12,12,12,12,12,12,12,
  149299. };
  149300. static float _vq_quantthresh__44u5__p9_0[] = {
  149301. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149302. 637.5, 892.5, 1147.5, 1402.5,
  149303. };
  149304. static long _vq_quantmap__44u5__p9_0[] = {
  149305. 11, 9, 7, 5, 3, 1, 0, 2,
  149306. 4, 6, 8, 10, 12,
  149307. };
  149308. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149309. _vq_quantthresh__44u5__p9_0,
  149310. _vq_quantmap__44u5__p9_0,
  149311. 13,
  149312. 13
  149313. };
  149314. static static_codebook _44u5__p9_0 = {
  149315. 2, 169,
  149316. _vq_lengthlist__44u5__p9_0,
  149317. 1, -514332672, 1627381760, 4, 0,
  149318. _vq_quantlist__44u5__p9_0,
  149319. NULL,
  149320. &_vq_auxt__44u5__p9_0,
  149321. NULL,
  149322. 0
  149323. };
  149324. static long _vq_quantlist__44u5__p9_1[] = {
  149325. 7,
  149326. 6,
  149327. 8,
  149328. 5,
  149329. 9,
  149330. 4,
  149331. 10,
  149332. 3,
  149333. 11,
  149334. 2,
  149335. 12,
  149336. 1,
  149337. 13,
  149338. 0,
  149339. 14,
  149340. };
  149341. static long _vq_lengthlist__44u5__p9_1[] = {
  149342. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149343. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149344. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149345. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149346. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149347. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149348. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149349. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149350. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149351. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149352. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149353. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149354. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149355. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149356. 14,
  149357. };
  149358. static float _vq_quantthresh__44u5__p9_1[] = {
  149359. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149360. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149361. };
  149362. static long _vq_quantmap__44u5__p9_1[] = {
  149363. 13, 11, 9, 7, 5, 3, 1, 0,
  149364. 2, 4, 6, 8, 10, 12, 14,
  149365. };
  149366. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149367. _vq_quantthresh__44u5__p9_1,
  149368. _vq_quantmap__44u5__p9_1,
  149369. 15,
  149370. 15
  149371. };
  149372. static static_codebook _44u5__p9_1 = {
  149373. 2, 225,
  149374. _vq_lengthlist__44u5__p9_1,
  149375. 1, -522338304, 1620115456, 4, 0,
  149376. _vq_quantlist__44u5__p9_1,
  149377. NULL,
  149378. &_vq_auxt__44u5__p9_1,
  149379. NULL,
  149380. 0
  149381. };
  149382. static long _vq_quantlist__44u5__p9_2[] = {
  149383. 8,
  149384. 7,
  149385. 9,
  149386. 6,
  149387. 10,
  149388. 5,
  149389. 11,
  149390. 4,
  149391. 12,
  149392. 3,
  149393. 13,
  149394. 2,
  149395. 14,
  149396. 1,
  149397. 15,
  149398. 0,
  149399. 16,
  149400. };
  149401. static long _vq_lengthlist__44u5__p9_2[] = {
  149402. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149403. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149404. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149405. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149406. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149407. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149408. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149409. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149410. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149411. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149412. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149413. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149414. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149415. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149416. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149417. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149418. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149419. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149420. 10,
  149421. };
  149422. static float _vq_quantthresh__44u5__p9_2[] = {
  149423. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149424. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149425. };
  149426. static long _vq_quantmap__44u5__p9_2[] = {
  149427. 15, 13, 11, 9, 7, 5, 3, 1,
  149428. 0, 2, 4, 6, 8, 10, 12, 14,
  149429. 16,
  149430. };
  149431. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149432. _vq_quantthresh__44u5__p9_2,
  149433. _vq_quantmap__44u5__p9_2,
  149434. 17,
  149435. 17
  149436. };
  149437. static static_codebook _44u5__p9_2 = {
  149438. 2, 289,
  149439. _vq_lengthlist__44u5__p9_2,
  149440. 1, -529530880, 1611661312, 5, 0,
  149441. _vq_quantlist__44u5__p9_2,
  149442. NULL,
  149443. &_vq_auxt__44u5__p9_2,
  149444. NULL,
  149445. 0
  149446. };
  149447. static long _huff_lengthlist__44u5__short[] = {
  149448. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149449. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149450. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149451. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149452. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149453. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149454. 6, 8,15,17,
  149455. };
  149456. static static_codebook _huff_book__44u5__short = {
  149457. 2, 100,
  149458. _huff_lengthlist__44u5__short,
  149459. 0, 0, 0, 0, 0,
  149460. NULL,
  149461. NULL,
  149462. NULL,
  149463. NULL,
  149464. 0
  149465. };
  149466. static long _huff_lengthlist__44u6__long[] = {
  149467. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149468. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149469. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149470. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149471. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149472. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149473. 13, 8, 7, 7,
  149474. };
  149475. static static_codebook _huff_book__44u6__long = {
  149476. 2, 100,
  149477. _huff_lengthlist__44u6__long,
  149478. 0, 0, 0, 0, 0,
  149479. NULL,
  149480. NULL,
  149481. NULL,
  149482. NULL,
  149483. 0
  149484. };
  149485. static long _vq_quantlist__44u6__p1_0[] = {
  149486. 1,
  149487. 0,
  149488. 2,
  149489. };
  149490. static long _vq_lengthlist__44u6__p1_0[] = {
  149491. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149492. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149493. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149494. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149495. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149496. 12,
  149497. };
  149498. static float _vq_quantthresh__44u6__p1_0[] = {
  149499. -0.5, 0.5,
  149500. };
  149501. static long _vq_quantmap__44u6__p1_0[] = {
  149502. 1, 0, 2,
  149503. };
  149504. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149505. _vq_quantthresh__44u6__p1_0,
  149506. _vq_quantmap__44u6__p1_0,
  149507. 3,
  149508. 3
  149509. };
  149510. static static_codebook _44u6__p1_0 = {
  149511. 4, 81,
  149512. _vq_lengthlist__44u6__p1_0,
  149513. 1, -535822336, 1611661312, 2, 0,
  149514. _vq_quantlist__44u6__p1_0,
  149515. NULL,
  149516. &_vq_auxt__44u6__p1_0,
  149517. NULL,
  149518. 0
  149519. };
  149520. static long _vq_quantlist__44u6__p2_0[] = {
  149521. 1,
  149522. 0,
  149523. 2,
  149524. };
  149525. static long _vq_lengthlist__44u6__p2_0[] = {
  149526. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149527. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149528. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149529. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149530. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149531. 9,
  149532. };
  149533. static float _vq_quantthresh__44u6__p2_0[] = {
  149534. -0.5, 0.5,
  149535. };
  149536. static long _vq_quantmap__44u6__p2_0[] = {
  149537. 1, 0, 2,
  149538. };
  149539. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149540. _vq_quantthresh__44u6__p2_0,
  149541. _vq_quantmap__44u6__p2_0,
  149542. 3,
  149543. 3
  149544. };
  149545. static static_codebook _44u6__p2_0 = {
  149546. 4, 81,
  149547. _vq_lengthlist__44u6__p2_0,
  149548. 1, -535822336, 1611661312, 2, 0,
  149549. _vq_quantlist__44u6__p2_0,
  149550. NULL,
  149551. &_vq_auxt__44u6__p2_0,
  149552. NULL,
  149553. 0
  149554. };
  149555. static long _vq_quantlist__44u6__p3_0[] = {
  149556. 2,
  149557. 1,
  149558. 3,
  149559. 0,
  149560. 4,
  149561. };
  149562. static long _vq_lengthlist__44u6__p3_0[] = {
  149563. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149564. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149565. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149566. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149567. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149568. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149569. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149570. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149571. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149572. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149573. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149574. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149575. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149576. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149577. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149578. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149579. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149580. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149581. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149582. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149583. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149584. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149585. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149586. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149587. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149588. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149589. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149590. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149591. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149592. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149593. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149594. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149595. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149596. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149597. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149598. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149599. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149600. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149601. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149602. 19,
  149603. };
  149604. static float _vq_quantthresh__44u6__p3_0[] = {
  149605. -1.5, -0.5, 0.5, 1.5,
  149606. };
  149607. static long _vq_quantmap__44u6__p3_0[] = {
  149608. 3, 1, 0, 2, 4,
  149609. };
  149610. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149611. _vq_quantthresh__44u6__p3_0,
  149612. _vq_quantmap__44u6__p3_0,
  149613. 5,
  149614. 5
  149615. };
  149616. static static_codebook _44u6__p3_0 = {
  149617. 4, 625,
  149618. _vq_lengthlist__44u6__p3_0,
  149619. 1, -533725184, 1611661312, 3, 0,
  149620. _vq_quantlist__44u6__p3_0,
  149621. NULL,
  149622. &_vq_auxt__44u6__p3_0,
  149623. NULL,
  149624. 0
  149625. };
  149626. static long _vq_quantlist__44u6__p4_0[] = {
  149627. 2,
  149628. 1,
  149629. 3,
  149630. 0,
  149631. 4,
  149632. };
  149633. static long _vq_lengthlist__44u6__p4_0[] = {
  149634. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149635. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149636. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149637. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149638. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149639. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149640. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149641. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149642. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149643. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149644. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149645. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149646. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149647. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149648. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149649. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149650. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149651. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149652. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149653. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149654. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149655. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149656. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149657. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149658. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149659. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149660. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149661. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149662. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149663. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149664. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149665. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149666. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149667. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149668. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149669. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149670. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149671. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149672. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149673. 13,
  149674. };
  149675. static float _vq_quantthresh__44u6__p4_0[] = {
  149676. -1.5, -0.5, 0.5, 1.5,
  149677. };
  149678. static long _vq_quantmap__44u6__p4_0[] = {
  149679. 3, 1, 0, 2, 4,
  149680. };
  149681. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149682. _vq_quantthresh__44u6__p4_0,
  149683. _vq_quantmap__44u6__p4_0,
  149684. 5,
  149685. 5
  149686. };
  149687. static static_codebook _44u6__p4_0 = {
  149688. 4, 625,
  149689. _vq_lengthlist__44u6__p4_0,
  149690. 1, -533725184, 1611661312, 3, 0,
  149691. _vq_quantlist__44u6__p4_0,
  149692. NULL,
  149693. &_vq_auxt__44u6__p4_0,
  149694. NULL,
  149695. 0
  149696. };
  149697. static long _vq_quantlist__44u6__p5_0[] = {
  149698. 4,
  149699. 3,
  149700. 5,
  149701. 2,
  149702. 6,
  149703. 1,
  149704. 7,
  149705. 0,
  149706. 8,
  149707. };
  149708. static long _vq_lengthlist__44u6__p5_0[] = {
  149709. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149710. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149711. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149712. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149713. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149714. 14,
  149715. };
  149716. static float _vq_quantthresh__44u6__p5_0[] = {
  149717. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149718. };
  149719. static long _vq_quantmap__44u6__p5_0[] = {
  149720. 7, 5, 3, 1, 0, 2, 4, 6,
  149721. 8,
  149722. };
  149723. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149724. _vq_quantthresh__44u6__p5_0,
  149725. _vq_quantmap__44u6__p5_0,
  149726. 9,
  149727. 9
  149728. };
  149729. static static_codebook _44u6__p5_0 = {
  149730. 2, 81,
  149731. _vq_lengthlist__44u6__p5_0,
  149732. 1, -531628032, 1611661312, 4, 0,
  149733. _vq_quantlist__44u6__p5_0,
  149734. NULL,
  149735. &_vq_auxt__44u6__p5_0,
  149736. NULL,
  149737. 0
  149738. };
  149739. static long _vq_quantlist__44u6__p6_0[] = {
  149740. 4,
  149741. 3,
  149742. 5,
  149743. 2,
  149744. 6,
  149745. 1,
  149746. 7,
  149747. 0,
  149748. 8,
  149749. };
  149750. static long _vq_lengthlist__44u6__p6_0[] = {
  149751. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149752. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149753. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149754. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149755. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149756. 12,
  149757. };
  149758. static float _vq_quantthresh__44u6__p6_0[] = {
  149759. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149760. };
  149761. static long _vq_quantmap__44u6__p6_0[] = {
  149762. 7, 5, 3, 1, 0, 2, 4, 6,
  149763. 8,
  149764. };
  149765. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149766. _vq_quantthresh__44u6__p6_0,
  149767. _vq_quantmap__44u6__p6_0,
  149768. 9,
  149769. 9
  149770. };
  149771. static static_codebook _44u6__p6_0 = {
  149772. 2, 81,
  149773. _vq_lengthlist__44u6__p6_0,
  149774. 1, -531628032, 1611661312, 4, 0,
  149775. _vq_quantlist__44u6__p6_0,
  149776. NULL,
  149777. &_vq_auxt__44u6__p6_0,
  149778. NULL,
  149779. 0
  149780. };
  149781. static long _vq_quantlist__44u6__p7_0[] = {
  149782. 1,
  149783. 0,
  149784. 2,
  149785. };
  149786. static long _vq_lengthlist__44u6__p7_0[] = {
  149787. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149788. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149789. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149790. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149791. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149792. 10,
  149793. };
  149794. static float _vq_quantthresh__44u6__p7_0[] = {
  149795. -5.5, 5.5,
  149796. };
  149797. static long _vq_quantmap__44u6__p7_0[] = {
  149798. 1, 0, 2,
  149799. };
  149800. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149801. _vq_quantthresh__44u6__p7_0,
  149802. _vq_quantmap__44u6__p7_0,
  149803. 3,
  149804. 3
  149805. };
  149806. static static_codebook _44u6__p7_0 = {
  149807. 4, 81,
  149808. _vq_lengthlist__44u6__p7_0,
  149809. 1, -529137664, 1618345984, 2, 0,
  149810. _vq_quantlist__44u6__p7_0,
  149811. NULL,
  149812. &_vq_auxt__44u6__p7_0,
  149813. NULL,
  149814. 0
  149815. };
  149816. static long _vq_quantlist__44u6__p7_1[] = {
  149817. 5,
  149818. 4,
  149819. 6,
  149820. 3,
  149821. 7,
  149822. 2,
  149823. 8,
  149824. 1,
  149825. 9,
  149826. 0,
  149827. 10,
  149828. };
  149829. static long _vq_lengthlist__44u6__p7_1[] = {
  149830. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149831. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149832. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149833. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149834. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149835. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149836. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149837. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149838. };
  149839. static float _vq_quantthresh__44u6__p7_1[] = {
  149840. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149841. 3.5, 4.5,
  149842. };
  149843. static long _vq_quantmap__44u6__p7_1[] = {
  149844. 9, 7, 5, 3, 1, 0, 2, 4,
  149845. 6, 8, 10,
  149846. };
  149847. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149848. _vq_quantthresh__44u6__p7_1,
  149849. _vq_quantmap__44u6__p7_1,
  149850. 11,
  149851. 11
  149852. };
  149853. static static_codebook _44u6__p7_1 = {
  149854. 2, 121,
  149855. _vq_lengthlist__44u6__p7_1,
  149856. 1, -531365888, 1611661312, 4, 0,
  149857. _vq_quantlist__44u6__p7_1,
  149858. NULL,
  149859. &_vq_auxt__44u6__p7_1,
  149860. NULL,
  149861. 0
  149862. };
  149863. static long _vq_quantlist__44u6__p8_0[] = {
  149864. 5,
  149865. 4,
  149866. 6,
  149867. 3,
  149868. 7,
  149869. 2,
  149870. 8,
  149871. 1,
  149872. 9,
  149873. 0,
  149874. 10,
  149875. };
  149876. static long _vq_lengthlist__44u6__p8_0[] = {
  149877. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149878. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149879. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149880. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149881. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149882. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149883. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149884. 12,13,13,14,14,14,15,15,15,
  149885. };
  149886. static float _vq_quantthresh__44u6__p8_0[] = {
  149887. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149888. 38.5, 49.5,
  149889. };
  149890. static long _vq_quantmap__44u6__p8_0[] = {
  149891. 9, 7, 5, 3, 1, 0, 2, 4,
  149892. 6, 8, 10,
  149893. };
  149894. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149895. _vq_quantthresh__44u6__p8_0,
  149896. _vq_quantmap__44u6__p8_0,
  149897. 11,
  149898. 11
  149899. };
  149900. static static_codebook _44u6__p8_0 = {
  149901. 2, 121,
  149902. _vq_lengthlist__44u6__p8_0,
  149903. 1, -524582912, 1618345984, 4, 0,
  149904. _vq_quantlist__44u6__p8_0,
  149905. NULL,
  149906. &_vq_auxt__44u6__p8_0,
  149907. NULL,
  149908. 0
  149909. };
  149910. static long _vq_quantlist__44u6__p8_1[] = {
  149911. 5,
  149912. 4,
  149913. 6,
  149914. 3,
  149915. 7,
  149916. 2,
  149917. 8,
  149918. 1,
  149919. 9,
  149920. 0,
  149921. 10,
  149922. };
  149923. static long _vq_lengthlist__44u6__p8_1[] = {
  149924. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149925. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149926. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149927. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149928. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149929. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149930. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149931. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149932. };
  149933. static float _vq_quantthresh__44u6__p8_1[] = {
  149934. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149935. 3.5, 4.5,
  149936. };
  149937. static long _vq_quantmap__44u6__p8_1[] = {
  149938. 9, 7, 5, 3, 1, 0, 2, 4,
  149939. 6, 8, 10,
  149940. };
  149941. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149942. _vq_quantthresh__44u6__p8_1,
  149943. _vq_quantmap__44u6__p8_1,
  149944. 11,
  149945. 11
  149946. };
  149947. static static_codebook _44u6__p8_1 = {
  149948. 2, 121,
  149949. _vq_lengthlist__44u6__p8_1,
  149950. 1, -531365888, 1611661312, 4, 0,
  149951. _vq_quantlist__44u6__p8_1,
  149952. NULL,
  149953. &_vq_auxt__44u6__p8_1,
  149954. NULL,
  149955. 0
  149956. };
  149957. static long _vq_quantlist__44u6__p9_0[] = {
  149958. 7,
  149959. 6,
  149960. 8,
  149961. 5,
  149962. 9,
  149963. 4,
  149964. 10,
  149965. 3,
  149966. 11,
  149967. 2,
  149968. 12,
  149969. 1,
  149970. 13,
  149971. 0,
  149972. 14,
  149973. };
  149974. static long _vq_lengthlist__44u6__p9_0[] = {
  149975. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149976. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149977. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149978. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149979. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149980. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149981. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149982. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149983. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149984. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149985. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149986. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149987. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149988. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149989. 14,
  149990. };
  149991. static float _vq_quantthresh__44u6__p9_0[] = {
  149992. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149993. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149994. };
  149995. static long _vq_quantmap__44u6__p9_0[] = {
  149996. 13, 11, 9, 7, 5, 3, 1, 0,
  149997. 2, 4, 6, 8, 10, 12, 14,
  149998. };
  149999. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150000. _vq_quantthresh__44u6__p9_0,
  150001. _vq_quantmap__44u6__p9_0,
  150002. 15,
  150003. 15
  150004. };
  150005. static static_codebook _44u6__p9_0 = {
  150006. 2, 225,
  150007. _vq_lengthlist__44u6__p9_0,
  150008. 1, -514071552, 1627381760, 4, 0,
  150009. _vq_quantlist__44u6__p9_0,
  150010. NULL,
  150011. &_vq_auxt__44u6__p9_0,
  150012. NULL,
  150013. 0
  150014. };
  150015. static long _vq_quantlist__44u6__p9_1[] = {
  150016. 7,
  150017. 6,
  150018. 8,
  150019. 5,
  150020. 9,
  150021. 4,
  150022. 10,
  150023. 3,
  150024. 11,
  150025. 2,
  150026. 12,
  150027. 1,
  150028. 13,
  150029. 0,
  150030. 14,
  150031. };
  150032. static long _vq_lengthlist__44u6__p9_1[] = {
  150033. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150034. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150035. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150036. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150037. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150038. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150039. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150040. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150041. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150042. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150043. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150044. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150045. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150046. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150047. 13,
  150048. };
  150049. static float _vq_quantthresh__44u6__p9_1[] = {
  150050. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150051. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150052. };
  150053. static long _vq_quantmap__44u6__p9_1[] = {
  150054. 13, 11, 9, 7, 5, 3, 1, 0,
  150055. 2, 4, 6, 8, 10, 12, 14,
  150056. };
  150057. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150058. _vq_quantthresh__44u6__p9_1,
  150059. _vq_quantmap__44u6__p9_1,
  150060. 15,
  150061. 15
  150062. };
  150063. static static_codebook _44u6__p9_1 = {
  150064. 2, 225,
  150065. _vq_lengthlist__44u6__p9_1,
  150066. 1, -522338304, 1620115456, 4, 0,
  150067. _vq_quantlist__44u6__p9_1,
  150068. NULL,
  150069. &_vq_auxt__44u6__p9_1,
  150070. NULL,
  150071. 0
  150072. };
  150073. static long _vq_quantlist__44u6__p9_2[] = {
  150074. 8,
  150075. 7,
  150076. 9,
  150077. 6,
  150078. 10,
  150079. 5,
  150080. 11,
  150081. 4,
  150082. 12,
  150083. 3,
  150084. 13,
  150085. 2,
  150086. 14,
  150087. 1,
  150088. 15,
  150089. 0,
  150090. 16,
  150091. };
  150092. static long _vq_lengthlist__44u6__p9_2[] = {
  150093. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150094. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150095. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150096. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150097. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150098. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150099. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150100. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150101. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150102. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150103. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150104. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150105. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150106. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150107. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150108. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150109. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150110. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150111. 10,
  150112. };
  150113. static float _vq_quantthresh__44u6__p9_2[] = {
  150114. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150115. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150116. };
  150117. static long _vq_quantmap__44u6__p9_2[] = {
  150118. 15, 13, 11, 9, 7, 5, 3, 1,
  150119. 0, 2, 4, 6, 8, 10, 12, 14,
  150120. 16,
  150121. };
  150122. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150123. _vq_quantthresh__44u6__p9_2,
  150124. _vq_quantmap__44u6__p9_2,
  150125. 17,
  150126. 17
  150127. };
  150128. static static_codebook _44u6__p9_2 = {
  150129. 2, 289,
  150130. _vq_lengthlist__44u6__p9_2,
  150131. 1, -529530880, 1611661312, 5, 0,
  150132. _vq_quantlist__44u6__p9_2,
  150133. NULL,
  150134. &_vq_auxt__44u6__p9_2,
  150135. NULL,
  150136. 0
  150137. };
  150138. static long _huff_lengthlist__44u6__short[] = {
  150139. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150140. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150141. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150142. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150143. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150144. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150145. 7, 6, 9,16,
  150146. };
  150147. static static_codebook _huff_book__44u6__short = {
  150148. 2, 100,
  150149. _huff_lengthlist__44u6__short,
  150150. 0, 0, 0, 0, 0,
  150151. NULL,
  150152. NULL,
  150153. NULL,
  150154. NULL,
  150155. 0
  150156. };
  150157. static long _huff_lengthlist__44u7__long[] = {
  150158. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150159. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150160. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150161. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150162. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150163. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150164. 12, 8, 6, 7,
  150165. };
  150166. static static_codebook _huff_book__44u7__long = {
  150167. 2, 100,
  150168. _huff_lengthlist__44u7__long,
  150169. 0, 0, 0, 0, 0,
  150170. NULL,
  150171. NULL,
  150172. NULL,
  150173. NULL,
  150174. 0
  150175. };
  150176. static long _vq_quantlist__44u7__p1_0[] = {
  150177. 1,
  150178. 0,
  150179. 2,
  150180. };
  150181. static long _vq_lengthlist__44u7__p1_0[] = {
  150182. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150183. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150184. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150185. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150186. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150187. 12,
  150188. };
  150189. static float _vq_quantthresh__44u7__p1_0[] = {
  150190. -0.5, 0.5,
  150191. };
  150192. static long _vq_quantmap__44u7__p1_0[] = {
  150193. 1, 0, 2,
  150194. };
  150195. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150196. _vq_quantthresh__44u7__p1_0,
  150197. _vq_quantmap__44u7__p1_0,
  150198. 3,
  150199. 3
  150200. };
  150201. static static_codebook _44u7__p1_0 = {
  150202. 4, 81,
  150203. _vq_lengthlist__44u7__p1_0,
  150204. 1, -535822336, 1611661312, 2, 0,
  150205. _vq_quantlist__44u7__p1_0,
  150206. NULL,
  150207. &_vq_auxt__44u7__p1_0,
  150208. NULL,
  150209. 0
  150210. };
  150211. static long _vq_quantlist__44u7__p2_0[] = {
  150212. 1,
  150213. 0,
  150214. 2,
  150215. };
  150216. static long _vq_lengthlist__44u7__p2_0[] = {
  150217. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150218. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150219. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150220. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150221. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150222. 9,
  150223. };
  150224. static float _vq_quantthresh__44u7__p2_0[] = {
  150225. -0.5, 0.5,
  150226. };
  150227. static long _vq_quantmap__44u7__p2_0[] = {
  150228. 1, 0, 2,
  150229. };
  150230. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150231. _vq_quantthresh__44u7__p2_0,
  150232. _vq_quantmap__44u7__p2_0,
  150233. 3,
  150234. 3
  150235. };
  150236. static static_codebook _44u7__p2_0 = {
  150237. 4, 81,
  150238. _vq_lengthlist__44u7__p2_0,
  150239. 1, -535822336, 1611661312, 2, 0,
  150240. _vq_quantlist__44u7__p2_0,
  150241. NULL,
  150242. &_vq_auxt__44u7__p2_0,
  150243. NULL,
  150244. 0
  150245. };
  150246. static long _vq_quantlist__44u7__p3_0[] = {
  150247. 2,
  150248. 1,
  150249. 3,
  150250. 0,
  150251. 4,
  150252. };
  150253. static long _vq_lengthlist__44u7__p3_0[] = {
  150254. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150255. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150256. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150257. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150258. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150259. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150260. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150261. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150262. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150263. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150264. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150265. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150266. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150267. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150268. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150269. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150270. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150271. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150272. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150273. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150274. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150275. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150276. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150277. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150278. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150279. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150280. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150281. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150282. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150283. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150284. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150285. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150286. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150287. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150288. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150289. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150290. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150291. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150292. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150293. 0,
  150294. };
  150295. static float _vq_quantthresh__44u7__p3_0[] = {
  150296. -1.5, -0.5, 0.5, 1.5,
  150297. };
  150298. static long _vq_quantmap__44u7__p3_0[] = {
  150299. 3, 1, 0, 2, 4,
  150300. };
  150301. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150302. _vq_quantthresh__44u7__p3_0,
  150303. _vq_quantmap__44u7__p3_0,
  150304. 5,
  150305. 5
  150306. };
  150307. static static_codebook _44u7__p3_0 = {
  150308. 4, 625,
  150309. _vq_lengthlist__44u7__p3_0,
  150310. 1, -533725184, 1611661312, 3, 0,
  150311. _vq_quantlist__44u7__p3_0,
  150312. NULL,
  150313. &_vq_auxt__44u7__p3_0,
  150314. NULL,
  150315. 0
  150316. };
  150317. static long _vq_quantlist__44u7__p4_0[] = {
  150318. 2,
  150319. 1,
  150320. 3,
  150321. 0,
  150322. 4,
  150323. };
  150324. static long _vq_lengthlist__44u7__p4_0[] = {
  150325. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150326. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150327. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150328. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150329. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150330. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150331. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150332. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150333. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150334. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150335. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150336. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150337. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150338. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150339. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150340. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150341. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150342. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150343. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150344. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150345. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150346. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150347. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150348. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150349. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150350. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150351. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150352. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150353. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150354. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150355. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150356. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150357. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150358. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150359. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150360. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150361. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150362. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150363. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150364. 14,
  150365. };
  150366. static float _vq_quantthresh__44u7__p4_0[] = {
  150367. -1.5, -0.5, 0.5, 1.5,
  150368. };
  150369. static long _vq_quantmap__44u7__p4_0[] = {
  150370. 3, 1, 0, 2, 4,
  150371. };
  150372. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150373. _vq_quantthresh__44u7__p4_0,
  150374. _vq_quantmap__44u7__p4_0,
  150375. 5,
  150376. 5
  150377. };
  150378. static static_codebook _44u7__p4_0 = {
  150379. 4, 625,
  150380. _vq_lengthlist__44u7__p4_0,
  150381. 1, -533725184, 1611661312, 3, 0,
  150382. _vq_quantlist__44u7__p4_0,
  150383. NULL,
  150384. &_vq_auxt__44u7__p4_0,
  150385. NULL,
  150386. 0
  150387. };
  150388. static long _vq_quantlist__44u7__p5_0[] = {
  150389. 4,
  150390. 3,
  150391. 5,
  150392. 2,
  150393. 6,
  150394. 1,
  150395. 7,
  150396. 0,
  150397. 8,
  150398. };
  150399. static long _vq_lengthlist__44u7__p5_0[] = {
  150400. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150401. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150402. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150403. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150404. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150405. 14,
  150406. };
  150407. static float _vq_quantthresh__44u7__p5_0[] = {
  150408. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150409. };
  150410. static long _vq_quantmap__44u7__p5_0[] = {
  150411. 7, 5, 3, 1, 0, 2, 4, 6,
  150412. 8,
  150413. };
  150414. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150415. _vq_quantthresh__44u7__p5_0,
  150416. _vq_quantmap__44u7__p5_0,
  150417. 9,
  150418. 9
  150419. };
  150420. static static_codebook _44u7__p5_0 = {
  150421. 2, 81,
  150422. _vq_lengthlist__44u7__p5_0,
  150423. 1, -531628032, 1611661312, 4, 0,
  150424. _vq_quantlist__44u7__p5_0,
  150425. NULL,
  150426. &_vq_auxt__44u7__p5_0,
  150427. NULL,
  150428. 0
  150429. };
  150430. static long _vq_quantlist__44u7__p6_0[] = {
  150431. 4,
  150432. 3,
  150433. 5,
  150434. 2,
  150435. 6,
  150436. 1,
  150437. 7,
  150438. 0,
  150439. 8,
  150440. };
  150441. static long _vq_lengthlist__44u7__p6_0[] = {
  150442. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150443. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150444. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150445. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150446. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150447. 12,
  150448. };
  150449. static float _vq_quantthresh__44u7__p6_0[] = {
  150450. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150451. };
  150452. static long _vq_quantmap__44u7__p6_0[] = {
  150453. 7, 5, 3, 1, 0, 2, 4, 6,
  150454. 8,
  150455. };
  150456. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150457. _vq_quantthresh__44u7__p6_0,
  150458. _vq_quantmap__44u7__p6_0,
  150459. 9,
  150460. 9
  150461. };
  150462. static static_codebook _44u7__p6_0 = {
  150463. 2, 81,
  150464. _vq_lengthlist__44u7__p6_0,
  150465. 1, -531628032, 1611661312, 4, 0,
  150466. _vq_quantlist__44u7__p6_0,
  150467. NULL,
  150468. &_vq_auxt__44u7__p6_0,
  150469. NULL,
  150470. 0
  150471. };
  150472. static long _vq_quantlist__44u7__p7_0[] = {
  150473. 1,
  150474. 0,
  150475. 2,
  150476. };
  150477. static long _vq_lengthlist__44u7__p7_0[] = {
  150478. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150479. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150480. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150481. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150482. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150483. 10,
  150484. };
  150485. static float _vq_quantthresh__44u7__p7_0[] = {
  150486. -5.5, 5.5,
  150487. };
  150488. static long _vq_quantmap__44u7__p7_0[] = {
  150489. 1, 0, 2,
  150490. };
  150491. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150492. _vq_quantthresh__44u7__p7_0,
  150493. _vq_quantmap__44u7__p7_0,
  150494. 3,
  150495. 3
  150496. };
  150497. static static_codebook _44u7__p7_0 = {
  150498. 4, 81,
  150499. _vq_lengthlist__44u7__p7_0,
  150500. 1, -529137664, 1618345984, 2, 0,
  150501. _vq_quantlist__44u7__p7_0,
  150502. NULL,
  150503. &_vq_auxt__44u7__p7_0,
  150504. NULL,
  150505. 0
  150506. };
  150507. static long _vq_quantlist__44u7__p7_1[] = {
  150508. 5,
  150509. 4,
  150510. 6,
  150511. 3,
  150512. 7,
  150513. 2,
  150514. 8,
  150515. 1,
  150516. 9,
  150517. 0,
  150518. 10,
  150519. };
  150520. static long _vq_lengthlist__44u7__p7_1[] = {
  150521. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150522. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150523. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150524. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150525. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150526. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150527. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150528. 8, 9, 9, 9, 9, 9,10,10,10,
  150529. };
  150530. static float _vq_quantthresh__44u7__p7_1[] = {
  150531. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150532. 3.5, 4.5,
  150533. };
  150534. static long _vq_quantmap__44u7__p7_1[] = {
  150535. 9, 7, 5, 3, 1, 0, 2, 4,
  150536. 6, 8, 10,
  150537. };
  150538. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150539. _vq_quantthresh__44u7__p7_1,
  150540. _vq_quantmap__44u7__p7_1,
  150541. 11,
  150542. 11
  150543. };
  150544. static static_codebook _44u7__p7_1 = {
  150545. 2, 121,
  150546. _vq_lengthlist__44u7__p7_1,
  150547. 1, -531365888, 1611661312, 4, 0,
  150548. _vq_quantlist__44u7__p7_1,
  150549. NULL,
  150550. &_vq_auxt__44u7__p7_1,
  150551. NULL,
  150552. 0
  150553. };
  150554. static long _vq_quantlist__44u7__p8_0[] = {
  150555. 5,
  150556. 4,
  150557. 6,
  150558. 3,
  150559. 7,
  150560. 2,
  150561. 8,
  150562. 1,
  150563. 9,
  150564. 0,
  150565. 10,
  150566. };
  150567. static long _vq_lengthlist__44u7__p8_0[] = {
  150568. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150569. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150570. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150571. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150572. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150573. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150574. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150575. 12,13,13,14,14,15,15,15,16,
  150576. };
  150577. static float _vq_quantthresh__44u7__p8_0[] = {
  150578. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150579. 38.5, 49.5,
  150580. };
  150581. static long _vq_quantmap__44u7__p8_0[] = {
  150582. 9, 7, 5, 3, 1, 0, 2, 4,
  150583. 6, 8, 10,
  150584. };
  150585. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150586. _vq_quantthresh__44u7__p8_0,
  150587. _vq_quantmap__44u7__p8_0,
  150588. 11,
  150589. 11
  150590. };
  150591. static static_codebook _44u7__p8_0 = {
  150592. 2, 121,
  150593. _vq_lengthlist__44u7__p8_0,
  150594. 1, -524582912, 1618345984, 4, 0,
  150595. _vq_quantlist__44u7__p8_0,
  150596. NULL,
  150597. &_vq_auxt__44u7__p8_0,
  150598. NULL,
  150599. 0
  150600. };
  150601. static long _vq_quantlist__44u7__p8_1[] = {
  150602. 5,
  150603. 4,
  150604. 6,
  150605. 3,
  150606. 7,
  150607. 2,
  150608. 8,
  150609. 1,
  150610. 9,
  150611. 0,
  150612. 10,
  150613. };
  150614. static long _vq_lengthlist__44u7__p8_1[] = {
  150615. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150616. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150617. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150618. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150619. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150620. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150621. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150622. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150623. };
  150624. static float _vq_quantthresh__44u7__p8_1[] = {
  150625. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150626. 3.5, 4.5,
  150627. };
  150628. static long _vq_quantmap__44u7__p8_1[] = {
  150629. 9, 7, 5, 3, 1, 0, 2, 4,
  150630. 6, 8, 10,
  150631. };
  150632. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150633. _vq_quantthresh__44u7__p8_1,
  150634. _vq_quantmap__44u7__p8_1,
  150635. 11,
  150636. 11
  150637. };
  150638. static static_codebook _44u7__p8_1 = {
  150639. 2, 121,
  150640. _vq_lengthlist__44u7__p8_1,
  150641. 1, -531365888, 1611661312, 4, 0,
  150642. _vq_quantlist__44u7__p8_1,
  150643. NULL,
  150644. &_vq_auxt__44u7__p8_1,
  150645. NULL,
  150646. 0
  150647. };
  150648. static long _vq_quantlist__44u7__p9_0[] = {
  150649. 5,
  150650. 4,
  150651. 6,
  150652. 3,
  150653. 7,
  150654. 2,
  150655. 8,
  150656. 1,
  150657. 9,
  150658. 0,
  150659. 10,
  150660. };
  150661. static long _vq_lengthlist__44u7__p9_0[] = {
  150662. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150663. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150667. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150668. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150669. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150670. };
  150671. static float _vq_quantthresh__44u7__p9_0[] = {
  150672. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150673. 2229.5, 2866.5,
  150674. };
  150675. static long _vq_quantmap__44u7__p9_0[] = {
  150676. 9, 7, 5, 3, 1, 0, 2, 4,
  150677. 6, 8, 10,
  150678. };
  150679. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150680. _vq_quantthresh__44u7__p9_0,
  150681. _vq_quantmap__44u7__p9_0,
  150682. 11,
  150683. 11
  150684. };
  150685. static static_codebook _44u7__p9_0 = {
  150686. 2, 121,
  150687. _vq_lengthlist__44u7__p9_0,
  150688. 1, -512171520, 1630791680, 4, 0,
  150689. _vq_quantlist__44u7__p9_0,
  150690. NULL,
  150691. &_vq_auxt__44u7__p9_0,
  150692. NULL,
  150693. 0
  150694. };
  150695. static long _vq_quantlist__44u7__p9_1[] = {
  150696. 6,
  150697. 5,
  150698. 7,
  150699. 4,
  150700. 8,
  150701. 3,
  150702. 9,
  150703. 2,
  150704. 10,
  150705. 1,
  150706. 11,
  150707. 0,
  150708. 12,
  150709. };
  150710. static long _vq_lengthlist__44u7__p9_1[] = {
  150711. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150712. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150713. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150714. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150715. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150716. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150717. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150718. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150719. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150720. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150721. 15,15,15,15,17,17,16,17,16,
  150722. };
  150723. static float _vq_quantthresh__44u7__p9_1[] = {
  150724. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150725. 122.5, 171.5, 220.5, 269.5,
  150726. };
  150727. static long _vq_quantmap__44u7__p9_1[] = {
  150728. 11, 9, 7, 5, 3, 1, 0, 2,
  150729. 4, 6, 8, 10, 12,
  150730. };
  150731. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150732. _vq_quantthresh__44u7__p9_1,
  150733. _vq_quantmap__44u7__p9_1,
  150734. 13,
  150735. 13
  150736. };
  150737. static static_codebook _44u7__p9_1 = {
  150738. 2, 169,
  150739. _vq_lengthlist__44u7__p9_1,
  150740. 1, -518889472, 1622704128, 4, 0,
  150741. _vq_quantlist__44u7__p9_1,
  150742. NULL,
  150743. &_vq_auxt__44u7__p9_1,
  150744. NULL,
  150745. 0
  150746. };
  150747. static long _vq_quantlist__44u7__p9_2[] = {
  150748. 24,
  150749. 23,
  150750. 25,
  150751. 22,
  150752. 26,
  150753. 21,
  150754. 27,
  150755. 20,
  150756. 28,
  150757. 19,
  150758. 29,
  150759. 18,
  150760. 30,
  150761. 17,
  150762. 31,
  150763. 16,
  150764. 32,
  150765. 15,
  150766. 33,
  150767. 14,
  150768. 34,
  150769. 13,
  150770. 35,
  150771. 12,
  150772. 36,
  150773. 11,
  150774. 37,
  150775. 10,
  150776. 38,
  150777. 9,
  150778. 39,
  150779. 8,
  150780. 40,
  150781. 7,
  150782. 41,
  150783. 6,
  150784. 42,
  150785. 5,
  150786. 43,
  150787. 4,
  150788. 44,
  150789. 3,
  150790. 45,
  150791. 2,
  150792. 46,
  150793. 1,
  150794. 47,
  150795. 0,
  150796. 48,
  150797. };
  150798. static long _vq_lengthlist__44u7__p9_2[] = {
  150799. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150800. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150801. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150802. 8,
  150803. };
  150804. static float _vq_quantthresh__44u7__p9_2[] = {
  150805. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150806. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150807. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150808. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150809. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150810. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150811. };
  150812. static long _vq_quantmap__44u7__p9_2[] = {
  150813. 47, 45, 43, 41, 39, 37, 35, 33,
  150814. 31, 29, 27, 25, 23, 21, 19, 17,
  150815. 15, 13, 11, 9, 7, 5, 3, 1,
  150816. 0, 2, 4, 6, 8, 10, 12, 14,
  150817. 16, 18, 20, 22, 24, 26, 28, 30,
  150818. 32, 34, 36, 38, 40, 42, 44, 46,
  150819. 48,
  150820. };
  150821. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150822. _vq_quantthresh__44u7__p9_2,
  150823. _vq_quantmap__44u7__p9_2,
  150824. 49,
  150825. 49
  150826. };
  150827. static static_codebook _44u7__p9_2 = {
  150828. 1, 49,
  150829. _vq_lengthlist__44u7__p9_2,
  150830. 1, -526909440, 1611661312, 6, 0,
  150831. _vq_quantlist__44u7__p9_2,
  150832. NULL,
  150833. &_vq_auxt__44u7__p9_2,
  150834. NULL,
  150835. 0
  150836. };
  150837. static long _huff_lengthlist__44u7__short[] = {
  150838. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150839. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150840. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150841. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150842. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150843. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150844. 6, 8, 5, 9,
  150845. };
  150846. static static_codebook _huff_book__44u7__short = {
  150847. 2, 100,
  150848. _huff_lengthlist__44u7__short,
  150849. 0, 0, 0, 0, 0,
  150850. NULL,
  150851. NULL,
  150852. NULL,
  150853. NULL,
  150854. 0
  150855. };
  150856. static long _huff_lengthlist__44u8__long[] = {
  150857. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150858. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150859. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150860. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150861. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150862. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150863. 10, 8, 8, 9,
  150864. };
  150865. static static_codebook _huff_book__44u8__long = {
  150866. 2, 100,
  150867. _huff_lengthlist__44u8__long,
  150868. 0, 0, 0, 0, 0,
  150869. NULL,
  150870. NULL,
  150871. NULL,
  150872. NULL,
  150873. 0
  150874. };
  150875. static long _huff_lengthlist__44u8__short[] = {
  150876. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150877. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150878. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150879. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150880. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150881. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150882. 10,10,15,17,
  150883. };
  150884. static static_codebook _huff_book__44u8__short = {
  150885. 2, 100,
  150886. _huff_lengthlist__44u8__short,
  150887. 0, 0, 0, 0, 0,
  150888. NULL,
  150889. NULL,
  150890. NULL,
  150891. NULL,
  150892. 0
  150893. };
  150894. static long _vq_quantlist__44u8_p1_0[] = {
  150895. 1,
  150896. 0,
  150897. 2,
  150898. };
  150899. static long _vq_lengthlist__44u8_p1_0[] = {
  150900. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150901. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150902. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150903. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150904. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150905. 10,
  150906. };
  150907. static float _vq_quantthresh__44u8_p1_0[] = {
  150908. -0.5, 0.5,
  150909. };
  150910. static long _vq_quantmap__44u8_p1_0[] = {
  150911. 1, 0, 2,
  150912. };
  150913. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150914. _vq_quantthresh__44u8_p1_0,
  150915. _vq_quantmap__44u8_p1_0,
  150916. 3,
  150917. 3
  150918. };
  150919. static static_codebook _44u8_p1_0 = {
  150920. 4, 81,
  150921. _vq_lengthlist__44u8_p1_0,
  150922. 1, -535822336, 1611661312, 2, 0,
  150923. _vq_quantlist__44u8_p1_0,
  150924. NULL,
  150925. &_vq_auxt__44u8_p1_0,
  150926. NULL,
  150927. 0
  150928. };
  150929. static long _vq_quantlist__44u8_p2_0[] = {
  150930. 2,
  150931. 1,
  150932. 3,
  150933. 0,
  150934. 4,
  150935. };
  150936. static long _vq_lengthlist__44u8_p2_0[] = {
  150937. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150938. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150939. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150940. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150941. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150942. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150943. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150944. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150945. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150946. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150947. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150948. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150949. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150950. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150951. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150952. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150953. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150954. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150955. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150956. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150957. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150958. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150959. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150960. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150961. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150962. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150963. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150964. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150965. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150966. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150967. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150968. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150969. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150970. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150971. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150972. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150973. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150974. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150975. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150976. 14,
  150977. };
  150978. static float _vq_quantthresh__44u8_p2_0[] = {
  150979. -1.5, -0.5, 0.5, 1.5,
  150980. };
  150981. static long _vq_quantmap__44u8_p2_0[] = {
  150982. 3, 1, 0, 2, 4,
  150983. };
  150984. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150985. _vq_quantthresh__44u8_p2_0,
  150986. _vq_quantmap__44u8_p2_0,
  150987. 5,
  150988. 5
  150989. };
  150990. static static_codebook _44u8_p2_0 = {
  150991. 4, 625,
  150992. _vq_lengthlist__44u8_p2_0,
  150993. 1, -533725184, 1611661312, 3, 0,
  150994. _vq_quantlist__44u8_p2_0,
  150995. NULL,
  150996. &_vq_auxt__44u8_p2_0,
  150997. NULL,
  150998. 0
  150999. };
  151000. static long _vq_quantlist__44u8_p3_0[] = {
  151001. 4,
  151002. 3,
  151003. 5,
  151004. 2,
  151005. 6,
  151006. 1,
  151007. 7,
  151008. 0,
  151009. 8,
  151010. };
  151011. static long _vq_lengthlist__44u8_p3_0[] = {
  151012. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151013. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151014. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151015. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151016. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151017. 12,
  151018. };
  151019. static float _vq_quantthresh__44u8_p3_0[] = {
  151020. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151021. };
  151022. static long _vq_quantmap__44u8_p3_0[] = {
  151023. 7, 5, 3, 1, 0, 2, 4, 6,
  151024. 8,
  151025. };
  151026. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151027. _vq_quantthresh__44u8_p3_0,
  151028. _vq_quantmap__44u8_p3_0,
  151029. 9,
  151030. 9
  151031. };
  151032. static static_codebook _44u8_p3_0 = {
  151033. 2, 81,
  151034. _vq_lengthlist__44u8_p3_0,
  151035. 1, -531628032, 1611661312, 4, 0,
  151036. _vq_quantlist__44u8_p3_0,
  151037. NULL,
  151038. &_vq_auxt__44u8_p3_0,
  151039. NULL,
  151040. 0
  151041. };
  151042. static long _vq_quantlist__44u8_p4_0[] = {
  151043. 8,
  151044. 7,
  151045. 9,
  151046. 6,
  151047. 10,
  151048. 5,
  151049. 11,
  151050. 4,
  151051. 12,
  151052. 3,
  151053. 13,
  151054. 2,
  151055. 14,
  151056. 1,
  151057. 15,
  151058. 0,
  151059. 16,
  151060. };
  151061. static long _vq_lengthlist__44u8_p4_0[] = {
  151062. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151063. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151064. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151065. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151066. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151067. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151068. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151069. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151070. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151071. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151072. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151073. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151074. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151075. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151076. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151077. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151078. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151079. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151080. 14,
  151081. };
  151082. static float _vq_quantthresh__44u8_p4_0[] = {
  151083. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151084. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151085. };
  151086. static long _vq_quantmap__44u8_p4_0[] = {
  151087. 15, 13, 11, 9, 7, 5, 3, 1,
  151088. 0, 2, 4, 6, 8, 10, 12, 14,
  151089. 16,
  151090. };
  151091. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151092. _vq_quantthresh__44u8_p4_0,
  151093. _vq_quantmap__44u8_p4_0,
  151094. 17,
  151095. 17
  151096. };
  151097. static static_codebook _44u8_p4_0 = {
  151098. 2, 289,
  151099. _vq_lengthlist__44u8_p4_0,
  151100. 1, -529530880, 1611661312, 5, 0,
  151101. _vq_quantlist__44u8_p4_0,
  151102. NULL,
  151103. &_vq_auxt__44u8_p4_0,
  151104. NULL,
  151105. 0
  151106. };
  151107. static long _vq_quantlist__44u8_p5_0[] = {
  151108. 1,
  151109. 0,
  151110. 2,
  151111. };
  151112. static long _vq_lengthlist__44u8_p5_0[] = {
  151113. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151114. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151115. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151116. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151117. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151118. 10,
  151119. };
  151120. static float _vq_quantthresh__44u8_p5_0[] = {
  151121. -5.5, 5.5,
  151122. };
  151123. static long _vq_quantmap__44u8_p5_0[] = {
  151124. 1, 0, 2,
  151125. };
  151126. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151127. _vq_quantthresh__44u8_p5_0,
  151128. _vq_quantmap__44u8_p5_0,
  151129. 3,
  151130. 3
  151131. };
  151132. static static_codebook _44u8_p5_0 = {
  151133. 4, 81,
  151134. _vq_lengthlist__44u8_p5_0,
  151135. 1, -529137664, 1618345984, 2, 0,
  151136. _vq_quantlist__44u8_p5_0,
  151137. NULL,
  151138. &_vq_auxt__44u8_p5_0,
  151139. NULL,
  151140. 0
  151141. };
  151142. static long _vq_quantlist__44u8_p5_1[] = {
  151143. 5,
  151144. 4,
  151145. 6,
  151146. 3,
  151147. 7,
  151148. 2,
  151149. 8,
  151150. 1,
  151151. 9,
  151152. 0,
  151153. 10,
  151154. };
  151155. static long _vq_lengthlist__44u8_p5_1[] = {
  151156. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151157. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151158. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151159. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151160. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151161. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151162. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151163. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151164. };
  151165. static float _vq_quantthresh__44u8_p5_1[] = {
  151166. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151167. 3.5, 4.5,
  151168. };
  151169. static long _vq_quantmap__44u8_p5_1[] = {
  151170. 9, 7, 5, 3, 1, 0, 2, 4,
  151171. 6, 8, 10,
  151172. };
  151173. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151174. _vq_quantthresh__44u8_p5_1,
  151175. _vq_quantmap__44u8_p5_1,
  151176. 11,
  151177. 11
  151178. };
  151179. static static_codebook _44u8_p5_1 = {
  151180. 2, 121,
  151181. _vq_lengthlist__44u8_p5_1,
  151182. 1, -531365888, 1611661312, 4, 0,
  151183. _vq_quantlist__44u8_p5_1,
  151184. NULL,
  151185. &_vq_auxt__44u8_p5_1,
  151186. NULL,
  151187. 0
  151188. };
  151189. static long _vq_quantlist__44u8_p6_0[] = {
  151190. 6,
  151191. 5,
  151192. 7,
  151193. 4,
  151194. 8,
  151195. 3,
  151196. 9,
  151197. 2,
  151198. 10,
  151199. 1,
  151200. 11,
  151201. 0,
  151202. 12,
  151203. };
  151204. static long _vq_lengthlist__44u8_p6_0[] = {
  151205. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151206. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151207. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151208. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151209. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151210. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151211. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151212. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151213. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151214. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151215. 11,11,11,11,11,12,11,12,12,
  151216. };
  151217. static float _vq_quantthresh__44u8_p6_0[] = {
  151218. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151219. 12.5, 17.5, 22.5, 27.5,
  151220. };
  151221. static long _vq_quantmap__44u8_p6_0[] = {
  151222. 11, 9, 7, 5, 3, 1, 0, 2,
  151223. 4, 6, 8, 10, 12,
  151224. };
  151225. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151226. _vq_quantthresh__44u8_p6_0,
  151227. _vq_quantmap__44u8_p6_0,
  151228. 13,
  151229. 13
  151230. };
  151231. static static_codebook _44u8_p6_0 = {
  151232. 2, 169,
  151233. _vq_lengthlist__44u8_p6_0,
  151234. 1, -526516224, 1616117760, 4, 0,
  151235. _vq_quantlist__44u8_p6_0,
  151236. NULL,
  151237. &_vq_auxt__44u8_p6_0,
  151238. NULL,
  151239. 0
  151240. };
  151241. static long _vq_quantlist__44u8_p6_1[] = {
  151242. 2,
  151243. 1,
  151244. 3,
  151245. 0,
  151246. 4,
  151247. };
  151248. static long _vq_lengthlist__44u8_p6_1[] = {
  151249. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151250. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151251. };
  151252. static float _vq_quantthresh__44u8_p6_1[] = {
  151253. -1.5, -0.5, 0.5, 1.5,
  151254. };
  151255. static long _vq_quantmap__44u8_p6_1[] = {
  151256. 3, 1, 0, 2, 4,
  151257. };
  151258. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151259. _vq_quantthresh__44u8_p6_1,
  151260. _vq_quantmap__44u8_p6_1,
  151261. 5,
  151262. 5
  151263. };
  151264. static static_codebook _44u8_p6_1 = {
  151265. 2, 25,
  151266. _vq_lengthlist__44u8_p6_1,
  151267. 1, -533725184, 1611661312, 3, 0,
  151268. _vq_quantlist__44u8_p6_1,
  151269. NULL,
  151270. &_vq_auxt__44u8_p6_1,
  151271. NULL,
  151272. 0
  151273. };
  151274. static long _vq_quantlist__44u8_p7_0[] = {
  151275. 6,
  151276. 5,
  151277. 7,
  151278. 4,
  151279. 8,
  151280. 3,
  151281. 9,
  151282. 2,
  151283. 10,
  151284. 1,
  151285. 11,
  151286. 0,
  151287. 12,
  151288. };
  151289. static long _vq_lengthlist__44u8_p7_0[] = {
  151290. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151291. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151292. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151293. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151294. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151295. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151296. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151297. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151298. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151299. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151300. 13,13,14,14,14,15,15,15,16,
  151301. };
  151302. static float _vq_quantthresh__44u8_p7_0[] = {
  151303. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151304. 27.5, 38.5, 49.5, 60.5,
  151305. };
  151306. static long _vq_quantmap__44u8_p7_0[] = {
  151307. 11, 9, 7, 5, 3, 1, 0, 2,
  151308. 4, 6, 8, 10, 12,
  151309. };
  151310. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151311. _vq_quantthresh__44u8_p7_0,
  151312. _vq_quantmap__44u8_p7_0,
  151313. 13,
  151314. 13
  151315. };
  151316. static static_codebook _44u8_p7_0 = {
  151317. 2, 169,
  151318. _vq_lengthlist__44u8_p7_0,
  151319. 1, -523206656, 1618345984, 4, 0,
  151320. _vq_quantlist__44u8_p7_0,
  151321. NULL,
  151322. &_vq_auxt__44u8_p7_0,
  151323. NULL,
  151324. 0
  151325. };
  151326. static long _vq_quantlist__44u8_p7_1[] = {
  151327. 5,
  151328. 4,
  151329. 6,
  151330. 3,
  151331. 7,
  151332. 2,
  151333. 8,
  151334. 1,
  151335. 9,
  151336. 0,
  151337. 10,
  151338. };
  151339. static long _vq_lengthlist__44u8_p7_1[] = {
  151340. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151341. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151342. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151343. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151344. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151345. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151346. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151347. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151348. };
  151349. static float _vq_quantthresh__44u8_p7_1[] = {
  151350. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151351. 3.5, 4.5,
  151352. };
  151353. static long _vq_quantmap__44u8_p7_1[] = {
  151354. 9, 7, 5, 3, 1, 0, 2, 4,
  151355. 6, 8, 10,
  151356. };
  151357. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151358. _vq_quantthresh__44u8_p7_1,
  151359. _vq_quantmap__44u8_p7_1,
  151360. 11,
  151361. 11
  151362. };
  151363. static static_codebook _44u8_p7_1 = {
  151364. 2, 121,
  151365. _vq_lengthlist__44u8_p7_1,
  151366. 1, -531365888, 1611661312, 4, 0,
  151367. _vq_quantlist__44u8_p7_1,
  151368. NULL,
  151369. &_vq_auxt__44u8_p7_1,
  151370. NULL,
  151371. 0
  151372. };
  151373. static long _vq_quantlist__44u8_p8_0[] = {
  151374. 7,
  151375. 6,
  151376. 8,
  151377. 5,
  151378. 9,
  151379. 4,
  151380. 10,
  151381. 3,
  151382. 11,
  151383. 2,
  151384. 12,
  151385. 1,
  151386. 13,
  151387. 0,
  151388. 14,
  151389. };
  151390. static long _vq_lengthlist__44u8_p8_0[] = {
  151391. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151392. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151393. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151394. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151395. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151396. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151397. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151398. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151399. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151400. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151401. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151402. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151403. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151404. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151405. 17,
  151406. };
  151407. static float _vq_quantthresh__44u8_p8_0[] = {
  151408. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151409. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151410. };
  151411. static long _vq_quantmap__44u8_p8_0[] = {
  151412. 13, 11, 9, 7, 5, 3, 1, 0,
  151413. 2, 4, 6, 8, 10, 12, 14,
  151414. };
  151415. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151416. _vq_quantthresh__44u8_p8_0,
  151417. _vq_quantmap__44u8_p8_0,
  151418. 15,
  151419. 15
  151420. };
  151421. static static_codebook _44u8_p8_0 = {
  151422. 2, 225,
  151423. _vq_lengthlist__44u8_p8_0,
  151424. 1, -520986624, 1620377600, 4, 0,
  151425. _vq_quantlist__44u8_p8_0,
  151426. NULL,
  151427. &_vq_auxt__44u8_p8_0,
  151428. NULL,
  151429. 0
  151430. };
  151431. static long _vq_quantlist__44u8_p8_1[] = {
  151432. 10,
  151433. 9,
  151434. 11,
  151435. 8,
  151436. 12,
  151437. 7,
  151438. 13,
  151439. 6,
  151440. 14,
  151441. 5,
  151442. 15,
  151443. 4,
  151444. 16,
  151445. 3,
  151446. 17,
  151447. 2,
  151448. 18,
  151449. 1,
  151450. 19,
  151451. 0,
  151452. 20,
  151453. };
  151454. static long _vq_lengthlist__44u8_p8_1[] = {
  151455. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151456. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151457. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151458. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151459. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151460. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151461. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151462. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151463. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151464. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151465. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151466. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151467. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151468. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151469. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151470. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151471. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151472. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151473. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151474. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151475. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151476. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151477. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151478. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151479. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151480. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151481. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151482. 10,10,10,10,10,10,10,10,10,
  151483. };
  151484. static float _vq_quantthresh__44u8_p8_1[] = {
  151485. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151486. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151487. 6.5, 7.5, 8.5, 9.5,
  151488. };
  151489. static long _vq_quantmap__44u8_p8_1[] = {
  151490. 19, 17, 15, 13, 11, 9, 7, 5,
  151491. 3, 1, 0, 2, 4, 6, 8, 10,
  151492. 12, 14, 16, 18, 20,
  151493. };
  151494. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151495. _vq_quantthresh__44u8_p8_1,
  151496. _vq_quantmap__44u8_p8_1,
  151497. 21,
  151498. 21
  151499. };
  151500. static static_codebook _44u8_p8_1 = {
  151501. 2, 441,
  151502. _vq_lengthlist__44u8_p8_1,
  151503. 1, -529268736, 1611661312, 5, 0,
  151504. _vq_quantlist__44u8_p8_1,
  151505. NULL,
  151506. &_vq_auxt__44u8_p8_1,
  151507. NULL,
  151508. 0
  151509. };
  151510. static long _vq_quantlist__44u8_p9_0[] = {
  151511. 4,
  151512. 3,
  151513. 5,
  151514. 2,
  151515. 6,
  151516. 1,
  151517. 7,
  151518. 0,
  151519. 8,
  151520. };
  151521. static long _vq_lengthlist__44u8_p9_0[] = {
  151522. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151523. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151524. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151525. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151526. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151527. 8,
  151528. };
  151529. static float _vq_quantthresh__44u8_p9_0[] = {
  151530. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151531. };
  151532. static long _vq_quantmap__44u8_p9_0[] = {
  151533. 7, 5, 3, 1, 0, 2, 4, 6,
  151534. 8,
  151535. };
  151536. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151537. _vq_quantthresh__44u8_p9_0,
  151538. _vq_quantmap__44u8_p9_0,
  151539. 9,
  151540. 9
  151541. };
  151542. static static_codebook _44u8_p9_0 = {
  151543. 2, 81,
  151544. _vq_lengthlist__44u8_p9_0,
  151545. 1, -511895552, 1631393792, 4, 0,
  151546. _vq_quantlist__44u8_p9_0,
  151547. NULL,
  151548. &_vq_auxt__44u8_p9_0,
  151549. NULL,
  151550. 0
  151551. };
  151552. static long _vq_quantlist__44u8_p9_1[] = {
  151553. 9,
  151554. 8,
  151555. 10,
  151556. 7,
  151557. 11,
  151558. 6,
  151559. 12,
  151560. 5,
  151561. 13,
  151562. 4,
  151563. 14,
  151564. 3,
  151565. 15,
  151566. 2,
  151567. 16,
  151568. 1,
  151569. 17,
  151570. 0,
  151571. 18,
  151572. };
  151573. static long _vq_lengthlist__44u8_p9_1[] = {
  151574. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151575. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151576. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151577. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151578. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151579. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151580. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151581. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151582. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151583. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151584. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151585. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151586. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151587. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151588. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151589. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151590. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151591. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151592. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151593. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151594. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151595. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151596. 16,15,16,16,16,16,16,16,16,
  151597. };
  151598. static float _vq_quantthresh__44u8_p9_1[] = {
  151599. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151600. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151601. 367.5, 416.5,
  151602. };
  151603. static long _vq_quantmap__44u8_p9_1[] = {
  151604. 17, 15, 13, 11, 9, 7, 5, 3,
  151605. 1, 0, 2, 4, 6, 8, 10, 12,
  151606. 14, 16, 18,
  151607. };
  151608. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151609. _vq_quantthresh__44u8_p9_1,
  151610. _vq_quantmap__44u8_p9_1,
  151611. 19,
  151612. 19
  151613. };
  151614. static static_codebook _44u8_p9_1 = {
  151615. 2, 361,
  151616. _vq_lengthlist__44u8_p9_1,
  151617. 1, -518287360, 1622704128, 5, 0,
  151618. _vq_quantlist__44u8_p9_1,
  151619. NULL,
  151620. &_vq_auxt__44u8_p9_1,
  151621. NULL,
  151622. 0
  151623. };
  151624. static long _vq_quantlist__44u8_p9_2[] = {
  151625. 24,
  151626. 23,
  151627. 25,
  151628. 22,
  151629. 26,
  151630. 21,
  151631. 27,
  151632. 20,
  151633. 28,
  151634. 19,
  151635. 29,
  151636. 18,
  151637. 30,
  151638. 17,
  151639. 31,
  151640. 16,
  151641. 32,
  151642. 15,
  151643. 33,
  151644. 14,
  151645. 34,
  151646. 13,
  151647. 35,
  151648. 12,
  151649. 36,
  151650. 11,
  151651. 37,
  151652. 10,
  151653. 38,
  151654. 9,
  151655. 39,
  151656. 8,
  151657. 40,
  151658. 7,
  151659. 41,
  151660. 6,
  151661. 42,
  151662. 5,
  151663. 43,
  151664. 4,
  151665. 44,
  151666. 3,
  151667. 45,
  151668. 2,
  151669. 46,
  151670. 1,
  151671. 47,
  151672. 0,
  151673. 48,
  151674. };
  151675. static long _vq_lengthlist__44u8_p9_2[] = {
  151676. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151677. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151678. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151679. 7,
  151680. };
  151681. static float _vq_quantthresh__44u8_p9_2[] = {
  151682. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151683. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151684. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151685. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151686. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151687. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151688. };
  151689. static long _vq_quantmap__44u8_p9_2[] = {
  151690. 47, 45, 43, 41, 39, 37, 35, 33,
  151691. 31, 29, 27, 25, 23, 21, 19, 17,
  151692. 15, 13, 11, 9, 7, 5, 3, 1,
  151693. 0, 2, 4, 6, 8, 10, 12, 14,
  151694. 16, 18, 20, 22, 24, 26, 28, 30,
  151695. 32, 34, 36, 38, 40, 42, 44, 46,
  151696. 48,
  151697. };
  151698. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151699. _vq_quantthresh__44u8_p9_2,
  151700. _vq_quantmap__44u8_p9_2,
  151701. 49,
  151702. 49
  151703. };
  151704. static static_codebook _44u8_p9_2 = {
  151705. 1, 49,
  151706. _vq_lengthlist__44u8_p9_2,
  151707. 1, -526909440, 1611661312, 6, 0,
  151708. _vq_quantlist__44u8_p9_2,
  151709. NULL,
  151710. &_vq_auxt__44u8_p9_2,
  151711. NULL,
  151712. 0
  151713. };
  151714. static long _huff_lengthlist__44u9__long[] = {
  151715. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151716. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151717. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151718. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151719. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151720. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151721. 10, 8, 8, 9,
  151722. };
  151723. static static_codebook _huff_book__44u9__long = {
  151724. 2, 100,
  151725. _huff_lengthlist__44u9__long,
  151726. 0, 0, 0, 0, 0,
  151727. NULL,
  151728. NULL,
  151729. NULL,
  151730. NULL,
  151731. 0
  151732. };
  151733. static long _huff_lengthlist__44u9__short[] = {
  151734. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151735. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151736. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151737. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151738. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151739. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151740. 9, 9,12,15,
  151741. };
  151742. static static_codebook _huff_book__44u9__short = {
  151743. 2, 100,
  151744. _huff_lengthlist__44u9__short,
  151745. 0, 0, 0, 0, 0,
  151746. NULL,
  151747. NULL,
  151748. NULL,
  151749. NULL,
  151750. 0
  151751. };
  151752. static long _vq_quantlist__44u9_p1_0[] = {
  151753. 1,
  151754. 0,
  151755. 2,
  151756. };
  151757. static long _vq_lengthlist__44u9_p1_0[] = {
  151758. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151759. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151760. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151761. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151762. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151763. 10,
  151764. };
  151765. static float _vq_quantthresh__44u9_p1_0[] = {
  151766. -0.5, 0.5,
  151767. };
  151768. static long _vq_quantmap__44u9_p1_0[] = {
  151769. 1, 0, 2,
  151770. };
  151771. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151772. _vq_quantthresh__44u9_p1_0,
  151773. _vq_quantmap__44u9_p1_0,
  151774. 3,
  151775. 3
  151776. };
  151777. static static_codebook _44u9_p1_0 = {
  151778. 4, 81,
  151779. _vq_lengthlist__44u9_p1_0,
  151780. 1, -535822336, 1611661312, 2, 0,
  151781. _vq_quantlist__44u9_p1_0,
  151782. NULL,
  151783. &_vq_auxt__44u9_p1_0,
  151784. NULL,
  151785. 0
  151786. };
  151787. static long _vq_quantlist__44u9_p2_0[] = {
  151788. 2,
  151789. 1,
  151790. 3,
  151791. 0,
  151792. 4,
  151793. };
  151794. static long _vq_lengthlist__44u9_p2_0[] = {
  151795. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151796. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151797. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151798. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151799. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151800. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151801. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151802. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151803. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151804. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151805. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151806. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151807. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151808. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151809. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151810. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151811. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151812. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151813. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151814. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151815. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151816. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151817. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151818. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151819. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151820. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151821. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151822. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151823. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151824. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151825. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151826. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151827. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151828. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151829. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151830. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151831. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151832. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151833. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151834. 14,
  151835. };
  151836. static float _vq_quantthresh__44u9_p2_0[] = {
  151837. -1.5, -0.5, 0.5, 1.5,
  151838. };
  151839. static long _vq_quantmap__44u9_p2_0[] = {
  151840. 3, 1, 0, 2, 4,
  151841. };
  151842. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151843. _vq_quantthresh__44u9_p2_0,
  151844. _vq_quantmap__44u9_p2_0,
  151845. 5,
  151846. 5
  151847. };
  151848. static static_codebook _44u9_p2_0 = {
  151849. 4, 625,
  151850. _vq_lengthlist__44u9_p2_0,
  151851. 1, -533725184, 1611661312, 3, 0,
  151852. _vq_quantlist__44u9_p2_0,
  151853. NULL,
  151854. &_vq_auxt__44u9_p2_0,
  151855. NULL,
  151856. 0
  151857. };
  151858. static long _vq_quantlist__44u9_p3_0[] = {
  151859. 4,
  151860. 3,
  151861. 5,
  151862. 2,
  151863. 6,
  151864. 1,
  151865. 7,
  151866. 0,
  151867. 8,
  151868. };
  151869. static long _vq_lengthlist__44u9_p3_0[] = {
  151870. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151871. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151872. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151873. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151874. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151875. 11,
  151876. };
  151877. static float _vq_quantthresh__44u9_p3_0[] = {
  151878. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151879. };
  151880. static long _vq_quantmap__44u9_p3_0[] = {
  151881. 7, 5, 3, 1, 0, 2, 4, 6,
  151882. 8,
  151883. };
  151884. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151885. _vq_quantthresh__44u9_p3_0,
  151886. _vq_quantmap__44u9_p3_0,
  151887. 9,
  151888. 9
  151889. };
  151890. static static_codebook _44u9_p3_0 = {
  151891. 2, 81,
  151892. _vq_lengthlist__44u9_p3_0,
  151893. 1, -531628032, 1611661312, 4, 0,
  151894. _vq_quantlist__44u9_p3_0,
  151895. NULL,
  151896. &_vq_auxt__44u9_p3_0,
  151897. NULL,
  151898. 0
  151899. };
  151900. static long _vq_quantlist__44u9_p4_0[] = {
  151901. 8,
  151902. 7,
  151903. 9,
  151904. 6,
  151905. 10,
  151906. 5,
  151907. 11,
  151908. 4,
  151909. 12,
  151910. 3,
  151911. 13,
  151912. 2,
  151913. 14,
  151914. 1,
  151915. 15,
  151916. 0,
  151917. 16,
  151918. };
  151919. static long _vq_lengthlist__44u9_p4_0[] = {
  151920. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151921. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151922. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151923. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151924. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151925. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151926. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151927. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151928. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151929. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151930. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151931. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151932. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151933. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151934. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151935. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151936. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151937. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151938. 14,
  151939. };
  151940. static float _vq_quantthresh__44u9_p4_0[] = {
  151941. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151942. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151943. };
  151944. static long _vq_quantmap__44u9_p4_0[] = {
  151945. 15, 13, 11, 9, 7, 5, 3, 1,
  151946. 0, 2, 4, 6, 8, 10, 12, 14,
  151947. 16,
  151948. };
  151949. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151950. _vq_quantthresh__44u9_p4_0,
  151951. _vq_quantmap__44u9_p4_0,
  151952. 17,
  151953. 17
  151954. };
  151955. static static_codebook _44u9_p4_0 = {
  151956. 2, 289,
  151957. _vq_lengthlist__44u9_p4_0,
  151958. 1, -529530880, 1611661312, 5, 0,
  151959. _vq_quantlist__44u9_p4_0,
  151960. NULL,
  151961. &_vq_auxt__44u9_p4_0,
  151962. NULL,
  151963. 0
  151964. };
  151965. static long _vq_quantlist__44u9_p5_0[] = {
  151966. 1,
  151967. 0,
  151968. 2,
  151969. };
  151970. static long _vq_lengthlist__44u9_p5_0[] = {
  151971. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151972. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151973. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151974. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151975. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151976. 10,
  151977. };
  151978. static float _vq_quantthresh__44u9_p5_0[] = {
  151979. -5.5, 5.5,
  151980. };
  151981. static long _vq_quantmap__44u9_p5_0[] = {
  151982. 1, 0, 2,
  151983. };
  151984. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151985. _vq_quantthresh__44u9_p5_0,
  151986. _vq_quantmap__44u9_p5_0,
  151987. 3,
  151988. 3
  151989. };
  151990. static static_codebook _44u9_p5_0 = {
  151991. 4, 81,
  151992. _vq_lengthlist__44u9_p5_0,
  151993. 1, -529137664, 1618345984, 2, 0,
  151994. _vq_quantlist__44u9_p5_0,
  151995. NULL,
  151996. &_vq_auxt__44u9_p5_0,
  151997. NULL,
  151998. 0
  151999. };
  152000. static long _vq_quantlist__44u9_p5_1[] = {
  152001. 5,
  152002. 4,
  152003. 6,
  152004. 3,
  152005. 7,
  152006. 2,
  152007. 8,
  152008. 1,
  152009. 9,
  152010. 0,
  152011. 10,
  152012. };
  152013. static long _vq_lengthlist__44u9_p5_1[] = {
  152014. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152015. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152016. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152017. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152018. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152019. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152020. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152021. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152022. };
  152023. static float _vq_quantthresh__44u9_p5_1[] = {
  152024. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152025. 3.5, 4.5,
  152026. };
  152027. static long _vq_quantmap__44u9_p5_1[] = {
  152028. 9, 7, 5, 3, 1, 0, 2, 4,
  152029. 6, 8, 10,
  152030. };
  152031. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152032. _vq_quantthresh__44u9_p5_1,
  152033. _vq_quantmap__44u9_p5_1,
  152034. 11,
  152035. 11
  152036. };
  152037. static static_codebook _44u9_p5_1 = {
  152038. 2, 121,
  152039. _vq_lengthlist__44u9_p5_1,
  152040. 1, -531365888, 1611661312, 4, 0,
  152041. _vq_quantlist__44u9_p5_1,
  152042. NULL,
  152043. &_vq_auxt__44u9_p5_1,
  152044. NULL,
  152045. 0
  152046. };
  152047. static long _vq_quantlist__44u9_p6_0[] = {
  152048. 6,
  152049. 5,
  152050. 7,
  152051. 4,
  152052. 8,
  152053. 3,
  152054. 9,
  152055. 2,
  152056. 10,
  152057. 1,
  152058. 11,
  152059. 0,
  152060. 12,
  152061. };
  152062. static long _vq_lengthlist__44u9_p6_0[] = {
  152063. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152064. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152065. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152066. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152067. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152068. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152069. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152070. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152071. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152072. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152073. 10,11,11,11,11,12,11,12,12,
  152074. };
  152075. static float _vq_quantthresh__44u9_p6_0[] = {
  152076. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152077. 12.5, 17.5, 22.5, 27.5,
  152078. };
  152079. static long _vq_quantmap__44u9_p6_0[] = {
  152080. 11, 9, 7, 5, 3, 1, 0, 2,
  152081. 4, 6, 8, 10, 12,
  152082. };
  152083. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152084. _vq_quantthresh__44u9_p6_0,
  152085. _vq_quantmap__44u9_p6_0,
  152086. 13,
  152087. 13
  152088. };
  152089. static static_codebook _44u9_p6_0 = {
  152090. 2, 169,
  152091. _vq_lengthlist__44u9_p6_0,
  152092. 1, -526516224, 1616117760, 4, 0,
  152093. _vq_quantlist__44u9_p6_0,
  152094. NULL,
  152095. &_vq_auxt__44u9_p6_0,
  152096. NULL,
  152097. 0
  152098. };
  152099. static long _vq_quantlist__44u9_p6_1[] = {
  152100. 2,
  152101. 1,
  152102. 3,
  152103. 0,
  152104. 4,
  152105. };
  152106. static long _vq_lengthlist__44u9_p6_1[] = {
  152107. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152108. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152109. };
  152110. static float _vq_quantthresh__44u9_p6_1[] = {
  152111. -1.5, -0.5, 0.5, 1.5,
  152112. };
  152113. static long _vq_quantmap__44u9_p6_1[] = {
  152114. 3, 1, 0, 2, 4,
  152115. };
  152116. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152117. _vq_quantthresh__44u9_p6_1,
  152118. _vq_quantmap__44u9_p6_1,
  152119. 5,
  152120. 5
  152121. };
  152122. static static_codebook _44u9_p6_1 = {
  152123. 2, 25,
  152124. _vq_lengthlist__44u9_p6_1,
  152125. 1, -533725184, 1611661312, 3, 0,
  152126. _vq_quantlist__44u9_p6_1,
  152127. NULL,
  152128. &_vq_auxt__44u9_p6_1,
  152129. NULL,
  152130. 0
  152131. };
  152132. static long _vq_quantlist__44u9_p7_0[] = {
  152133. 6,
  152134. 5,
  152135. 7,
  152136. 4,
  152137. 8,
  152138. 3,
  152139. 9,
  152140. 2,
  152141. 10,
  152142. 1,
  152143. 11,
  152144. 0,
  152145. 12,
  152146. };
  152147. static long _vq_lengthlist__44u9_p7_0[] = {
  152148. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152149. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152150. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152151. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152152. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152153. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152154. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152155. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152156. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152157. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152158. 12,13,13,14,14,14,15,15,15,
  152159. };
  152160. static float _vq_quantthresh__44u9_p7_0[] = {
  152161. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152162. 27.5, 38.5, 49.5, 60.5,
  152163. };
  152164. static long _vq_quantmap__44u9_p7_0[] = {
  152165. 11, 9, 7, 5, 3, 1, 0, 2,
  152166. 4, 6, 8, 10, 12,
  152167. };
  152168. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152169. _vq_quantthresh__44u9_p7_0,
  152170. _vq_quantmap__44u9_p7_0,
  152171. 13,
  152172. 13
  152173. };
  152174. static static_codebook _44u9_p7_0 = {
  152175. 2, 169,
  152176. _vq_lengthlist__44u9_p7_0,
  152177. 1, -523206656, 1618345984, 4, 0,
  152178. _vq_quantlist__44u9_p7_0,
  152179. NULL,
  152180. &_vq_auxt__44u9_p7_0,
  152181. NULL,
  152182. 0
  152183. };
  152184. static long _vq_quantlist__44u9_p7_1[] = {
  152185. 5,
  152186. 4,
  152187. 6,
  152188. 3,
  152189. 7,
  152190. 2,
  152191. 8,
  152192. 1,
  152193. 9,
  152194. 0,
  152195. 10,
  152196. };
  152197. static long _vq_lengthlist__44u9_p7_1[] = {
  152198. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152199. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152200. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152201. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152202. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152203. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152204. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152205. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152206. };
  152207. static float _vq_quantthresh__44u9_p7_1[] = {
  152208. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152209. 3.5, 4.5,
  152210. };
  152211. static long _vq_quantmap__44u9_p7_1[] = {
  152212. 9, 7, 5, 3, 1, 0, 2, 4,
  152213. 6, 8, 10,
  152214. };
  152215. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152216. _vq_quantthresh__44u9_p7_1,
  152217. _vq_quantmap__44u9_p7_1,
  152218. 11,
  152219. 11
  152220. };
  152221. static static_codebook _44u9_p7_1 = {
  152222. 2, 121,
  152223. _vq_lengthlist__44u9_p7_1,
  152224. 1, -531365888, 1611661312, 4, 0,
  152225. _vq_quantlist__44u9_p7_1,
  152226. NULL,
  152227. &_vq_auxt__44u9_p7_1,
  152228. NULL,
  152229. 0
  152230. };
  152231. static long _vq_quantlist__44u9_p8_0[] = {
  152232. 7,
  152233. 6,
  152234. 8,
  152235. 5,
  152236. 9,
  152237. 4,
  152238. 10,
  152239. 3,
  152240. 11,
  152241. 2,
  152242. 12,
  152243. 1,
  152244. 13,
  152245. 0,
  152246. 14,
  152247. };
  152248. static long _vq_lengthlist__44u9_p8_0[] = {
  152249. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152250. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152251. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152252. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152253. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152254. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152255. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152256. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152257. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152258. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152259. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152260. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152261. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152262. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152263. 15,
  152264. };
  152265. static float _vq_quantthresh__44u9_p8_0[] = {
  152266. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152267. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152268. };
  152269. static long _vq_quantmap__44u9_p8_0[] = {
  152270. 13, 11, 9, 7, 5, 3, 1, 0,
  152271. 2, 4, 6, 8, 10, 12, 14,
  152272. };
  152273. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152274. _vq_quantthresh__44u9_p8_0,
  152275. _vq_quantmap__44u9_p8_0,
  152276. 15,
  152277. 15
  152278. };
  152279. static static_codebook _44u9_p8_0 = {
  152280. 2, 225,
  152281. _vq_lengthlist__44u9_p8_0,
  152282. 1, -520986624, 1620377600, 4, 0,
  152283. _vq_quantlist__44u9_p8_0,
  152284. NULL,
  152285. &_vq_auxt__44u9_p8_0,
  152286. NULL,
  152287. 0
  152288. };
  152289. static long _vq_quantlist__44u9_p8_1[] = {
  152290. 10,
  152291. 9,
  152292. 11,
  152293. 8,
  152294. 12,
  152295. 7,
  152296. 13,
  152297. 6,
  152298. 14,
  152299. 5,
  152300. 15,
  152301. 4,
  152302. 16,
  152303. 3,
  152304. 17,
  152305. 2,
  152306. 18,
  152307. 1,
  152308. 19,
  152309. 0,
  152310. 20,
  152311. };
  152312. static long _vq_lengthlist__44u9_p8_1[] = {
  152313. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152314. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152315. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152316. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152317. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152318. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152319. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152320. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152321. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152322. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152323. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152324. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152325. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152326. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152327. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152328. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152329. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152330. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152331. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152332. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152333. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152334. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152335. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152336. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152337. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152338. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152339. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152340. 10,10,10,10,10,10,10,10,10,
  152341. };
  152342. static float _vq_quantthresh__44u9_p8_1[] = {
  152343. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152344. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152345. 6.5, 7.5, 8.5, 9.5,
  152346. };
  152347. static long _vq_quantmap__44u9_p8_1[] = {
  152348. 19, 17, 15, 13, 11, 9, 7, 5,
  152349. 3, 1, 0, 2, 4, 6, 8, 10,
  152350. 12, 14, 16, 18, 20,
  152351. };
  152352. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152353. _vq_quantthresh__44u9_p8_1,
  152354. _vq_quantmap__44u9_p8_1,
  152355. 21,
  152356. 21
  152357. };
  152358. static static_codebook _44u9_p8_1 = {
  152359. 2, 441,
  152360. _vq_lengthlist__44u9_p8_1,
  152361. 1, -529268736, 1611661312, 5, 0,
  152362. _vq_quantlist__44u9_p8_1,
  152363. NULL,
  152364. &_vq_auxt__44u9_p8_1,
  152365. NULL,
  152366. 0
  152367. };
  152368. static long _vq_quantlist__44u9_p9_0[] = {
  152369. 7,
  152370. 6,
  152371. 8,
  152372. 5,
  152373. 9,
  152374. 4,
  152375. 10,
  152376. 3,
  152377. 11,
  152378. 2,
  152379. 12,
  152380. 1,
  152381. 13,
  152382. 0,
  152383. 14,
  152384. };
  152385. static long _vq_lengthlist__44u9_p9_0[] = {
  152386. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152387. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152388. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152394. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152395. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152396. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152397. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152398. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152399. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152400. 10,
  152401. };
  152402. static float _vq_quantthresh__44u9_p9_0[] = {
  152403. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152404. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152405. };
  152406. static long _vq_quantmap__44u9_p9_0[] = {
  152407. 13, 11, 9, 7, 5, 3, 1, 0,
  152408. 2, 4, 6, 8, 10, 12, 14,
  152409. };
  152410. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152411. _vq_quantthresh__44u9_p9_0,
  152412. _vq_quantmap__44u9_p9_0,
  152413. 15,
  152414. 15
  152415. };
  152416. static static_codebook _44u9_p9_0 = {
  152417. 2, 225,
  152418. _vq_lengthlist__44u9_p9_0,
  152419. 1, -510036736, 1631393792, 4, 0,
  152420. _vq_quantlist__44u9_p9_0,
  152421. NULL,
  152422. &_vq_auxt__44u9_p9_0,
  152423. NULL,
  152424. 0
  152425. };
  152426. static long _vq_quantlist__44u9_p9_1[] = {
  152427. 9,
  152428. 8,
  152429. 10,
  152430. 7,
  152431. 11,
  152432. 6,
  152433. 12,
  152434. 5,
  152435. 13,
  152436. 4,
  152437. 14,
  152438. 3,
  152439. 15,
  152440. 2,
  152441. 16,
  152442. 1,
  152443. 17,
  152444. 0,
  152445. 18,
  152446. };
  152447. static long _vq_lengthlist__44u9_p9_1[] = {
  152448. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152449. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152450. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152451. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152452. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152453. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152454. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152455. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152456. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152457. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152458. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152459. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152460. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152461. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152462. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152463. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152464. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152465. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152466. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152467. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152468. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152469. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152470. 17,17,15,17,15,17,16,16,17,
  152471. };
  152472. static float _vq_quantthresh__44u9_p9_1[] = {
  152473. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152474. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152475. 367.5, 416.5,
  152476. };
  152477. static long _vq_quantmap__44u9_p9_1[] = {
  152478. 17, 15, 13, 11, 9, 7, 5, 3,
  152479. 1, 0, 2, 4, 6, 8, 10, 12,
  152480. 14, 16, 18,
  152481. };
  152482. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152483. _vq_quantthresh__44u9_p9_1,
  152484. _vq_quantmap__44u9_p9_1,
  152485. 19,
  152486. 19
  152487. };
  152488. static static_codebook _44u9_p9_1 = {
  152489. 2, 361,
  152490. _vq_lengthlist__44u9_p9_1,
  152491. 1, -518287360, 1622704128, 5, 0,
  152492. _vq_quantlist__44u9_p9_1,
  152493. NULL,
  152494. &_vq_auxt__44u9_p9_1,
  152495. NULL,
  152496. 0
  152497. };
  152498. static long _vq_quantlist__44u9_p9_2[] = {
  152499. 24,
  152500. 23,
  152501. 25,
  152502. 22,
  152503. 26,
  152504. 21,
  152505. 27,
  152506. 20,
  152507. 28,
  152508. 19,
  152509. 29,
  152510. 18,
  152511. 30,
  152512. 17,
  152513. 31,
  152514. 16,
  152515. 32,
  152516. 15,
  152517. 33,
  152518. 14,
  152519. 34,
  152520. 13,
  152521. 35,
  152522. 12,
  152523. 36,
  152524. 11,
  152525. 37,
  152526. 10,
  152527. 38,
  152528. 9,
  152529. 39,
  152530. 8,
  152531. 40,
  152532. 7,
  152533. 41,
  152534. 6,
  152535. 42,
  152536. 5,
  152537. 43,
  152538. 4,
  152539. 44,
  152540. 3,
  152541. 45,
  152542. 2,
  152543. 46,
  152544. 1,
  152545. 47,
  152546. 0,
  152547. 48,
  152548. };
  152549. static long _vq_lengthlist__44u9_p9_2[] = {
  152550. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152551. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152552. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152553. 7,
  152554. };
  152555. static float _vq_quantthresh__44u9_p9_2[] = {
  152556. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152557. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152558. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152559. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152560. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152561. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152562. };
  152563. static long _vq_quantmap__44u9_p9_2[] = {
  152564. 47, 45, 43, 41, 39, 37, 35, 33,
  152565. 31, 29, 27, 25, 23, 21, 19, 17,
  152566. 15, 13, 11, 9, 7, 5, 3, 1,
  152567. 0, 2, 4, 6, 8, 10, 12, 14,
  152568. 16, 18, 20, 22, 24, 26, 28, 30,
  152569. 32, 34, 36, 38, 40, 42, 44, 46,
  152570. 48,
  152571. };
  152572. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152573. _vq_quantthresh__44u9_p9_2,
  152574. _vq_quantmap__44u9_p9_2,
  152575. 49,
  152576. 49
  152577. };
  152578. static static_codebook _44u9_p9_2 = {
  152579. 1, 49,
  152580. _vq_lengthlist__44u9_p9_2,
  152581. 1, -526909440, 1611661312, 6, 0,
  152582. _vq_quantlist__44u9_p9_2,
  152583. NULL,
  152584. &_vq_auxt__44u9_p9_2,
  152585. NULL,
  152586. 0
  152587. };
  152588. static long _huff_lengthlist__44un1__long[] = {
  152589. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152590. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152591. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152592. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152593. };
  152594. static static_codebook _huff_book__44un1__long = {
  152595. 2, 64,
  152596. _huff_lengthlist__44un1__long,
  152597. 0, 0, 0, 0, 0,
  152598. NULL,
  152599. NULL,
  152600. NULL,
  152601. NULL,
  152602. 0
  152603. };
  152604. static long _vq_quantlist__44un1__p1_0[] = {
  152605. 1,
  152606. 0,
  152607. 2,
  152608. };
  152609. static long _vq_lengthlist__44un1__p1_0[] = {
  152610. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152611. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152612. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152613. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152614. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152615. 12,
  152616. };
  152617. static float _vq_quantthresh__44un1__p1_0[] = {
  152618. -0.5, 0.5,
  152619. };
  152620. static long _vq_quantmap__44un1__p1_0[] = {
  152621. 1, 0, 2,
  152622. };
  152623. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152624. _vq_quantthresh__44un1__p1_0,
  152625. _vq_quantmap__44un1__p1_0,
  152626. 3,
  152627. 3
  152628. };
  152629. static static_codebook _44un1__p1_0 = {
  152630. 4, 81,
  152631. _vq_lengthlist__44un1__p1_0,
  152632. 1, -535822336, 1611661312, 2, 0,
  152633. _vq_quantlist__44un1__p1_0,
  152634. NULL,
  152635. &_vq_auxt__44un1__p1_0,
  152636. NULL,
  152637. 0
  152638. };
  152639. static long _vq_quantlist__44un1__p2_0[] = {
  152640. 1,
  152641. 0,
  152642. 2,
  152643. };
  152644. static long _vq_lengthlist__44un1__p2_0[] = {
  152645. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152646. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152647. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152648. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152649. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152650. 8,
  152651. };
  152652. static float _vq_quantthresh__44un1__p2_0[] = {
  152653. -0.5, 0.5,
  152654. };
  152655. static long _vq_quantmap__44un1__p2_0[] = {
  152656. 1, 0, 2,
  152657. };
  152658. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152659. _vq_quantthresh__44un1__p2_0,
  152660. _vq_quantmap__44un1__p2_0,
  152661. 3,
  152662. 3
  152663. };
  152664. static static_codebook _44un1__p2_0 = {
  152665. 4, 81,
  152666. _vq_lengthlist__44un1__p2_0,
  152667. 1, -535822336, 1611661312, 2, 0,
  152668. _vq_quantlist__44un1__p2_0,
  152669. NULL,
  152670. &_vq_auxt__44un1__p2_0,
  152671. NULL,
  152672. 0
  152673. };
  152674. static long _vq_quantlist__44un1__p3_0[] = {
  152675. 2,
  152676. 1,
  152677. 3,
  152678. 0,
  152679. 4,
  152680. };
  152681. static long _vq_lengthlist__44un1__p3_0[] = {
  152682. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152683. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152684. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152685. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152686. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152687. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152688. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152689. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152690. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152691. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152692. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152693. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152694. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152695. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152696. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152697. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152698. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152699. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152700. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152701. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152702. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152703. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152704. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152705. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152706. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152707. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152708. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152709. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152710. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152711. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152712. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152713. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152714. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152715. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152716. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152717. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152718. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152719. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152720. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152721. 17,
  152722. };
  152723. static float _vq_quantthresh__44un1__p3_0[] = {
  152724. -1.5, -0.5, 0.5, 1.5,
  152725. };
  152726. static long _vq_quantmap__44un1__p3_0[] = {
  152727. 3, 1, 0, 2, 4,
  152728. };
  152729. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152730. _vq_quantthresh__44un1__p3_0,
  152731. _vq_quantmap__44un1__p3_0,
  152732. 5,
  152733. 5
  152734. };
  152735. static static_codebook _44un1__p3_0 = {
  152736. 4, 625,
  152737. _vq_lengthlist__44un1__p3_0,
  152738. 1, -533725184, 1611661312, 3, 0,
  152739. _vq_quantlist__44un1__p3_0,
  152740. NULL,
  152741. &_vq_auxt__44un1__p3_0,
  152742. NULL,
  152743. 0
  152744. };
  152745. static long _vq_quantlist__44un1__p4_0[] = {
  152746. 2,
  152747. 1,
  152748. 3,
  152749. 0,
  152750. 4,
  152751. };
  152752. static long _vq_lengthlist__44un1__p4_0[] = {
  152753. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152754. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152755. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152756. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152757. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152758. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152759. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152760. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152761. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152762. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152763. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152764. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152765. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152766. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152767. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152768. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152769. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152770. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152771. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152772. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152773. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152774. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152775. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152776. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152777. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152778. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152779. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152780. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152781. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152782. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152783. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152784. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152785. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152786. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152787. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152788. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152789. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152790. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152791. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152792. 12,
  152793. };
  152794. static float _vq_quantthresh__44un1__p4_0[] = {
  152795. -1.5, -0.5, 0.5, 1.5,
  152796. };
  152797. static long _vq_quantmap__44un1__p4_0[] = {
  152798. 3, 1, 0, 2, 4,
  152799. };
  152800. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152801. _vq_quantthresh__44un1__p4_0,
  152802. _vq_quantmap__44un1__p4_0,
  152803. 5,
  152804. 5
  152805. };
  152806. static static_codebook _44un1__p4_0 = {
  152807. 4, 625,
  152808. _vq_lengthlist__44un1__p4_0,
  152809. 1, -533725184, 1611661312, 3, 0,
  152810. _vq_quantlist__44un1__p4_0,
  152811. NULL,
  152812. &_vq_auxt__44un1__p4_0,
  152813. NULL,
  152814. 0
  152815. };
  152816. static long _vq_quantlist__44un1__p5_0[] = {
  152817. 4,
  152818. 3,
  152819. 5,
  152820. 2,
  152821. 6,
  152822. 1,
  152823. 7,
  152824. 0,
  152825. 8,
  152826. };
  152827. static long _vq_lengthlist__44un1__p5_0[] = {
  152828. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152829. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152830. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152831. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152832. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152833. 12,
  152834. };
  152835. static float _vq_quantthresh__44un1__p5_0[] = {
  152836. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152837. };
  152838. static long _vq_quantmap__44un1__p5_0[] = {
  152839. 7, 5, 3, 1, 0, 2, 4, 6,
  152840. 8,
  152841. };
  152842. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152843. _vq_quantthresh__44un1__p5_0,
  152844. _vq_quantmap__44un1__p5_0,
  152845. 9,
  152846. 9
  152847. };
  152848. static static_codebook _44un1__p5_0 = {
  152849. 2, 81,
  152850. _vq_lengthlist__44un1__p5_0,
  152851. 1, -531628032, 1611661312, 4, 0,
  152852. _vq_quantlist__44un1__p5_0,
  152853. NULL,
  152854. &_vq_auxt__44un1__p5_0,
  152855. NULL,
  152856. 0
  152857. };
  152858. static long _vq_quantlist__44un1__p6_0[] = {
  152859. 6,
  152860. 5,
  152861. 7,
  152862. 4,
  152863. 8,
  152864. 3,
  152865. 9,
  152866. 2,
  152867. 10,
  152868. 1,
  152869. 11,
  152870. 0,
  152871. 12,
  152872. };
  152873. static long _vq_lengthlist__44un1__p6_0[] = {
  152874. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152875. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152876. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152877. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152878. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152879. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152880. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152881. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152882. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152883. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152884. 16, 0,15,18,18, 0,16, 0, 0,
  152885. };
  152886. static float _vq_quantthresh__44un1__p6_0[] = {
  152887. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152888. 12.5, 17.5, 22.5, 27.5,
  152889. };
  152890. static long _vq_quantmap__44un1__p6_0[] = {
  152891. 11, 9, 7, 5, 3, 1, 0, 2,
  152892. 4, 6, 8, 10, 12,
  152893. };
  152894. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152895. _vq_quantthresh__44un1__p6_0,
  152896. _vq_quantmap__44un1__p6_0,
  152897. 13,
  152898. 13
  152899. };
  152900. static static_codebook _44un1__p6_0 = {
  152901. 2, 169,
  152902. _vq_lengthlist__44un1__p6_0,
  152903. 1, -526516224, 1616117760, 4, 0,
  152904. _vq_quantlist__44un1__p6_0,
  152905. NULL,
  152906. &_vq_auxt__44un1__p6_0,
  152907. NULL,
  152908. 0
  152909. };
  152910. static long _vq_quantlist__44un1__p6_1[] = {
  152911. 2,
  152912. 1,
  152913. 3,
  152914. 0,
  152915. 4,
  152916. };
  152917. static long _vq_lengthlist__44un1__p6_1[] = {
  152918. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152919. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152920. };
  152921. static float _vq_quantthresh__44un1__p6_1[] = {
  152922. -1.5, -0.5, 0.5, 1.5,
  152923. };
  152924. static long _vq_quantmap__44un1__p6_1[] = {
  152925. 3, 1, 0, 2, 4,
  152926. };
  152927. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152928. _vq_quantthresh__44un1__p6_1,
  152929. _vq_quantmap__44un1__p6_1,
  152930. 5,
  152931. 5
  152932. };
  152933. static static_codebook _44un1__p6_1 = {
  152934. 2, 25,
  152935. _vq_lengthlist__44un1__p6_1,
  152936. 1, -533725184, 1611661312, 3, 0,
  152937. _vq_quantlist__44un1__p6_1,
  152938. NULL,
  152939. &_vq_auxt__44un1__p6_1,
  152940. NULL,
  152941. 0
  152942. };
  152943. static long _vq_quantlist__44un1__p7_0[] = {
  152944. 2,
  152945. 1,
  152946. 3,
  152947. 0,
  152948. 4,
  152949. };
  152950. static long _vq_lengthlist__44un1__p7_0[] = {
  152951. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152952. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152954. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152958. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152959. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152960. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152961. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152962. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152963. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152964. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152965. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152966. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152967. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152968. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152969. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152970. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152971. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152972. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152973. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152974. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152975. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152976. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152977. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152978. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152979. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152980. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152981. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152982. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152983. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152984. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152985. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152986. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152987. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152988. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152989. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152990. 10,
  152991. };
  152992. static float _vq_quantthresh__44un1__p7_0[] = {
  152993. -253.5, -84.5, 84.5, 253.5,
  152994. };
  152995. static long _vq_quantmap__44un1__p7_0[] = {
  152996. 3, 1, 0, 2, 4,
  152997. };
  152998. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152999. _vq_quantthresh__44un1__p7_0,
  153000. _vq_quantmap__44un1__p7_0,
  153001. 5,
  153002. 5
  153003. };
  153004. static static_codebook _44un1__p7_0 = {
  153005. 4, 625,
  153006. _vq_lengthlist__44un1__p7_0,
  153007. 1, -518709248, 1626677248, 3, 0,
  153008. _vq_quantlist__44un1__p7_0,
  153009. NULL,
  153010. &_vq_auxt__44un1__p7_0,
  153011. NULL,
  153012. 0
  153013. };
  153014. static long _vq_quantlist__44un1__p7_1[] = {
  153015. 6,
  153016. 5,
  153017. 7,
  153018. 4,
  153019. 8,
  153020. 3,
  153021. 9,
  153022. 2,
  153023. 10,
  153024. 1,
  153025. 11,
  153026. 0,
  153027. 12,
  153028. };
  153029. static long _vq_lengthlist__44un1__p7_1[] = {
  153030. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153031. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153032. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153033. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153034. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153035. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153036. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153037. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153038. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153039. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153040. 12,13,13,12,13,13,14,14,14,
  153041. };
  153042. static float _vq_quantthresh__44un1__p7_1[] = {
  153043. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153044. 32.5, 45.5, 58.5, 71.5,
  153045. };
  153046. static long _vq_quantmap__44un1__p7_1[] = {
  153047. 11, 9, 7, 5, 3, 1, 0, 2,
  153048. 4, 6, 8, 10, 12,
  153049. };
  153050. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153051. _vq_quantthresh__44un1__p7_1,
  153052. _vq_quantmap__44un1__p7_1,
  153053. 13,
  153054. 13
  153055. };
  153056. static static_codebook _44un1__p7_1 = {
  153057. 2, 169,
  153058. _vq_lengthlist__44un1__p7_1,
  153059. 1, -523010048, 1618608128, 4, 0,
  153060. _vq_quantlist__44un1__p7_1,
  153061. NULL,
  153062. &_vq_auxt__44un1__p7_1,
  153063. NULL,
  153064. 0
  153065. };
  153066. static long _vq_quantlist__44un1__p7_2[] = {
  153067. 6,
  153068. 5,
  153069. 7,
  153070. 4,
  153071. 8,
  153072. 3,
  153073. 9,
  153074. 2,
  153075. 10,
  153076. 1,
  153077. 11,
  153078. 0,
  153079. 12,
  153080. };
  153081. static long _vq_lengthlist__44un1__p7_2[] = {
  153082. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153083. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153084. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153085. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153086. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153087. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153088. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153089. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153090. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153091. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153092. 9, 9, 9,10,10,10,10,10,10,
  153093. };
  153094. static float _vq_quantthresh__44un1__p7_2[] = {
  153095. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153096. 2.5, 3.5, 4.5, 5.5,
  153097. };
  153098. static long _vq_quantmap__44un1__p7_2[] = {
  153099. 11, 9, 7, 5, 3, 1, 0, 2,
  153100. 4, 6, 8, 10, 12,
  153101. };
  153102. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153103. _vq_quantthresh__44un1__p7_2,
  153104. _vq_quantmap__44un1__p7_2,
  153105. 13,
  153106. 13
  153107. };
  153108. static static_codebook _44un1__p7_2 = {
  153109. 2, 169,
  153110. _vq_lengthlist__44un1__p7_2,
  153111. 1, -531103744, 1611661312, 4, 0,
  153112. _vq_quantlist__44un1__p7_2,
  153113. NULL,
  153114. &_vq_auxt__44un1__p7_2,
  153115. NULL,
  153116. 0
  153117. };
  153118. static long _huff_lengthlist__44un1__short[] = {
  153119. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153120. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153121. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153122. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153123. };
  153124. static static_codebook _huff_book__44un1__short = {
  153125. 2, 64,
  153126. _huff_lengthlist__44un1__short,
  153127. 0, 0, 0, 0, 0,
  153128. NULL,
  153129. NULL,
  153130. NULL,
  153131. NULL,
  153132. 0
  153133. };
  153134. /*** End of inlined file: res_books_uncoupled.h ***/
  153135. /***** residue backends *********************************************/
  153136. static vorbis_info_residue0 _residue_44_low_un={
  153137. 0,-1, -1, 8,-1,
  153138. {0},
  153139. {-1},
  153140. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153141. { -1, 25, -1, 45, -1, -1, -1}
  153142. };
  153143. static vorbis_info_residue0 _residue_44_mid_un={
  153144. 0,-1, -1, 10,-1,
  153145. /* 0 1 2 3 4 5 6 7 8 9 */
  153146. {0},
  153147. {-1},
  153148. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153149. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153150. };
  153151. static vorbis_info_residue0 _residue_44_hi_un={
  153152. 0,-1, -1, 10,-1,
  153153. /* 0 1 2 3 4 5 6 7 8 9 */
  153154. {0},
  153155. {-1},
  153156. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153157. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153158. };
  153159. /* mapping conventions:
  153160. only one submap (this would change for efficient 5.1 support for example)*/
  153161. /* Four psychoacoustic profiles are used, one for each blocktype */
  153162. static vorbis_info_mapping0 _map_nominal_u[2]={
  153163. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153164. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153165. };
  153166. static static_bookblock _resbook_44u_n1={
  153167. {
  153168. {0},
  153169. {0,0,&_44un1__p1_0},
  153170. {0,0,&_44un1__p2_0},
  153171. {0,0,&_44un1__p3_0},
  153172. {0,0,&_44un1__p4_0},
  153173. {0,0,&_44un1__p5_0},
  153174. {&_44un1__p6_0,&_44un1__p6_1},
  153175. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153176. }
  153177. };
  153178. static static_bookblock _resbook_44u_0={
  153179. {
  153180. {0},
  153181. {0,0,&_44u0__p1_0},
  153182. {0,0,&_44u0__p2_0},
  153183. {0,0,&_44u0__p3_0},
  153184. {0,0,&_44u0__p4_0},
  153185. {0,0,&_44u0__p5_0},
  153186. {&_44u0__p6_0,&_44u0__p6_1},
  153187. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153188. }
  153189. };
  153190. static static_bookblock _resbook_44u_1={
  153191. {
  153192. {0},
  153193. {0,0,&_44u1__p1_0},
  153194. {0,0,&_44u1__p2_0},
  153195. {0,0,&_44u1__p3_0},
  153196. {0,0,&_44u1__p4_0},
  153197. {0,0,&_44u1__p5_0},
  153198. {&_44u1__p6_0,&_44u1__p6_1},
  153199. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153200. }
  153201. };
  153202. static static_bookblock _resbook_44u_2={
  153203. {
  153204. {0},
  153205. {0,0,&_44u2__p1_0},
  153206. {0,0,&_44u2__p2_0},
  153207. {0,0,&_44u2__p3_0},
  153208. {0,0,&_44u2__p4_0},
  153209. {0,0,&_44u2__p5_0},
  153210. {&_44u2__p6_0,&_44u2__p6_1},
  153211. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153212. }
  153213. };
  153214. static static_bookblock _resbook_44u_3={
  153215. {
  153216. {0},
  153217. {0,0,&_44u3__p1_0},
  153218. {0,0,&_44u3__p2_0},
  153219. {0,0,&_44u3__p3_0},
  153220. {0,0,&_44u3__p4_0},
  153221. {0,0,&_44u3__p5_0},
  153222. {&_44u3__p6_0,&_44u3__p6_1},
  153223. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153224. }
  153225. };
  153226. static static_bookblock _resbook_44u_4={
  153227. {
  153228. {0},
  153229. {0,0,&_44u4__p1_0},
  153230. {0,0,&_44u4__p2_0},
  153231. {0,0,&_44u4__p3_0},
  153232. {0,0,&_44u4__p4_0},
  153233. {0,0,&_44u4__p5_0},
  153234. {&_44u4__p6_0,&_44u4__p6_1},
  153235. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153236. }
  153237. };
  153238. static static_bookblock _resbook_44u_5={
  153239. {
  153240. {0},
  153241. {0,0,&_44u5__p1_0},
  153242. {0,0,&_44u5__p2_0},
  153243. {0,0,&_44u5__p3_0},
  153244. {0,0,&_44u5__p4_0},
  153245. {0,0,&_44u5__p5_0},
  153246. {0,0,&_44u5__p6_0},
  153247. {&_44u5__p7_0,&_44u5__p7_1},
  153248. {&_44u5__p8_0,&_44u5__p8_1},
  153249. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153250. }
  153251. };
  153252. static static_bookblock _resbook_44u_6={
  153253. {
  153254. {0},
  153255. {0,0,&_44u6__p1_0},
  153256. {0,0,&_44u6__p2_0},
  153257. {0,0,&_44u6__p3_0},
  153258. {0,0,&_44u6__p4_0},
  153259. {0,0,&_44u6__p5_0},
  153260. {0,0,&_44u6__p6_0},
  153261. {&_44u6__p7_0,&_44u6__p7_1},
  153262. {&_44u6__p8_0,&_44u6__p8_1},
  153263. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153264. }
  153265. };
  153266. static static_bookblock _resbook_44u_7={
  153267. {
  153268. {0},
  153269. {0,0,&_44u7__p1_0},
  153270. {0,0,&_44u7__p2_0},
  153271. {0,0,&_44u7__p3_0},
  153272. {0,0,&_44u7__p4_0},
  153273. {0,0,&_44u7__p5_0},
  153274. {0,0,&_44u7__p6_0},
  153275. {&_44u7__p7_0,&_44u7__p7_1},
  153276. {&_44u7__p8_0,&_44u7__p8_1},
  153277. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153278. }
  153279. };
  153280. static static_bookblock _resbook_44u_8={
  153281. {
  153282. {0},
  153283. {0,0,&_44u8_p1_0},
  153284. {0,0,&_44u8_p2_0},
  153285. {0,0,&_44u8_p3_0},
  153286. {0,0,&_44u8_p4_0},
  153287. {&_44u8_p5_0,&_44u8_p5_1},
  153288. {&_44u8_p6_0,&_44u8_p6_1},
  153289. {&_44u8_p7_0,&_44u8_p7_1},
  153290. {&_44u8_p8_0,&_44u8_p8_1},
  153291. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153292. }
  153293. };
  153294. static static_bookblock _resbook_44u_9={
  153295. {
  153296. {0},
  153297. {0,0,&_44u9_p1_0},
  153298. {0,0,&_44u9_p2_0},
  153299. {0,0,&_44u9_p3_0},
  153300. {0,0,&_44u9_p4_0},
  153301. {&_44u9_p5_0,&_44u9_p5_1},
  153302. {&_44u9_p6_0,&_44u9_p6_1},
  153303. {&_44u9_p7_0,&_44u9_p7_1},
  153304. {&_44u9_p8_0,&_44u9_p8_1},
  153305. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153306. }
  153307. };
  153308. static vorbis_residue_template _res_44u_n1[]={
  153309. {1,0, &_residue_44_low_un,
  153310. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153311. &_resbook_44u_n1,&_resbook_44u_n1},
  153312. {1,0, &_residue_44_low_un,
  153313. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153314. &_resbook_44u_n1,&_resbook_44u_n1}
  153315. };
  153316. static vorbis_residue_template _res_44u_0[]={
  153317. {1,0, &_residue_44_low_un,
  153318. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153319. &_resbook_44u_0,&_resbook_44u_0},
  153320. {1,0, &_residue_44_low_un,
  153321. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153322. &_resbook_44u_0,&_resbook_44u_0}
  153323. };
  153324. static vorbis_residue_template _res_44u_1[]={
  153325. {1,0, &_residue_44_low_un,
  153326. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153327. &_resbook_44u_1,&_resbook_44u_1},
  153328. {1,0, &_residue_44_low_un,
  153329. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153330. &_resbook_44u_1,&_resbook_44u_1}
  153331. };
  153332. static vorbis_residue_template _res_44u_2[]={
  153333. {1,0, &_residue_44_low_un,
  153334. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153335. &_resbook_44u_2,&_resbook_44u_2},
  153336. {1,0, &_residue_44_low_un,
  153337. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153338. &_resbook_44u_2,&_resbook_44u_2}
  153339. };
  153340. static vorbis_residue_template _res_44u_3[]={
  153341. {1,0, &_residue_44_low_un,
  153342. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153343. &_resbook_44u_3,&_resbook_44u_3},
  153344. {1,0, &_residue_44_low_un,
  153345. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153346. &_resbook_44u_3,&_resbook_44u_3}
  153347. };
  153348. static vorbis_residue_template _res_44u_4[]={
  153349. {1,0, &_residue_44_low_un,
  153350. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153351. &_resbook_44u_4,&_resbook_44u_4},
  153352. {1,0, &_residue_44_low_un,
  153353. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153354. &_resbook_44u_4,&_resbook_44u_4}
  153355. };
  153356. static vorbis_residue_template _res_44u_5[]={
  153357. {1,0, &_residue_44_mid_un,
  153358. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153359. &_resbook_44u_5,&_resbook_44u_5},
  153360. {1,0, &_residue_44_mid_un,
  153361. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153362. &_resbook_44u_5,&_resbook_44u_5}
  153363. };
  153364. static vorbis_residue_template _res_44u_6[]={
  153365. {1,0, &_residue_44_mid_un,
  153366. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153367. &_resbook_44u_6,&_resbook_44u_6},
  153368. {1,0, &_residue_44_mid_un,
  153369. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153370. &_resbook_44u_6,&_resbook_44u_6}
  153371. };
  153372. static vorbis_residue_template _res_44u_7[]={
  153373. {1,0, &_residue_44_mid_un,
  153374. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153375. &_resbook_44u_7,&_resbook_44u_7},
  153376. {1,0, &_residue_44_mid_un,
  153377. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153378. &_resbook_44u_7,&_resbook_44u_7}
  153379. };
  153380. static vorbis_residue_template _res_44u_8[]={
  153381. {1,0, &_residue_44_hi_un,
  153382. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153383. &_resbook_44u_8,&_resbook_44u_8},
  153384. {1,0, &_residue_44_hi_un,
  153385. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153386. &_resbook_44u_8,&_resbook_44u_8}
  153387. };
  153388. static vorbis_residue_template _res_44u_9[]={
  153389. {1,0, &_residue_44_hi_un,
  153390. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153391. &_resbook_44u_9,&_resbook_44u_9},
  153392. {1,0, &_residue_44_hi_un,
  153393. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153394. &_resbook_44u_9,&_resbook_44u_9}
  153395. };
  153396. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153397. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153398. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153399. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153400. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153401. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153402. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153403. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153404. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153405. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153406. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153407. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153408. };
  153409. /*** End of inlined file: residue_44u.h ***/
  153410. static double rate_mapping_44_un[12]={
  153411. 32000.,48000.,60000.,70000.,80000.,86000.,
  153412. 96000.,110000.,120000.,140000.,160000.,240001.
  153413. };
  153414. ve_setup_data_template ve_setup_44_uncoupled={
  153415. 11,
  153416. rate_mapping_44_un,
  153417. quality_mapping_44,
  153418. -1,
  153419. 40000,
  153420. 50000,
  153421. blocksize_short_44,
  153422. blocksize_long_44,
  153423. _psy_tone_masteratt_44,
  153424. _psy_tone_0dB,
  153425. _psy_tone_suppress,
  153426. _vp_tonemask_adj_otherblock,
  153427. _vp_tonemask_adj_longblock,
  153428. _vp_tonemask_adj_otherblock,
  153429. _psy_noiseguards_44,
  153430. _psy_noisebias_impulse,
  153431. _psy_noisebias_padding,
  153432. _psy_noisebias_trans,
  153433. _psy_noisebias_long,
  153434. _psy_noise_suppress,
  153435. _psy_compand_44,
  153436. _psy_compand_short_mapping,
  153437. _psy_compand_long_mapping,
  153438. {_noise_start_short_44,_noise_start_long_44},
  153439. {_noise_part_short_44,_noise_part_long_44},
  153440. _noise_thresh_44,
  153441. _psy_ath_floater,
  153442. _psy_ath_abs,
  153443. _psy_lowpass_44,
  153444. _psy_global_44,
  153445. _global_mapping_44,
  153446. NULL,
  153447. _floor_books,
  153448. _floor,
  153449. _floor_short_mapping_44,
  153450. _floor_long_mapping_44,
  153451. _mapres_template_44_uncoupled
  153452. };
  153453. /*** End of inlined file: setup_44u.h ***/
  153454. /*** Start of inlined file: setup_32.h ***/
  153455. static double rate_mapping_32[12]={
  153456. 18000.,28000.,35000.,45000.,56000.,60000.,
  153457. 75000.,90000.,100000.,115000.,150000.,190000.,
  153458. };
  153459. static double rate_mapping_32_un[12]={
  153460. 30000.,42000.,52000.,64000.,72000.,78000.,
  153461. 86000.,92000.,110000.,120000.,140000.,190000.,
  153462. };
  153463. static double _psy_lowpass_32[12]={
  153464. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153465. };
  153466. ve_setup_data_template ve_setup_32_stereo={
  153467. 11,
  153468. rate_mapping_32,
  153469. quality_mapping_44,
  153470. 2,
  153471. 26000,
  153472. 40000,
  153473. blocksize_short_44,
  153474. blocksize_long_44,
  153475. _psy_tone_masteratt_44,
  153476. _psy_tone_0dB,
  153477. _psy_tone_suppress,
  153478. _vp_tonemask_adj_otherblock,
  153479. _vp_tonemask_adj_longblock,
  153480. _vp_tonemask_adj_otherblock,
  153481. _psy_noiseguards_44,
  153482. _psy_noisebias_impulse,
  153483. _psy_noisebias_padding,
  153484. _psy_noisebias_trans,
  153485. _psy_noisebias_long,
  153486. _psy_noise_suppress,
  153487. _psy_compand_44,
  153488. _psy_compand_short_mapping,
  153489. _psy_compand_long_mapping,
  153490. {_noise_start_short_44,_noise_start_long_44},
  153491. {_noise_part_short_44,_noise_part_long_44},
  153492. _noise_thresh_44,
  153493. _psy_ath_floater,
  153494. _psy_ath_abs,
  153495. _psy_lowpass_32,
  153496. _psy_global_44,
  153497. _global_mapping_44,
  153498. _psy_stereo_modes_44,
  153499. _floor_books,
  153500. _floor,
  153501. _floor_short_mapping_44,
  153502. _floor_long_mapping_44,
  153503. _mapres_template_44_stereo
  153504. };
  153505. ve_setup_data_template ve_setup_32_uncoupled={
  153506. 11,
  153507. rate_mapping_32_un,
  153508. quality_mapping_44,
  153509. -1,
  153510. 26000,
  153511. 40000,
  153512. blocksize_short_44,
  153513. blocksize_long_44,
  153514. _psy_tone_masteratt_44,
  153515. _psy_tone_0dB,
  153516. _psy_tone_suppress,
  153517. _vp_tonemask_adj_otherblock,
  153518. _vp_tonemask_adj_longblock,
  153519. _vp_tonemask_adj_otherblock,
  153520. _psy_noiseguards_44,
  153521. _psy_noisebias_impulse,
  153522. _psy_noisebias_padding,
  153523. _psy_noisebias_trans,
  153524. _psy_noisebias_long,
  153525. _psy_noise_suppress,
  153526. _psy_compand_44,
  153527. _psy_compand_short_mapping,
  153528. _psy_compand_long_mapping,
  153529. {_noise_start_short_44,_noise_start_long_44},
  153530. {_noise_part_short_44,_noise_part_long_44},
  153531. _noise_thresh_44,
  153532. _psy_ath_floater,
  153533. _psy_ath_abs,
  153534. _psy_lowpass_32,
  153535. _psy_global_44,
  153536. _global_mapping_44,
  153537. NULL,
  153538. _floor_books,
  153539. _floor,
  153540. _floor_short_mapping_44,
  153541. _floor_long_mapping_44,
  153542. _mapres_template_44_uncoupled
  153543. };
  153544. /*** End of inlined file: setup_32.h ***/
  153545. /*** Start of inlined file: setup_8.h ***/
  153546. /*** Start of inlined file: psych_8.h ***/
  153547. static att3 _psy_tone_masteratt_8[3]={
  153548. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153549. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153550. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153551. };
  153552. static vp_adjblock _vp_tonemask_adj_8[3]={
  153553. /* adjust for mode zero */
  153554. /* 63 125 250 500 1 2 4 8 16 */
  153555. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153556. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153557. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153558. };
  153559. static noise3 _psy_noisebias_8[3]={
  153560. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153561. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153562. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153563. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153564. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153565. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153566. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153567. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153568. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153569. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153570. };
  153571. /* stereo mode by base quality level */
  153572. static adj_stereo _psy_stereo_modes_8[3]={
  153573. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153574. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153575. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153576. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153577. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153578. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153579. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153580. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153581. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153582. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153583. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153584. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153585. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153586. };
  153587. static noiseguard _psy_noiseguards_8[2]={
  153588. {10,10,-1},
  153589. {10,10,-1},
  153590. };
  153591. static compandblock _psy_compand_8[2]={
  153592. {{
  153593. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153594. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153595. 12,12,13,13,14,14,15, 15, /* 23dB */
  153596. 16,16,17,17,17,18,18, 19, /* 31dB */
  153597. 19,19,20,21,22,23,24, 25, /* 39dB */
  153598. }},
  153599. {{
  153600. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153601. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153602. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153603. 9,10,11,12,13,14,15, 16, /* 31dB */
  153604. 17,18,19,20,21,22,23, 24, /* 39dB */
  153605. }},
  153606. };
  153607. static double _psy_lowpass_8[3]={3.,4.,4.};
  153608. static int _noise_start_8[2]={
  153609. 64,64,
  153610. };
  153611. static int _noise_part_8[2]={
  153612. 8,8,
  153613. };
  153614. static int _psy_ath_floater_8[3]={
  153615. -100,-100,-105,
  153616. };
  153617. static int _psy_ath_abs_8[3]={
  153618. -130,-130,-140,
  153619. };
  153620. /*** End of inlined file: psych_8.h ***/
  153621. /*** Start of inlined file: residue_8.h ***/
  153622. /***** residue backends *********************************************/
  153623. static static_bookblock _resbook_8s_0={
  153624. {
  153625. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153626. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153627. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153628. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153629. }
  153630. };
  153631. static static_bookblock _resbook_8s_1={
  153632. {
  153633. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153634. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153635. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153636. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153637. }
  153638. };
  153639. static vorbis_residue_template _res_8s_0[]={
  153640. {2,0, &_residue_44_mid,
  153641. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153642. &_resbook_8s_0,&_resbook_8s_0},
  153643. };
  153644. static vorbis_residue_template _res_8s_1[]={
  153645. {2,0, &_residue_44_mid,
  153646. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153647. &_resbook_8s_1,&_resbook_8s_1},
  153648. };
  153649. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153650. { _map_nominal, _res_8s_0 }, /* 0 */
  153651. { _map_nominal, _res_8s_1 }, /* 1 */
  153652. };
  153653. static static_bookblock _resbook_8u_0={
  153654. {
  153655. {0},
  153656. {0,0,&_8u0__p1_0},
  153657. {0,0,&_8u0__p2_0},
  153658. {0,0,&_8u0__p3_0},
  153659. {0,0,&_8u0__p4_0},
  153660. {0,0,&_8u0__p5_0},
  153661. {&_8u0__p6_0,&_8u0__p6_1},
  153662. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153663. }
  153664. };
  153665. static static_bookblock _resbook_8u_1={
  153666. {
  153667. {0},
  153668. {0,0,&_8u1__p1_0},
  153669. {0,0,&_8u1__p2_0},
  153670. {0,0,&_8u1__p3_0},
  153671. {0,0,&_8u1__p4_0},
  153672. {0,0,&_8u1__p5_0},
  153673. {0,0,&_8u1__p6_0},
  153674. {&_8u1__p7_0,&_8u1__p7_1},
  153675. {&_8u1__p8_0,&_8u1__p8_1},
  153676. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153677. }
  153678. };
  153679. static vorbis_residue_template _res_8u_0[]={
  153680. {1,0, &_residue_44_low_un,
  153681. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153682. &_resbook_8u_0,&_resbook_8u_0},
  153683. };
  153684. static vorbis_residue_template _res_8u_1[]={
  153685. {1,0, &_residue_44_mid_un,
  153686. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153687. &_resbook_8u_1,&_resbook_8u_1},
  153688. };
  153689. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153690. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153691. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153692. };
  153693. /*** End of inlined file: residue_8.h ***/
  153694. static int blocksize_8[2]={
  153695. 512,512
  153696. };
  153697. static int _floor_mapping_8[2]={
  153698. 6,6,
  153699. };
  153700. static double rate_mapping_8[3]={
  153701. 6000.,9000.,32000.,
  153702. };
  153703. static double rate_mapping_8_uncoupled[3]={
  153704. 8000.,14000.,42000.,
  153705. };
  153706. static double quality_mapping_8[3]={
  153707. -.1,.0,1.
  153708. };
  153709. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153710. static double _global_mapping_8[3]={ 1., 2., 3. };
  153711. ve_setup_data_template ve_setup_8_stereo={
  153712. 2,
  153713. rate_mapping_8,
  153714. quality_mapping_8,
  153715. 2,
  153716. 8000,
  153717. 9000,
  153718. blocksize_8,
  153719. blocksize_8,
  153720. _psy_tone_masteratt_8,
  153721. _psy_tone_0dB,
  153722. _psy_tone_suppress,
  153723. _vp_tonemask_adj_8,
  153724. NULL,
  153725. _vp_tonemask_adj_8,
  153726. _psy_noiseguards_8,
  153727. _psy_noisebias_8,
  153728. _psy_noisebias_8,
  153729. NULL,
  153730. NULL,
  153731. _psy_noise_suppress,
  153732. _psy_compand_8,
  153733. _psy_compand_8_mapping,
  153734. NULL,
  153735. {_noise_start_8,_noise_start_8},
  153736. {_noise_part_8,_noise_part_8},
  153737. _noise_thresh_5only,
  153738. _psy_ath_floater_8,
  153739. _psy_ath_abs_8,
  153740. _psy_lowpass_8,
  153741. _psy_global_44,
  153742. _global_mapping_8,
  153743. _psy_stereo_modes_8,
  153744. _floor_books,
  153745. _floor,
  153746. _floor_mapping_8,
  153747. NULL,
  153748. _mapres_template_8_stereo
  153749. };
  153750. ve_setup_data_template ve_setup_8_uncoupled={
  153751. 2,
  153752. rate_mapping_8_uncoupled,
  153753. quality_mapping_8,
  153754. -1,
  153755. 8000,
  153756. 9000,
  153757. blocksize_8,
  153758. blocksize_8,
  153759. _psy_tone_masteratt_8,
  153760. _psy_tone_0dB,
  153761. _psy_tone_suppress,
  153762. _vp_tonemask_adj_8,
  153763. NULL,
  153764. _vp_tonemask_adj_8,
  153765. _psy_noiseguards_8,
  153766. _psy_noisebias_8,
  153767. _psy_noisebias_8,
  153768. NULL,
  153769. NULL,
  153770. _psy_noise_suppress,
  153771. _psy_compand_8,
  153772. _psy_compand_8_mapping,
  153773. NULL,
  153774. {_noise_start_8,_noise_start_8},
  153775. {_noise_part_8,_noise_part_8},
  153776. _noise_thresh_5only,
  153777. _psy_ath_floater_8,
  153778. _psy_ath_abs_8,
  153779. _psy_lowpass_8,
  153780. _psy_global_44,
  153781. _global_mapping_8,
  153782. _psy_stereo_modes_8,
  153783. _floor_books,
  153784. _floor,
  153785. _floor_mapping_8,
  153786. NULL,
  153787. _mapres_template_8_uncoupled
  153788. };
  153789. /*** End of inlined file: setup_8.h ***/
  153790. /*** Start of inlined file: setup_11.h ***/
  153791. /*** Start of inlined file: psych_11.h ***/
  153792. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153793. static att3 _psy_tone_masteratt_11[3]={
  153794. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153795. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153796. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153797. };
  153798. static vp_adjblock _vp_tonemask_adj_11[3]={
  153799. /* adjust for mode zero */
  153800. /* 63 125 250 500 1 2 4 8 16 */
  153801. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153802. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153803. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153804. };
  153805. static noise3 _psy_noisebias_11[3]={
  153806. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153807. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153808. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153809. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153810. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153811. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153812. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153813. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153814. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153815. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153816. };
  153817. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153818. /*** End of inlined file: psych_11.h ***/
  153819. static int blocksize_11[2]={
  153820. 512,512
  153821. };
  153822. static int _floor_mapping_11[2]={
  153823. 6,6,
  153824. };
  153825. static double rate_mapping_11[3]={
  153826. 8000.,13000.,44000.,
  153827. };
  153828. static double rate_mapping_11_uncoupled[3]={
  153829. 12000.,20000.,50000.,
  153830. };
  153831. static double quality_mapping_11[3]={
  153832. -.1,.0,1.
  153833. };
  153834. ve_setup_data_template ve_setup_11_stereo={
  153835. 2,
  153836. rate_mapping_11,
  153837. quality_mapping_11,
  153838. 2,
  153839. 9000,
  153840. 15000,
  153841. blocksize_11,
  153842. blocksize_11,
  153843. _psy_tone_masteratt_11,
  153844. _psy_tone_0dB,
  153845. _psy_tone_suppress,
  153846. _vp_tonemask_adj_11,
  153847. NULL,
  153848. _vp_tonemask_adj_11,
  153849. _psy_noiseguards_8,
  153850. _psy_noisebias_11,
  153851. _psy_noisebias_11,
  153852. NULL,
  153853. NULL,
  153854. _psy_noise_suppress,
  153855. _psy_compand_8,
  153856. _psy_compand_8_mapping,
  153857. NULL,
  153858. {_noise_start_8,_noise_start_8},
  153859. {_noise_part_8,_noise_part_8},
  153860. _noise_thresh_11,
  153861. _psy_ath_floater_8,
  153862. _psy_ath_abs_8,
  153863. _psy_lowpass_11,
  153864. _psy_global_44,
  153865. _global_mapping_8,
  153866. _psy_stereo_modes_8,
  153867. _floor_books,
  153868. _floor,
  153869. _floor_mapping_11,
  153870. NULL,
  153871. _mapres_template_8_stereo
  153872. };
  153873. ve_setup_data_template ve_setup_11_uncoupled={
  153874. 2,
  153875. rate_mapping_11_uncoupled,
  153876. quality_mapping_11,
  153877. -1,
  153878. 9000,
  153879. 15000,
  153880. blocksize_11,
  153881. blocksize_11,
  153882. _psy_tone_masteratt_11,
  153883. _psy_tone_0dB,
  153884. _psy_tone_suppress,
  153885. _vp_tonemask_adj_11,
  153886. NULL,
  153887. _vp_tonemask_adj_11,
  153888. _psy_noiseguards_8,
  153889. _psy_noisebias_11,
  153890. _psy_noisebias_11,
  153891. NULL,
  153892. NULL,
  153893. _psy_noise_suppress,
  153894. _psy_compand_8,
  153895. _psy_compand_8_mapping,
  153896. NULL,
  153897. {_noise_start_8,_noise_start_8},
  153898. {_noise_part_8,_noise_part_8},
  153899. _noise_thresh_11,
  153900. _psy_ath_floater_8,
  153901. _psy_ath_abs_8,
  153902. _psy_lowpass_11,
  153903. _psy_global_44,
  153904. _global_mapping_8,
  153905. _psy_stereo_modes_8,
  153906. _floor_books,
  153907. _floor,
  153908. _floor_mapping_11,
  153909. NULL,
  153910. _mapres_template_8_uncoupled
  153911. };
  153912. /*** End of inlined file: setup_11.h ***/
  153913. /*** Start of inlined file: setup_16.h ***/
  153914. /*** Start of inlined file: psych_16.h ***/
  153915. /* stereo mode by base quality level */
  153916. static adj_stereo _psy_stereo_modes_16[4]={
  153917. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153918. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153919. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153920. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153921. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153922. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153923. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153924. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153925. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153926. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153927. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153928. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153929. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153930. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153931. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153932. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153933. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153934. };
  153935. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153936. static att3 _psy_tone_masteratt_16[4]={
  153937. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153938. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153939. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153940. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153941. };
  153942. static vp_adjblock _vp_tonemask_adj_16[4]={
  153943. /* adjust for mode zero */
  153944. /* 63 125 250 500 1 2 4 8 16 */
  153945. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153946. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153947. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153948. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153949. };
  153950. static noise3 _psy_noisebias_16_short[4]={
  153951. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153952. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153953. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153954. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153955. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153956. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153957. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153958. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153959. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153960. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153961. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153962. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153963. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153964. };
  153965. static noise3 _psy_noisebias_16_impulse[4]={
  153966. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153967. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153968. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153969. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153970. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153971. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153972. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153973. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153974. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153975. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153976. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153977. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153978. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153979. };
  153980. static noise3 _psy_noisebias_16[4]={
  153981. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153982. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153983. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153984. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153985. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153986. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153987. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153988. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153989. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153990. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153991. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153992. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153993. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153994. };
  153995. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153996. static int _noise_start_16[3]={ 256,256,9999 };
  153997. static int _noise_part_16[4]={ 8,8,8,8 };
  153998. static int _psy_ath_floater_16[4]={
  153999. -100,-100,-100,-105,
  154000. };
  154001. static int _psy_ath_abs_16[4]={
  154002. -130,-130,-130,-140,
  154003. };
  154004. /*** End of inlined file: psych_16.h ***/
  154005. /*** Start of inlined file: residue_16.h ***/
  154006. /***** residue backends *********************************************/
  154007. static static_bookblock _resbook_16s_0={
  154008. {
  154009. {0},
  154010. {0,0,&_16c0_s_p1_0},
  154011. {0,0,&_16c0_s_p2_0},
  154012. {0,0,&_16c0_s_p3_0},
  154013. {0,0,&_16c0_s_p4_0},
  154014. {0,0,&_16c0_s_p5_0},
  154015. {0,0,&_16c0_s_p6_0},
  154016. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154017. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154018. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154019. }
  154020. };
  154021. static static_bookblock _resbook_16s_1={
  154022. {
  154023. {0},
  154024. {0,0,&_16c1_s_p1_0},
  154025. {0,0,&_16c1_s_p2_0},
  154026. {0,0,&_16c1_s_p3_0},
  154027. {0,0,&_16c1_s_p4_0},
  154028. {0,0,&_16c1_s_p5_0},
  154029. {0,0,&_16c1_s_p6_0},
  154030. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154031. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154032. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154033. }
  154034. };
  154035. static static_bookblock _resbook_16s_2={
  154036. {
  154037. {0},
  154038. {0,0,&_16c2_s_p1_0},
  154039. {0,0,&_16c2_s_p2_0},
  154040. {0,0,&_16c2_s_p3_0},
  154041. {0,0,&_16c2_s_p4_0},
  154042. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154043. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154044. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154045. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154046. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154047. }
  154048. };
  154049. static vorbis_residue_template _res_16s_0[]={
  154050. {2,0, &_residue_44_mid,
  154051. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154052. &_resbook_16s_0,&_resbook_16s_0},
  154053. };
  154054. static vorbis_residue_template _res_16s_1[]={
  154055. {2,0, &_residue_44_mid,
  154056. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154057. &_resbook_16s_1,&_resbook_16s_1},
  154058. {2,0, &_residue_44_mid,
  154059. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154060. &_resbook_16s_1,&_resbook_16s_1}
  154061. };
  154062. static vorbis_residue_template _res_16s_2[]={
  154063. {2,0, &_residue_44_high,
  154064. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154065. &_resbook_16s_2,&_resbook_16s_2},
  154066. {2,0, &_residue_44_high,
  154067. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154068. &_resbook_16s_2,&_resbook_16s_2}
  154069. };
  154070. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154071. { _map_nominal, _res_16s_0 }, /* 0 */
  154072. { _map_nominal, _res_16s_1 }, /* 1 */
  154073. { _map_nominal, _res_16s_2 }, /* 2 */
  154074. };
  154075. static static_bookblock _resbook_16u_0={
  154076. {
  154077. {0},
  154078. {0,0,&_16u0__p1_0},
  154079. {0,0,&_16u0__p2_0},
  154080. {0,0,&_16u0__p3_0},
  154081. {0,0,&_16u0__p4_0},
  154082. {0,0,&_16u0__p5_0},
  154083. {&_16u0__p6_0,&_16u0__p6_1},
  154084. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154085. }
  154086. };
  154087. static static_bookblock _resbook_16u_1={
  154088. {
  154089. {0},
  154090. {0,0,&_16u1__p1_0},
  154091. {0,0,&_16u1__p2_0},
  154092. {0,0,&_16u1__p3_0},
  154093. {0,0,&_16u1__p4_0},
  154094. {0,0,&_16u1__p5_0},
  154095. {0,0,&_16u1__p6_0},
  154096. {&_16u1__p7_0,&_16u1__p7_1},
  154097. {&_16u1__p8_0,&_16u1__p8_1},
  154098. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154099. }
  154100. };
  154101. static static_bookblock _resbook_16u_2={
  154102. {
  154103. {0},
  154104. {0,0,&_16u2_p1_0},
  154105. {0,0,&_16u2_p2_0},
  154106. {0,0,&_16u2_p3_0},
  154107. {0,0,&_16u2_p4_0},
  154108. {&_16u2_p5_0,&_16u2_p5_1},
  154109. {&_16u2_p6_0,&_16u2_p6_1},
  154110. {&_16u2_p7_0,&_16u2_p7_1},
  154111. {&_16u2_p8_0,&_16u2_p8_1},
  154112. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154113. }
  154114. };
  154115. static vorbis_residue_template _res_16u_0[]={
  154116. {1,0, &_residue_44_low_un,
  154117. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154118. &_resbook_16u_0,&_resbook_16u_0},
  154119. };
  154120. static vorbis_residue_template _res_16u_1[]={
  154121. {1,0, &_residue_44_mid_un,
  154122. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154123. &_resbook_16u_1,&_resbook_16u_1},
  154124. {1,0, &_residue_44_mid_un,
  154125. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154126. &_resbook_16u_1,&_resbook_16u_1}
  154127. };
  154128. static vorbis_residue_template _res_16u_2[]={
  154129. {1,0, &_residue_44_hi_un,
  154130. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154131. &_resbook_16u_2,&_resbook_16u_2},
  154132. {1,0, &_residue_44_hi_un,
  154133. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154134. &_resbook_16u_2,&_resbook_16u_2}
  154135. };
  154136. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154137. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154138. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154139. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154140. };
  154141. /*** End of inlined file: residue_16.h ***/
  154142. static int blocksize_16_short[3]={
  154143. 1024,512,512
  154144. };
  154145. static int blocksize_16_long[3]={
  154146. 1024,1024,1024
  154147. };
  154148. static int _floor_mapping_16_short[3]={
  154149. 9,3,3
  154150. };
  154151. static int _floor_mapping_16[3]={
  154152. 9,9,9
  154153. };
  154154. static double rate_mapping_16[4]={
  154155. 12000.,20000.,44000.,86000.
  154156. };
  154157. static double rate_mapping_16_uncoupled[4]={
  154158. 16000.,28000.,64000.,100000.
  154159. };
  154160. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154161. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154162. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154163. ve_setup_data_template ve_setup_16_stereo={
  154164. 3,
  154165. rate_mapping_16,
  154166. quality_mapping_16,
  154167. 2,
  154168. 15000,
  154169. 19000,
  154170. blocksize_16_short,
  154171. blocksize_16_long,
  154172. _psy_tone_masteratt_16,
  154173. _psy_tone_0dB,
  154174. _psy_tone_suppress,
  154175. _vp_tonemask_adj_16,
  154176. _vp_tonemask_adj_16,
  154177. _vp_tonemask_adj_16,
  154178. _psy_noiseguards_8,
  154179. _psy_noisebias_16_impulse,
  154180. _psy_noisebias_16_short,
  154181. _psy_noisebias_16_short,
  154182. _psy_noisebias_16,
  154183. _psy_noise_suppress,
  154184. _psy_compand_8,
  154185. _psy_compand_16_mapping,
  154186. _psy_compand_16_mapping,
  154187. {_noise_start_16,_noise_start_16},
  154188. { _noise_part_16, _noise_part_16},
  154189. _noise_thresh_16,
  154190. _psy_ath_floater_16,
  154191. _psy_ath_abs_16,
  154192. _psy_lowpass_16,
  154193. _psy_global_44,
  154194. _global_mapping_16,
  154195. _psy_stereo_modes_16,
  154196. _floor_books,
  154197. _floor,
  154198. _floor_mapping_16_short,
  154199. _floor_mapping_16,
  154200. _mapres_template_16_stereo
  154201. };
  154202. ve_setup_data_template ve_setup_16_uncoupled={
  154203. 3,
  154204. rate_mapping_16_uncoupled,
  154205. quality_mapping_16,
  154206. -1,
  154207. 15000,
  154208. 19000,
  154209. blocksize_16_short,
  154210. blocksize_16_long,
  154211. _psy_tone_masteratt_16,
  154212. _psy_tone_0dB,
  154213. _psy_tone_suppress,
  154214. _vp_tonemask_adj_16,
  154215. _vp_tonemask_adj_16,
  154216. _vp_tonemask_adj_16,
  154217. _psy_noiseguards_8,
  154218. _psy_noisebias_16_impulse,
  154219. _psy_noisebias_16_short,
  154220. _psy_noisebias_16_short,
  154221. _psy_noisebias_16,
  154222. _psy_noise_suppress,
  154223. _psy_compand_8,
  154224. _psy_compand_16_mapping,
  154225. _psy_compand_16_mapping,
  154226. {_noise_start_16,_noise_start_16},
  154227. { _noise_part_16, _noise_part_16},
  154228. _noise_thresh_16,
  154229. _psy_ath_floater_16,
  154230. _psy_ath_abs_16,
  154231. _psy_lowpass_16,
  154232. _psy_global_44,
  154233. _global_mapping_16,
  154234. _psy_stereo_modes_16,
  154235. _floor_books,
  154236. _floor,
  154237. _floor_mapping_16_short,
  154238. _floor_mapping_16,
  154239. _mapres_template_16_uncoupled
  154240. };
  154241. /*** End of inlined file: setup_16.h ***/
  154242. /*** Start of inlined file: setup_22.h ***/
  154243. static double rate_mapping_22[4]={
  154244. 15000.,20000.,44000.,86000.
  154245. };
  154246. static double rate_mapping_22_uncoupled[4]={
  154247. 16000.,28000.,50000.,90000.
  154248. };
  154249. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154250. ve_setup_data_template ve_setup_22_stereo={
  154251. 3,
  154252. rate_mapping_22,
  154253. quality_mapping_16,
  154254. 2,
  154255. 19000,
  154256. 26000,
  154257. blocksize_16_short,
  154258. blocksize_16_long,
  154259. _psy_tone_masteratt_16,
  154260. _psy_tone_0dB,
  154261. _psy_tone_suppress,
  154262. _vp_tonemask_adj_16,
  154263. _vp_tonemask_adj_16,
  154264. _vp_tonemask_adj_16,
  154265. _psy_noiseguards_8,
  154266. _psy_noisebias_16_impulse,
  154267. _psy_noisebias_16_short,
  154268. _psy_noisebias_16_short,
  154269. _psy_noisebias_16,
  154270. _psy_noise_suppress,
  154271. _psy_compand_8,
  154272. _psy_compand_8_mapping,
  154273. _psy_compand_8_mapping,
  154274. {_noise_start_16,_noise_start_16},
  154275. { _noise_part_16, _noise_part_16},
  154276. _noise_thresh_16,
  154277. _psy_ath_floater_16,
  154278. _psy_ath_abs_16,
  154279. _psy_lowpass_22,
  154280. _psy_global_44,
  154281. _global_mapping_16,
  154282. _psy_stereo_modes_16,
  154283. _floor_books,
  154284. _floor,
  154285. _floor_mapping_16_short,
  154286. _floor_mapping_16,
  154287. _mapres_template_16_stereo
  154288. };
  154289. ve_setup_data_template ve_setup_22_uncoupled={
  154290. 3,
  154291. rate_mapping_22_uncoupled,
  154292. quality_mapping_16,
  154293. -1,
  154294. 19000,
  154295. 26000,
  154296. blocksize_16_short,
  154297. blocksize_16_long,
  154298. _psy_tone_masteratt_16,
  154299. _psy_tone_0dB,
  154300. _psy_tone_suppress,
  154301. _vp_tonemask_adj_16,
  154302. _vp_tonemask_adj_16,
  154303. _vp_tonemask_adj_16,
  154304. _psy_noiseguards_8,
  154305. _psy_noisebias_16_impulse,
  154306. _psy_noisebias_16_short,
  154307. _psy_noisebias_16_short,
  154308. _psy_noisebias_16,
  154309. _psy_noise_suppress,
  154310. _psy_compand_8,
  154311. _psy_compand_8_mapping,
  154312. _psy_compand_8_mapping,
  154313. {_noise_start_16,_noise_start_16},
  154314. { _noise_part_16, _noise_part_16},
  154315. _noise_thresh_16,
  154316. _psy_ath_floater_16,
  154317. _psy_ath_abs_16,
  154318. _psy_lowpass_22,
  154319. _psy_global_44,
  154320. _global_mapping_16,
  154321. _psy_stereo_modes_16,
  154322. _floor_books,
  154323. _floor,
  154324. _floor_mapping_16_short,
  154325. _floor_mapping_16,
  154326. _mapres_template_16_uncoupled
  154327. };
  154328. /*** End of inlined file: setup_22.h ***/
  154329. /*** Start of inlined file: setup_X.h ***/
  154330. static double rate_mapping_X[12]={
  154331. -1.,-1.,-1.,-1.,-1.,-1.,
  154332. -1.,-1.,-1.,-1.,-1.,-1.
  154333. };
  154334. ve_setup_data_template ve_setup_X_stereo={
  154335. 11,
  154336. rate_mapping_X,
  154337. quality_mapping_44,
  154338. 2,
  154339. 50000,
  154340. 200000,
  154341. blocksize_short_44,
  154342. blocksize_long_44,
  154343. _psy_tone_masteratt_44,
  154344. _psy_tone_0dB,
  154345. _psy_tone_suppress,
  154346. _vp_tonemask_adj_otherblock,
  154347. _vp_tonemask_adj_longblock,
  154348. _vp_tonemask_adj_otherblock,
  154349. _psy_noiseguards_44,
  154350. _psy_noisebias_impulse,
  154351. _psy_noisebias_padding,
  154352. _psy_noisebias_trans,
  154353. _psy_noisebias_long,
  154354. _psy_noise_suppress,
  154355. _psy_compand_44,
  154356. _psy_compand_short_mapping,
  154357. _psy_compand_long_mapping,
  154358. {_noise_start_short_44,_noise_start_long_44},
  154359. {_noise_part_short_44,_noise_part_long_44},
  154360. _noise_thresh_44,
  154361. _psy_ath_floater,
  154362. _psy_ath_abs,
  154363. _psy_lowpass_44,
  154364. _psy_global_44,
  154365. _global_mapping_44,
  154366. _psy_stereo_modes_44,
  154367. _floor_books,
  154368. _floor,
  154369. _floor_short_mapping_44,
  154370. _floor_long_mapping_44,
  154371. _mapres_template_44_stereo
  154372. };
  154373. ve_setup_data_template ve_setup_X_uncoupled={
  154374. 11,
  154375. rate_mapping_X,
  154376. quality_mapping_44,
  154377. -1,
  154378. 50000,
  154379. 200000,
  154380. blocksize_short_44,
  154381. blocksize_long_44,
  154382. _psy_tone_masteratt_44,
  154383. _psy_tone_0dB,
  154384. _psy_tone_suppress,
  154385. _vp_tonemask_adj_otherblock,
  154386. _vp_tonemask_adj_longblock,
  154387. _vp_tonemask_adj_otherblock,
  154388. _psy_noiseguards_44,
  154389. _psy_noisebias_impulse,
  154390. _psy_noisebias_padding,
  154391. _psy_noisebias_trans,
  154392. _psy_noisebias_long,
  154393. _psy_noise_suppress,
  154394. _psy_compand_44,
  154395. _psy_compand_short_mapping,
  154396. _psy_compand_long_mapping,
  154397. {_noise_start_short_44,_noise_start_long_44},
  154398. {_noise_part_short_44,_noise_part_long_44},
  154399. _noise_thresh_44,
  154400. _psy_ath_floater,
  154401. _psy_ath_abs,
  154402. _psy_lowpass_44,
  154403. _psy_global_44,
  154404. _global_mapping_44,
  154405. NULL,
  154406. _floor_books,
  154407. _floor,
  154408. _floor_short_mapping_44,
  154409. _floor_long_mapping_44,
  154410. _mapres_template_44_uncoupled
  154411. };
  154412. ve_setup_data_template ve_setup_XX_stereo={
  154413. 2,
  154414. rate_mapping_X,
  154415. quality_mapping_8,
  154416. 2,
  154417. 0,
  154418. 8000,
  154419. blocksize_8,
  154420. blocksize_8,
  154421. _psy_tone_masteratt_8,
  154422. _psy_tone_0dB,
  154423. _psy_tone_suppress,
  154424. _vp_tonemask_adj_8,
  154425. NULL,
  154426. _vp_tonemask_adj_8,
  154427. _psy_noiseguards_8,
  154428. _psy_noisebias_8,
  154429. _psy_noisebias_8,
  154430. NULL,
  154431. NULL,
  154432. _psy_noise_suppress,
  154433. _psy_compand_8,
  154434. _psy_compand_8_mapping,
  154435. NULL,
  154436. {_noise_start_8,_noise_start_8},
  154437. {_noise_part_8,_noise_part_8},
  154438. _noise_thresh_5only,
  154439. _psy_ath_floater_8,
  154440. _psy_ath_abs_8,
  154441. _psy_lowpass_8,
  154442. _psy_global_44,
  154443. _global_mapping_8,
  154444. _psy_stereo_modes_8,
  154445. _floor_books,
  154446. _floor,
  154447. _floor_mapping_8,
  154448. NULL,
  154449. _mapres_template_8_stereo
  154450. };
  154451. ve_setup_data_template ve_setup_XX_uncoupled={
  154452. 2,
  154453. rate_mapping_X,
  154454. quality_mapping_8,
  154455. -1,
  154456. 0,
  154457. 8000,
  154458. blocksize_8,
  154459. blocksize_8,
  154460. _psy_tone_masteratt_8,
  154461. _psy_tone_0dB,
  154462. _psy_tone_suppress,
  154463. _vp_tonemask_adj_8,
  154464. NULL,
  154465. _vp_tonemask_adj_8,
  154466. _psy_noiseguards_8,
  154467. _psy_noisebias_8,
  154468. _psy_noisebias_8,
  154469. NULL,
  154470. NULL,
  154471. _psy_noise_suppress,
  154472. _psy_compand_8,
  154473. _psy_compand_8_mapping,
  154474. NULL,
  154475. {_noise_start_8,_noise_start_8},
  154476. {_noise_part_8,_noise_part_8},
  154477. _noise_thresh_5only,
  154478. _psy_ath_floater_8,
  154479. _psy_ath_abs_8,
  154480. _psy_lowpass_8,
  154481. _psy_global_44,
  154482. _global_mapping_8,
  154483. _psy_stereo_modes_8,
  154484. _floor_books,
  154485. _floor,
  154486. _floor_mapping_8,
  154487. NULL,
  154488. _mapres_template_8_uncoupled
  154489. };
  154490. /*** End of inlined file: setup_X.h ***/
  154491. static ve_setup_data_template *setup_list[]={
  154492. &ve_setup_44_stereo,
  154493. &ve_setup_44_uncoupled,
  154494. &ve_setup_32_stereo,
  154495. &ve_setup_32_uncoupled,
  154496. &ve_setup_22_stereo,
  154497. &ve_setup_22_uncoupled,
  154498. &ve_setup_16_stereo,
  154499. &ve_setup_16_uncoupled,
  154500. &ve_setup_11_stereo,
  154501. &ve_setup_11_uncoupled,
  154502. &ve_setup_8_stereo,
  154503. &ve_setup_8_uncoupled,
  154504. &ve_setup_X_stereo,
  154505. &ve_setup_X_uncoupled,
  154506. &ve_setup_XX_stereo,
  154507. &ve_setup_XX_uncoupled,
  154508. 0
  154509. };
  154510. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154511. if(vi && vi->codec_setup){
  154512. vi->version=0;
  154513. vi->channels=ch;
  154514. vi->rate=rate;
  154515. return(0);
  154516. }
  154517. return(OV_EINVAL);
  154518. }
  154519. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154520. static_codebook ***books,
  154521. vorbis_info_floor1 *in,
  154522. int *x){
  154523. int i,k,is=s;
  154524. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154525. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154526. memcpy(f,in+x[is],sizeof(*f));
  154527. /* fill in the lowpass field, even if it's temporary */
  154528. f->n=ci->blocksizes[block]>>1;
  154529. /* books */
  154530. {
  154531. int partitions=f->partitions;
  154532. int maxclass=-1;
  154533. int maxbook=-1;
  154534. for(i=0;i<partitions;i++)
  154535. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154536. for(i=0;i<=maxclass;i++){
  154537. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154538. f->class_book[i]+=ci->books;
  154539. for(k=0;k<(1<<f->class_subs[i]);k++){
  154540. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154541. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154542. }
  154543. }
  154544. for(i=0;i<=maxbook;i++)
  154545. ci->book_param[ci->books++]=books[x[is]][i];
  154546. }
  154547. /* for now, we're only using floor 1 */
  154548. ci->floor_type[ci->floors]=1;
  154549. ci->floor_param[ci->floors]=f;
  154550. ci->floors++;
  154551. return;
  154552. }
  154553. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154554. vorbis_info_psy_global *in,
  154555. double *x){
  154556. int i,is=s;
  154557. double ds=s-is;
  154558. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154559. vorbis_info_psy_global *g=&ci->psy_g_param;
  154560. memcpy(g,in+(int)x[is],sizeof(*g));
  154561. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154562. is=(int)ds;
  154563. ds-=is;
  154564. if(ds==0 && is>0){
  154565. is--;
  154566. ds=1.;
  154567. }
  154568. /* interpolate the trigger threshholds */
  154569. for(i=0;i<4;i++){
  154570. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154571. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154572. }
  154573. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154574. return;
  154575. }
  154576. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154577. highlevel_encode_setup *hi,
  154578. adj_stereo *p){
  154579. float s=hi->stereo_point_setting;
  154580. int i,is=s;
  154581. double ds=s-is;
  154582. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154583. vorbis_info_psy_global *g=&ci->psy_g_param;
  154584. if(p){
  154585. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154586. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154587. if(hi->managed){
  154588. /* interpolate the kHz threshholds */
  154589. for(i=0;i<PACKETBLOBS;i++){
  154590. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154591. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154592. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154593. g->coupling_pkHz[i]=kHz;
  154594. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154595. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154596. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154597. }
  154598. }else{
  154599. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154600. for(i=0;i<PACKETBLOBS;i++){
  154601. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154602. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154603. g->coupling_pkHz[i]=kHz;
  154604. }
  154605. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154606. for(i=0;i<PACKETBLOBS;i++){
  154607. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154608. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154609. }
  154610. }
  154611. }else{
  154612. for(i=0;i<PACKETBLOBS;i++){
  154613. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154614. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154615. }
  154616. }
  154617. return;
  154618. }
  154619. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154620. int *nn_start,
  154621. int *nn_partition,
  154622. double *nn_thresh,
  154623. int block){
  154624. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154625. vorbis_info_psy *p=ci->psy_param[block];
  154626. highlevel_encode_setup *hi=&ci->hi;
  154627. int is=s;
  154628. if(block>=ci->psys)
  154629. ci->psys=block+1;
  154630. if(!p){
  154631. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154632. ci->psy_param[block]=p;
  154633. }
  154634. memcpy(p,&_psy_info_template,sizeof(*p));
  154635. p->blockflag=block>>1;
  154636. if(hi->noise_normalize_p){
  154637. p->normal_channel_p=1;
  154638. p->normal_point_p=1;
  154639. p->normal_start=nn_start[is];
  154640. p->normal_partition=nn_partition[is];
  154641. p->normal_thresh=nn_thresh[is];
  154642. }
  154643. return;
  154644. }
  154645. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154646. att3 *att,
  154647. int *max,
  154648. vp_adjblock *in){
  154649. int i,is=s;
  154650. double ds=s-is;
  154651. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154652. vorbis_info_psy *p=ci->psy_param[block];
  154653. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154654. filling the values in here */
  154655. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154656. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154657. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154658. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154659. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154660. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154661. for(i=0;i<P_BANDS;i++)
  154662. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154663. return;
  154664. }
  154665. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154666. compandblock *in, double *x){
  154667. int i,is=s;
  154668. double ds=s-is;
  154669. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154670. vorbis_info_psy *p=ci->psy_param[block];
  154671. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154672. is=(int)ds;
  154673. ds-=is;
  154674. if(ds==0 && is>0){
  154675. is--;
  154676. ds=1.;
  154677. }
  154678. /* interpolate the compander settings */
  154679. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154680. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154681. return;
  154682. }
  154683. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154684. int *suppress){
  154685. int is=s;
  154686. double ds=s-is;
  154687. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154688. vorbis_info_psy *p=ci->psy_param[block];
  154689. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154690. return;
  154691. }
  154692. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154693. int *suppress,
  154694. noise3 *in,
  154695. noiseguard *guard,
  154696. double userbias){
  154697. int i,is=s,j;
  154698. double ds=s-is;
  154699. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154700. vorbis_info_psy *p=ci->psy_param[block];
  154701. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154702. p->noisewindowlomin=guard[block].lo;
  154703. p->noisewindowhimin=guard[block].hi;
  154704. p->noisewindowfixed=guard[block].fixed;
  154705. for(j=0;j<P_NOISECURVES;j++)
  154706. for(i=0;i<P_BANDS;i++)
  154707. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154708. /* impulse blocks may take a user specified bias to boost the
  154709. nominal/high noise encoding depth */
  154710. for(j=0;j<P_NOISECURVES;j++){
  154711. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154712. for(i=0;i<P_BANDS;i++){
  154713. p->noiseoff[j][i]+=userbias;
  154714. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154715. }
  154716. }
  154717. return;
  154718. }
  154719. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154720. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154721. vorbis_info_psy *p=ci->psy_param[block];
  154722. p->ath_adjatt=ci->hi.ath_floating_dB;
  154723. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154724. return;
  154725. }
  154726. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154727. int i;
  154728. for(i=0;i<ci->books;i++)
  154729. if(ci->book_param[i]==book)return(i);
  154730. return(ci->books++);
  154731. }
  154732. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154733. int *shortb,int *longb){
  154734. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154735. int is=s;
  154736. int blockshort=shortb[is];
  154737. int blocklong=longb[is];
  154738. ci->blocksizes[0]=blockshort;
  154739. ci->blocksizes[1]=blocklong;
  154740. }
  154741. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154742. int number, int block,
  154743. vorbis_residue_template *res){
  154744. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154745. int i,n;
  154746. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154747. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154748. memcpy(r,res->res,sizeof(*r));
  154749. if(ci->residues<=number)ci->residues=number+1;
  154750. switch(ci->blocksizes[block]){
  154751. case 64:case 128:case 256:
  154752. r->grouping=16;
  154753. break;
  154754. default:
  154755. r->grouping=32;
  154756. break;
  154757. }
  154758. ci->residue_type[number]=res->res_type;
  154759. /* to be adjusted by lowpass/pointlimit later */
  154760. n=r->end=ci->blocksizes[block]>>1;
  154761. if(res->res_type==2)
  154762. n=r->end*=vi->channels;
  154763. /* fill in all the books */
  154764. {
  154765. int booklist=0,k;
  154766. if(ci->hi.managed){
  154767. for(i=0;i<r->partitions;i++)
  154768. for(k=0;k<3;k++)
  154769. if(res->books_base_managed->books[i][k])
  154770. r->secondstages[i]|=(1<<k);
  154771. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154772. ci->book_param[r->groupbook]=res->book_aux_managed;
  154773. for(i=0;i<r->partitions;i++){
  154774. for(k=0;k<3;k++){
  154775. if(res->books_base_managed->books[i][k]){
  154776. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154777. r->booklist[booklist++]=bookid;
  154778. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154779. }
  154780. }
  154781. }
  154782. }else{
  154783. for(i=0;i<r->partitions;i++)
  154784. for(k=0;k<3;k++)
  154785. if(res->books_base->books[i][k])
  154786. r->secondstages[i]|=(1<<k);
  154787. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154788. ci->book_param[r->groupbook]=res->book_aux;
  154789. for(i=0;i<r->partitions;i++){
  154790. for(k=0;k<3;k++){
  154791. if(res->books_base->books[i][k]){
  154792. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154793. r->booklist[booklist++]=bookid;
  154794. ci->book_param[bookid]=res->books_base->books[i][k];
  154795. }
  154796. }
  154797. }
  154798. }
  154799. }
  154800. /* lowpass setup/pointlimit */
  154801. {
  154802. double freq=ci->hi.lowpass_kHz*1000.;
  154803. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154804. double nyq=vi->rate/2.;
  154805. long blocksize=ci->blocksizes[block]>>1;
  154806. /* lowpass needs to be set in the floor and the residue. */
  154807. if(freq>nyq)freq=nyq;
  154808. /* in the floor, the granularity can be very fine; it doesn't alter
  154809. the encoding structure, only the samples used to fit the floor
  154810. approximation */
  154811. f->n=freq/nyq*blocksize;
  154812. /* this res may by limited by the maximum pointlimit of the mode,
  154813. not the lowpass. the floor is always lowpass limited. */
  154814. if(res->limit_type){
  154815. if(ci->hi.managed)
  154816. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154817. else
  154818. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154819. if(freq>nyq)freq=nyq;
  154820. }
  154821. /* in the residue, we're constrained, physically, by partition
  154822. boundaries. We still lowpass 'wherever', but we have to round up
  154823. here to next boundary, or the vorbis spec will round it *down* to
  154824. previous boundary in encode/decode */
  154825. if(ci->residue_type[block]==2)
  154826. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154827. r->grouping;
  154828. else
  154829. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154830. r->grouping;
  154831. }
  154832. }
  154833. /* we assume two maps in this encoder */
  154834. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154835. vorbis_mapping_template *maps){
  154836. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154837. int i,j,is=s,modes=2;
  154838. vorbis_info_mapping0 *map=maps[is].map;
  154839. vorbis_info_mode *mode=_mode_template;
  154840. vorbis_residue_template *res=maps[is].res;
  154841. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154842. for(i=0;i<modes;i++){
  154843. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154844. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154845. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154846. if(i>=ci->modes)ci->modes=i+1;
  154847. ci->map_type[i]=0;
  154848. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154849. if(i>=ci->maps)ci->maps=i+1;
  154850. for(j=0;j<map[i].submaps;j++)
  154851. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154852. ,res+map[i].residuesubmap[j]);
  154853. }
  154854. }
  154855. static double setting_to_approx_bitrate(vorbis_info *vi){
  154856. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154857. highlevel_encode_setup *hi=&ci->hi;
  154858. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154859. int is=hi->base_setting;
  154860. double ds=hi->base_setting-is;
  154861. int ch=vi->channels;
  154862. double *r=setup->rate_mapping;
  154863. if(r==NULL)
  154864. return(-1);
  154865. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154866. }
  154867. static void get_setup_template(vorbis_info *vi,
  154868. long ch,long srate,
  154869. double req,int q_or_bitrate){
  154870. int i=0,j;
  154871. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154872. highlevel_encode_setup *hi=&ci->hi;
  154873. if(q_or_bitrate)req/=ch;
  154874. while(setup_list[i]){
  154875. if(setup_list[i]->coupling_restriction==-1 ||
  154876. setup_list[i]->coupling_restriction==ch){
  154877. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154878. srate<=setup_list[i]->samplerate_max_restriction){
  154879. int mappings=setup_list[i]->mappings;
  154880. double *map=(q_or_bitrate?
  154881. setup_list[i]->rate_mapping:
  154882. setup_list[i]->quality_mapping);
  154883. /* the template matches. Does the requested quality mode
  154884. fall within this template's modes? */
  154885. if(req<map[0]){++i;continue;}
  154886. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154887. for(j=0;j<mappings;j++)
  154888. if(req>=map[j] && req<map[j+1])break;
  154889. /* an all-points match */
  154890. hi->setup=setup_list[i];
  154891. if(j==mappings)
  154892. hi->base_setting=j-.001;
  154893. else{
  154894. float low=map[j];
  154895. float high=map[j+1];
  154896. float del=(req-low)/(high-low);
  154897. hi->base_setting=j+del;
  154898. }
  154899. return;
  154900. }
  154901. }
  154902. i++;
  154903. }
  154904. hi->setup=NULL;
  154905. }
  154906. /* encoders will need to use vorbis_info_init beforehand and call
  154907. vorbis_info clear when all done */
  154908. /* two interfaces; this, more detailed one, and later a convenience
  154909. layer on top */
  154910. /* the final setup call */
  154911. int vorbis_encode_setup_init(vorbis_info *vi){
  154912. int i0=0,singleblock=0;
  154913. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154914. ve_setup_data_template *setup=NULL;
  154915. highlevel_encode_setup *hi=&ci->hi;
  154916. if(ci==NULL)return(OV_EINVAL);
  154917. if(!hi->impulse_block_p)i0=1;
  154918. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154919. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154920. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154921. /* again, bound this to avoid the app shooting itself int he foot
  154922. too badly */
  154923. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154924. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154925. /* get the appropriate setup template; matches the fetch in previous
  154926. stages */
  154927. setup=(ve_setup_data_template *)hi->setup;
  154928. if(setup==NULL)return(OV_EINVAL);
  154929. hi->set_in_stone=1;
  154930. /* choose block sizes from configured sizes as well as paying
  154931. attention to long_block_p and short_block_p. If the configured
  154932. short and long blocks are the same length, we set long_block_p
  154933. and unset short_block_p */
  154934. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154935. setup->blocksize_short,
  154936. setup->blocksize_long);
  154937. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154938. /* floor setup; choose proper floor params. Allocated on the floor
  154939. stack in order; if we alloc only long floor, it's 0 */
  154940. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154941. setup->floor_books,
  154942. setup->floor_params,
  154943. setup->floor_short_mapping);
  154944. if(!singleblock)
  154945. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154946. setup->floor_books,
  154947. setup->floor_params,
  154948. setup->floor_long_mapping);
  154949. /* setup of [mostly] short block detection and stereo*/
  154950. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154951. setup->global_params,
  154952. setup->global_mapping);
  154953. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154954. /* basic psych setup and noise normalization */
  154955. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154956. setup->psy_noise_normal_start[0],
  154957. setup->psy_noise_normal_partition[0],
  154958. setup->psy_noise_normal_thresh,
  154959. 0);
  154960. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154961. setup->psy_noise_normal_start[0],
  154962. setup->psy_noise_normal_partition[0],
  154963. setup->psy_noise_normal_thresh,
  154964. 1);
  154965. if(!singleblock){
  154966. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154967. setup->psy_noise_normal_start[1],
  154968. setup->psy_noise_normal_partition[1],
  154969. setup->psy_noise_normal_thresh,
  154970. 2);
  154971. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154972. setup->psy_noise_normal_start[1],
  154973. setup->psy_noise_normal_partition[1],
  154974. setup->psy_noise_normal_thresh,
  154975. 3);
  154976. }
  154977. /* tone masking setup */
  154978. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154979. setup->psy_tone_masteratt,
  154980. setup->psy_tone_0dB,
  154981. setup->psy_tone_adj_impulse);
  154982. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154983. setup->psy_tone_masteratt,
  154984. setup->psy_tone_0dB,
  154985. setup->psy_tone_adj_other);
  154986. if(!singleblock){
  154987. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154988. setup->psy_tone_masteratt,
  154989. setup->psy_tone_0dB,
  154990. setup->psy_tone_adj_other);
  154991. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154992. setup->psy_tone_masteratt,
  154993. setup->psy_tone_0dB,
  154994. setup->psy_tone_adj_long);
  154995. }
  154996. /* noise companding setup */
  154997. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154998. setup->psy_noise_compand,
  154999. setup->psy_noise_compand_short_mapping);
  155000. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155001. setup->psy_noise_compand,
  155002. setup->psy_noise_compand_short_mapping);
  155003. if(!singleblock){
  155004. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155005. setup->psy_noise_compand,
  155006. setup->psy_noise_compand_long_mapping);
  155007. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155008. setup->psy_noise_compand,
  155009. setup->psy_noise_compand_long_mapping);
  155010. }
  155011. /* peak guarding setup */
  155012. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155013. setup->psy_tone_dBsuppress);
  155014. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155015. setup->psy_tone_dBsuppress);
  155016. if(!singleblock){
  155017. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155018. setup->psy_tone_dBsuppress);
  155019. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155020. setup->psy_tone_dBsuppress);
  155021. }
  155022. /* noise bias setup */
  155023. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155024. setup->psy_noise_dBsuppress,
  155025. setup->psy_noise_bias_impulse,
  155026. setup->psy_noiseguards,
  155027. (i0==0?hi->impulse_noisetune:0.));
  155028. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155029. setup->psy_noise_dBsuppress,
  155030. setup->psy_noise_bias_padding,
  155031. setup->psy_noiseguards,0.);
  155032. if(!singleblock){
  155033. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155034. setup->psy_noise_dBsuppress,
  155035. setup->psy_noise_bias_trans,
  155036. setup->psy_noiseguards,0.);
  155037. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155038. setup->psy_noise_dBsuppress,
  155039. setup->psy_noise_bias_long,
  155040. setup->psy_noiseguards,0.);
  155041. }
  155042. vorbis_encode_ath_setup(vi,0);
  155043. vorbis_encode_ath_setup(vi,1);
  155044. if(!singleblock){
  155045. vorbis_encode_ath_setup(vi,2);
  155046. vorbis_encode_ath_setup(vi,3);
  155047. }
  155048. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155049. /* set bitrate readonlies and management */
  155050. if(hi->bitrate_av>0)
  155051. vi->bitrate_nominal=hi->bitrate_av;
  155052. else{
  155053. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155054. }
  155055. vi->bitrate_lower=hi->bitrate_min;
  155056. vi->bitrate_upper=hi->bitrate_max;
  155057. if(hi->bitrate_av)
  155058. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155059. else
  155060. vi->bitrate_window=0.;
  155061. if(hi->managed){
  155062. ci->bi.avg_rate=hi->bitrate_av;
  155063. ci->bi.min_rate=hi->bitrate_min;
  155064. ci->bi.max_rate=hi->bitrate_max;
  155065. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155066. ci->bi.reservoir_bias=
  155067. hi->bitrate_reservoir_bias;
  155068. ci->bi.slew_damp=hi->bitrate_av_damp;
  155069. }
  155070. return(0);
  155071. }
  155072. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155073. long channels,
  155074. long rate){
  155075. int ret=0,i,is;
  155076. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155077. highlevel_encode_setup *hi=&ci->hi;
  155078. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155079. double ds;
  155080. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155081. if(ret)return(ret);
  155082. is=hi->base_setting;
  155083. ds=hi->base_setting-is;
  155084. hi->short_setting=hi->base_setting;
  155085. hi->long_setting=hi->base_setting;
  155086. hi->managed=0;
  155087. hi->impulse_block_p=1;
  155088. hi->noise_normalize_p=1;
  155089. hi->stereo_point_setting=hi->base_setting;
  155090. hi->lowpass_kHz=
  155091. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155092. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155093. setup->psy_ath_float[is+1]*ds;
  155094. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155095. setup->psy_ath_abs[is+1]*ds;
  155096. hi->amplitude_track_dBpersec=-6.;
  155097. hi->trigger_setting=hi->base_setting;
  155098. for(i=0;i<4;i++){
  155099. hi->block[i].tone_mask_setting=hi->base_setting;
  155100. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155101. hi->block[i].noise_bias_setting=hi->base_setting;
  155102. hi->block[i].noise_compand_setting=hi->base_setting;
  155103. }
  155104. return(ret);
  155105. }
  155106. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155107. long channels,
  155108. long rate,
  155109. float quality){
  155110. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155111. highlevel_encode_setup *hi=&ci->hi;
  155112. quality+=.0000001;
  155113. if(quality>=1.)quality=.9999;
  155114. get_setup_template(vi,channels,rate,quality,0);
  155115. if(!hi->setup)return OV_EIMPL;
  155116. return vorbis_encode_setup_setting(vi,channels,rate);
  155117. }
  155118. int vorbis_encode_init_vbr(vorbis_info *vi,
  155119. long channels,
  155120. long rate,
  155121. float base_quality /* 0. to 1. */
  155122. ){
  155123. int ret=0;
  155124. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155125. if(ret){
  155126. vorbis_info_clear(vi);
  155127. return ret;
  155128. }
  155129. ret=vorbis_encode_setup_init(vi);
  155130. if(ret)
  155131. vorbis_info_clear(vi);
  155132. return(ret);
  155133. }
  155134. int vorbis_encode_setup_managed(vorbis_info *vi,
  155135. long channels,
  155136. long rate,
  155137. long max_bitrate,
  155138. long nominal_bitrate,
  155139. long min_bitrate){
  155140. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155141. highlevel_encode_setup *hi=&ci->hi;
  155142. double tnominal=nominal_bitrate;
  155143. int ret=0;
  155144. if(nominal_bitrate<=0.){
  155145. if(max_bitrate>0.){
  155146. if(min_bitrate>0.)
  155147. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155148. else
  155149. nominal_bitrate=max_bitrate*.875;
  155150. }else{
  155151. if(min_bitrate>0.){
  155152. nominal_bitrate=min_bitrate;
  155153. }else{
  155154. return(OV_EINVAL);
  155155. }
  155156. }
  155157. }
  155158. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155159. if(!hi->setup)return OV_EIMPL;
  155160. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155161. if(ret){
  155162. vorbis_info_clear(vi);
  155163. return ret;
  155164. }
  155165. /* initialize management with sane defaults */
  155166. hi->managed=1;
  155167. hi->bitrate_min=min_bitrate;
  155168. hi->bitrate_max=max_bitrate;
  155169. hi->bitrate_av=tnominal;
  155170. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155171. hi->bitrate_reservoir=nominal_bitrate*2;
  155172. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155173. return(ret);
  155174. }
  155175. int vorbis_encode_init(vorbis_info *vi,
  155176. long channels,
  155177. long rate,
  155178. long max_bitrate,
  155179. long nominal_bitrate,
  155180. long min_bitrate){
  155181. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155182. max_bitrate,
  155183. nominal_bitrate,
  155184. min_bitrate);
  155185. if(ret){
  155186. vorbis_info_clear(vi);
  155187. return(ret);
  155188. }
  155189. ret=vorbis_encode_setup_init(vi);
  155190. if(ret)
  155191. vorbis_info_clear(vi);
  155192. return(ret);
  155193. }
  155194. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155195. if(vi){
  155196. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155197. highlevel_encode_setup *hi=&ci->hi;
  155198. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155199. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155200. switch(number){
  155201. /* now deprecated *****************/
  155202. case OV_ECTL_RATEMANAGE_GET:
  155203. {
  155204. struct ovectl_ratemanage_arg *ai=
  155205. (struct ovectl_ratemanage_arg *)arg;
  155206. ai->management_active=hi->managed;
  155207. ai->bitrate_hard_window=ai->bitrate_av_window=
  155208. (double)hi->bitrate_reservoir/vi->rate;
  155209. ai->bitrate_av_window_center=1.;
  155210. ai->bitrate_hard_min=hi->bitrate_min;
  155211. ai->bitrate_hard_max=hi->bitrate_max;
  155212. ai->bitrate_av_lo=hi->bitrate_av;
  155213. ai->bitrate_av_hi=hi->bitrate_av;
  155214. }
  155215. return(0);
  155216. /* now deprecated *****************/
  155217. case OV_ECTL_RATEMANAGE_SET:
  155218. {
  155219. struct ovectl_ratemanage_arg *ai=
  155220. (struct ovectl_ratemanage_arg *)arg;
  155221. if(ai==NULL){
  155222. hi->managed=0;
  155223. }else{
  155224. hi->managed=ai->management_active;
  155225. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155226. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155227. }
  155228. }
  155229. return 0;
  155230. /* now deprecated *****************/
  155231. case OV_ECTL_RATEMANAGE_AVG:
  155232. {
  155233. struct ovectl_ratemanage_arg *ai=
  155234. (struct ovectl_ratemanage_arg *)arg;
  155235. if(ai==NULL){
  155236. hi->bitrate_av=0;
  155237. }else{
  155238. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155239. }
  155240. }
  155241. return(0);
  155242. /* now deprecated *****************/
  155243. case OV_ECTL_RATEMANAGE_HARD:
  155244. {
  155245. struct ovectl_ratemanage_arg *ai=
  155246. (struct ovectl_ratemanage_arg *)arg;
  155247. if(ai==NULL){
  155248. hi->bitrate_min=0;
  155249. hi->bitrate_max=0;
  155250. }else{
  155251. hi->bitrate_min=ai->bitrate_hard_min;
  155252. hi->bitrate_max=ai->bitrate_hard_max;
  155253. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155254. (hi->bitrate_max+hi->bitrate_min)*.5;
  155255. }
  155256. if(hi->bitrate_reservoir<128.)
  155257. hi->bitrate_reservoir=128.;
  155258. }
  155259. return(0);
  155260. /* replacement ratemanage interface */
  155261. case OV_ECTL_RATEMANAGE2_GET:
  155262. {
  155263. struct ovectl_ratemanage2_arg *ai=
  155264. (struct ovectl_ratemanage2_arg *)arg;
  155265. if(ai==NULL)return OV_EINVAL;
  155266. ai->management_active=hi->managed;
  155267. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155268. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155269. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155270. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155271. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155272. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155273. }
  155274. return (0);
  155275. case OV_ECTL_RATEMANAGE2_SET:
  155276. {
  155277. struct ovectl_ratemanage2_arg *ai=
  155278. (struct ovectl_ratemanage2_arg *)arg;
  155279. if(ai==NULL){
  155280. hi->managed=0;
  155281. }else{
  155282. /* sanity check; only catch invariant violations */
  155283. if(ai->bitrate_limit_min_kbps>0 &&
  155284. ai->bitrate_average_kbps>0 &&
  155285. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155286. return OV_EINVAL;
  155287. if(ai->bitrate_limit_max_kbps>0 &&
  155288. ai->bitrate_average_kbps>0 &&
  155289. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155290. return OV_EINVAL;
  155291. if(ai->bitrate_limit_min_kbps>0 &&
  155292. ai->bitrate_limit_max_kbps>0 &&
  155293. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155294. return OV_EINVAL;
  155295. if(ai->bitrate_average_damping <= 0.)
  155296. return OV_EINVAL;
  155297. if(ai->bitrate_limit_reservoir_bits < 0)
  155298. return OV_EINVAL;
  155299. if(ai->bitrate_limit_reservoir_bias < 0.)
  155300. return OV_EINVAL;
  155301. if(ai->bitrate_limit_reservoir_bias > 1.)
  155302. return OV_EINVAL;
  155303. hi->managed=ai->management_active;
  155304. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155305. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155306. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155307. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155308. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155309. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155310. }
  155311. }
  155312. return 0;
  155313. case OV_ECTL_LOWPASS_GET:
  155314. {
  155315. double *farg=(double *)arg;
  155316. *farg=hi->lowpass_kHz;
  155317. }
  155318. return(0);
  155319. case OV_ECTL_LOWPASS_SET:
  155320. {
  155321. double *farg=(double *)arg;
  155322. hi->lowpass_kHz=*farg;
  155323. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155324. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155325. }
  155326. return(0);
  155327. case OV_ECTL_IBLOCK_GET:
  155328. {
  155329. double *farg=(double *)arg;
  155330. *farg=hi->impulse_noisetune;
  155331. }
  155332. return(0);
  155333. case OV_ECTL_IBLOCK_SET:
  155334. {
  155335. double *farg=(double *)arg;
  155336. hi->impulse_noisetune=*farg;
  155337. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155338. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155339. }
  155340. return(0);
  155341. }
  155342. return(OV_EIMPL);
  155343. }
  155344. return(OV_EINVAL);
  155345. }
  155346. #endif
  155347. /*** End of inlined file: vorbisenc.c ***/
  155348. /*** Start of inlined file: vorbisfile.c ***/
  155349. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155350. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155351. // tasks..
  155352. #if JUCE_MSVC
  155353. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155354. #endif
  155355. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155356. #if JUCE_USE_OGGVORBIS
  155357. #include <stdlib.h>
  155358. #include <stdio.h>
  155359. #include <errno.h>
  155360. #include <string.h>
  155361. #include <math.h>
  155362. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155363. one logical bitstream arranged end to end (the only form of Ogg
  155364. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155365. multiplexing] is not allowed in Vorbis) */
  155366. /* A Vorbis file can be played beginning to end (streamed) without
  155367. worrying ahead of time about chaining (see decoder_example.c). If
  155368. we have the whole file, however, and want random access
  155369. (seeking/scrubbing) or desire to know the total length/time of a
  155370. file, we need to account for the possibility of chaining. */
  155371. /* We can handle things a number of ways; we can determine the entire
  155372. bitstream structure right off the bat, or find pieces on demand.
  155373. This example determines and caches structure for the entire
  155374. bitstream, but builds a virtual decoder on the fly when moving
  155375. between links in the chain. */
  155376. /* There are also different ways to implement seeking. Enough
  155377. information exists in an Ogg bitstream to seek to
  155378. sample-granularity positions in the output. Or, one can seek by
  155379. picking some portion of the stream roughly in the desired area if
  155380. we only want coarse navigation through the stream. */
  155381. /*************************************************************************
  155382. * Many, many internal helpers. The intention is not to be confusing;
  155383. * rampant duplication and monolithic function implementation would be
  155384. * harder to understand anyway. The high level functions are last. Begin
  155385. * grokking near the end of the file */
  155386. /* read a little more data from the file/pipe into the ogg_sync framer
  155387. */
  155388. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155389. over 8k gets what they deserve */
  155390. static long _get_data(OggVorbis_File *vf){
  155391. errno=0;
  155392. if(vf->datasource){
  155393. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155394. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155395. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155396. if(bytes==0 && errno)return(-1);
  155397. return(bytes);
  155398. }else
  155399. return(0);
  155400. }
  155401. /* save a tiny smidge of verbosity to make the code more readable */
  155402. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155403. if(vf->datasource){
  155404. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155405. vf->offset=offset;
  155406. ogg_sync_reset(&vf->oy);
  155407. }else{
  155408. /* shouldn't happen unless someone writes a broken callback */
  155409. return;
  155410. }
  155411. }
  155412. /* The read/seek functions track absolute position within the stream */
  155413. /* from the head of the stream, get the next page. boundary specifies
  155414. if the function is allowed to fetch more data from the stream (and
  155415. how much) or only use internally buffered data.
  155416. boundary: -1) unbounded search
  155417. 0) read no additional data; use cached only
  155418. n) search for a new page beginning for n bytes
  155419. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155420. n) found a page at absolute offset n */
  155421. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155422. ogg_int64_t boundary){
  155423. if(boundary>0)boundary+=vf->offset;
  155424. while(1){
  155425. long more;
  155426. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155427. more=ogg_sync_pageseek(&vf->oy,og);
  155428. if(more<0){
  155429. /* skipped n bytes */
  155430. vf->offset-=more;
  155431. }else{
  155432. if(more==0){
  155433. /* send more paramedics */
  155434. if(!boundary)return(OV_FALSE);
  155435. {
  155436. long ret=_get_data(vf);
  155437. if(ret==0)return(OV_EOF);
  155438. if(ret<0)return(OV_EREAD);
  155439. }
  155440. }else{
  155441. /* got a page. Return the offset at the page beginning,
  155442. advance the internal offset past the page end */
  155443. ogg_int64_t ret=vf->offset;
  155444. vf->offset+=more;
  155445. return(ret);
  155446. }
  155447. }
  155448. }
  155449. }
  155450. /* find the latest page beginning before the current stream cursor
  155451. position. Much dirtier than the above as Ogg doesn't have any
  155452. backward search linkage. no 'readp' as it will certainly have to
  155453. read. */
  155454. /* returns offset or OV_EREAD, OV_FAULT */
  155455. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155456. ogg_int64_t begin=vf->offset;
  155457. ogg_int64_t end=begin;
  155458. ogg_int64_t ret;
  155459. ogg_int64_t offset=-1;
  155460. while(offset==-1){
  155461. begin-=CHUNKSIZE;
  155462. if(begin<0)
  155463. begin=0;
  155464. _seek_helper(vf,begin);
  155465. while(vf->offset<end){
  155466. ret=_get_next_page(vf,og,end-vf->offset);
  155467. if(ret==OV_EREAD)return(OV_EREAD);
  155468. if(ret<0){
  155469. break;
  155470. }else{
  155471. offset=ret;
  155472. }
  155473. }
  155474. }
  155475. /* we have the offset. Actually snork and hold the page now */
  155476. _seek_helper(vf,offset);
  155477. ret=_get_next_page(vf,og,CHUNKSIZE);
  155478. if(ret<0)
  155479. /* this shouldn't be possible */
  155480. return(OV_EFAULT);
  155481. return(offset);
  155482. }
  155483. /* finds each bitstream link one at a time using a bisection search
  155484. (has to begin by knowing the offset of the lb's initial page).
  155485. Recurses for each link so it can alloc the link storage after
  155486. finding them all, then unroll and fill the cache at the same time */
  155487. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155488. ogg_int64_t begin,
  155489. ogg_int64_t searched,
  155490. ogg_int64_t end,
  155491. long currentno,
  155492. long m){
  155493. ogg_int64_t endsearched=end;
  155494. ogg_int64_t next=end;
  155495. ogg_page og;
  155496. ogg_int64_t ret;
  155497. /* the below guards against garbage seperating the last and
  155498. first pages of two links. */
  155499. while(searched<endsearched){
  155500. ogg_int64_t bisect;
  155501. if(endsearched-searched<CHUNKSIZE){
  155502. bisect=searched;
  155503. }else{
  155504. bisect=(searched+endsearched)/2;
  155505. }
  155506. _seek_helper(vf,bisect);
  155507. ret=_get_next_page(vf,&og,-1);
  155508. if(ret==OV_EREAD)return(OV_EREAD);
  155509. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155510. endsearched=bisect;
  155511. if(ret>=0)next=ret;
  155512. }else{
  155513. searched=ret+og.header_len+og.body_len;
  155514. }
  155515. }
  155516. _seek_helper(vf,next);
  155517. ret=_get_next_page(vf,&og,-1);
  155518. if(ret==OV_EREAD)return(OV_EREAD);
  155519. if(searched>=end || ret<0){
  155520. vf->links=m+1;
  155521. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155522. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155523. vf->offsets[m+1]=searched;
  155524. }else{
  155525. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155526. end,ogg_page_serialno(&og),m+1);
  155527. if(ret==OV_EREAD)return(OV_EREAD);
  155528. }
  155529. vf->offsets[m]=begin;
  155530. vf->serialnos[m]=currentno;
  155531. return(0);
  155532. }
  155533. /* uses the local ogg_stream storage in vf; this is important for
  155534. non-streaming input sources */
  155535. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155536. long *serialno,ogg_page *og_ptr){
  155537. ogg_page og;
  155538. ogg_packet op;
  155539. int i,ret;
  155540. if(!og_ptr){
  155541. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155542. if(llret==OV_EREAD)return(OV_EREAD);
  155543. if(llret<0)return OV_ENOTVORBIS;
  155544. og_ptr=&og;
  155545. }
  155546. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155547. if(serialno)*serialno=vf->os.serialno;
  155548. vf->ready_state=STREAMSET;
  155549. /* extract the initial header from the first page and verify that the
  155550. Ogg bitstream is in fact Vorbis data */
  155551. vorbis_info_init(vi);
  155552. vorbis_comment_init(vc);
  155553. i=0;
  155554. while(i<3){
  155555. ogg_stream_pagein(&vf->os,og_ptr);
  155556. while(i<3){
  155557. int result=ogg_stream_packetout(&vf->os,&op);
  155558. if(result==0)break;
  155559. if(result==-1){
  155560. ret=OV_EBADHEADER;
  155561. goto bail_header;
  155562. }
  155563. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155564. goto bail_header;
  155565. }
  155566. i++;
  155567. }
  155568. if(i<3)
  155569. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155570. ret=OV_EBADHEADER;
  155571. goto bail_header;
  155572. }
  155573. }
  155574. return 0;
  155575. bail_header:
  155576. vorbis_info_clear(vi);
  155577. vorbis_comment_clear(vc);
  155578. vf->ready_state=OPENED;
  155579. return ret;
  155580. }
  155581. /* last step of the OggVorbis_File initialization; get all the
  155582. vorbis_info structs and PCM positions. Only called by the seekable
  155583. initialization (local stream storage is hacked slightly; pay
  155584. attention to how that's done) */
  155585. /* this is void and does not propogate errors up because we want to be
  155586. able to open and use damaged bitstreams as well as we can. Just
  155587. watch out for missing information for links in the OggVorbis_File
  155588. struct */
  155589. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155590. ogg_page og;
  155591. int i;
  155592. ogg_int64_t ret;
  155593. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155594. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155595. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155596. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155597. for(i=0;i<vf->links;i++){
  155598. if(i==0){
  155599. /* we already grabbed the initial header earlier. Just set the offset */
  155600. vf->dataoffsets[i]=dataoffset;
  155601. _seek_helper(vf,dataoffset);
  155602. }else{
  155603. /* seek to the location of the initial header */
  155604. _seek_helper(vf,vf->offsets[i]);
  155605. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155606. vf->dataoffsets[i]=-1;
  155607. }else{
  155608. vf->dataoffsets[i]=vf->offset;
  155609. }
  155610. }
  155611. /* fetch beginning PCM offset */
  155612. if(vf->dataoffsets[i]!=-1){
  155613. ogg_int64_t accumulated=0;
  155614. long lastblock=-1;
  155615. int result;
  155616. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155617. while(1){
  155618. ogg_packet op;
  155619. ret=_get_next_page(vf,&og,-1);
  155620. if(ret<0)
  155621. /* this should not be possible unless the file is
  155622. truncated/mangled */
  155623. break;
  155624. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155625. break;
  155626. /* count blocksizes of all frames in the page */
  155627. ogg_stream_pagein(&vf->os,&og);
  155628. while((result=ogg_stream_packetout(&vf->os,&op))){
  155629. if(result>0){ /* ignore holes */
  155630. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155631. if(lastblock!=-1)
  155632. accumulated+=(lastblock+thisblock)>>2;
  155633. lastblock=thisblock;
  155634. }
  155635. }
  155636. if(ogg_page_granulepos(&og)!=-1){
  155637. /* pcm offset of last packet on the first audio page */
  155638. accumulated= ogg_page_granulepos(&og)-accumulated;
  155639. break;
  155640. }
  155641. }
  155642. /* less than zero? This is a stream with samples trimmed off
  155643. the beginning, a normal occurrence; set the offset to zero */
  155644. if(accumulated<0)accumulated=0;
  155645. vf->pcmlengths[i*2]=accumulated;
  155646. }
  155647. /* get the PCM length of this link. To do this,
  155648. get the last page of the stream */
  155649. {
  155650. ogg_int64_t end=vf->offsets[i+1];
  155651. _seek_helper(vf,end);
  155652. while(1){
  155653. ret=_get_prev_page(vf,&og);
  155654. if(ret<0){
  155655. /* this should not be possible */
  155656. vorbis_info_clear(vf->vi+i);
  155657. vorbis_comment_clear(vf->vc+i);
  155658. break;
  155659. }
  155660. if(ogg_page_granulepos(&og)!=-1){
  155661. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155662. break;
  155663. }
  155664. vf->offset=ret;
  155665. }
  155666. }
  155667. }
  155668. }
  155669. static int _make_decode_ready(OggVorbis_File *vf){
  155670. if(vf->ready_state>STREAMSET)return 0;
  155671. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155672. if(vf->seekable){
  155673. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155674. return OV_EBADLINK;
  155675. }else{
  155676. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155677. return OV_EBADLINK;
  155678. }
  155679. vorbis_block_init(&vf->vd,&vf->vb);
  155680. vf->ready_state=INITSET;
  155681. vf->bittrack=0.f;
  155682. vf->samptrack=0.f;
  155683. return 0;
  155684. }
  155685. static int _open_seekable2(OggVorbis_File *vf){
  155686. long serialno=vf->current_serialno;
  155687. ogg_int64_t dataoffset=vf->offset, end;
  155688. ogg_page og;
  155689. /* we're partially open and have a first link header state in
  155690. storage in vf */
  155691. /* we can seek, so set out learning all about this file */
  155692. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155693. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155694. /* We get the offset for the last page of the physical bitstream.
  155695. Most OggVorbis files will contain a single logical bitstream */
  155696. end=_get_prev_page(vf,&og);
  155697. if(end<0)return(end);
  155698. /* more than one logical bitstream? */
  155699. if(ogg_page_serialno(&og)!=serialno){
  155700. /* Chained bitstream. Bisect-search each logical bitstream
  155701. section. Do so based on serial number only */
  155702. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155703. }else{
  155704. /* Only one logical bitstream */
  155705. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155706. }
  155707. /* the initial header memory is referenced by vf after; don't free it */
  155708. _prefetch_all_headers(vf,dataoffset);
  155709. return(ov_raw_seek(vf,0));
  155710. }
  155711. /* clear out the current logical bitstream decoder */
  155712. static void _decode_clear(OggVorbis_File *vf){
  155713. vorbis_dsp_clear(&vf->vd);
  155714. vorbis_block_clear(&vf->vb);
  155715. vf->ready_state=OPENED;
  155716. }
  155717. /* fetch and process a packet. Handles the case where we're at a
  155718. bitstream boundary and dumps the decoding machine. If the decoding
  155719. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155720. date (seek and read both use this. seek uses a special hack with
  155721. readp).
  155722. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155723. 0) need more data (only if readp==0)
  155724. 1) got a packet
  155725. */
  155726. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155727. ogg_packet *op_in,
  155728. int readp,
  155729. int spanp){
  155730. ogg_page og;
  155731. /* handle one packet. Try to fetch it from current stream state */
  155732. /* extract packets from page */
  155733. while(1){
  155734. /* process a packet if we can. If the machine isn't loaded,
  155735. neither is a page */
  155736. if(vf->ready_state==INITSET){
  155737. while(1) {
  155738. ogg_packet op;
  155739. ogg_packet *op_ptr=(op_in?op_in:&op);
  155740. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155741. ogg_int64_t granulepos;
  155742. op_in=NULL;
  155743. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155744. if(result>0){
  155745. /* got a packet. process it */
  155746. granulepos=op_ptr->granulepos;
  155747. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155748. header handling. The
  155749. header packets aren't
  155750. audio, so if/when we
  155751. submit them,
  155752. vorbis_synthesis will
  155753. reject them */
  155754. /* suck in the synthesis data and track bitrate */
  155755. {
  155756. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155757. /* for proper use of libvorbis within libvorbisfile,
  155758. oldsamples will always be zero. */
  155759. if(oldsamples)return(OV_EFAULT);
  155760. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155761. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155762. vf->bittrack+=op_ptr->bytes*8;
  155763. }
  155764. /* update the pcm offset. */
  155765. if(granulepos!=-1 && !op_ptr->e_o_s){
  155766. int link=(vf->seekable?vf->current_link:0);
  155767. int i,samples;
  155768. /* this packet has a pcm_offset on it (the last packet
  155769. completed on a page carries the offset) After processing
  155770. (above), we know the pcm position of the *last* sample
  155771. ready to be returned. Find the offset of the *first*
  155772. As an aside, this trick is inaccurate if we begin
  155773. reading anew right at the last page; the end-of-stream
  155774. granulepos declares the last frame in the stream, and the
  155775. last packet of the last page may be a partial frame.
  155776. So, we need a previous granulepos from an in-sequence page
  155777. to have a reference point. Thus the !op_ptr->e_o_s clause
  155778. above */
  155779. if(vf->seekable && link>0)
  155780. granulepos-=vf->pcmlengths[link*2];
  155781. if(granulepos<0)granulepos=0; /* actually, this
  155782. shouldn't be possible
  155783. here unless the stream
  155784. is very broken */
  155785. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155786. granulepos-=samples;
  155787. for(i=0;i<link;i++)
  155788. granulepos+=vf->pcmlengths[i*2+1];
  155789. vf->pcm_offset=granulepos;
  155790. }
  155791. return(1);
  155792. }
  155793. }
  155794. else
  155795. break;
  155796. }
  155797. }
  155798. if(vf->ready_state>=OPENED){
  155799. ogg_int64_t ret;
  155800. if(!readp)return(0);
  155801. if((ret=_get_next_page(vf,&og,-1))<0){
  155802. return(OV_EOF); /* eof.
  155803. leave unitialized */
  155804. }
  155805. /* bitrate tracking; add the header's bytes here, the body bytes
  155806. are done by packet above */
  155807. vf->bittrack+=og.header_len*8;
  155808. /* has our decoding just traversed a bitstream boundary? */
  155809. if(vf->ready_state==INITSET){
  155810. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155811. if(!spanp)
  155812. return(OV_EOF);
  155813. _decode_clear(vf);
  155814. if(!vf->seekable){
  155815. vorbis_info_clear(vf->vi);
  155816. vorbis_comment_clear(vf->vc);
  155817. }
  155818. }
  155819. }
  155820. }
  155821. /* Do we need to load a new machine before submitting the page? */
  155822. /* This is different in the seekable and non-seekable cases.
  155823. In the seekable case, we already have all the header
  155824. information loaded and cached; we just initialize the machine
  155825. with it and continue on our merry way.
  155826. In the non-seekable (streaming) case, we'll only be at a
  155827. boundary if we just left the previous logical bitstream and
  155828. we're now nominally at the header of the next bitstream
  155829. */
  155830. if(vf->ready_state!=INITSET){
  155831. int link;
  155832. if(vf->ready_state<STREAMSET){
  155833. if(vf->seekable){
  155834. vf->current_serialno=ogg_page_serialno(&og);
  155835. /* match the serialno to bitstream section. We use this rather than
  155836. offset positions to avoid problems near logical bitstream
  155837. boundaries */
  155838. for(link=0;link<vf->links;link++)
  155839. if(vf->serialnos[link]==vf->current_serialno)break;
  155840. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155841. stream. error out,
  155842. leave machine
  155843. uninitialized */
  155844. vf->current_link=link;
  155845. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155846. vf->ready_state=STREAMSET;
  155847. }else{
  155848. /* we're streaming */
  155849. /* fetch the three header packets, build the info struct */
  155850. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155851. if(ret)return(ret);
  155852. vf->current_link++;
  155853. link=0;
  155854. }
  155855. }
  155856. {
  155857. int ret=_make_decode_ready(vf);
  155858. if(ret<0)return ret;
  155859. }
  155860. }
  155861. ogg_stream_pagein(&vf->os,&og);
  155862. }
  155863. }
  155864. /* if, eg, 64 bit stdio is configured by default, this will build with
  155865. fseek64 */
  155866. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155867. if(f==NULL)return(-1);
  155868. return fseek(f,off,whence);
  155869. }
  155870. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155871. long ibytes, ov_callbacks callbacks){
  155872. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155873. int ret;
  155874. memset(vf,0,sizeof(*vf));
  155875. vf->datasource=f;
  155876. vf->callbacks = callbacks;
  155877. /* init the framing state */
  155878. ogg_sync_init(&vf->oy);
  155879. /* perhaps some data was previously read into a buffer for testing
  155880. against other stream types. Allow initialization from this
  155881. previously read data (as we may be reading from a non-seekable
  155882. stream) */
  155883. if(initial){
  155884. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155885. memcpy(buffer,initial,ibytes);
  155886. ogg_sync_wrote(&vf->oy,ibytes);
  155887. }
  155888. /* can we seek? Stevens suggests the seek test was portable */
  155889. if(offsettest!=-1)vf->seekable=1;
  155890. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155891. entry for partial open */
  155892. vf->links=1;
  155893. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155894. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155895. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155896. /* Try to fetch the headers, maintaining all the storage */
  155897. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155898. vf->datasource=NULL;
  155899. ov_clear(vf);
  155900. }else
  155901. vf->ready_state=PARTOPEN;
  155902. return(ret);
  155903. }
  155904. static int _ov_open2(OggVorbis_File *vf){
  155905. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155906. vf->ready_state=OPENED;
  155907. if(vf->seekable){
  155908. int ret=_open_seekable2(vf);
  155909. if(ret){
  155910. vf->datasource=NULL;
  155911. ov_clear(vf);
  155912. }
  155913. return(ret);
  155914. }else
  155915. vf->ready_state=STREAMSET;
  155916. return 0;
  155917. }
  155918. /* clear out the OggVorbis_File struct */
  155919. int ov_clear(OggVorbis_File *vf){
  155920. if(vf){
  155921. vorbis_block_clear(&vf->vb);
  155922. vorbis_dsp_clear(&vf->vd);
  155923. ogg_stream_clear(&vf->os);
  155924. if(vf->vi && vf->links){
  155925. int i;
  155926. for(i=0;i<vf->links;i++){
  155927. vorbis_info_clear(vf->vi+i);
  155928. vorbis_comment_clear(vf->vc+i);
  155929. }
  155930. _ogg_free(vf->vi);
  155931. _ogg_free(vf->vc);
  155932. }
  155933. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155934. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155935. if(vf->serialnos)_ogg_free(vf->serialnos);
  155936. if(vf->offsets)_ogg_free(vf->offsets);
  155937. ogg_sync_clear(&vf->oy);
  155938. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155939. memset(vf,0,sizeof(*vf));
  155940. }
  155941. #ifdef DEBUG_LEAKS
  155942. _VDBG_dump();
  155943. #endif
  155944. return(0);
  155945. }
  155946. /* inspects the OggVorbis file and finds/documents all the logical
  155947. bitstreams contained in it. Tries to be tolerant of logical
  155948. bitstream sections that are truncated/woogie.
  155949. return: -1) error
  155950. 0) OK
  155951. */
  155952. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155953. ov_callbacks callbacks){
  155954. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155955. if(ret)return ret;
  155956. return _ov_open2(vf);
  155957. }
  155958. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155959. ov_callbacks callbacks = {
  155960. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155961. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155962. (int (*)(void *)) fclose,
  155963. (long (*)(void *)) ftell
  155964. };
  155965. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155966. }
  155967. /* cheap hack for game usage where downsampling is desirable; there's
  155968. no need for SRC as we can just do it cheaply in libvorbis. */
  155969. int ov_halfrate(OggVorbis_File *vf,int flag){
  155970. int i;
  155971. if(vf->vi==NULL)return OV_EINVAL;
  155972. if(!vf->seekable)return OV_EINVAL;
  155973. if(vf->ready_state>=STREAMSET)
  155974. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155975. will be able to swap this on the fly, but
  155976. for now dumping the decode machine is needed
  155977. to reinit the MDCT lookups. 1.1 libvorbis
  155978. is planned to be able to switch on the fly */
  155979. for(i=0;i<vf->links;i++){
  155980. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155981. ov_halfrate(vf,0);
  155982. return OV_EINVAL;
  155983. }
  155984. }
  155985. return 0;
  155986. }
  155987. int ov_halfrate_p(OggVorbis_File *vf){
  155988. if(vf->vi==NULL)return OV_EINVAL;
  155989. return vorbis_synthesis_halfrate_p(vf->vi);
  155990. }
  155991. /* Only partially open the vorbis file; test for Vorbisness, and load
  155992. the headers for the first chain. Do not seek (although test for
  155993. seekability). Use ov_test_open to finish opening the file, else
  155994. ov_clear to close/free it. Same return codes as open. */
  155995. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155996. ov_callbacks callbacks)
  155997. {
  155998. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155999. }
  156000. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156001. ov_callbacks callbacks = {
  156002. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156003. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156004. (int (*)(void *)) fclose,
  156005. (long (*)(void *)) ftell
  156006. };
  156007. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156008. }
  156009. int ov_test_open(OggVorbis_File *vf){
  156010. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156011. return _ov_open2(vf);
  156012. }
  156013. /* How many logical bitstreams in this physical bitstream? */
  156014. long ov_streams(OggVorbis_File *vf){
  156015. return vf->links;
  156016. }
  156017. /* Is the FILE * associated with vf seekable? */
  156018. long ov_seekable(OggVorbis_File *vf){
  156019. return vf->seekable;
  156020. }
  156021. /* returns the bitrate for a given logical bitstream or the entire
  156022. physical bitstream. If the file is open for random access, it will
  156023. find the *actual* average bitrate. If the file is streaming, it
  156024. returns the nominal bitrate (if set) else the average of the
  156025. upper/lower bounds (if set) else -1 (unset).
  156026. If you want the actual bitrate field settings, get them from the
  156027. vorbis_info structs */
  156028. long ov_bitrate(OggVorbis_File *vf,int i){
  156029. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156030. if(i>=vf->links)return(OV_EINVAL);
  156031. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156032. if(i<0){
  156033. ogg_int64_t bits=0;
  156034. int i;
  156035. float br;
  156036. for(i=0;i<vf->links;i++)
  156037. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156038. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156039. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156040. * so this is slightly transformed to make it work.
  156041. */
  156042. br = bits/ov_time_total(vf,-1);
  156043. return(rint(br));
  156044. }else{
  156045. if(vf->seekable){
  156046. /* return the actual bitrate */
  156047. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156048. }else{
  156049. /* return nominal if set */
  156050. if(vf->vi[i].bitrate_nominal>0){
  156051. return vf->vi[i].bitrate_nominal;
  156052. }else{
  156053. if(vf->vi[i].bitrate_upper>0){
  156054. if(vf->vi[i].bitrate_lower>0){
  156055. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156056. }else{
  156057. return vf->vi[i].bitrate_upper;
  156058. }
  156059. }
  156060. return(OV_FALSE);
  156061. }
  156062. }
  156063. }
  156064. }
  156065. /* returns the actual bitrate since last call. returns -1 if no
  156066. additional data to offer since last call (or at beginning of stream),
  156067. EINVAL if stream is only partially open
  156068. */
  156069. long ov_bitrate_instant(OggVorbis_File *vf){
  156070. int link=(vf->seekable?vf->current_link:0);
  156071. long ret;
  156072. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156073. if(vf->samptrack==0)return(OV_FALSE);
  156074. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156075. vf->bittrack=0.f;
  156076. vf->samptrack=0.f;
  156077. return(ret);
  156078. }
  156079. /* Guess */
  156080. long ov_serialnumber(OggVorbis_File *vf,int i){
  156081. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156082. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156083. if(i<0){
  156084. return(vf->current_serialno);
  156085. }else{
  156086. return(vf->serialnos[i]);
  156087. }
  156088. }
  156089. /* returns: total raw (compressed) length of content if i==-1
  156090. raw (compressed) length of that logical bitstream for i==0 to n
  156091. OV_EINVAL if the stream is not seekable (we can't know the length)
  156092. or if stream is only partially open
  156093. */
  156094. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156095. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156096. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156097. if(i<0){
  156098. ogg_int64_t acc=0;
  156099. int i;
  156100. for(i=0;i<vf->links;i++)
  156101. acc+=ov_raw_total(vf,i);
  156102. return(acc);
  156103. }else{
  156104. return(vf->offsets[i+1]-vf->offsets[i]);
  156105. }
  156106. }
  156107. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156108. (samples) of that logical bitstream for i==0 to n
  156109. OV_EINVAL if the stream is not seekable (we can't know the
  156110. length) or only partially open
  156111. */
  156112. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156113. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156114. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156115. if(i<0){
  156116. ogg_int64_t acc=0;
  156117. int i;
  156118. for(i=0;i<vf->links;i++)
  156119. acc+=ov_pcm_total(vf,i);
  156120. return(acc);
  156121. }else{
  156122. return(vf->pcmlengths[i*2+1]);
  156123. }
  156124. }
  156125. /* returns: total seconds of content if i==-1
  156126. seconds in that logical bitstream for i==0 to n
  156127. OV_EINVAL if the stream is not seekable (we can't know the
  156128. length) or only partially open
  156129. */
  156130. double ov_time_total(OggVorbis_File *vf,int i){
  156131. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156132. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156133. if(i<0){
  156134. double acc=0;
  156135. int i;
  156136. for(i=0;i<vf->links;i++)
  156137. acc+=ov_time_total(vf,i);
  156138. return(acc);
  156139. }else{
  156140. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156141. }
  156142. }
  156143. /* seek to an offset relative to the *compressed* data. This also
  156144. scans packets to update the PCM cursor. It will cross a logical
  156145. bitstream boundary, but only if it can't get any packets out of the
  156146. tail of the bitstream we seek to (so no surprises).
  156147. returns zero on success, nonzero on failure */
  156148. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156149. ogg_stream_state work_os;
  156150. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156151. if(!vf->seekable)
  156152. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156153. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156154. /* don't yet clear out decoding machine (if it's initialized), in
  156155. the case we're in the same link. Restart the decode lapping, and
  156156. let _fetch_and_process_packet deal with a potential bitstream
  156157. boundary */
  156158. vf->pcm_offset=-1;
  156159. ogg_stream_reset_serialno(&vf->os,
  156160. vf->current_serialno); /* must set serialno */
  156161. vorbis_synthesis_restart(&vf->vd);
  156162. _seek_helper(vf,pos);
  156163. /* we need to make sure the pcm_offset is set, but we don't want to
  156164. advance the raw cursor past good packets just to get to the first
  156165. with a granulepos. That's not equivalent behavior to beginning
  156166. decoding as immediately after the seek position as possible.
  156167. So, a hack. We use two stream states; a local scratch state and
  156168. the shared vf->os stream state. We use the local state to
  156169. scan, and the shared state as a buffer for later decode.
  156170. Unfortuantely, on the last page we still advance to last packet
  156171. because the granulepos on the last page is not necessarily on a
  156172. packet boundary, and we need to make sure the granpos is
  156173. correct.
  156174. */
  156175. {
  156176. ogg_page og;
  156177. ogg_packet op;
  156178. int lastblock=0;
  156179. int accblock=0;
  156180. int thisblock;
  156181. int eosflag;
  156182. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156183. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156184. return from not necessarily
  156185. starting from the beginning */
  156186. while(1){
  156187. if(vf->ready_state>=STREAMSET){
  156188. /* snarf/scan a packet if we can */
  156189. int result=ogg_stream_packetout(&work_os,&op);
  156190. if(result>0){
  156191. if(vf->vi[vf->current_link].codec_setup){
  156192. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156193. if(thisblock<0){
  156194. ogg_stream_packetout(&vf->os,NULL);
  156195. thisblock=0;
  156196. }else{
  156197. if(eosflag)
  156198. ogg_stream_packetout(&vf->os,NULL);
  156199. else
  156200. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156201. }
  156202. if(op.granulepos!=-1){
  156203. int i,link=vf->current_link;
  156204. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156205. if(granulepos<0)granulepos=0;
  156206. for(i=0;i<link;i++)
  156207. granulepos+=vf->pcmlengths[i*2+1];
  156208. vf->pcm_offset=granulepos-accblock;
  156209. break;
  156210. }
  156211. lastblock=thisblock;
  156212. continue;
  156213. }else
  156214. ogg_stream_packetout(&vf->os,NULL);
  156215. }
  156216. }
  156217. if(!lastblock){
  156218. if(_get_next_page(vf,&og,-1)<0){
  156219. vf->pcm_offset=ov_pcm_total(vf,-1);
  156220. break;
  156221. }
  156222. }else{
  156223. /* huh? Bogus stream with packets but no granulepos */
  156224. vf->pcm_offset=-1;
  156225. break;
  156226. }
  156227. /* has our decoding just traversed a bitstream boundary? */
  156228. if(vf->ready_state>=STREAMSET)
  156229. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156230. _decode_clear(vf); /* clear out stream state */
  156231. ogg_stream_clear(&work_os);
  156232. }
  156233. if(vf->ready_state<STREAMSET){
  156234. int link;
  156235. vf->current_serialno=ogg_page_serialno(&og);
  156236. for(link=0;link<vf->links;link++)
  156237. if(vf->serialnos[link]==vf->current_serialno)break;
  156238. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156239. error out, leave
  156240. machine uninitialized */
  156241. vf->current_link=link;
  156242. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156243. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156244. vf->ready_state=STREAMSET;
  156245. }
  156246. ogg_stream_pagein(&vf->os,&og);
  156247. ogg_stream_pagein(&work_os,&og);
  156248. eosflag=ogg_page_eos(&og);
  156249. }
  156250. }
  156251. ogg_stream_clear(&work_os);
  156252. vf->bittrack=0.f;
  156253. vf->samptrack=0.f;
  156254. return(0);
  156255. seek_error:
  156256. /* dump the machine so we're in a known state */
  156257. vf->pcm_offset=-1;
  156258. ogg_stream_clear(&work_os);
  156259. _decode_clear(vf);
  156260. return OV_EBADLINK;
  156261. }
  156262. /* Page granularity seek (faster than sample granularity because we
  156263. don't do the last bit of decode to find a specific sample).
  156264. Seek to the last [granule marked] page preceeding the specified pos
  156265. location, such that decoding past the returned point will quickly
  156266. arrive at the requested position. */
  156267. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156268. int link=-1;
  156269. ogg_int64_t result=0;
  156270. ogg_int64_t total=ov_pcm_total(vf,-1);
  156271. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156272. if(!vf->seekable)return(OV_ENOSEEK);
  156273. if(pos<0 || pos>total)return(OV_EINVAL);
  156274. /* which bitstream section does this pcm offset occur in? */
  156275. for(link=vf->links-1;link>=0;link--){
  156276. total-=vf->pcmlengths[link*2+1];
  156277. if(pos>=total)break;
  156278. }
  156279. /* search within the logical bitstream for the page with the highest
  156280. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156281. missing pages or incorrect frame number information in the
  156282. bitstream could make our task impossible. Account for that (it
  156283. would be an error condition) */
  156284. /* new search algorithm by HB (Nicholas Vinen) */
  156285. {
  156286. ogg_int64_t end=vf->offsets[link+1];
  156287. ogg_int64_t begin=vf->offsets[link];
  156288. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156289. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156290. ogg_int64_t target=pos-total+begintime;
  156291. ogg_int64_t best=begin;
  156292. ogg_page og;
  156293. while(begin<end){
  156294. ogg_int64_t bisect;
  156295. if(end-begin<CHUNKSIZE){
  156296. bisect=begin;
  156297. }else{
  156298. /* take a (pretty decent) guess. */
  156299. bisect=begin +
  156300. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156301. if(bisect<=begin)
  156302. bisect=begin+1;
  156303. }
  156304. _seek_helper(vf,bisect);
  156305. while(begin<end){
  156306. result=_get_next_page(vf,&og,end-vf->offset);
  156307. if(result==OV_EREAD) goto seek_error;
  156308. if(result<0){
  156309. if(bisect<=begin+1)
  156310. end=begin; /* found it */
  156311. else{
  156312. if(bisect==0) goto seek_error;
  156313. bisect-=CHUNKSIZE;
  156314. if(bisect<=begin)bisect=begin+1;
  156315. _seek_helper(vf,bisect);
  156316. }
  156317. }else{
  156318. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156319. if(granulepos==-1)continue;
  156320. if(granulepos<target){
  156321. best=result; /* raw offset of packet with granulepos */
  156322. begin=vf->offset; /* raw offset of next page */
  156323. begintime=granulepos;
  156324. if(target-begintime>44100)break;
  156325. bisect=begin; /* *not* begin + 1 */
  156326. }else{
  156327. if(bisect<=begin+1)
  156328. end=begin; /* found it */
  156329. else{
  156330. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156331. end=result;
  156332. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156333. if(bisect<=begin)bisect=begin+1;
  156334. _seek_helper(vf,bisect);
  156335. }else{
  156336. end=result;
  156337. endtime=granulepos;
  156338. break;
  156339. }
  156340. }
  156341. }
  156342. }
  156343. }
  156344. }
  156345. /* found our page. seek to it, update pcm offset. Easier case than
  156346. raw_seek, don't keep packets preceeding granulepos. */
  156347. {
  156348. ogg_page og;
  156349. ogg_packet op;
  156350. /* seek */
  156351. _seek_helper(vf,best);
  156352. vf->pcm_offset=-1;
  156353. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156354. if(link!=vf->current_link){
  156355. /* Different link; dump entire decode machine */
  156356. _decode_clear(vf);
  156357. vf->current_link=link;
  156358. vf->current_serialno=ogg_page_serialno(&og);
  156359. vf->ready_state=STREAMSET;
  156360. }else{
  156361. vorbis_synthesis_restart(&vf->vd);
  156362. }
  156363. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156364. ogg_stream_pagein(&vf->os,&og);
  156365. /* pull out all but last packet; the one with granulepos */
  156366. while(1){
  156367. result=ogg_stream_packetpeek(&vf->os,&op);
  156368. if(result==0){
  156369. /* !!! the packet finishing this page originated on a
  156370. preceeding page. Keep fetching previous pages until we
  156371. get one with a granulepos or without the 'continued' flag
  156372. set. Then just use raw_seek for simplicity. */
  156373. _seek_helper(vf,best);
  156374. while(1){
  156375. result=_get_prev_page(vf,&og);
  156376. if(result<0) goto seek_error;
  156377. if(ogg_page_granulepos(&og)>-1 ||
  156378. !ogg_page_continued(&og)){
  156379. return ov_raw_seek(vf,result);
  156380. }
  156381. vf->offset=result;
  156382. }
  156383. }
  156384. if(result<0){
  156385. result = OV_EBADPACKET;
  156386. goto seek_error;
  156387. }
  156388. if(op.granulepos!=-1){
  156389. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156390. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156391. vf->pcm_offset+=total;
  156392. break;
  156393. }else
  156394. result=ogg_stream_packetout(&vf->os,NULL);
  156395. }
  156396. }
  156397. }
  156398. /* verify result */
  156399. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156400. result=OV_EFAULT;
  156401. goto seek_error;
  156402. }
  156403. vf->bittrack=0.f;
  156404. vf->samptrack=0.f;
  156405. return(0);
  156406. seek_error:
  156407. /* dump machine so we're in a known state */
  156408. vf->pcm_offset=-1;
  156409. _decode_clear(vf);
  156410. return (int)result;
  156411. }
  156412. /* seek to a sample offset relative to the decompressed pcm stream
  156413. returns zero on success, nonzero on failure */
  156414. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156415. int thisblock,lastblock=0;
  156416. int ret=ov_pcm_seek_page(vf,pos);
  156417. if(ret<0)return(ret);
  156418. if((ret=_make_decode_ready(vf)))return ret;
  156419. /* discard leading packets we don't need for the lapping of the
  156420. position we want; don't decode them */
  156421. while(1){
  156422. ogg_packet op;
  156423. ogg_page og;
  156424. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156425. if(ret>0){
  156426. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156427. if(thisblock<0){
  156428. ogg_stream_packetout(&vf->os,NULL);
  156429. continue; /* non audio packet */
  156430. }
  156431. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156432. if(vf->pcm_offset+((thisblock+
  156433. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156434. /* remove the packet from packet queue and track its granulepos */
  156435. ogg_stream_packetout(&vf->os,NULL);
  156436. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156437. only tracking, no
  156438. pcm_decode */
  156439. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156440. /* end of logical stream case is hard, especially with exact
  156441. length positioning. */
  156442. if(op.granulepos>-1){
  156443. int i;
  156444. /* always believe the stream markers */
  156445. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156446. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156447. for(i=0;i<vf->current_link;i++)
  156448. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156449. }
  156450. lastblock=thisblock;
  156451. }else{
  156452. if(ret<0 && ret!=OV_HOLE)break;
  156453. /* suck in a new page */
  156454. if(_get_next_page(vf,&og,-1)<0)break;
  156455. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156456. if(vf->ready_state<STREAMSET){
  156457. int link;
  156458. vf->current_serialno=ogg_page_serialno(&og);
  156459. for(link=0;link<vf->links;link++)
  156460. if(vf->serialnos[link]==vf->current_serialno)break;
  156461. if(link==vf->links)return(OV_EBADLINK);
  156462. vf->current_link=link;
  156463. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156464. vf->ready_state=STREAMSET;
  156465. ret=_make_decode_ready(vf);
  156466. if(ret)return ret;
  156467. lastblock=0;
  156468. }
  156469. ogg_stream_pagein(&vf->os,&og);
  156470. }
  156471. }
  156472. vf->bittrack=0.f;
  156473. vf->samptrack=0.f;
  156474. /* discard samples until we reach the desired position. Crossing a
  156475. logical bitstream boundary with abandon is OK. */
  156476. while(vf->pcm_offset<pos){
  156477. ogg_int64_t target=pos-vf->pcm_offset;
  156478. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156479. if(samples>target)samples=target;
  156480. vorbis_synthesis_read(&vf->vd,samples);
  156481. vf->pcm_offset+=samples;
  156482. if(samples<target)
  156483. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156484. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156485. }
  156486. return 0;
  156487. }
  156488. /* seek to a playback time relative to the decompressed pcm stream
  156489. returns zero on success, nonzero on failure */
  156490. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156491. /* translate time to PCM position and call ov_pcm_seek */
  156492. int link=-1;
  156493. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156494. double time_total=ov_time_total(vf,-1);
  156495. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156496. if(!vf->seekable)return(OV_ENOSEEK);
  156497. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156498. /* which bitstream section does this time offset occur in? */
  156499. for(link=vf->links-1;link>=0;link--){
  156500. pcm_total-=vf->pcmlengths[link*2+1];
  156501. time_total-=ov_time_total(vf,link);
  156502. if(seconds>=time_total)break;
  156503. }
  156504. /* enough information to convert time offset to pcm offset */
  156505. {
  156506. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156507. return(ov_pcm_seek(vf,target));
  156508. }
  156509. }
  156510. /* page-granularity version of ov_time_seek
  156511. returns zero on success, nonzero on failure */
  156512. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156513. /* translate time to PCM position and call ov_pcm_seek */
  156514. int link=-1;
  156515. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156516. double time_total=ov_time_total(vf,-1);
  156517. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156518. if(!vf->seekable)return(OV_ENOSEEK);
  156519. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156520. /* which bitstream section does this time offset occur in? */
  156521. for(link=vf->links-1;link>=0;link--){
  156522. pcm_total-=vf->pcmlengths[link*2+1];
  156523. time_total-=ov_time_total(vf,link);
  156524. if(seconds>=time_total)break;
  156525. }
  156526. /* enough information to convert time offset to pcm offset */
  156527. {
  156528. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156529. return(ov_pcm_seek_page(vf,target));
  156530. }
  156531. }
  156532. /* tell the current stream offset cursor. Note that seek followed by
  156533. tell will likely not give the set offset due to caching */
  156534. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156535. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156536. return(vf->offset);
  156537. }
  156538. /* return PCM offset (sample) of next PCM sample to be read */
  156539. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156540. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156541. return(vf->pcm_offset);
  156542. }
  156543. /* return time offset (seconds) of next PCM sample to be read */
  156544. double ov_time_tell(OggVorbis_File *vf){
  156545. int link=0;
  156546. ogg_int64_t pcm_total=0;
  156547. double time_total=0.f;
  156548. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156549. if(vf->seekable){
  156550. pcm_total=ov_pcm_total(vf,-1);
  156551. time_total=ov_time_total(vf,-1);
  156552. /* which bitstream section does this time offset occur in? */
  156553. for(link=vf->links-1;link>=0;link--){
  156554. pcm_total-=vf->pcmlengths[link*2+1];
  156555. time_total-=ov_time_total(vf,link);
  156556. if(vf->pcm_offset>=pcm_total)break;
  156557. }
  156558. }
  156559. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156560. }
  156561. /* link: -1) return the vorbis_info struct for the bitstream section
  156562. currently being decoded
  156563. 0-n) to request information for a specific bitstream section
  156564. In the case of a non-seekable bitstream, any call returns the
  156565. current bitstream. NULL in the case that the machine is not
  156566. initialized */
  156567. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156568. if(vf->seekable){
  156569. if(link<0)
  156570. if(vf->ready_state>=STREAMSET)
  156571. return vf->vi+vf->current_link;
  156572. else
  156573. return vf->vi;
  156574. else
  156575. if(link>=vf->links)
  156576. return NULL;
  156577. else
  156578. return vf->vi+link;
  156579. }else{
  156580. return vf->vi;
  156581. }
  156582. }
  156583. /* grr, strong typing, grr, no templates/inheritence, grr */
  156584. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156585. if(vf->seekable){
  156586. if(link<0)
  156587. if(vf->ready_state>=STREAMSET)
  156588. return vf->vc+vf->current_link;
  156589. else
  156590. return vf->vc;
  156591. else
  156592. if(link>=vf->links)
  156593. return NULL;
  156594. else
  156595. return vf->vc+link;
  156596. }else{
  156597. return vf->vc;
  156598. }
  156599. }
  156600. static int host_is_big_endian() {
  156601. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156602. unsigned char *bytewise = (unsigned char *)&pattern;
  156603. if (bytewise[0] == 0xfe) return 1;
  156604. return 0;
  156605. }
  156606. /* up to this point, everything could more or less hide the multiple
  156607. logical bitstream nature of chaining from the toplevel application
  156608. if the toplevel application didn't particularly care. However, at
  156609. the point that we actually read audio back, the multiple-section
  156610. nature must surface: Multiple bitstream sections do not necessarily
  156611. have to have the same number of channels or sampling rate.
  156612. ov_read returns the sequential logical bitstream number currently
  156613. being decoded along with the PCM data in order that the toplevel
  156614. application can take action on channel/sample rate changes. This
  156615. number will be incremented even for streamed (non-seekable) streams
  156616. (for seekable streams, it represents the actual logical bitstream
  156617. index within the physical bitstream. Note that the accessor
  156618. functions above are aware of this dichotomy).
  156619. input values: buffer) a buffer to hold packed PCM data for return
  156620. length) the byte length requested to be placed into buffer
  156621. bigendianp) should the data be packed LSB first (0) or
  156622. MSB first (1)
  156623. word) word size for output. currently 1 (byte) or
  156624. 2 (16 bit short)
  156625. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156626. 0) EOF
  156627. n) number of bytes of PCM actually returned. The
  156628. below works on a packet-by-packet basis, so the
  156629. return length is not related to the 'length' passed
  156630. in, just guaranteed to fit.
  156631. *section) set to the logical bitstream number */
  156632. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156633. int bigendianp,int word,int sgned,int *bitstream){
  156634. int i,j;
  156635. int host_endian = host_is_big_endian();
  156636. float **pcm;
  156637. long samples;
  156638. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156639. while(1){
  156640. if(vf->ready_state==INITSET){
  156641. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156642. if(samples)break;
  156643. }
  156644. /* suck in another packet */
  156645. {
  156646. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156647. if(ret==OV_EOF)
  156648. return(0);
  156649. if(ret<=0)
  156650. return(ret);
  156651. }
  156652. }
  156653. if(samples>0){
  156654. /* yay! proceed to pack data into the byte buffer */
  156655. long channels=ov_info(vf,-1)->channels;
  156656. long bytespersample=word * channels;
  156657. vorbis_fpu_control fpu;
  156658. (void) fpu; // (to avoid a warning about it being unused)
  156659. if(samples>length/bytespersample)samples=length/bytespersample;
  156660. if(samples <= 0)
  156661. return OV_EINVAL;
  156662. /* a tight loop to pack each size */
  156663. {
  156664. int val;
  156665. if(word==1){
  156666. int off=(sgned?0:128);
  156667. vorbis_fpu_setround(&fpu);
  156668. for(j=0;j<samples;j++)
  156669. for(i=0;i<channels;i++){
  156670. val=vorbis_ftoi(pcm[i][j]*128.f);
  156671. if(val>127)val=127;
  156672. else if(val<-128)val=-128;
  156673. *buffer++=val+off;
  156674. }
  156675. vorbis_fpu_restore(fpu);
  156676. }else{
  156677. int off=(sgned?0:32768);
  156678. if(host_endian==bigendianp){
  156679. if(sgned){
  156680. vorbis_fpu_setround(&fpu);
  156681. for(i=0;i<channels;i++) { /* It's faster in this order */
  156682. float *src=pcm[i];
  156683. short *dest=((short *)buffer)+i;
  156684. for(j=0;j<samples;j++) {
  156685. val=vorbis_ftoi(src[j]*32768.f);
  156686. if(val>32767)val=32767;
  156687. else if(val<-32768)val=-32768;
  156688. *dest=val;
  156689. dest+=channels;
  156690. }
  156691. }
  156692. vorbis_fpu_restore(fpu);
  156693. }else{
  156694. vorbis_fpu_setround(&fpu);
  156695. for(i=0;i<channels;i++) {
  156696. float *src=pcm[i];
  156697. short *dest=((short *)buffer)+i;
  156698. for(j=0;j<samples;j++) {
  156699. val=vorbis_ftoi(src[j]*32768.f);
  156700. if(val>32767)val=32767;
  156701. else if(val<-32768)val=-32768;
  156702. *dest=val+off;
  156703. dest+=channels;
  156704. }
  156705. }
  156706. vorbis_fpu_restore(fpu);
  156707. }
  156708. }else if(bigendianp){
  156709. vorbis_fpu_setround(&fpu);
  156710. for(j=0;j<samples;j++)
  156711. for(i=0;i<channels;i++){
  156712. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156713. if(val>32767)val=32767;
  156714. else if(val<-32768)val=-32768;
  156715. val+=off;
  156716. *buffer++=(val>>8);
  156717. *buffer++=(val&0xff);
  156718. }
  156719. vorbis_fpu_restore(fpu);
  156720. }else{
  156721. int val;
  156722. vorbis_fpu_setround(&fpu);
  156723. for(j=0;j<samples;j++)
  156724. for(i=0;i<channels;i++){
  156725. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156726. if(val>32767)val=32767;
  156727. else if(val<-32768)val=-32768;
  156728. val+=off;
  156729. *buffer++=(val&0xff);
  156730. *buffer++=(val>>8);
  156731. }
  156732. vorbis_fpu_restore(fpu);
  156733. }
  156734. }
  156735. }
  156736. vorbis_synthesis_read(&vf->vd,samples);
  156737. vf->pcm_offset+=samples;
  156738. if(bitstream)*bitstream=vf->current_link;
  156739. return(samples*bytespersample);
  156740. }else{
  156741. return(samples);
  156742. }
  156743. }
  156744. /* input values: pcm_channels) a float vector per channel of output
  156745. length) the sample length being read by the app
  156746. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156747. 0) EOF
  156748. n) number of samples of PCM actually returned. The
  156749. below works on a packet-by-packet basis, so the
  156750. return length is not related to the 'length' passed
  156751. in, just guaranteed to fit.
  156752. *section) set to the logical bitstream number */
  156753. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156754. int *bitstream){
  156755. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156756. while(1){
  156757. if(vf->ready_state==INITSET){
  156758. float **pcm;
  156759. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156760. if(samples){
  156761. if(pcm_channels)*pcm_channels=pcm;
  156762. if(samples>length)samples=length;
  156763. vorbis_synthesis_read(&vf->vd,samples);
  156764. vf->pcm_offset+=samples;
  156765. if(bitstream)*bitstream=vf->current_link;
  156766. return samples;
  156767. }
  156768. }
  156769. /* suck in another packet */
  156770. {
  156771. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156772. if(ret==OV_EOF)return(0);
  156773. if(ret<=0)return(ret);
  156774. }
  156775. }
  156776. }
  156777. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156778. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156779. ogg_int64_t off);
  156780. static void _ov_splice(float **pcm,float **lappcm,
  156781. int n1, int n2,
  156782. int ch1, int ch2,
  156783. float *w1, float *w2){
  156784. int i,j;
  156785. float *w=w1;
  156786. int n=n1;
  156787. if(n1>n2){
  156788. n=n2;
  156789. w=w2;
  156790. }
  156791. /* splice */
  156792. for(j=0;j<ch1 && j<ch2;j++){
  156793. float *s=lappcm[j];
  156794. float *d=pcm[j];
  156795. for(i=0;i<n;i++){
  156796. float wd=w[i]*w[i];
  156797. float ws=1.-wd;
  156798. d[i]=d[i]*wd + s[i]*ws;
  156799. }
  156800. }
  156801. /* window from zero */
  156802. for(;j<ch2;j++){
  156803. float *d=pcm[j];
  156804. for(i=0;i<n;i++){
  156805. float wd=w[i]*w[i];
  156806. d[i]=d[i]*wd;
  156807. }
  156808. }
  156809. }
  156810. /* make sure vf is INITSET */
  156811. static int _ov_initset(OggVorbis_File *vf){
  156812. while(1){
  156813. if(vf->ready_state==INITSET)break;
  156814. /* suck in another packet */
  156815. {
  156816. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156817. if(ret<0 && ret!=OV_HOLE)return(ret);
  156818. }
  156819. }
  156820. return 0;
  156821. }
  156822. /* make sure vf is INITSET and that we have a primed buffer; if
  156823. we're crosslapping at a stream section boundary, this also makes
  156824. sure we're sanity checking against the right stream information */
  156825. static int _ov_initprime(OggVorbis_File *vf){
  156826. vorbis_dsp_state *vd=&vf->vd;
  156827. while(1){
  156828. if(vf->ready_state==INITSET)
  156829. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156830. /* suck in another packet */
  156831. {
  156832. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156833. if(ret<0 && ret!=OV_HOLE)return(ret);
  156834. }
  156835. }
  156836. return 0;
  156837. }
  156838. /* grab enough data for lapping from vf; this may be in the form of
  156839. unreturned, already-decoded pcm, remaining PCM we will need to
  156840. decode, or synthetic postextrapolation from last packets. */
  156841. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156842. float **lappcm,int lapsize){
  156843. int lapcount=0,i;
  156844. float **pcm;
  156845. /* try first to decode the lapping data */
  156846. while(lapcount<lapsize){
  156847. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156848. if(samples){
  156849. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156850. for(i=0;i<vi->channels;i++)
  156851. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156852. lapcount+=samples;
  156853. vorbis_synthesis_read(vd,samples);
  156854. }else{
  156855. /* suck in another packet */
  156856. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156857. if(ret==OV_EOF)break;
  156858. }
  156859. }
  156860. if(lapcount<lapsize){
  156861. /* failed to get lapping data from normal decode; pry it from the
  156862. postextrapolation buffering, or the second half of the MDCT
  156863. from the last packet */
  156864. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156865. if(samples==0){
  156866. for(i=0;i<vi->channels;i++)
  156867. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156868. lapcount=lapsize;
  156869. }else{
  156870. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156871. for(i=0;i<vi->channels;i++)
  156872. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156873. lapcount+=samples;
  156874. }
  156875. }
  156876. }
  156877. /* this sets up crosslapping of a sample by using trailing data from
  156878. sample 1 and lapping it into the windowing buffer of sample 2 */
  156879. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156880. vorbis_info *vi1,*vi2;
  156881. float **lappcm;
  156882. float **pcm;
  156883. float *w1,*w2;
  156884. int n1,n2,i,ret,hs1,hs2;
  156885. if(vf1==vf2)return(0); /* degenerate case */
  156886. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156887. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156888. /* the relevant overlap buffers must be pre-checked and pre-primed
  156889. before looking at settings in the event that priming would cross
  156890. a bitstream boundary. So, do it now */
  156891. ret=_ov_initset(vf1);
  156892. if(ret)return(ret);
  156893. ret=_ov_initprime(vf2);
  156894. if(ret)return(ret);
  156895. vi1=ov_info(vf1,-1);
  156896. vi2=ov_info(vf2,-1);
  156897. hs1=ov_halfrate_p(vf1);
  156898. hs2=ov_halfrate_p(vf2);
  156899. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156900. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156901. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156902. w1=vorbis_window(&vf1->vd,0);
  156903. w2=vorbis_window(&vf2->vd,0);
  156904. for(i=0;i<vi1->channels;i++)
  156905. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156906. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156907. /* have a lapping buffer from vf1; now to splice it into the lapping
  156908. buffer of vf2 */
  156909. /* consolidate and expose the buffer. */
  156910. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156911. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156912. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156913. /* splice */
  156914. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156915. /* done */
  156916. return(0);
  156917. }
  156918. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156919. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156920. vorbis_info *vi;
  156921. float **lappcm;
  156922. float **pcm;
  156923. float *w1,*w2;
  156924. int n1,n2,ch1,ch2,hs;
  156925. int i,ret;
  156926. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156927. ret=_ov_initset(vf);
  156928. if(ret)return(ret);
  156929. vi=ov_info(vf,-1);
  156930. hs=ov_halfrate_p(vf);
  156931. ch1=vi->channels;
  156932. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156933. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156934. persistent; even if the decode state
  156935. from this link gets dumped, this
  156936. window array continues to exist */
  156937. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156938. for(i=0;i<ch1;i++)
  156939. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156940. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156941. /* have lapping data; seek and prime the buffer */
  156942. ret=localseek(vf,pos);
  156943. if(ret)return ret;
  156944. ret=_ov_initprime(vf);
  156945. if(ret)return(ret);
  156946. /* Guard against cross-link changes; they're perfectly legal */
  156947. vi=ov_info(vf,-1);
  156948. ch2=vi->channels;
  156949. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156950. w2=vorbis_window(&vf->vd,0);
  156951. /* consolidate and expose the buffer. */
  156952. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156953. /* splice */
  156954. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156955. /* done */
  156956. return(0);
  156957. }
  156958. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156959. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156960. }
  156961. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156962. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156963. }
  156964. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156965. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156966. }
  156967. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156968. int (*localseek)(OggVorbis_File *,double)){
  156969. vorbis_info *vi;
  156970. float **lappcm;
  156971. float **pcm;
  156972. float *w1,*w2;
  156973. int n1,n2,ch1,ch2,hs;
  156974. int i,ret;
  156975. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156976. ret=_ov_initset(vf);
  156977. if(ret)return(ret);
  156978. vi=ov_info(vf,-1);
  156979. hs=ov_halfrate_p(vf);
  156980. ch1=vi->channels;
  156981. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156982. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156983. persistent; even if the decode state
  156984. from this link gets dumped, this
  156985. window array continues to exist */
  156986. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156987. for(i=0;i<ch1;i++)
  156988. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156989. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156990. /* have lapping data; seek and prime the buffer */
  156991. ret=localseek(vf,pos);
  156992. if(ret)return ret;
  156993. ret=_ov_initprime(vf);
  156994. if(ret)return(ret);
  156995. /* Guard against cross-link changes; they're perfectly legal */
  156996. vi=ov_info(vf,-1);
  156997. ch2=vi->channels;
  156998. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156999. w2=vorbis_window(&vf->vd,0);
  157000. /* consolidate and expose the buffer. */
  157001. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157002. /* splice */
  157003. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157004. /* done */
  157005. return(0);
  157006. }
  157007. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157008. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157009. }
  157010. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157011. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157012. }
  157013. #endif
  157014. /*** End of inlined file: vorbisfile.c ***/
  157015. /*** Start of inlined file: window.c ***/
  157016. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157017. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157018. // tasks..
  157019. #if JUCE_MSVC
  157020. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157021. #endif
  157022. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157023. #if JUCE_USE_OGGVORBIS
  157024. #include <stdlib.h>
  157025. #include <math.h>
  157026. static float vwin64[32] = {
  157027. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157028. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157029. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157030. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157031. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157032. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157033. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157034. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157035. };
  157036. static float vwin128[64] = {
  157037. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157038. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157039. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157040. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157041. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157042. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157043. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157044. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157045. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157046. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157047. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157048. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157049. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157050. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157051. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157052. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157053. };
  157054. static float vwin256[128] = {
  157055. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157056. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157057. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157058. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157059. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157060. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157061. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157062. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157063. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157064. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157065. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157066. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157067. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157068. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157069. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157070. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157071. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157072. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157073. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157074. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157075. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157076. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157077. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157078. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157079. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157080. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157081. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157082. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157083. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157084. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157085. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157086. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157087. };
  157088. static float vwin512[256] = {
  157089. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157090. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157091. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157092. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157093. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157094. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157095. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157096. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157097. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157098. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157099. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157100. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157101. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157102. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157103. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157104. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157105. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157106. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157107. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157108. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157109. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157110. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157111. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157112. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157113. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157114. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157115. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157116. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157117. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157118. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157119. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157120. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157121. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157122. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157123. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157124. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157125. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157126. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157127. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157128. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157129. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157130. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157131. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157132. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157133. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157134. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157135. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157136. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157137. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157138. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157139. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157140. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157141. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157142. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157143. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157144. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157145. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157146. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157147. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157148. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157149. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157150. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157151. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157152. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157153. };
  157154. static float vwin1024[512] = {
  157155. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157156. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157157. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157158. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157159. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157160. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157161. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157162. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157163. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157164. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157165. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157166. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157167. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157168. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157169. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157170. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157171. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157172. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157173. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157174. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157175. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157176. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157177. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157178. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157179. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157180. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157181. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157182. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157183. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157184. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157185. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157186. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157187. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157188. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157189. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157190. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157191. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157192. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157193. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157194. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157195. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157196. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157197. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157198. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157199. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157200. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157201. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157202. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157203. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157204. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157205. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157206. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157207. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157208. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157209. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157210. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157211. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157212. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157213. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157214. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157215. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157216. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157217. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157218. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157219. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157220. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157221. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157222. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157223. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157224. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157225. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157226. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157227. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157228. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157229. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157230. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157231. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157232. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157233. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157234. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157235. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157236. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157237. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157238. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157239. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157240. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157241. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157242. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157243. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157244. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157245. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157246. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157247. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157248. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157249. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157250. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157251. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157252. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157253. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157254. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157255. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157256. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157257. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157258. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157259. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157260. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157261. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157262. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157263. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157264. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157265. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157266. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157267. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157268. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157269. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157270. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157271. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157272. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157273. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157274. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157275. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157276. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157277. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157278. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157279. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157280. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157281. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157282. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157283. };
  157284. static float vwin2048[1024] = {
  157285. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157286. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157287. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157288. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157289. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157290. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157291. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157292. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157293. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157294. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157295. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157296. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157297. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157298. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157299. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157300. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157301. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157302. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157303. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157304. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157305. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157306. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157307. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157308. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157309. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157310. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157311. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157312. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157313. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157314. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157315. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157316. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157317. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157318. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157319. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157320. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157321. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157322. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157323. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157324. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157325. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157326. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157327. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157328. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157329. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157330. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157331. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157332. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157333. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157334. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157335. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157336. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157337. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157338. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157339. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157340. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157341. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157342. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157343. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157344. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157345. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157346. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157347. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157348. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157349. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157350. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157351. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157352. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157353. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157354. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157355. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157356. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157357. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157358. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157359. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157360. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157361. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157362. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157363. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157364. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157365. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157366. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157367. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157368. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157369. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157370. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157371. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157372. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157373. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157374. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157375. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157376. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157377. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157378. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157379. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157380. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157381. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157382. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157383. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157384. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157385. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157386. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157387. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157388. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157389. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157390. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157391. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157392. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157393. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157394. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157395. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157396. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157397. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157398. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157399. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157400. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157401. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157402. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157403. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157404. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157405. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157406. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157407. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157408. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157409. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157410. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157411. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157412. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157413. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157414. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157415. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157416. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157417. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157418. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157419. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157420. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157421. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157422. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157423. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157424. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157425. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157426. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157427. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157428. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157429. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157430. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157431. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157432. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157433. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157434. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157435. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157436. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157437. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157438. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157439. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157440. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157441. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157442. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157443. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157444. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157445. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157446. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157447. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157448. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157449. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157450. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157451. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157452. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157453. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157454. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157455. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157456. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157457. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157458. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157459. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157460. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157461. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157462. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157463. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157464. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157465. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157466. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157467. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157468. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157469. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157470. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157471. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157472. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157473. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157474. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157475. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157476. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157477. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157478. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157479. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157480. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157481. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157482. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157483. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157484. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157485. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157486. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157487. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157488. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157489. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157490. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157491. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157492. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157493. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157494. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157495. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157496. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157497. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157498. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157499. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157500. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157501. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157502. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157503. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157504. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157505. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157506. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157507. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157508. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157509. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157510. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157511. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157512. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157513. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157514. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157515. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157516. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157517. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157518. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157519. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157520. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157521. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157522. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157523. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157524. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157525. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157526. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157527. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157528. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157529. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157530. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157531. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157532. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157533. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157534. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157535. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157536. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157537. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157538. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157539. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157540. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157541. };
  157542. static float vwin4096[2048] = {
  157543. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157544. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157545. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157546. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157547. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157548. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157549. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157550. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157551. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157552. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157553. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157554. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157555. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157556. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157557. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157558. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157559. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157560. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157561. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157562. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157563. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157564. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157565. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157566. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157567. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157568. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157569. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157570. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157571. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157572. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157573. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157574. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157575. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157576. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157577. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157578. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157579. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157580. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157581. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157582. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157583. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157584. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157585. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157586. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157587. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157588. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157589. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157590. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157591. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157592. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157593. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157594. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157595. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157596. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157597. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157598. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157599. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157600. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157601. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157602. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157603. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157604. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157605. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157606. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157607. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157608. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157609. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157610. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157611. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157612. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157613. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157614. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157615. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157616. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157617. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157618. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157619. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157620. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157621. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157622. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157623. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157624. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157625. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157626. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157627. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157628. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157629. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157630. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157631. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157632. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157633. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157634. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157635. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157636. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157637. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157638. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157639. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157640. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157641. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157642. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157643. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157644. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157645. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157646. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157647. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157648. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157649. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157650. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157651. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157652. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157653. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157654. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157655. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157656. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157657. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157658. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157659. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157660. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157661. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157662. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157663. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157664. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157665. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157666. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157667. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157668. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157669. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157670. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157671. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157672. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157673. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157674. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157675. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157676. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157677. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157678. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157679. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157680. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157681. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157682. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157683. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157684. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157685. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157686. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157687. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157688. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157689. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157690. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157691. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157692. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157693. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157694. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157695. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157696. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157697. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157698. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157699. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157700. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157701. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157702. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157703. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157704. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157705. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157706. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157707. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157708. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157709. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157710. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157711. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157712. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157713. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157714. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157715. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157716. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157717. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157718. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157719. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157720. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157721. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157722. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157723. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157724. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157725. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157726. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157727. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157728. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157729. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157730. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157731. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157732. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157733. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157734. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157735. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157736. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157737. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157738. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157739. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157740. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157741. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157742. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157743. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157744. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157745. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157746. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157747. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157748. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157749. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157750. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157751. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157752. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157753. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157754. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157755. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157756. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157757. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157758. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157759. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157760. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157761. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157762. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157763. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157764. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157765. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157766. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157767. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157768. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157769. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157770. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157771. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157772. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157773. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157774. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157775. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157776. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157777. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157778. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157779. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157780. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157781. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157782. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157783. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157784. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157785. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157786. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157787. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157788. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157789. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157790. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157791. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157792. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157793. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157794. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157795. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157796. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157797. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157798. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157799. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157800. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157801. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157802. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157803. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157804. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157805. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157806. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157807. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157808. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157809. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157810. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157811. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157812. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157813. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157814. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157815. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157816. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157817. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157818. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157819. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157820. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157821. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157822. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157823. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157824. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157825. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157826. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157827. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157828. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157829. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157830. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157831. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157832. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157833. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157834. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157835. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157836. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157837. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157838. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157839. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157840. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157841. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157842. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157843. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157844. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157845. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157846. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157847. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157848. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157849. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157850. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157851. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157852. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157853. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157854. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157855. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157856. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157857. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157858. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157859. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157860. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157861. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157862. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157863. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157864. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157865. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157866. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157867. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157868. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157869. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157870. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157871. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157872. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157873. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157874. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157875. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157876. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157877. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157878. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157879. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157880. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157881. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157882. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157883. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157884. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157885. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157886. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157887. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157888. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157889. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157890. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157891. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157892. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157893. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157894. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157895. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157896. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157897. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157898. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157899. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157900. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157901. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157902. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157903. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157904. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157905. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157906. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157907. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157908. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157909. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157910. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157911. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157912. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157913. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157914. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157915. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157916. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157917. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157918. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157919. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157920. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157921. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157922. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157923. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157924. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157925. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157926. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157927. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157928. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157929. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157930. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157931. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157932. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157933. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157934. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157935. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157936. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157937. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157938. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157939. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157940. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157941. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157942. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157943. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157944. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157945. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157946. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157947. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157948. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157949. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157950. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157951. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157952. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157953. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157954. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157955. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157956. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157957. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157958. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157959. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157960. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157961. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157962. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157963. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157964. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157965. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157966. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157967. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157968. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157969. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157970. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157971. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157972. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157973. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157974. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157975. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157976. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157977. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157978. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157979. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157980. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157981. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157982. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157983. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157984. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157985. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157986. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157987. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157988. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157989. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157990. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157991. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157992. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157993. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157994. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157995. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157996. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157997. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157998. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157999. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158000. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158001. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158002. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158003. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158004. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158005. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158006. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158007. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158008. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158009. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158010. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158011. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158012. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158013. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158014. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158015. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158016. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158017. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158018. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158019. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158020. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158021. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158022. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158023. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158024. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158025. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158026. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158027. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158028. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158029. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158030. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158031. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158032. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158033. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158034. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158035. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158036. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158037. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158038. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158039. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158040. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158041. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158042. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158043. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158044. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158045. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158046. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158047. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158048. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158049. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158050. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158051. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158052. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158053. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158054. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158055. };
  158056. static float vwin8192[4096] = {
  158057. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158058. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158059. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158060. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158061. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158062. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158063. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158064. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158065. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158066. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158067. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158068. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158069. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158070. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158071. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158072. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158073. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158074. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158075. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158076. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158077. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158078. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158079. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158080. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158081. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158082. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158083. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158084. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158085. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158086. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158087. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158088. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158089. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158090. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158091. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158092. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158093. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158094. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158095. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158096. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158097. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158098. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158099. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158100. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158101. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158102. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158103. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158104. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158105. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158106. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158107. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158108. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158109. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158110. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158111. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158112. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158113. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158114. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158115. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158116. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158117. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158118. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158119. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158120. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158121. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158122. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158123. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158124. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158125. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158126. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158127. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158128. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158129. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158130. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158131. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158132. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158133. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158134. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158135. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158136. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158137. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158138. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158139. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158140. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158141. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158142. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158143. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158144. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158145. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158146. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158147. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158148. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158149. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158150. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158151. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158152. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158153. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158154. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158155. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158156. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158157. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158158. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158159. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158160. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158161. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158162. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158163. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158164. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158165. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158166. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158167. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158168. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158169. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158170. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158171. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158172. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158173. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158174. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158175. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158176. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158177. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158178. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158179. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158180. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158181. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158182. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158183. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158184. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158185. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158186. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158187. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158188. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158189. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158190. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158191. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158192. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158193. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158194. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158195. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158196. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158197. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158198. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158199. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158200. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158201. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158202. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158203. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158204. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158205. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158206. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158207. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158208. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158209. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158210. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158211. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158212. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158213. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158214. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158215. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158216. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158217. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158218. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158219. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158220. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158221. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158222. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158223. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158224. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158225. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158226. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158227. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158228. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158229. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158230. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158231. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158232. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158233. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158234. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158235. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158236. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158237. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158238. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158239. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158240. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158241. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158242. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158243. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158244. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158245. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158246. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158247. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158248. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158249. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158250. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158251. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158252. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158253. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158254. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158255. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158256. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158257. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158258. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158259. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158260. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158261. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158262. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158263. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158264. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158265. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158266. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158267. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158268. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158269. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158270. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158271. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158272. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158273. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158274. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158275. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158276. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158277. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158278. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158279. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158280. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158281. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158282. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158283. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158284. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158285. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158286. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158287. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158288. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158289. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158290. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158291. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158292. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158293. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158294. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158295. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158296. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158297. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158298. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158299. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158300. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158301. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158302. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158303. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158304. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158305. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158306. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158307. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158308. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158309. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158310. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158311. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158312. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158313. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158314. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158315. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158316. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158317. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158318. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158319. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158320. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158321. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158322. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158323. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158324. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158325. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158326. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158327. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158328. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158329. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158330. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158331. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158332. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158333. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158334. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158335. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158336. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158337. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158338. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158339. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158340. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158341. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158342. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158343. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158344. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158345. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158346. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158347. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158348. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158349. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158350. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158351. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158352. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158353. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158354. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158355. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158356. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158357. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158358. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158359. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158360. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158361. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158362. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158363. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158364. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158365. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158366. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158367. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158368. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158369. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158370. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158371. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158372. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158373. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158374. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158375. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158376. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158377. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158378. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158379. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158380. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158381. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158382. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158383. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158384. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158385. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158386. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158387. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158388. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158389. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158390. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158391. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158392. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158393. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158394. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158395. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158396. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158397. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158398. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158399. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158400. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158401. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158402. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158403. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158404. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158405. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158406. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158407. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158408. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158409. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158410. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158411. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158412. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158413. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158414. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158415. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158416. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158417. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158418. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158419. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158420. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158421. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158422. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158423. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158424. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158425. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158426. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158427. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158428. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158429. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158430. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158431. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158432. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158433. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158434. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158435. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158436. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158437. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158438. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158439. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158440. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158441. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158442. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158443. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158444. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158445. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158446. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158447. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158448. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158449. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158450. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158451. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158452. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158453. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158454. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158455. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158456. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158457. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158458. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158459. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158460. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158461. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158462. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158463. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158464. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158465. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158466. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158467. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158468. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158469. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158470. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158471. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158472. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158473. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158474. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158475. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158476. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158477. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158478. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158479. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158480. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158481. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158482. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158483. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158484. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158485. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158486. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158487. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158488. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158489. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158490. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158491. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158492. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158493. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158494. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158495. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158496. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158497. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158498. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158499. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158500. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158501. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158502. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158503. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158504. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158505. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158506. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158507. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158508. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158509. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158510. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158511. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158512. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158513. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158514. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158515. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158516. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158517. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158518. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158519. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158520. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158521. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158522. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158523. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158524. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158525. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158526. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158527. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158528. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158529. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158530. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158531. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158532. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158533. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158534. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158535. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158536. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158537. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158538. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158539. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158540. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158541. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158542. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158543. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158544. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158545. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158546. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158547. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158548. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158549. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158550. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158551. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158552. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158553. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158554. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158555. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158556. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158557. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158558. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158559. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158560. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158561. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158562. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158563. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158564. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158565. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158566. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158567. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158568. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158569. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158570. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158571. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158572. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158573. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158574. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158575. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158576. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158577. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158578. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158579. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158580. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158581. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158582. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158583. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158584. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158585. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158586. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158587. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158588. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158589. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158590. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158591. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158592. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158593. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158594. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158595. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158596. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158597. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158598. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158599. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158600. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158601. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158602. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158603. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158604. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158605. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158606. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158607. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158608. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158609. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158610. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158611. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158612. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158613. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158614. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158615. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158616. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158617. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158618. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158619. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158620. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158621. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158622. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158623. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158624. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158625. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158626. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158627. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158628. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158629. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158630. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158631. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158632. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158633. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158634. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158635. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158636. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158637. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158638. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158639. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158640. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158641. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158642. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158643. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158644. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158645. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158646. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158647. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158648. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158649. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158650. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158651. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158652. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158653. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158654. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158655. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158656. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158657. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158658. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158659. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158660. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158661. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158662. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158663. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158664. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158665. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158666. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158667. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158668. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158669. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158670. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158671. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158672. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158673. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158674. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158675. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158676. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158677. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158678. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158679. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158680. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158681. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158682. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158683. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158684. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158685. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158686. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158687. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158688. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158689. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158690. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158691. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158692. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158693. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158694. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158695. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158696. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158697. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158698. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158699. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158700. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158701. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158702. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158703. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158704. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158705. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158706. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158707. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158708. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158709. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158710. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158711. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158712. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158713. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158714. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158715. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158716. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158717. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158718. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158719. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158720. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158721. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158722. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158723. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158724. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158725. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158726. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158727. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158728. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158729. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158730. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158731. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158732. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158733. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158734. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158735. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158736. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158737. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158738. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158739. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158740. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158741. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158742. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158743. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158744. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158745. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158746. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158747. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158748. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158749. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158750. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158751. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158752. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158753. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158754. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158755. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158756. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158757. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158758. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158759. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158760. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158761. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158762. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158763. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158764. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158765. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158766. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158767. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158768. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158769. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158770. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158771. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158772. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158773. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158774. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158775. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158776. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158777. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158778. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158779. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158780. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158781. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158782. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158783. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158784. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158785. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158786. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158787. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158788. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158789. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158790. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158791. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158792. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158793. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158794. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158795. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158796. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158797. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158798. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158799. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158800. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158801. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158802. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158803. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158804. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158805. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158806. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158807. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158808. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158809. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158810. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158811. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158812. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158813. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158814. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158815. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158816. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158817. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158818. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158819. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158820. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158821. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158822. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158823. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158824. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158825. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158826. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158827. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158828. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158829. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158830. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158831. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158832. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158833. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158834. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158835. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158836. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158837. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158838. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158839. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158840. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158841. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158842. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158843. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158844. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158845. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158846. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158847. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158848. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158849. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158850. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158851. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158852. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158853. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158854. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158855. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158856. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158857. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158858. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158859. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158860. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158861. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158862. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158863. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158864. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158865. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158866. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158867. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158868. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158869. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158870. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158871. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158872. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158873. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158874. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158875. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158876. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158877. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158878. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158879. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158880. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158881. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158882. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158883. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158884. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158885. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158886. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158887. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158888. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158889. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158890. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158891. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158892. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158893. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158894. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158895. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158896. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158897. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158898. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158899. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158900. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158901. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158902. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158903. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158904. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158905. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158906. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158907. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158908. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158909. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158910. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158911. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158912. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158913. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158914. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158915. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158916. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158917. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158918. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158919. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158920. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158921. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158922. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158923. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158924. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158925. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158926. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158927. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158928. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158929. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158930. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158931. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158932. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158933. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158934. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158935. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158936. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158937. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158938. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158939. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158940. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158941. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158942. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158943. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158944. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158945. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158946. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158947. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158948. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158949. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158950. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158951. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158952. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158953. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158954. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158955. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158956. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158957. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158958. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158959. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158960. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158961. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158962. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158963. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158964. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158965. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158966. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158967. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158968. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158969. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158970. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158971. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158972. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158973. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158974. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158975. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158976. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158977. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158978. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158979. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158980. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158981. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158982. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158983. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158984. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158985. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158986. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158987. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158988. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158989. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158990. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158991. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158992. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158993. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158994. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158995. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158996. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158997. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158998. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158999. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159000. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159001. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159002. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159003. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159004. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159005. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159006. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159007. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159008. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159009. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159010. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159011. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159012. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159013. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159014. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159015. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159016. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159017. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159018. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159019. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159020. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159021. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159022. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159023. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159024. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159025. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159026. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159027. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159028. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159029. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159030. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159031. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159032. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159033. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159034. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159035. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159036. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159037. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159038. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159039. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159040. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159041. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159042. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159043. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159044. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159045. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159046. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159047. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159048. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159049. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159050. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159051. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159052. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159053. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159054. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159055. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159056. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159057. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159058. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159059. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159060. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159061. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159062. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159063. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159064. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159065. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159066. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159067. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159068. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159069. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159070. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159071. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159072. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159073. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159074. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159075. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159076. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159077. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159078. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159079. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159080. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159081. };
  159082. static float *vwin[8] = {
  159083. vwin64,
  159084. vwin128,
  159085. vwin256,
  159086. vwin512,
  159087. vwin1024,
  159088. vwin2048,
  159089. vwin4096,
  159090. vwin8192,
  159091. };
  159092. float *_vorbis_window_get(int n){
  159093. return vwin[n];
  159094. }
  159095. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159096. int lW,int W,int nW){
  159097. lW=(W?lW:0);
  159098. nW=(W?nW:0);
  159099. {
  159100. float *windowLW=vwin[winno[lW]];
  159101. float *windowNW=vwin[winno[nW]];
  159102. long n=blocksizes[W];
  159103. long ln=blocksizes[lW];
  159104. long rn=blocksizes[nW];
  159105. long leftbegin=n/4-ln/4;
  159106. long leftend=leftbegin+ln/2;
  159107. long rightbegin=n/2+n/4-rn/4;
  159108. long rightend=rightbegin+rn/2;
  159109. int i,p;
  159110. for(i=0;i<leftbegin;i++)
  159111. d[i]=0.f;
  159112. for(p=0;i<leftend;i++,p++)
  159113. d[i]*=windowLW[p];
  159114. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159115. d[i]*=windowNW[p];
  159116. for(;i<n;i++)
  159117. d[i]=0.f;
  159118. }
  159119. }
  159120. #endif
  159121. /*** End of inlined file: window.c ***/
  159122. #else
  159123. #include <vorbis/vorbisenc.h>
  159124. #include <vorbis/codec.h>
  159125. #include <vorbis/vorbisfile.h>
  159126. #endif
  159127. }
  159128. #undef max
  159129. #undef min
  159130. BEGIN_JUCE_NAMESPACE
  159131. static const char* const oggFormatName = "Ogg-Vorbis file";
  159132. static const char* const oggExtensions[] = { ".ogg", 0 };
  159133. class OggReader : public AudioFormatReader
  159134. {
  159135. OggVorbisNamespace::OggVorbis_File ovFile;
  159136. OggVorbisNamespace::ov_callbacks callbacks;
  159137. AudioSampleBuffer reservoir;
  159138. int reservoirStart, samplesInReservoir;
  159139. public:
  159140. OggReader (InputStream* const inp)
  159141. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159142. reservoir (2, 4096),
  159143. reservoirStart (0),
  159144. samplesInReservoir (0)
  159145. {
  159146. using namespace OggVorbisNamespace;
  159147. sampleRate = 0;
  159148. usesFloatingPointData = true;
  159149. callbacks.read_func = &oggReadCallback;
  159150. callbacks.seek_func = &oggSeekCallback;
  159151. callbacks.close_func = &oggCloseCallback;
  159152. callbacks.tell_func = &oggTellCallback;
  159153. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159154. if (err == 0)
  159155. {
  159156. vorbis_info* info = ov_info (&ovFile, -1);
  159157. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159158. numChannels = info->channels;
  159159. bitsPerSample = 16;
  159160. sampleRate = info->rate;
  159161. reservoir.setSize (numChannels,
  159162. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159163. }
  159164. }
  159165. ~OggReader()
  159166. {
  159167. OggVorbisNamespace::ov_clear (&ovFile);
  159168. }
  159169. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159170. int64 startSampleInFile, int numSamples)
  159171. {
  159172. while (numSamples > 0)
  159173. {
  159174. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159175. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159176. {
  159177. // got a few samples overlapping, so use them before seeking..
  159178. const int numToUse = jmin (numSamples, numAvailable);
  159179. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159180. if (destSamples[i] != 0)
  159181. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159182. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159183. sizeof (float) * numToUse);
  159184. startSampleInFile += numToUse;
  159185. numSamples -= numToUse;
  159186. startOffsetInDestBuffer += numToUse;
  159187. if (numSamples == 0)
  159188. break;
  159189. }
  159190. if (startSampleInFile < reservoirStart
  159191. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159192. {
  159193. // buffer miss, so refill the reservoir
  159194. int bitStream = 0;
  159195. reservoirStart = jmax (0, (int) startSampleInFile);
  159196. samplesInReservoir = reservoir.getNumSamples();
  159197. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159198. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159199. int offset = 0;
  159200. int numToRead = samplesInReservoir;
  159201. while (numToRead > 0)
  159202. {
  159203. float** dataIn = 0;
  159204. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159205. if (samps <= 0)
  159206. break;
  159207. jassert (samps <= numToRead);
  159208. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159209. {
  159210. memcpy (reservoir.getSampleData (i, offset),
  159211. dataIn[i],
  159212. sizeof (float) * samps);
  159213. }
  159214. numToRead -= samps;
  159215. offset += samps;
  159216. }
  159217. if (numToRead > 0)
  159218. reservoir.clear (offset, numToRead);
  159219. }
  159220. }
  159221. if (numSamples > 0)
  159222. {
  159223. for (int i = numDestChannels; --i >= 0;)
  159224. if (destSamples[i] != 0)
  159225. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159226. sizeof (int) * numSamples);
  159227. }
  159228. return true;
  159229. }
  159230. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159231. {
  159232. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159233. }
  159234. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159235. {
  159236. InputStream* const in = static_cast <InputStream*> (datasource);
  159237. if (whence == SEEK_CUR)
  159238. offset += in->getPosition();
  159239. else if (whence == SEEK_END)
  159240. offset += in->getTotalLength();
  159241. in->setPosition (offset);
  159242. return 0;
  159243. }
  159244. static int oggCloseCallback (void*)
  159245. {
  159246. return 0;
  159247. }
  159248. static long oggTellCallback (void* datasource)
  159249. {
  159250. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159251. }
  159252. private:
  159253. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159254. };
  159255. class OggWriter : public AudioFormatWriter
  159256. {
  159257. OggVorbisNamespace::ogg_stream_state os;
  159258. OggVorbisNamespace::ogg_page og;
  159259. OggVorbisNamespace::ogg_packet op;
  159260. OggVorbisNamespace::vorbis_info vi;
  159261. OggVorbisNamespace::vorbis_comment vc;
  159262. OggVorbisNamespace::vorbis_dsp_state vd;
  159263. OggVorbisNamespace::vorbis_block vb;
  159264. public:
  159265. bool ok;
  159266. OggWriter (OutputStream* const out,
  159267. const double sampleRate,
  159268. const int numChannels,
  159269. const int bitsPerSample,
  159270. const int qualityIndex)
  159271. : AudioFormatWriter (out, TRANS (oggFormatName),
  159272. sampleRate,
  159273. numChannels,
  159274. bitsPerSample)
  159275. {
  159276. using namespace OggVorbisNamespace;
  159277. ok = false;
  159278. vorbis_info_init (&vi);
  159279. if (vorbis_encode_init_vbr (&vi,
  159280. numChannels,
  159281. (int) sampleRate,
  159282. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159283. {
  159284. vorbis_comment_init (&vc);
  159285. if (JUCEApplication::getInstance() != 0)
  159286. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159287. vorbis_analysis_init (&vd, &vi);
  159288. vorbis_block_init (&vd, &vb);
  159289. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159290. ogg_packet header;
  159291. ogg_packet header_comm;
  159292. ogg_packet header_code;
  159293. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159294. ogg_stream_packetin (&os, &header);
  159295. ogg_stream_packetin (&os, &header_comm);
  159296. ogg_stream_packetin (&os, &header_code);
  159297. for (;;)
  159298. {
  159299. if (ogg_stream_flush (&os, &og) == 0)
  159300. break;
  159301. output->write (og.header, og.header_len);
  159302. output->write (og.body, og.body_len);
  159303. }
  159304. ok = true;
  159305. }
  159306. }
  159307. ~OggWriter()
  159308. {
  159309. using namespace OggVorbisNamespace;
  159310. if (ok)
  159311. {
  159312. // write a zero-length packet to show ogg that we're finished..
  159313. write (0, 0);
  159314. ogg_stream_clear (&os);
  159315. vorbis_block_clear (&vb);
  159316. vorbis_dsp_clear (&vd);
  159317. vorbis_comment_clear (&vc);
  159318. vorbis_info_clear (&vi);
  159319. output->flush();
  159320. }
  159321. else
  159322. {
  159323. vorbis_info_clear (&vi);
  159324. output = 0; // to stop the base class deleting this, as it needs to be returned
  159325. // to the caller of createWriter()
  159326. }
  159327. }
  159328. bool write (const int** samplesToWrite, int numSamples)
  159329. {
  159330. using namespace OggVorbisNamespace;
  159331. if (! ok)
  159332. return false;
  159333. if (numSamples > 0)
  159334. {
  159335. const double gain = 1.0 / 0x80000000u;
  159336. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159337. for (int i = numChannels; --i >= 0;)
  159338. {
  159339. float* const dst = vorbisBuffer[i];
  159340. const int* const src = samplesToWrite [i];
  159341. if (src != 0 && dst != 0)
  159342. {
  159343. for (int j = 0; j < numSamples; ++j)
  159344. dst[j] = (float) (src[j] * gain);
  159345. }
  159346. }
  159347. }
  159348. vorbis_analysis_wrote (&vd, numSamples);
  159349. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159350. {
  159351. vorbis_analysis (&vb, 0);
  159352. vorbis_bitrate_addblock (&vb);
  159353. while (vorbis_bitrate_flushpacket (&vd, &op))
  159354. {
  159355. ogg_stream_packetin (&os, &op);
  159356. for (;;)
  159357. {
  159358. if (ogg_stream_pageout (&os, &og) == 0)
  159359. break;
  159360. output->write (og.header, og.header_len);
  159361. output->write (og.body, og.body_len);
  159362. if (ogg_page_eos (&og))
  159363. break;
  159364. }
  159365. }
  159366. }
  159367. return true;
  159368. }
  159369. private:
  159370. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159371. };
  159372. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159373. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159374. {
  159375. }
  159376. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159377. {
  159378. }
  159379. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159380. {
  159381. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159382. return Array <int> (rates);
  159383. }
  159384. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159385. {
  159386. const int depths[] = { 32, 0 };
  159387. return Array <int> (depths);
  159388. }
  159389. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159390. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159391. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159392. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159393. const bool deleteStreamIfOpeningFails)
  159394. {
  159395. ScopedPointer <OggReader> r (new OggReader (in));
  159396. if (r->sampleRate != 0)
  159397. return r.release();
  159398. if (! deleteStreamIfOpeningFails)
  159399. r->input = 0;
  159400. return 0;
  159401. }
  159402. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159403. double sampleRate,
  159404. unsigned int numChannels,
  159405. int bitsPerSample,
  159406. const StringPairArray& /*metadataValues*/,
  159407. int qualityOptionIndex)
  159408. {
  159409. ScopedPointer <OggWriter> w (new OggWriter (out,
  159410. sampleRate,
  159411. numChannels,
  159412. bitsPerSample,
  159413. qualityOptionIndex));
  159414. return w->ok ? w.release() : 0;
  159415. }
  159416. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159417. {
  159418. StringArray s;
  159419. s.add ("Low Quality");
  159420. s.add ("Medium Quality");
  159421. s.add ("High Quality");
  159422. return s;
  159423. }
  159424. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159425. {
  159426. FileInputStream* const in = source.createInputStream();
  159427. if (in != 0)
  159428. {
  159429. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159430. if (r != 0)
  159431. {
  159432. const int64 numSamps = r->lengthInSamples;
  159433. r = 0;
  159434. const int64 fileNumSamps = source.getSize() / 4;
  159435. const double ratio = numSamps / (double) fileNumSamps;
  159436. if (ratio > 12.0)
  159437. return 0;
  159438. else if (ratio > 6.0)
  159439. return 1;
  159440. else
  159441. return 2;
  159442. }
  159443. }
  159444. return 1;
  159445. }
  159446. END_JUCE_NAMESPACE
  159447. #endif
  159448. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159449. #endif
  159450. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159451. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159452. #if JUCE_MSVC
  159453. #pragma warning (push)
  159454. #endif
  159455. namespace jpeglibNamespace
  159456. {
  159457. #if JUCE_INCLUDE_JPEGLIB_CODE
  159458. #if JUCE_MINGW
  159459. typedef unsigned char boolean;
  159460. #endif
  159461. #define JPEG_INTERNALS
  159462. #undef FAR
  159463. /*** Start of inlined file: jpeglib.h ***/
  159464. #ifndef JPEGLIB_H
  159465. #define JPEGLIB_H
  159466. /*
  159467. * First we include the configuration files that record how this
  159468. * installation of the JPEG library is set up. jconfig.h can be
  159469. * generated automatically for many systems. jmorecfg.h contains
  159470. * manual configuration options that most people need not worry about.
  159471. */
  159472. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159473. /*** Start of inlined file: jconfig.h ***/
  159474. /* see jconfig.doc for explanations */
  159475. // disable all the warnings under MSVC
  159476. #ifdef _MSC_VER
  159477. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159478. #endif
  159479. #ifdef __BORLANDC__
  159480. #pragma warn -8057
  159481. #pragma warn -8019
  159482. #pragma warn -8004
  159483. #pragma warn -8008
  159484. #endif
  159485. #define HAVE_PROTOTYPES
  159486. #define HAVE_UNSIGNED_CHAR
  159487. #define HAVE_UNSIGNED_SHORT
  159488. /* #define void char */
  159489. /* #define const */
  159490. #undef CHAR_IS_UNSIGNED
  159491. #define HAVE_STDDEF_H
  159492. #define HAVE_STDLIB_H
  159493. #undef NEED_BSD_STRINGS
  159494. #undef NEED_SYS_TYPES_H
  159495. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159496. #undef NEED_SHORT_EXTERNAL_NAMES
  159497. #undef INCOMPLETE_TYPES_BROKEN
  159498. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159499. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159500. typedef unsigned char boolean;
  159501. #endif
  159502. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159503. #ifdef JPEG_INTERNALS
  159504. #undef RIGHT_SHIFT_IS_UNSIGNED
  159505. #endif /* JPEG_INTERNALS */
  159506. #ifdef JPEG_CJPEG_DJPEG
  159507. #define BMP_SUPPORTED /* BMP image file format */
  159508. #define GIF_SUPPORTED /* GIF image file format */
  159509. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159510. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159511. #define TARGA_SUPPORTED /* Targa image file format */
  159512. #define TWO_FILE_COMMANDLINE /* optional */
  159513. #define USE_SETMODE /* Microsoft has setmode() */
  159514. #undef NEED_SIGNAL_CATCHER
  159515. #undef DONT_USE_B_MODE
  159516. #undef PROGRESS_REPORT /* optional */
  159517. #endif /* JPEG_CJPEG_DJPEG */
  159518. /*** End of inlined file: jconfig.h ***/
  159519. /* widely used configuration options */
  159520. #endif
  159521. /*** Start of inlined file: jmorecfg.h ***/
  159522. /*
  159523. * Define BITS_IN_JSAMPLE as either
  159524. * 8 for 8-bit sample values (the usual setting)
  159525. * 12 for 12-bit sample values
  159526. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159527. * JPEG standard, and the IJG code does not support anything else!
  159528. * We do not support run-time selection of data precision, sorry.
  159529. */
  159530. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159531. /*
  159532. * Maximum number of components (color channels) allowed in JPEG image.
  159533. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159534. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159535. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159536. * really short on memory. (Each allowed component costs a hundred or so
  159537. * bytes of storage, whether actually used in an image or not.)
  159538. */
  159539. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159540. /*
  159541. * Basic data types.
  159542. * You may need to change these if you have a machine with unusual data
  159543. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159544. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159545. * but it had better be at least 16.
  159546. */
  159547. /* Representation of a single sample (pixel element value).
  159548. * We frequently allocate large arrays of these, so it's important to keep
  159549. * them small. But if you have memory to burn and access to char or short
  159550. * arrays is very slow on your hardware, you might want to change these.
  159551. */
  159552. #if BITS_IN_JSAMPLE == 8
  159553. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159554. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159555. */
  159556. #ifdef HAVE_UNSIGNED_CHAR
  159557. typedef unsigned char JSAMPLE;
  159558. #define GETJSAMPLE(value) ((int) (value))
  159559. #else /* not HAVE_UNSIGNED_CHAR */
  159560. typedef char JSAMPLE;
  159561. #ifdef CHAR_IS_UNSIGNED
  159562. #define GETJSAMPLE(value) ((int) (value))
  159563. #else
  159564. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159565. #endif /* CHAR_IS_UNSIGNED */
  159566. #endif /* HAVE_UNSIGNED_CHAR */
  159567. #define MAXJSAMPLE 255
  159568. #define CENTERJSAMPLE 128
  159569. #endif /* BITS_IN_JSAMPLE == 8 */
  159570. #if BITS_IN_JSAMPLE == 12
  159571. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159572. * On nearly all machines "short" will do nicely.
  159573. */
  159574. typedef short JSAMPLE;
  159575. #define GETJSAMPLE(value) ((int) (value))
  159576. #define MAXJSAMPLE 4095
  159577. #define CENTERJSAMPLE 2048
  159578. #endif /* BITS_IN_JSAMPLE == 12 */
  159579. /* Representation of a DCT frequency coefficient.
  159580. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159581. * Again, we allocate large arrays of these, but you can change to int
  159582. * if you have memory to burn and "short" is really slow.
  159583. */
  159584. typedef short JCOEF;
  159585. /* Compressed datastreams are represented as arrays of JOCTET.
  159586. * These must be EXACTLY 8 bits wide, at least once they are written to
  159587. * external storage. Note that when using the stdio data source/destination
  159588. * managers, this is also the data type passed to fread/fwrite.
  159589. */
  159590. #ifdef HAVE_UNSIGNED_CHAR
  159591. typedef unsigned char JOCTET;
  159592. #define GETJOCTET(value) (value)
  159593. #else /* not HAVE_UNSIGNED_CHAR */
  159594. typedef char JOCTET;
  159595. #ifdef CHAR_IS_UNSIGNED
  159596. #define GETJOCTET(value) (value)
  159597. #else
  159598. #define GETJOCTET(value) ((value) & 0xFF)
  159599. #endif /* CHAR_IS_UNSIGNED */
  159600. #endif /* HAVE_UNSIGNED_CHAR */
  159601. /* These typedefs are used for various table entries and so forth.
  159602. * They must be at least as wide as specified; but making them too big
  159603. * won't cost a huge amount of memory, so we don't provide special
  159604. * extraction code like we did for JSAMPLE. (In other words, these
  159605. * typedefs live at a different point on the speed/space tradeoff curve.)
  159606. */
  159607. /* UINT8 must hold at least the values 0..255. */
  159608. #ifdef HAVE_UNSIGNED_CHAR
  159609. typedef unsigned char UINT8;
  159610. #else /* not HAVE_UNSIGNED_CHAR */
  159611. #ifdef CHAR_IS_UNSIGNED
  159612. typedef char UINT8;
  159613. #else /* not CHAR_IS_UNSIGNED */
  159614. typedef short UINT8;
  159615. #endif /* CHAR_IS_UNSIGNED */
  159616. #endif /* HAVE_UNSIGNED_CHAR */
  159617. /* UINT16 must hold at least the values 0..65535. */
  159618. #ifdef HAVE_UNSIGNED_SHORT
  159619. typedef unsigned short UINT16;
  159620. #else /* not HAVE_UNSIGNED_SHORT */
  159621. typedef unsigned int UINT16;
  159622. #endif /* HAVE_UNSIGNED_SHORT */
  159623. /* INT16 must hold at least the values -32768..32767. */
  159624. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159625. typedef short INT16;
  159626. #endif
  159627. /* INT32 must hold at least signed 32-bit values. */
  159628. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159629. typedef long INT32;
  159630. #endif
  159631. /* Datatype used for image dimensions. The JPEG standard only supports
  159632. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159633. * "unsigned int" is sufficient on all machines. However, if you need to
  159634. * handle larger images and you don't mind deviating from the spec, you
  159635. * can change this datatype.
  159636. */
  159637. typedef unsigned int JDIMENSION;
  159638. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159639. /* These macros are used in all function definitions and extern declarations.
  159640. * You could modify them if you need to change function linkage conventions;
  159641. * in particular, you'll need to do that to make the library a Windows DLL.
  159642. * Another application is to make all functions global for use with debuggers
  159643. * or code profilers that require it.
  159644. */
  159645. /* a function called through method pointers: */
  159646. #define METHODDEF(type) static type
  159647. /* a function used only in its module: */
  159648. #define LOCAL(type) static type
  159649. /* a function referenced thru EXTERNs: */
  159650. #define GLOBAL(type) type
  159651. /* a reference to a GLOBAL function: */
  159652. #define EXTERN(type) extern type
  159653. /* This macro is used to declare a "method", that is, a function pointer.
  159654. * We want to supply prototype parameters if the compiler can cope.
  159655. * Note that the arglist parameter must be parenthesized!
  159656. * Again, you can customize this if you need special linkage keywords.
  159657. */
  159658. #ifdef HAVE_PROTOTYPES
  159659. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159660. #else
  159661. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159662. #endif
  159663. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159664. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159665. * by just saying "FAR *" where such a pointer is needed. In a few places
  159666. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159667. */
  159668. #ifdef NEED_FAR_POINTERS
  159669. #define FAR far
  159670. #else
  159671. #define FAR
  159672. #endif
  159673. /*
  159674. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159675. * in standard header files. Or you may have conflicts with application-
  159676. * specific header files that you want to include together with these files.
  159677. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159678. */
  159679. #ifndef HAVE_BOOLEAN
  159680. typedef int boolean;
  159681. #endif
  159682. #ifndef FALSE /* in case these macros already exist */
  159683. #define FALSE 0 /* values of boolean */
  159684. #endif
  159685. #ifndef TRUE
  159686. #define TRUE 1
  159687. #endif
  159688. /*
  159689. * The remaining options affect code selection within the JPEG library,
  159690. * but they don't need to be visible to most applications using the library.
  159691. * To minimize application namespace pollution, the symbols won't be
  159692. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159693. */
  159694. #ifdef JPEG_INTERNALS
  159695. #define JPEG_INTERNAL_OPTIONS
  159696. #endif
  159697. #ifdef JPEG_INTERNAL_OPTIONS
  159698. /*
  159699. * These defines indicate whether to include various optional functions.
  159700. * Undefining some of these symbols will produce a smaller but less capable
  159701. * library. Note that you can leave certain source files out of the
  159702. * compilation/linking process if you've #undef'd the corresponding symbols.
  159703. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159704. */
  159705. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159706. /* Capability options common to encoder and decoder: */
  159707. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159708. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159709. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159710. /* Encoder capability options: */
  159711. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159712. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159713. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159714. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159715. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159716. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159717. * precision, so jchuff.c normally uses entropy optimization to compute
  159718. * usable tables for higher precision. If you don't want to do optimization,
  159719. * you'll have to supply different default Huffman tables.
  159720. * The exact same statements apply for progressive JPEG: the default tables
  159721. * don't work for progressive mode. (This may get fixed, however.)
  159722. */
  159723. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159724. /* Decoder capability options: */
  159725. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159726. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159727. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159728. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159729. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159730. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159731. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159732. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159733. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159734. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159735. /* more capability options later, no doubt */
  159736. /*
  159737. * Ordering of RGB data in scanlines passed to or from the application.
  159738. * If your application wants to deal with data in the order B,G,R, just
  159739. * change these macros. You can also deal with formats such as R,G,B,X
  159740. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159741. * the offsets will also change the order in which colormap data is organized.
  159742. * RESTRICTIONS:
  159743. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159744. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159745. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159746. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159747. * is not 3 (they don't understand about dummy color components!). So you
  159748. * can't use color quantization if you change that value.
  159749. */
  159750. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159751. #define RGB_GREEN 1 /* Offset of Green */
  159752. #define RGB_BLUE 2 /* Offset of Blue */
  159753. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159754. /* Definitions for speed-related optimizations. */
  159755. /* If your compiler supports inline functions, define INLINE
  159756. * as the inline keyword; otherwise define it as empty.
  159757. */
  159758. #ifndef INLINE
  159759. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159760. #define INLINE __inline__
  159761. #endif
  159762. #ifndef INLINE
  159763. #define INLINE /* default is to define it as empty */
  159764. #endif
  159765. #endif
  159766. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159767. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159768. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159769. */
  159770. #ifndef MULTIPLIER
  159771. #define MULTIPLIER int /* type for fastest integer multiply */
  159772. #endif
  159773. /* FAST_FLOAT should be either float or double, whichever is done faster
  159774. * by your compiler. (Note that this type is only used in the floating point
  159775. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159776. * Typically, float is faster in ANSI C compilers, while double is faster in
  159777. * pre-ANSI compilers (because they insist on converting to double anyway).
  159778. * The code below therefore chooses float if we have ANSI-style prototypes.
  159779. */
  159780. #ifndef FAST_FLOAT
  159781. #ifdef HAVE_PROTOTYPES
  159782. #define FAST_FLOAT float
  159783. #else
  159784. #define FAST_FLOAT double
  159785. #endif
  159786. #endif
  159787. #endif /* JPEG_INTERNAL_OPTIONS */
  159788. /*** End of inlined file: jmorecfg.h ***/
  159789. /* seldom changed options */
  159790. /* Version ID for the JPEG library.
  159791. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159792. */
  159793. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159794. /* Various constants determining the sizes of things.
  159795. * All of these are specified by the JPEG standard, so don't change them
  159796. * if you want to be compatible.
  159797. */
  159798. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159799. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159800. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159801. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159802. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159803. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159804. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159805. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159806. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159807. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159808. * to handle it. We even let you do this from the jconfig.h file. However,
  159809. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159810. * sometimes emits noncompliant files doesn't mean you should too.
  159811. */
  159812. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159813. #ifndef D_MAX_BLOCKS_IN_MCU
  159814. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159815. #endif
  159816. /* Data structures for images (arrays of samples and of DCT coefficients).
  159817. * On 80x86 machines, the image arrays are too big for near pointers,
  159818. * but the pointer arrays can fit in near memory.
  159819. */
  159820. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159821. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159822. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159823. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159824. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159825. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159826. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159827. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159828. /* Types for JPEG compression parameters and working tables. */
  159829. /* DCT coefficient quantization tables. */
  159830. typedef struct {
  159831. /* This array gives the coefficient quantizers in natural array order
  159832. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159833. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159834. */
  159835. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159836. /* This field is used only during compression. It's initialized FALSE when
  159837. * the table is created, and set TRUE when it's been output to the file.
  159838. * You could suppress output of a table by setting this to TRUE.
  159839. * (See jpeg_suppress_tables for an example.)
  159840. */
  159841. boolean sent_table; /* TRUE when table has been output */
  159842. } JQUANT_TBL;
  159843. /* Huffman coding tables. */
  159844. typedef struct {
  159845. /* These two fields directly represent the contents of a JPEG DHT marker */
  159846. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159847. /* length k bits; bits[0] is unused */
  159848. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159849. /* This field is used only during compression. It's initialized FALSE when
  159850. * the table is created, and set TRUE when it's been output to the file.
  159851. * You could suppress output of a table by setting this to TRUE.
  159852. * (See jpeg_suppress_tables for an example.)
  159853. */
  159854. boolean sent_table; /* TRUE when table has been output */
  159855. } JHUFF_TBL;
  159856. /* Basic info about one component (color channel). */
  159857. typedef struct {
  159858. /* These values are fixed over the whole image. */
  159859. /* For compression, they must be supplied by parameter setup; */
  159860. /* for decompression, they are read from the SOF marker. */
  159861. int component_id; /* identifier for this component (0..255) */
  159862. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159863. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159864. int v_samp_factor; /* vertical sampling factor (1..4) */
  159865. int quant_tbl_no; /* quantization table selector (0..3) */
  159866. /* These values may vary between scans. */
  159867. /* For compression, they must be supplied by parameter setup; */
  159868. /* for decompression, they are read from the SOS marker. */
  159869. /* The decompressor output side may not use these variables. */
  159870. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159871. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159872. /* Remaining fields should be treated as private by applications. */
  159873. /* These values are computed during compression or decompression startup: */
  159874. /* Component's size in DCT blocks.
  159875. * Any dummy blocks added to complete an MCU are not counted; therefore
  159876. * these values do not depend on whether a scan is interleaved or not.
  159877. */
  159878. JDIMENSION width_in_blocks;
  159879. JDIMENSION height_in_blocks;
  159880. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159881. * For decompression this is the size of the output from one DCT block,
  159882. * reflecting any scaling we choose to apply during the IDCT step.
  159883. * Values of 1,2,4,8 are likely to be supported. Note that different
  159884. * components may receive different IDCT scalings.
  159885. */
  159886. int DCT_scaled_size;
  159887. /* The downsampled dimensions are the component's actual, unpadded number
  159888. * of samples at the main buffer (preprocessing/compression interface), thus
  159889. * downsampled_width = ceil(image_width * Hi/Hmax)
  159890. * and similarly for height. For decompression, IDCT scaling is included, so
  159891. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159892. */
  159893. JDIMENSION downsampled_width; /* actual width in samples */
  159894. JDIMENSION downsampled_height; /* actual height in samples */
  159895. /* This flag is used only for decompression. In cases where some of the
  159896. * components will be ignored (eg grayscale output from YCbCr image),
  159897. * we can skip most computations for the unused components.
  159898. */
  159899. boolean component_needed; /* do we need the value of this component? */
  159900. /* These values are computed before starting a scan of the component. */
  159901. /* The decompressor output side may not use these variables. */
  159902. int MCU_width; /* number of blocks per MCU, horizontally */
  159903. int MCU_height; /* number of blocks per MCU, vertically */
  159904. int MCU_blocks; /* MCU_width * MCU_height */
  159905. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159906. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159907. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159908. /* Saved quantization table for component; NULL if none yet saved.
  159909. * See jdinput.c comments about the need for this information.
  159910. * This field is currently used only for decompression.
  159911. */
  159912. JQUANT_TBL * quant_table;
  159913. /* Private per-component storage for DCT or IDCT subsystem. */
  159914. void * dct_table;
  159915. } jpeg_component_info;
  159916. /* The script for encoding a multiple-scan file is an array of these: */
  159917. typedef struct {
  159918. int comps_in_scan; /* number of components encoded in this scan */
  159919. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159920. int Ss, Se; /* progressive JPEG spectral selection parms */
  159921. int Ah, Al; /* progressive JPEG successive approx. parms */
  159922. } jpeg_scan_info;
  159923. /* The decompressor can save APPn and COM markers in a list of these: */
  159924. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159925. struct jpeg_marker_struct {
  159926. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159927. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159928. unsigned int original_length; /* # bytes of data in the file */
  159929. unsigned int data_length; /* # bytes of data saved at data[] */
  159930. JOCTET FAR * data; /* the data contained in the marker */
  159931. /* the marker length word is not counted in data_length or original_length */
  159932. };
  159933. /* Known color spaces. */
  159934. typedef enum {
  159935. JCS_UNKNOWN, /* error/unspecified */
  159936. JCS_GRAYSCALE, /* monochrome */
  159937. JCS_RGB, /* red/green/blue */
  159938. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159939. JCS_CMYK, /* C/M/Y/K */
  159940. JCS_YCCK /* Y/Cb/Cr/K */
  159941. } J_COLOR_SPACE;
  159942. /* DCT/IDCT algorithm options. */
  159943. typedef enum {
  159944. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159945. JDCT_IFAST, /* faster, less accurate integer method */
  159946. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159947. } J_DCT_METHOD;
  159948. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159949. #define JDCT_DEFAULT JDCT_ISLOW
  159950. #endif
  159951. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159952. #define JDCT_FASTEST JDCT_IFAST
  159953. #endif
  159954. /* Dithering options for decompression. */
  159955. typedef enum {
  159956. JDITHER_NONE, /* no dithering */
  159957. JDITHER_ORDERED, /* simple ordered dither */
  159958. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159959. } J_DITHER_MODE;
  159960. /* Common fields between JPEG compression and decompression master structs. */
  159961. #define jpeg_common_fields \
  159962. struct jpeg_error_mgr * err; /* Error handler module */\
  159963. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159964. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159965. void * client_data; /* Available for use by application */\
  159966. boolean is_decompressor; /* So common code can tell which is which */\
  159967. int global_state /* For checking call sequence validity */
  159968. /* Routines that are to be used by both halves of the library are declared
  159969. * to receive a pointer to this structure. There are no actual instances of
  159970. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159971. */
  159972. struct jpeg_common_struct {
  159973. jpeg_common_fields; /* Fields common to both master struct types */
  159974. /* Additional fields follow in an actual jpeg_compress_struct or
  159975. * jpeg_decompress_struct. All three structs must agree on these
  159976. * initial fields! (This would be a lot cleaner in C++.)
  159977. */
  159978. };
  159979. typedef struct jpeg_common_struct * j_common_ptr;
  159980. typedef struct jpeg_compress_struct * j_compress_ptr;
  159981. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159982. /* Master record for a compression instance */
  159983. struct jpeg_compress_struct {
  159984. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159985. /* Destination for compressed data */
  159986. struct jpeg_destination_mgr * dest;
  159987. /* Description of source image --- these fields must be filled in by
  159988. * outer application before starting compression. in_color_space must
  159989. * be correct before you can even call jpeg_set_defaults().
  159990. */
  159991. JDIMENSION image_width; /* input image width */
  159992. JDIMENSION image_height; /* input image height */
  159993. int input_components; /* # of color components in input image */
  159994. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159995. double input_gamma; /* image gamma of input image */
  159996. /* Compression parameters --- these fields must be set before calling
  159997. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159998. * initialize everything to reasonable defaults, then changing anything
  159999. * the application specifically wants to change. That way you won't get
  160000. * burnt when new parameters are added. Also note that there are several
  160001. * helper routines to simplify changing parameters.
  160002. */
  160003. int data_precision; /* bits of precision in image data */
  160004. int num_components; /* # of color components in JPEG image */
  160005. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160006. jpeg_component_info * comp_info;
  160007. /* comp_info[i] describes component that appears i'th in SOF */
  160008. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160009. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160010. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160011. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160012. /* ptrs to Huffman coding tables, or NULL if not defined */
  160013. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160014. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160015. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160016. int num_scans; /* # of entries in scan_info array */
  160017. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160018. /* The default value of scan_info is NULL, which causes a single-scan
  160019. * sequential JPEG file to be emitted. To create a multi-scan file,
  160020. * set num_scans and scan_info to point to an array of scan definitions.
  160021. */
  160022. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160023. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160024. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160025. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160026. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160027. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160028. /* The restart interval can be specified in absolute MCUs by setting
  160029. * restart_interval, or in MCU rows by setting restart_in_rows
  160030. * (in which case the correct restart_interval will be figured
  160031. * for each scan).
  160032. */
  160033. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160034. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160035. /* Parameters controlling emission of special markers. */
  160036. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160037. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160038. UINT8 JFIF_minor_version;
  160039. /* These three values are not used by the JPEG code, merely copied */
  160040. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160041. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160042. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160043. UINT8 density_unit; /* JFIF code for pixel size units */
  160044. UINT16 X_density; /* Horizontal pixel density */
  160045. UINT16 Y_density; /* Vertical pixel density */
  160046. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160047. /* State variable: index of next scanline to be written to
  160048. * jpeg_write_scanlines(). Application may use this to control its
  160049. * processing loop, e.g., "while (next_scanline < image_height)".
  160050. */
  160051. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160052. /* Remaining fields are known throughout compressor, but generally
  160053. * should not be touched by a surrounding application.
  160054. */
  160055. /*
  160056. * These fields are computed during compression startup
  160057. */
  160058. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160059. int max_h_samp_factor; /* largest h_samp_factor */
  160060. int max_v_samp_factor; /* largest v_samp_factor */
  160061. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160062. /* The coefficient controller receives data in units of MCU rows as defined
  160063. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160064. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160065. * "iMCU" (interleaved MCU) row.
  160066. */
  160067. /*
  160068. * These fields are valid during any one scan.
  160069. * They describe the components and MCUs actually appearing in the scan.
  160070. */
  160071. int comps_in_scan; /* # of JPEG components in this scan */
  160072. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160073. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160074. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160075. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160076. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160077. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160078. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160079. /* i'th block in an MCU */
  160080. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160081. /*
  160082. * Links to compression subobjects (methods and private variables of modules)
  160083. */
  160084. struct jpeg_comp_master * master;
  160085. struct jpeg_c_main_controller * main;
  160086. struct jpeg_c_prep_controller * prep;
  160087. struct jpeg_c_coef_controller * coef;
  160088. struct jpeg_marker_writer * marker;
  160089. struct jpeg_color_converter * cconvert;
  160090. struct jpeg_downsampler * downsample;
  160091. struct jpeg_forward_dct * fdct;
  160092. struct jpeg_entropy_encoder * entropy;
  160093. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160094. int script_space_size;
  160095. };
  160096. /* Master record for a decompression instance */
  160097. struct jpeg_decompress_struct {
  160098. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160099. /* Source of compressed data */
  160100. struct jpeg_source_mgr * src;
  160101. /* Basic description of image --- filled in by jpeg_read_header(). */
  160102. /* Application may inspect these values to decide how to process image. */
  160103. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160104. JDIMENSION image_height; /* nominal image height */
  160105. int num_components; /* # of color components in JPEG image */
  160106. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160107. /* Decompression processing parameters --- these fields must be set before
  160108. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160109. * them to default values.
  160110. */
  160111. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160112. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160113. double output_gamma; /* image gamma wanted in output */
  160114. boolean buffered_image; /* TRUE=multiple output passes */
  160115. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160116. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160117. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160118. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160119. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160120. /* the following are ignored if not quantize_colors: */
  160121. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160122. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160123. int desired_number_of_colors; /* max # colors to use in created colormap */
  160124. /* these are significant only in buffered-image mode: */
  160125. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160126. boolean enable_external_quant;/* enable future use of external colormap */
  160127. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160128. /* Description of actual output image that will be returned to application.
  160129. * These fields are computed by jpeg_start_decompress().
  160130. * You can also use jpeg_calc_output_dimensions() to determine these values
  160131. * in advance of calling jpeg_start_decompress().
  160132. */
  160133. JDIMENSION output_width; /* scaled image width */
  160134. JDIMENSION output_height; /* scaled image height */
  160135. int out_color_components; /* # of color components in out_color_space */
  160136. int output_components; /* # of color components returned */
  160137. /* output_components is 1 (a colormap index) when quantizing colors;
  160138. * otherwise it equals out_color_components.
  160139. */
  160140. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160141. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160142. * high, space and time will be wasted due to unnecessary data copying.
  160143. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160144. */
  160145. /* When quantizing colors, the output colormap is described by these fields.
  160146. * The application can supply a colormap by setting colormap non-NULL before
  160147. * calling jpeg_start_decompress; otherwise a colormap is created during
  160148. * jpeg_start_decompress or jpeg_start_output.
  160149. * The map has out_color_components rows and actual_number_of_colors columns.
  160150. */
  160151. int actual_number_of_colors; /* number of entries in use */
  160152. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160153. /* State variables: these variables indicate the progress of decompression.
  160154. * The application may examine these but must not modify them.
  160155. */
  160156. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160157. * Application may use this to control its processing loop, e.g.,
  160158. * "while (output_scanline < output_height)".
  160159. */
  160160. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160161. /* Current input scan number and number of iMCU rows completed in scan.
  160162. * These indicate the progress of the decompressor input side.
  160163. */
  160164. int input_scan_number; /* Number of SOS markers seen so far */
  160165. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160166. /* The "output scan number" is the notional scan being displayed by the
  160167. * output side. The decompressor will not allow output scan/row number
  160168. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160169. */
  160170. int output_scan_number; /* Nominal scan number being displayed */
  160171. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160172. /* Current progression status. coef_bits[c][i] indicates the precision
  160173. * with which component c's DCT coefficient i (in zigzag order) is known.
  160174. * It is -1 when no data has yet been received, otherwise it is the point
  160175. * transform (shift) value for the most recent scan of the coefficient
  160176. * (thus, 0 at completion of the progression).
  160177. * This pointer is NULL when reading a non-progressive file.
  160178. */
  160179. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160180. /* Internal JPEG parameters --- the application usually need not look at
  160181. * these fields. Note that the decompressor output side may not use
  160182. * any parameters that can change between scans.
  160183. */
  160184. /* Quantization and Huffman tables are carried forward across input
  160185. * datastreams when processing abbreviated JPEG datastreams.
  160186. */
  160187. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160188. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160189. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160190. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160191. /* ptrs to Huffman coding tables, or NULL if not defined */
  160192. /* These parameters are never carried across datastreams, since they
  160193. * are given in SOF/SOS markers or defined to be reset by SOI.
  160194. */
  160195. int data_precision; /* bits of precision in image data */
  160196. jpeg_component_info * comp_info;
  160197. /* comp_info[i] describes component that appears i'th in SOF */
  160198. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160199. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160200. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160201. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160202. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160203. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160204. /* These fields record data obtained from optional markers recognized by
  160205. * the JPEG library.
  160206. */
  160207. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160208. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160209. UINT8 JFIF_major_version; /* JFIF version number */
  160210. UINT8 JFIF_minor_version;
  160211. UINT8 density_unit; /* JFIF code for pixel size units */
  160212. UINT16 X_density; /* Horizontal pixel density */
  160213. UINT16 Y_density; /* Vertical pixel density */
  160214. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160215. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160216. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160217. /* Aside from the specific data retained from APPn markers known to the
  160218. * library, the uninterpreted contents of any or all APPn and COM markers
  160219. * can be saved in a list for examination by the application.
  160220. */
  160221. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160222. /* Remaining fields are known throughout decompressor, but generally
  160223. * should not be touched by a surrounding application.
  160224. */
  160225. /*
  160226. * These fields are computed during decompression startup
  160227. */
  160228. int max_h_samp_factor; /* largest h_samp_factor */
  160229. int max_v_samp_factor; /* largest v_samp_factor */
  160230. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160231. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160232. /* The coefficient controller's input and output progress is measured in
  160233. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160234. * in fully interleaved JPEG scans, but are used whether the scan is
  160235. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160236. * rows of each component. Therefore, the IDCT output contains
  160237. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160238. */
  160239. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160240. /*
  160241. * These fields are valid during any one scan.
  160242. * They describe the components and MCUs actually appearing in the scan.
  160243. * Note that the decompressor output side must not use these fields.
  160244. */
  160245. int comps_in_scan; /* # of JPEG components in this scan */
  160246. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160247. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160248. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160249. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160250. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160251. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160252. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160253. /* i'th block in an MCU */
  160254. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160255. /* This field is shared between entropy decoder and marker parser.
  160256. * It is either zero or the code of a JPEG marker that has been
  160257. * read from the data source, but has not yet been processed.
  160258. */
  160259. int unread_marker;
  160260. /*
  160261. * Links to decompression subobjects (methods, private variables of modules)
  160262. */
  160263. struct jpeg_decomp_master * master;
  160264. struct jpeg_d_main_controller * main;
  160265. struct jpeg_d_coef_controller * coef;
  160266. struct jpeg_d_post_controller * post;
  160267. struct jpeg_input_controller * inputctl;
  160268. struct jpeg_marker_reader * marker;
  160269. struct jpeg_entropy_decoder * entropy;
  160270. struct jpeg_inverse_dct * idct;
  160271. struct jpeg_upsampler * upsample;
  160272. struct jpeg_color_deconverter * cconvert;
  160273. struct jpeg_color_quantizer * cquantize;
  160274. };
  160275. /* "Object" declarations for JPEG modules that may be supplied or called
  160276. * directly by the surrounding application.
  160277. * As with all objects in the JPEG library, these structs only define the
  160278. * publicly visible methods and state variables of a module. Additional
  160279. * private fields may exist after the public ones.
  160280. */
  160281. /* Error handler object */
  160282. struct jpeg_error_mgr {
  160283. /* Error exit handler: does not return to caller */
  160284. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160285. /* Conditionally emit a trace or warning message */
  160286. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160287. /* Routine that actually outputs a trace or error message */
  160288. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160289. /* Format a message string for the most recent JPEG error or message */
  160290. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160291. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160292. /* Reset error state variables at start of a new image */
  160293. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160294. /* The message ID code and any parameters are saved here.
  160295. * A message can have one string parameter or up to 8 int parameters.
  160296. */
  160297. int msg_code;
  160298. #define JMSG_STR_PARM_MAX 80
  160299. union {
  160300. int i[8];
  160301. char s[JMSG_STR_PARM_MAX];
  160302. } msg_parm;
  160303. /* Standard state variables for error facility */
  160304. int trace_level; /* max msg_level that will be displayed */
  160305. /* For recoverable corrupt-data errors, we emit a warning message,
  160306. * but keep going unless emit_message chooses to abort. emit_message
  160307. * should count warnings in num_warnings. The surrounding application
  160308. * can check for bad data by seeing if num_warnings is nonzero at the
  160309. * end of processing.
  160310. */
  160311. long num_warnings; /* number of corrupt-data warnings */
  160312. /* These fields point to the table(s) of error message strings.
  160313. * An application can change the table pointer to switch to a different
  160314. * message list (typically, to change the language in which errors are
  160315. * reported). Some applications may wish to add additional error codes
  160316. * that will be handled by the JPEG library error mechanism; the second
  160317. * table pointer is used for this purpose.
  160318. *
  160319. * First table includes all errors generated by JPEG library itself.
  160320. * Error code 0 is reserved for a "no such error string" message.
  160321. */
  160322. const char * const * jpeg_message_table; /* Library errors */
  160323. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160324. /* Second table can be added by application (see cjpeg/djpeg for example).
  160325. * It contains strings numbered first_addon_message..last_addon_message.
  160326. */
  160327. const char * const * addon_message_table; /* Non-library errors */
  160328. int first_addon_message; /* code for first string in addon table */
  160329. int last_addon_message; /* code for last string in addon table */
  160330. };
  160331. /* Progress monitor object */
  160332. struct jpeg_progress_mgr {
  160333. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160334. long pass_counter; /* work units completed in this pass */
  160335. long pass_limit; /* total number of work units in this pass */
  160336. int completed_passes; /* passes completed so far */
  160337. int total_passes; /* total number of passes expected */
  160338. };
  160339. /* Data destination object for compression */
  160340. struct jpeg_destination_mgr {
  160341. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160342. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160343. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160344. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160345. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160346. };
  160347. /* Data source object for decompression */
  160348. struct jpeg_source_mgr {
  160349. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160350. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160351. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160352. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160353. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160354. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160355. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160356. };
  160357. /* Memory manager object.
  160358. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160359. * and "really big" objects (virtual arrays with backing store if needed).
  160360. * The memory manager does not allow individual objects to be freed; rather,
  160361. * each created object is assigned to a pool, and whole pools can be freed
  160362. * at once. This is faster and more convenient than remembering exactly what
  160363. * to free, especially where malloc()/free() are not too speedy.
  160364. * NB: alloc routines never return NULL. They exit to error_exit if not
  160365. * successful.
  160366. */
  160367. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160368. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160369. #define JPOOL_NUMPOOLS 2
  160370. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160371. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160372. struct jpeg_memory_mgr {
  160373. /* Method pointers */
  160374. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160375. size_t sizeofobject));
  160376. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160377. size_t sizeofobject));
  160378. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160379. JDIMENSION samplesperrow,
  160380. JDIMENSION numrows));
  160381. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160382. JDIMENSION blocksperrow,
  160383. JDIMENSION numrows));
  160384. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160385. int pool_id,
  160386. boolean pre_zero,
  160387. JDIMENSION samplesperrow,
  160388. JDIMENSION numrows,
  160389. JDIMENSION maxaccess));
  160390. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160391. int pool_id,
  160392. boolean pre_zero,
  160393. JDIMENSION blocksperrow,
  160394. JDIMENSION numrows,
  160395. JDIMENSION maxaccess));
  160396. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160397. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160398. jvirt_sarray_ptr ptr,
  160399. JDIMENSION start_row,
  160400. JDIMENSION num_rows,
  160401. boolean writable));
  160402. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160403. jvirt_barray_ptr ptr,
  160404. JDIMENSION start_row,
  160405. JDIMENSION num_rows,
  160406. boolean writable));
  160407. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160408. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160409. /* Limit on memory allocation for this JPEG object. (Note that this is
  160410. * merely advisory, not a guaranteed maximum; it only affects the space
  160411. * used for virtual-array buffers.) May be changed by outer application
  160412. * after creating the JPEG object.
  160413. */
  160414. long max_memory_to_use;
  160415. /* Maximum allocation request accepted by alloc_large. */
  160416. long max_alloc_chunk;
  160417. };
  160418. /* Routine signature for application-supplied marker processing methods.
  160419. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160420. */
  160421. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160422. /* Declarations for routines called by application.
  160423. * The JPP macro hides prototype parameters from compilers that can't cope.
  160424. * Note JPP requires double parentheses.
  160425. */
  160426. #ifdef HAVE_PROTOTYPES
  160427. #define JPP(arglist) arglist
  160428. #else
  160429. #define JPP(arglist) ()
  160430. #endif
  160431. /* Short forms of external names for systems with brain-damaged linkers.
  160432. * We shorten external names to be unique in the first six letters, which
  160433. * is good enough for all known systems.
  160434. * (If your compiler itself needs names to be unique in less than 15
  160435. * characters, you are out of luck. Get a better compiler.)
  160436. */
  160437. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160438. #define jpeg_std_error jStdError
  160439. #define jpeg_CreateCompress jCreaCompress
  160440. #define jpeg_CreateDecompress jCreaDecompress
  160441. #define jpeg_destroy_compress jDestCompress
  160442. #define jpeg_destroy_decompress jDestDecompress
  160443. #define jpeg_stdio_dest jStdDest
  160444. #define jpeg_stdio_src jStdSrc
  160445. #define jpeg_set_defaults jSetDefaults
  160446. #define jpeg_set_colorspace jSetColorspace
  160447. #define jpeg_default_colorspace jDefColorspace
  160448. #define jpeg_set_quality jSetQuality
  160449. #define jpeg_set_linear_quality jSetLQuality
  160450. #define jpeg_add_quant_table jAddQuantTable
  160451. #define jpeg_quality_scaling jQualityScaling
  160452. #define jpeg_simple_progression jSimProgress
  160453. #define jpeg_suppress_tables jSuppressTables
  160454. #define jpeg_alloc_quant_table jAlcQTable
  160455. #define jpeg_alloc_huff_table jAlcHTable
  160456. #define jpeg_start_compress jStrtCompress
  160457. #define jpeg_write_scanlines jWrtScanlines
  160458. #define jpeg_finish_compress jFinCompress
  160459. #define jpeg_write_raw_data jWrtRawData
  160460. #define jpeg_write_marker jWrtMarker
  160461. #define jpeg_write_m_header jWrtMHeader
  160462. #define jpeg_write_m_byte jWrtMByte
  160463. #define jpeg_write_tables jWrtTables
  160464. #define jpeg_read_header jReadHeader
  160465. #define jpeg_start_decompress jStrtDecompress
  160466. #define jpeg_read_scanlines jReadScanlines
  160467. #define jpeg_finish_decompress jFinDecompress
  160468. #define jpeg_read_raw_data jReadRawData
  160469. #define jpeg_has_multiple_scans jHasMultScn
  160470. #define jpeg_start_output jStrtOutput
  160471. #define jpeg_finish_output jFinOutput
  160472. #define jpeg_input_complete jInComplete
  160473. #define jpeg_new_colormap jNewCMap
  160474. #define jpeg_consume_input jConsumeInput
  160475. #define jpeg_calc_output_dimensions jCalcDimensions
  160476. #define jpeg_save_markers jSaveMarkers
  160477. #define jpeg_set_marker_processor jSetMarker
  160478. #define jpeg_read_coefficients jReadCoefs
  160479. #define jpeg_write_coefficients jWrtCoefs
  160480. #define jpeg_copy_critical_parameters jCopyCrit
  160481. #define jpeg_abort_compress jAbrtCompress
  160482. #define jpeg_abort_decompress jAbrtDecompress
  160483. #define jpeg_abort jAbort
  160484. #define jpeg_destroy jDestroy
  160485. #define jpeg_resync_to_restart jResyncRestart
  160486. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160487. /* Default error-management setup */
  160488. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160489. JPP((struct jpeg_error_mgr * err));
  160490. /* Initialization of JPEG compression objects.
  160491. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160492. * names that applications should call. These expand to calls on
  160493. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160494. * passed for version mismatch checking.
  160495. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160496. */
  160497. #define jpeg_create_compress(cinfo) \
  160498. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160499. (size_t) sizeof(struct jpeg_compress_struct))
  160500. #define jpeg_create_decompress(cinfo) \
  160501. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160502. (size_t) sizeof(struct jpeg_decompress_struct))
  160503. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160504. int version, size_t structsize));
  160505. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160506. int version, size_t structsize));
  160507. /* Destruction of JPEG compression objects */
  160508. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160509. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160510. /* Standard data source and destination managers: stdio streams. */
  160511. /* Caller is responsible for opening the file before and closing after. */
  160512. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160513. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160514. /* Default parameter setup for compression */
  160515. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160516. /* Compression parameter setup aids */
  160517. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160518. J_COLOR_SPACE colorspace));
  160519. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160520. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160521. boolean force_baseline));
  160522. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160523. int scale_factor,
  160524. boolean force_baseline));
  160525. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160526. const unsigned int *basic_table,
  160527. int scale_factor,
  160528. boolean force_baseline));
  160529. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160530. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160531. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160532. boolean suppress));
  160533. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160534. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160535. /* Main entry points for compression */
  160536. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160537. boolean write_all_tables));
  160538. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160539. JSAMPARRAY scanlines,
  160540. JDIMENSION num_lines));
  160541. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160542. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160543. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160544. JSAMPIMAGE data,
  160545. JDIMENSION num_lines));
  160546. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160547. EXTERN(void) jpeg_write_marker
  160548. JPP((j_compress_ptr cinfo, int marker,
  160549. const JOCTET * dataptr, unsigned int datalen));
  160550. /* Same, but piecemeal. */
  160551. EXTERN(void) jpeg_write_m_header
  160552. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160553. EXTERN(void) jpeg_write_m_byte
  160554. JPP((j_compress_ptr cinfo, int val));
  160555. /* Alternate compression function: just write an abbreviated table file */
  160556. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160557. /* Decompression startup: read start of JPEG datastream to see what's there */
  160558. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160559. boolean require_image));
  160560. /* Return value is one of: */
  160561. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160562. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160563. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160564. /* If you pass require_image = TRUE (normal case), you need not check for
  160565. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160566. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160567. * give a suspension return (the stdio source module doesn't).
  160568. */
  160569. /* Main entry points for decompression */
  160570. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160571. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160572. JSAMPARRAY scanlines,
  160573. JDIMENSION max_lines));
  160574. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160575. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160576. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160577. JSAMPIMAGE data,
  160578. JDIMENSION max_lines));
  160579. /* Additional entry points for buffered-image mode. */
  160580. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160581. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160582. int scan_number));
  160583. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160584. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160585. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160586. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160587. /* Return value is one of: */
  160588. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160589. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160590. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160591. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160592. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160593. /* Precalculate output dimensions for current decompression parameters. */
  160594. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160595. /* Control saving of COM and APPn markers into marker_list. */
  160596. EXTERN(void) jpeg_save_markers
  160597. JPP((j_decompress_ptr cinfo, int marker_code,
  160598. unsigned int length_limit));
  160599. /* Install a special processing method for COM or APPn markers. */
  160600. EXTERN(void) jpeg_set_marker_processor
  160601. JPP((j_decompress_ptr cinfo, int marker_code,
  160602. jpeg_marker_parser_method routine));
  160603. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160604. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160605. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160606. jvirt_barray_ptr * coef_arrays));
  160607. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160608. j_compress_ptr dstinfo));
  160609. /* If you choose to abort compression or decompression before completing
  160610. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160611. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160612. * if you're done with the JPEG object, but if you want to clean it up and
  160613. * reuse it, call this:
  160614. */
  160615. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160616. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160617. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160618. * flavor of JPEG object. These may be more convenient in some places.
  160619. */
  160620. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160621. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160622. /* Default restart-marker-resync procedure for use by data source modules */
  160623. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160624. int desired));
  160625. /* These marker codes are exported since applications and data source modules
  160626. * are likely to want to use them.
  160627. */
  160628. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160629. #define JPEG_EOI 0xD9 /* EOI marker code */
  160630. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160631. #define JPEG_COM 0xFE /* COM marker code */
  160632. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160633. * for structure definitions that are never filled in, keep it quiet by
  160634. * supplying dummy definitions for the various substructures.
  160635. */
  160636. #ifdef INCOMPLETE_TYPES_BROKEN
  160637. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160638. struct jvirt_sarray_control { long dummy; };
  160639. struct jvirt_barray_control { long dummy; };
  160640. struct jpeg_comp_master { long dummy; };
  160641. struct jpeg_c_main_controller { long dummy; };
  160642. struct jpeg_c_prep_controller { long dummy; };
  160643. struct jpeg_c_coef_controller { long dummy; };
  160644. struct jpeg_marker_writer { long dummy; };
  160645. struct jpeg_color_converter { long dummy; };
  160646. struct jpeg_downsampler { long dummy; };
  160647. struct jpeg_forward_dct { long dummy; };
  160648. struct jpeg_entropy_encoder { long dummy; };
  160649. struct jpeg_decomp_master { long dummy; };
  160650. struct jpeg_d_main_controller { long dummy; };
  160651. struct jpeg_d_coef_controller { long dummy; };
  160652. struct jpeg_d_post_controller { long dummy; };
  160653. struct jpeg_input_controller { long dummy; };
  160654. struct jpeg_marker_reader { long dummy; };
  160655. struct jpeg_entropy_decoder { long dummy; };
  160656. struct jpeg_inverse_dct { long dummy; };
  160657. struct jpeg_upsampler { long dummy; };
  160658. struct jpeg_color_deconverter { long dummy; };
  160659. struct jpeg_color_quantizer { long dummy; };
  160660. #endif /* JPEG_INTERNALS */
  160661. #endif /* INCOMPLETE_TYPES_BROKEN */
  160662. /*
  160663. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160664. * The internal structure declarations are read only when that is true.
  160665. * Applications using the library should not include jpegint.h, but may wish
  160666. * to include jerror.h.
  160667. */
  160668. #ifdef JPEG_INTERNALS
  160669. /*** Start of inlined file: jpegint.h ***/
  160670. /* Declarations for both compression & decompression */
  160671. typedef enum { /* Operating modes for buffer controllers */
  160672. JBUF_PASS_THRU, /* Plain stripwise operation */
  160673. /* Remaining modes require a full-image buffer to have been created */
  160674. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160675. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160676. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160677. } J_BUF_MODE;
  160678. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160679. #define CSTATE_START 100 /* after create_compress */
  160680. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160681. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160682. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160683. #define DSTATE_START 200 /* after create_decompress */
  160684. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160685. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160686. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160687. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160688. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160689. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160690. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160691. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160692. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160693. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160694. /* Declarations for compression modules */
  160695. /* Master control module */
  160696. struct jpeg_comp_master {
  160697. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160698. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160699. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160700. /* State variables made visible to other modules */
  160701. boolean call_pass_startup; /* True if pass_startup must be called */
  160702. boolean is_last_pass; /* True during last pass */
  160703. };
  160704. /* Main buffer control (downsampled-data buffer) */
  160705. struct jpeg_c_main_controller {
  160706. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160707. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160708. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160709. JDIMENSION in_rows_avail));
  160710. };
  160711. /* Compression preprocessing (downsampling input buffer control) */
  160712. struct jpeg_c_prep_controller {
  160713. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160714. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160715. JSAMPARRAY input_buf,
  160716. JDIMENSION *in_row_ctr,
  160717. JDIMENSION in_rows_avail,
  160718. JSAMPIMAGE output_buf,
  160719. JDIMENSION *out_row_group_ctr,
  160720. JDIMENSION out_row_groups_avail));
  160721. };
  160722. /* Coefficient buffer control */
  160723. struct jpeg_c_coef_controller {
  160724. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160725. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160726. JSAMPIMAGE input_buf));
  160727. };
  160728. /* Colorspace conversion */
  160729. struct jpeg_color_converter {
  160730. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160731. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160732. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160733. JDIMENSION output_row, int num_rows));
  160734. };
  160735. /* Downsampling */
  160736. struct jpeg_downsampler {
  160737. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160738. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160739. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160740. JSAMPIMAGE output_buf,
  160741. JDIMENSION out_row_group_index));
  160742. boolean need_context_rows; /* TRUE if need rows above & below */
  160743. };
  160744. /* Forward DCT (also controls coefficient quantization) */
  160745. struct jpeg_forward_dct {
  160746. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160747. /* perhaps this should be an array??? */
  160748. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160749. jpeg_component_info * compptr,
  160750. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160751. JDIMENSION start_row, JDIMENSION start_col,
  160752. JDIMENSION num_blocks));
  160753. };
  160754. /* Entropy encoding */
  160755. struct jpeg_entropy_encoder {
  160756. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160757. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160758. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160759. };
  160760. /* Marker writing */
  160761. struct jpeg_marker_writer {
  160762. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160763. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160764. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160765. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160766. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160767. /* These routines are exported to allow insertion of extra markers */
  160768. /* Probably only COM and APPn markers should be written this way */
  160769. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160770. unsigned int datalen));
  160771. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160772. };
  160773. /* Declarations for decompression modules */
  160774. /* Master control module */
  160775. struct jpeg_decomp_master {
  160776. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160777. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160778. /* State variables made visible to other modules */
  160779. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160780. };
  160781. /* Input control module */
  160782. struct jpeg_input_controller {
  160783. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160784. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160785. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160786. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160787. /* State variables made visible to other modules */
  160788. boolean has_multiple_scans; /* True if file has multiple scans */
  160789. boolean eoi_reached; /* True when EOI has been consumed */
  160790. };
  160791. /* Main buffer control (downsampled-data buffer) */
  160792. struct jpeg_d_main_controller {
  160793. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160794. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160795. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160796. JDIMENSION out_rows_avail));
  160797. };
  160798. /* Coefficient buffer control */
  160799. struct jpeg_d_coef_controller {
  160800. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160801. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160802. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160803. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160804. JSAMPIMAGE output_buf));
  160805. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160806. jvirt_barray_ptr *coef_arrays;
  160807. };
  160808. /* Decompression postprocessing (color quantization buffer control) */
  160809. struct jpeg_d_post_controller {
  160810. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160811. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160812. JSAMPIMAGE input_buf,
  160813. JDIMENSION *in_row_group_ctr,
  160814. JDIMENSION in_row_groups_avail,
  160815. JSAMPARRAY output_buf,
  160816. JDIMENSION *out_row_ctr,
  160817. JDIMENSION out_rows_avail));
  160818. };
  160819. /* Marker reading & parsing */
  160820. struct jpeg_marker_reader {
  160821. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160822. /* Read markers until SOS or EOI.
  160823. * Returns same codes as are defined for jpeg_consume_input:
  160824. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160825. */
  160826. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160827. /* Read a restart marker --- exported for use by entropy decoder only */
  160828. jpeg_marker_parser_method read_restart_marker;
  160829. /* State of marker reader --- nominally internal, but applications
  160830. * supplying COM or APPn handlers might like to know the state.
  160831. */
  160832. boolean saw_SOI; /* found SOI? */
  160833. boolean saw_SOF; /* found SOF? */
  160834. int next_restart_num; /* next restart number expected (0-7) */
  160835. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160836. };
  160837. /* Entropy decoding */
  160838. struct jpeg_entropy_decoder {
  160839. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160840. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160841. JBLOCKROW *MCU_data));
  160842. /* This is here to share code between baseline and progressive decoders; */
  160843. /* other modules probably should not use it */
  160844. boolean insufficient_data; /* set TRUE after emitting warning */
  160845. };
  160846. /* Inverse DCT (also performs dequantization) */
  160847. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160848. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160849. JCOEFPTR coef_block,
  160850. JSAMPARRAY output_buf, JDIMENSION output_col));
  160851. struct jpeg_inverse_dct {
  160852. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160853. /* It is useful to allow each component to have a separate IDCT method. */
  160854. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160855. };
  160856. /* Upsampling (note that upsampler must also call color converter) */
  160857. struct jpeg_upsampler {
  160858. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160859. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160860. JSAMPIMAGE input_buf,
  160861. JDIMENSION *in_row_group_ctr,
  160862. JDIMENSION in_row_groups_avail,
  160863. JSAMPARRAY output_buf,
  160864. JDIMENSION *out_row_ctr,
  160865. JDIMENSION out_rows_avail));
  160866. boolean need_context_rows; /* TRUE if need rows above & below */
  160867. };
  160868. /* Colorspace conversion */
  160869. struct jpeg_color_deconverter {
  160870. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160871. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160872. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160873. JSAMPARRAY output_buf, int num_rows));
  160874. };
  160875. /* Color quantization or color precision reduction */
  160876. struct jpeg_color_quantizer {
  160877. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160878. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160879. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160880. int num_rows));
  160881. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160882. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160883. };
  160884. /* Miscellaneous useful macros */
  160885. #undef MAX
  160886. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160887. #undef MIN
  160888. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160889. /* We assume that right shift corresponds to signed division by 2 with
  160890. * rounding towards minus infinity. This is correct for typical "arithmetic
  160891. * shift" instructions that shift in copies of the sign bit. But some
  160892. * C compilers implement >> with an unsigned shift. For these machines you
  160893. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160894. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160895. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160896. * included in the variables of any routine using RIGHT_SHIFT.
  160897. */
  160898. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160899. #define SHIFT_TEMPS INT32 shift_temp;
  160900. #define RIGHT_SHIFT(x,shft) \
  160901. ((shift_temp = (x)) < 0 ? \
  160902. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160903. (shift_temp >> (shft)))
  160904. #else
  160905. #define SHIFT_TEMPS
  160906. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160907. #endif
  160908. /* Short forms of external names for systems with brain-damaged linkers. */
  160909. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160910. #define jinit_compress_master jICompress
  160911. #define jinit_c_master_control jICMaster
  160912. #define jinit_c_main_controller jICMainC
  160913. #define jinit_c_prep_controller jICPrepC
  160914. #define jinit_c_coef_controller jICCoefC
  160915. #define jinit_color_converter jICColor
  160916. #define jinit_downsampler jIDownsampler
  160917. #define jinit_forward_dct jIFDCT
  160918. #define jinit_huff_encoder jIHEncoder
  160919. #define jinit_phuff_encoder jIPHEncoder
  160920. #define jinit_marker_writer jIMWriter
  160921. #define jinit_master_decompress jIDMaster
  160922. #define jinit_d_main_controller jIDMainC
  160923. #define jinit_d_coef_controller jIDCoefC
  160924. #define jinit_d_post_controller jIDPostC
  160925. #define jinit_input_controller jIInCtlr
  160926. #define jinit_marker_reader jIMReader
  160927. #define jinit_huff_decoder jIHDecoder
  160928. #define jinit_phuff_decoder jIPHDecoder
  160929. #define jinit_inverse_dct jIIDCT
  160930. #define jinit_upsampler jIUpsampler
  160931. #define jinit_color_deconverter jIDColor
  160932. #define jinit_1pass_quantizer jI1Quant
  160933. #define jinit_2pass_quantizer jI2Quant
  160934. #define jinit_merged_upsampler jIMUpsampler
  160935. #define jinit_memory_mgr jIMemMgr
  160936. #define jdiv_round_up jDivRound
  160937. #define jround_up jRound
  160938. #define jcopy_sample_rows jCopySamples
  160939. #define jcopy_block_row jCopyBlocks
  160940. #define jzero_far jZeroFar
  160941. #define jpeg_zigzag_order jZIGTable
  160942. #define jpeg_natural_order jZAGTable
  160943. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160944. /* Compression module initialization routines */
  160945. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160946. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160947. boolean transcode_only));
  160948. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160949. boolean need_full_buffer));
  160950. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160951. boolean need_full_buffer));
  160952. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160953. boolean need_full_buffer));
  160954. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160955. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160956. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160957. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160958. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160959. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160960. /* Decompression module initialization routines */
  160961. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160962. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160963. boolean need_full_buffer));
  160964. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160965. boolean need_full_buffer));
  160966. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160967. boolean need_full_buffer));
  160968. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160969. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160970. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160971. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160972. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160973. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160974. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160975. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160976. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160977. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160978. /* Memory manager initialization */
  160979. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160980. /* Utility routines in jutils.c */
  160981. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160982. EXTERN(long) jround_up JPP((long a, long b));
  160983. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160984. JSAMPARRAY output_array, int dest_row,
  160985. int num_rows, JDIMENSION num_cols));
  160986. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160987. JDIMENSION num_blocks));
  160988. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160989. /* Constant tables in jutils.c */
  160990. #if 0 /* This table is not actually needed in v6a */
  160991. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160992. #endif
  160993. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160994. /* Suppress undefined-structure complaints if necessary. */
  160995. #ifdef INCOMPLETE_TYPES_BROKEN
  160996. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160997. struct jvirt_sarray_control { long dummy; };
  160998. struct jvirt_barray_control { long dummy; };
  160999. #endif
  161000. #endif /* INCOMPLETE_TYPES_BROKEN */
  161001. /*** End of inlined file: jpegint.h ***/
  161002. /* fetch private declarations */
  161003. /*** Start of inlined file: jerror.h ***/
  161004. /*
  161005. * To define the enum list of message codes, include this file without
  161006. * defining macro JMESSAGE. To create a message string table, include it
  161007. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161008. */
  161009. #ifndef JMESSAGE
  161010. #ifndef JERROR_H
  161011. /* First time through, define the enum list */
  161012. #define JMAKE_ENUM_LIST
  161013. #else
  161014. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161015. #define JMESSAGE(code,string)
  161016. #endif /* JERROR_H */
  161017. #endif /* JMESSAGE */
  161018. #ifdef JMAKE_ENUM_LIST
  161019. typedef enum {
  161020. #define JMESSAGE(code,string) code ,
  161021. #endif /* JMAKE_ENUM_LIST */
  161022. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161023. /* For maintenance convenience, list is alphabetical by message code name */
  161024. JMESSAGE(JERR_ARITH_NOTIMPL,
  161025. "Sorry, there are legal restrictions on arithmetic coding")
  161026. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161027. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161028. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161029. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161030. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161031. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161032. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161033. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161034. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161035. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161036. JMESSAGE(JERR_BAD_LIB_VERSION,
  161037. "Wrong JPEG library version: library is %d, caller expects %d")
  161038. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161039. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161040. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161041. JMESSAGE(JERR_BAD_PROGRESSION,
  161042. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161043. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161044. "Invalid progressive parameters at scan script entry %d")
  161045. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161046. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161047. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161048. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161049. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161050. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161051. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161052. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161053. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161054. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161055. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161056. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161057. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161058. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161059. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161060. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161061. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161062. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161063. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161064. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161065. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161066. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161067. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161068. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161069. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161070. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161071. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161072. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161073. "Cannot transcode due to multiple use of quantization table %d")
  161074. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161075. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161076. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161077. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161078. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161079. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161080. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161081. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161082. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161083. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161084. JMESSAGE(JERR_QUANT_COMPONENTS,
  161085. "Cannot quantize more than %d color components")
  161086. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161087. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161088. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161089. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161090. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161091. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161092. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161093. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161094. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161095. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161096. JMESSAGE(JERR_TFILE_WRITE,
  161097. "Write failed on temporary file --- out of disk space?")
  161098. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161099. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161100. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161101. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161102. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161103. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161104. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161105. JMESSAGE(JMSG_VERSION, JVERSION)
  161106. JMESSAGE(JTRC_16BIT_TABLES,
  161107. "Caution: quantization tables are too coarse for baseline JPEG")
  161108. JMESSAGE(JTRC_ADOBE,
  161109. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161110. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161111. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161112. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161113. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161114. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161115. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161116. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161117. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161118. JMESSAGE(JTRC_EOI, "End Of Image")
  161119. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161120. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161121. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161122. "Warning: thumbnail image size does not match data length %u")
  161123. JMESSAGE(JTRC_JFIF_EXTENSION,
  161124. "JFIF extension marker: type 0x%02x, length %u")
  161125. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161126. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161127. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161128. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161129. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161130. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161131. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161132. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161133. JMESSAGE(JTRC_RST, "RST%d")
  161134. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161135. "Smoothing not supported with nonstandard sampling ratios")
  161136. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161137. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161138. JMESSAGE(JTRC_SOI, "Start of Image")
  161139. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161140. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161141. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161142. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161143. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161144. JMESSAGE(JTRC_THUMB_JPEG,
  161145. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161146. JMESSAGE(JTRC_THUMB_PALETTE,
  161147. "JFIF extension marker: palette thumbnail image, length %u")
  161148. JMESSAGE(JTRC_THUMB_RGB,
  161149. "JFIF extension marker: RGB thumbnail image, length %u")
  161150. JMESSAGE(JTRC_UNKNOWN_IDS,
  161151. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161152. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161153. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161154. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161155. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161156. "Inconsistent progression sequence for component %d coefficient %d")
  161157. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161158. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161159. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161160. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161161. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161162. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161163. JMESSAGE(JWRN_MUST_RESYNC,
  161164. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161165. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161166. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161167. #ifdef JMAKE_ENUM_LIST
  161168. JMSG_LASTMSGCODE
  161169. } J_MESSAGE_CODE;
  161170. #undef JMAKE_ENUM_LIST
  161171. #endif /* JMAKE_ENUM_LIST */
  161172. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161173. #undef JMESSAGE
  161174. #ifndef JERROR_H
  161175. #define JERROR_H
  161176. /* Macros to simplify using the error and trace message stuff */
  161177. /* The first parameter is either type of cinfo pointer */
  161178. /* Fatal errors (print message and exit) */
  161179. #define ERREXIT(cinfo,code) \
  161180. ((cinfo)->err->msg_code = (code), \
  161181. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161182. #define ERREXIT1(cinfo,code,p1) \
  161183. ((cinfo)->err->msg_code = (code), \
  161184. (cinfo)->err->msg_parm.i[0] = (p1), \
  161185. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161186. #define ERREXIT2(cinfo,code,p1,p2) \
  161187. ((cinfo)->err->msg_code = (code), \
  161188. (cinfo)->err->msg_parm.i[0] = (p1), \
  161189. (cinfo)->err->msg_parm.i[1] = (p2), \
  161190. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161191. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161192. ((cinfo)->err->msg_code = (code), \
  161193. (cinfo)->err->msg_parm.i[0] = (p1), \
  161194. (cinfo)->err->msg_parm.i[1] = (p2), \
  161195. (cinfo)->err->msg_parm.i[2] = (p3), \
  161196. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161197. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161198. ((cinfo)->err->msg_code = (code), \
  161199. (cinfo)->err->msg_parm.i[0] = (p1), \
  161200. (cinfo)->err->msg_parm.i[1] = (p2), \
  161201. (cinfo)->err->msg_parm.i[2] = (p3), \
  161202. (cinfo)->err->msg_parm.i[3] = (p4), \
  161203. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161204. #define ERREXITS(cinfo,code,str) \
  161205. ((cinfo)->err->msg_code = (code), \
  161206. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161207. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161208. #define MAKESTMT(stuff) do { stuff } while (0)
  161209. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161210. #define WARNMS(cinfo,code) \
  161211. ((cinfo)->err->msg_code = (code), \
  161212. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161213. #define WARNMS1(cinfo,code,p1) \
  161214. ((cinfo)->err->msg_code = (code), \
  161215. (cinfo)->err->msg_parm.i[0] = (p1), \
  161216. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161217. #define WARNMS2(cinfo,code,p1,p2) \
  161218. ((cinfo)->err->msg_code = (code), \
  161219. (cinfo)->err->msg_parm.i[0] = (p1), \
  161220. (cinfo)->err->msg_parm.i[1] = (p2), \
  161221. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161222. /* Informational/debugging messages */
  161223. #define TRACEMS(cinfo,lvl,code) \
  161224. ((cinfo)->err->msg_code = (code), \
  161225. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161226. #define TRACEMS1(cinfo,lvl,code,p1) \
  161227. ((cinfo)->err->msg_code = (code), \
  161228. (cinfo)->err->msg_parm.i[0] = (p1), \
  161229. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161230. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161231. ((cinfo)->err->msg_code = (code), \
  161232. (cinfo)->err->msg_parm.i[0] = (p1), \
  161233. (cinfo)->err->msg_parm.i[1] = (p2), \
  161234. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161235. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161236. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161237. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161238. (cinfo)->err->msg_code = (code); \
  161239. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161240. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161241. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161242. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161243. (cinfo)->err->msg_code = (code); \
  161244. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161245. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161246. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161247. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161248. _mp[4] = (p5); \
  161249. (cinfo)->err->msg_code = (code); \
  161250. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161251. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161252. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161253. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161254. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161255. (cinfo)->err->msg_code = (code); \
  161256. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161257. #define TRACEMSS(cinfo,lvl,code,str) \
  161258. ((cinfo)->err->msg_code = (code), \
  161259. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161260. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161261. #endif /* JERROR_H */
  161262. /*** End of inlined file: jerror.h ***/
  161263. /* fetch error codes too */
  161264. #endif
  161265. #endif /* JPEGLIB_H */
  161266. /*** End of inlined file: jpeglib.h ***/
  161267. /*** Start of inlined file: jcapimin.c ***/
  161268. #define JPEG_INTERNALS
  161269. /*** Start of inlined file: jinclude.h ***/
  161270. /* Include auto-config file to find out which system include files we need. */
  161271. #ifndef __jinclude_h__
  161272. #define __jinclude_h__
  161273. /*** Start of inlined file: jconfig.h ***/
  161274. /* see jconfig.doc for explanations */
  161275. // disable all the warnings under MSVC
  161276. #ifdef _MSC_VER
  161277. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161278. #endif
  161279. #ifdef __BORLANDC__
  161280. #pragma warn -8057
  161281. #pragma warn -8019
  161282. #pragma warn -8004
  161283. #pragma warn -8008
  161284. #endif
  161285. #define HAVE_PROTOTYPES
  161286. #define HAVE_UNSIGNED_CHAR
  161287. #define HAVE_UNSIGNED_SHORT
  161288. /* #define void char */
  161289. /* #define const */
  161290. #undef CHAR_IS_UNSIGNED
  161291. #define HAVE_STDDEF_H
  161292. #define HAVE_STDLIB_H
  161293. #undef NEED_BSD_STRINGS
  161294. #undef NEED_SYS_TYPES_H
  161295. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161296. #undef NEED_SHORT_EXTERNAL_NAMES
  161297. #undef INCOMPLETE_TYPES_BROKEN
  161298. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161299. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161300. typedef unsigned char boolean;
  161301. #endif
  161302. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161303. #ifdef JPEG_INTERNALS
  161304. #undef RIGHT_SHIFT_IS_UNSIGNED
  161305. #endif /* JPEG_INTERNALS */
  161306. #ifdef JPEG_CJPEG_DJPEG
  161307. #define BMP_SUPPORTED /* BMP image file format */
  161308. #define GIF_SUPPORTED /* GIF image file format */
  161309. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161310. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161311. #define TARGA_SUPPORTED /* Targa image file format */
  161312. #define TWO_FILE_COMMANDLINE /* optional */
  161313. #define USE_SETMODE /* Microsoft has setmode() */
  161314. #undef NEED_SIGNAL_CATCHER
  161315. #undef DONT_USE_B_MODE
  161316. #undef PROGRESS_REPORT /* optional */
  161317. #endif /* JPEG_CJPEG_DJPEG */
  161318. /*** End of inlined file: jconfig.h ***/
  161319. /* auto configuration options */
  161320. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161321. /*
  161322. * We need the NULL macro and size_t typedef.
  161323. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161324. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161325. * pull in <sys/types.h> as well.
  161326. * Note that the core JPEG library does not require <stdio.h>;
  161327. * only the default error handler and data source/destination modules do.
  161328. * But we must pull it in because of the references to FILE in jpeglib.h.
  161329. * You can remove those references if you want to compile without <stdio.h>.
  161330. */
  161331. #ifdef HAVE_STDDEF_H
  161332. #include <stddef.h>
  161333. #endif
  161334. #ifdef HAVE_STDLIB_H
  161335. #include <stdlib.h>
  161336. #endif
  161337. #ifdef NEED_SYS_TYPES_H
  161338. #include <sys/types.h>
  161339. #endif
  161340. #include <stdio.h>
  161341. /*
  161342. * We need memory copying and zeroing functions, plus strncpy().
  161343. * ANSI and System V implementations declare these in <string.h>.
  161344. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161345. * Some systems may declare memset and memcpy in <memory.h>.
  161346. *
  161347. * NOTE: we assume the size parameters to these functions are of type size_t.
  161348. * Change the casts in these macros if not!
  161349. */
  161350. #ifdef NEED_BSD_STRINGS
  161351. #include <strings.h>
  161352. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161353. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161354. #else /* not BSD, assume ANSI/SysV string lib */
  161355. #include <string.h>
  161356. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161357. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161358. #endif
  161359. /*
  161360. * In ANSI C, and indeed any rational implementation, size_t is also the
  161361. * type returned by sizeof(). However, it seems there are some irrational
  161362. * implementations out there, in which sizeof() returns an int even though
  161363. * size_t is defined as long or unsigned long. To ensure consistent results
  161364. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161365. */
  161366. #define SIZEOF(object) ((size_t) sizeof(object))
  161367. /*
  161368. * The modules that use fread() and fwrite() always invoke them through
  161369. * these macros. On some systems you may need to twiddle the argument casts.
  161370. * CAUTION: argument order is different from underlying functions!
  161371. */
  161372. #define JFREAD(file,buf,sizeofbuf) \
  161373. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161374. #define JFWRITE(file,buf,sizeofbuf) \
  161375. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161376. typedef enum { /* JPEG marker codes */
  161377. M_SOF0 = 0xc0,
  161378. M_SOF1 = 0xc1,
  161379. M_SOF2 = 0xc2,
  161380. M_SOF3 = 0xc3,
  161381. M_SOF5 = 0xc5,
  161382. M_SOF6 = 0xc6,
  161383. M_SOF7 = 0xc7,
  161384. M_JPG = 0xc8,
  161385. M_SOF9 = 0xc9,
  161386. M_SOF10 = 0xca,
  161387. M_SOF11 = 0xcb,
  161388. M_SOF13 = 0xcd,
  161389. M_SOF14 = 0xce,
  161390. M_SOF15 = 0xcf,
  161391. M_DHT = 0xc4,
  161392. M_DAC = 0xcc,
  161393. M_RST0 = 0xd0,
  161394. M_RST1 = 0xd1,
  161395. M_RST2 = 0xd2,
  161396. M_RST3 = 0xd3,
  161397. M_RST4 = 0xd4,
  161398. M_RST5 = 0xd5,
  161399. M_RST6 = 0xd6,
  161400. M_RST7 = 0xd7,
  161401. M_SOI = 0xd8,
  161402. M_EOI = 0xd9,
  161403. M_SOS = 0xda,
  161404. M_DQT = 0xdb,
  161405. M_DNL = 0xdc,
  161406. M_DRI = 0xdd,
  161407. M_DHP = 0xde,
  161408. M_EXP = 0xdf,
  161409. M_APP0 = 0xe0,
  161410. M_APP1 = 0xe1,
  161411. M_APP2 = 0xe2,
  161412. M_APP3 = 0xe3,
  161413. M_APP4 = 0xe4,
  161414. M_APP5 = 0xe5,
  161415. M_APP6 = 0xe6,
  161416. M_APP7 = 0xe7,
  161417. M_APP8 = 0xe8,
  161418. M_APP9 = 0xe9,
  161419. M_APP10 = 0xea,
  161420. M_APP11 = 0xeb,
  161421. M_APP12 = 0xec,
  161422. M_APP13 = 0xed,
  161423. M_APP14 = 0xee,
  161424. M_APP15 = 0xef,
  161425. M_JPG0 = 0xf0,
  161426. M_JPG13 = 0xfd,
  161427. M_COM = 0xfe,
  161428. M_TEM = 0x01,
  161429. M_ERROR = 0x100
  161430. } JPEG_MARKER;
  161431. /*
  161432. * Figure F.12: extend sign bit.
  161433. * On some machines, a shift and add will be faster than a table lookup.
  161434. */
  161435. #ifdef AVOID_TABLES
  161436. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161437. #else
  161438. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161439. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161440. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161441. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161442. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161443. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161444. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161445. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161446. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161447. #endif /* AVOID_TABLES */
  161448. #endif
  161449. /*** End of inlined file: jinclude.h ***/
  161450. /*
  161451. * Initialization of a JPEG compression object.
  161452. * The error manager must already be set up (in case memory manager fails).
  161453. */
  161454. GLOBAL(void)
  161455. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161456. {
  161457. int i;
  161458. /* Guard against version mismatches between library and caller. */
  161459. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161460. if (version != JPEG_LIB_VERSION)
  161461. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161462. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161463. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161464. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161465. /* For debugging purposes, we zero the whole master structure.
  161466. * But the application has already set the err pointer, and may have set
  161467. * client_data, so we have to save and restore those fields.
  161468. * Note: if application hasn't set client_data, tools like Purify may
  161469. * complain here.
  161470. */
  161471. {
  161472. struct jpeg_error_mgr * err = cinfo->err;
  161473. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161474. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161475. cinfo->err = err;
  161476. cinfo->client_data = client_data;
  161477. }
  161478. cinfo->is_decompressor = FALSE;
  161479. /* Initialize a memory manager instance for this object */
  161480. jinit_memory_mgr((j_common_ptr) cinfo);
  161481. /* Zero out pointers to permanent structures. */
  161482. cinfo->progress = NULL;
  161483. cinfo->dest = NULL;
  161484. cinfo->comp_info = NULL;
  161485. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161486. cinfo->quant_tbl_ptrs[i] = NULL;
  161487. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161488. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161489. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161490. }
  161491. cinfo->script_space = NULL;
  161492. cinfo->input_gamma = 1.0; /* in case application forgets */
  161493. /* OK, I'm ready */
  161494. cinfo->global_state = CSTATE_START;
  161495. }
  161496. /*
  161497. * Destruction of a JPEG compression object
  161498. */
  161499. GLOBAL(void)
  161500. jpeg_destroy_compress (j_compress_ptr cinfo)
  161501. {
  161502. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161503. }
  161504. /*
  161505. * Abort processing of a JPEG compression operation,
  161506. * but don't destroy the object itself.
  161507. */
  161508. GLOBAL(void)
  161509. jpeg_abort_compress (j_compress_ptr cinfo)
  161510. {
  161511. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161512. }
  161513. /*
  161514. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161515. * Marks all currently defined tables as already written (if suppress)
  161516. * or not written (if !suppress). This will control whether they get emitted
  161517. * by a subsequent jpeg_start_compress call.
  161518. *
  161519. * This routine is exported for use by applications that want to produce
  161520. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161521. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161522. * jcparam.o would be linked whether the application used it or not.
  161523. */
  161524. GLOBAL(void)
  161525. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161526. {
  161527. int i;
  161528. JQUANT_TBL * qtbl;
  161529. JHUFF_TBL * htbl;
  161530. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161531. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161532. qtbl->sent_table = suppress;
  161533. }
  161534. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161535. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161536. htbl->sent_table = suppress;
  161537. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161538. htbl->sent_table = suppress;
  161539. }
  161540. }
  161541. /*
  161542. * Finish JPEG compression.
  161543. *
  161544. * If a multipass operating mode was selected, this may do a great deal of
  161545. * work including most of the actual output.
  161546. */
  161547. GLOBAL(void)
  161548. jpeg_finish_compress (j_compress_ptr cinfo)
  161549. {
  161550. JDIMENSION iMCU_row;
  161551. if (cinfo->global_state == CSTATE_SCANNING ||
  161552. cinfo->global_state == CSTATE_RAW_OK) {
  161553. /* Terminate first pass */
  161554. if (cinfo->next_scanline < cinfo->image_height)
  161555. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161556. (*cinfo->master->finish_pass) (cinfo);
  161557. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161558. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161559. /* Perform any remaining passes */
  161560. while (! cinfo->master->is_last_pass) {
  161561. (*cinfo->master->prepare_for_pass) (cinfo);
  161562. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161563. if (cinfo->progress != NULL) {
  161564. cinfo->progress->pass_counter = (long) iMCU_row;
  161565. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161566. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161567. }
  161568. /* We bypass the main controller and invoke coef controller directly;
  161569. * all work is being done from the coefficient buffer.
  161570. */
  161571. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161572. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161573. }
  161574. (*cinfo->master->finish_pass) (cinfo);
  161575. }
  161576. /* Write EOI, do final cleanup */
  161577. (*cinfo->marker->write_file_trailer) (cinfo);
  161578. (*cinfo->dest->term_destination) (cinfo);
  161579. /* We can use jpeg_abort to release memory and reset global_state */
  161580. jpeg_abort((j_common_ptr) cinfo);
  161581. }
  161582. /*
  161583. * Write a special marker.
  161584. * This is only recommended for writing COM or APPn markers.
  161585. * Must be called after jpeg_start_compress() and before
  161586. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161587. */
  161588. GLOBAL(void)
  161589. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161590. const JOCTET *dataptr, unsigned int datalen)
  161591. {
  161592. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161593. if (cinfo->next_scanline != 0 ||
  161594. (cinfo->global_state != CSTATE_SCANNING &&
  161595. cinfo->global_state != CSTATE_RAW_OK &&
  161596. cinfo->global_state != CSTATE_WRCOEFS))
  161597. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161598. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161599. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161600. while (datalen--) {
  161601. (*write_marker_byte) (cinfo, *dataptr);
  161602. dataptr++;
  161603. }
  161604. }
  161605. /* Same, but piecemeal. */
  161606. GLOBAL(void)
  161607. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161608. {
  161609. if (cinfo->next_scanline != 0 ||
  161610. (cinfo->global_state != CSTATE_SCANNING &&
  161611. cinfo->global_state != CSTATE_RAW_OK &&
  161612. cinfo->global_state != CSTATE_WRCOEFS))
  161613. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161614. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161615. }
  161616. GLOBAL(void)
  161617. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161618. {
  161619. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161620. }
  161621. /*
  161622. * Alternate compression function: just write an abbreviated table file.
  161623. * Before calling this, all parameters and a data destination must be set up.
  161624. *
  161625. * To produce a pair of files containing abbreviated tables and abbreviated
  161626. * image data, one would proceed as follows:
  161627. *
  161628. * initialize JPEG object
  161629. * set JPEG parameters
  161630. * set destination to table file
  161631. * jpeg_write_tables(cinfo);
  161632. * set destination to image file
  161633. * jpeg_start_compress(cinfo, FALSE);
  161634. * write data...
  161635. * jpeg_finish_compress(cinfo);
  161636. *
  161637. * jpeg_write_tables has the side effect of marking all tables written
  161638. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161639. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161640. */
  161641. GLOBAL(void)
  161642. jpeg_write_tables (j_compress_ptr cinfo)
  161643. {
  161644. if (cinfo->global_state != CSTATE_START)
  161645. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161646. /* (Re)initialize error mgr and destination modules */
  161647. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161648. (*cinfo->dest->init_destination) (cinfo);
  161649. /* Initialize the marker writer ... bit of a crock to do it here. */
  161650. jinit_marker_writer(cinfo);
  161651. /* Write them tables! */
  161652. (*cinfo->marker->write_tables_only) (cinfo);
  161653. /* And clean up. */
  161654. (*cinfo->dest->term_destination) (cinfo);
  161655. /*
  161656. * In library releases up through v6a, we called jpeg_abort() here to free
  161657. * any working memory allocated by the destination manager and marker
  161658. * writer. Some applications had a problem with that: they allocated space
  161659. * of their own from the library memory manager, and didn't want it to go
  161660. * away during write_tables. So now we do nothing. This will cause a
  161661. * memory leak if an app calls write_tables repeatedly without doing a full
  161662. * compression cycle or otherwise resetting the JPEG object. However, that
  161663. * seems less bad than unexpectedly freeing memory in the normal case.
  161664. * An app that prefers the old behavior can call jpeg_abort for itself after
  161665. * each call to jpeg_write_tables().
  161666. */
  161667. }
  161668. /*** End of inlined file: jcapimin.c ***/
  161669. /*** Start of inlined file: jcapistd.c ***/
  161670. #define JPEG_INTERNALS
  161671. /*
  161672. * Compression initialization.
  161673. * Before calling this, all parameters and a data destination must be set up.
  161674. *
  161675. * We require a write_all_tables parameter as a failsafe check when writing
  161676. * multiple datastreams from the same compression object. Since prior runs
  161677. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161678. * would emit an abbreviated stream (no tables) by default. This may be what
  161679. * is wanted, but for safety's sake it should not be the default behavior:
  161680. * programmers should have to make a deliberate choice to emit abbreviated
  161681. * images. Therefore the documentation and examples should encourage people
  161682. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161683. * wrong thing.
  161684. */
  161685. GLOBAL(void)
  161686. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161687. {
  161688. if (cinfo->global_state != CSTATE_START)
  161689. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161690. if (write_all_tables)
  161691. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161692. /* (Re)initialize error mgr and destination modules */
  161693. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161694. (*cinfo->dest->init_destination) (cinfo);
  161695. /* Perform master selection of active modules */
  161696. jinit_compress_master(cinfo);
  161697. /* Set up for the first pass */
  161698. (*cinfo->master->prepare_for_pass) (cinfo);
  161699. /* Ready for application to drive first pass through jpeg_write_scanlines
  161700. * or jpeg_write_raw_data.
  161701. */
  161702. cinfo->next_scanline = 0;
  161703. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161704. }
  161705. /*
  161706. * Write some scanlines of data to the JPEG compressor.
  161707. *
  161708. * The return value will be the number of lines actually written.
  161709. * This should be less than the supplied num_lines only in case that
  161710. * the data destination module has requested suspension of the compressor,
  161711. * or if more than image_height scanlines are passed in.
  161712. *
  161713. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161714. * this likely signals an application programmer error. However,
  161715. * excess scanlines passed in the last valid call are *silently* ignored,
  161716. * so that the application need not adjust num_lines for end-of-image
  161717. * when using a multiple-scanline buffer.
  161718. */
  161719. GLOBAL(JDIMENSION)
  161720. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161721. JDIMENSION num_lines)
  161722. {
  161723. JDIMENSION row_ctr, rows_left;
  161724. if (cinfo->global_state != CSTATE_SCANNING)
  161725. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161726. if (cinfo->next_scanline >= cinfo->image_height)
  161727. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161728. /* Call progress monitor hook if present */
  161729. if (cinfo->progress != NULL) {
  161730. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161731. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161732. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161733. }
  161734. /* Give master control module another chance if this is first call to
  161735. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161736. * delayed so that application can write COM, etc, markers between
  161737. * jpeg_start_compress and jpeg_write_scanlines.
  161738. */
  161739. if (cinfo->master->call_pass_startup)
  161740. (*cinfo->master->pass_startup) (cinfo);
  161741. /* Ignore any extra scanlines at bottom of image. */
  161742. rows_left = cinfo->image_height - cinfo->next_scanline;
  161743. if (num_lines > rows_left)
  161744. num_lines = rows_left;
  161745. row_ctr = 0;
  161746. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161747. cinfo->next_scanline += row_ctr;
  161748. return row_ctr;
  161749. }
  161750. /*
  161751. * Alternate entry point to write raw data.
  161752. * Processes exactly one iMCU row per call, unless suspended.
  161753. */
  161754. GLOBAL(JDIMENSION)
  161755. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161756. JDIMENSION num_lines)
  161757. {
  161758. JDIMENSION lines_per_iMCU_row;
  161759. if (cinfo->global_state != CSTATE_RAW_OK)
  161760. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161761. if (cinfo->next_scanline >= cinfo->image_height) {
  161762. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161763. return 0;
  161764. }
  161765. /* Call progress monitor hook if present */
  161766. if (cinfo->progress != NULL) {
  161767. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161768. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161769. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161770. }
  161771. /* Give master control module another chance if this is first call to
  161772. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161773. * delayed so that application can write COM, etc, markers between
  161774. * jpeg_start_compress and jpeg_write_raw_data.
  161775. */
  161776. if (cinfo->master->call_pass_startup)
  161777. (*cinfo->master->pass_startup) (cinfo);
  161778. /* Verify that at least one iMCU row has been passed. */
  161779. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161780. if (num_lines < lines_per_iMCU_row)
  161781. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161782. /* Directly compress the row. */
  161783. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161784. /* If compressor did not consume the whole row, suspend processing. */
  161785. return 0;
  161786. }
  161787. /* OK, we processed one iMCU row. */
  161788. cinfo->next_scanline += lines_per_iMCU_row;
  161789. return lines_per_iMCU_row;
  161790. }
  161791. /*** End of inlined file: jcapistd.c ***/
  161792. /*** Start of inlined file: jccoefct.c ***/
  161793. #define JPEG_INTERNALS
  161794. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161795. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161796. * step is run during the first pass, and subsequent passes need only read
  161797. * the buffered coefficients.
  161798. */
  161799. #ifdef ENTROPY_OPT_SUPPORTED
  161800. #define FULL_COEF_BUFFER_SUPPORTED
  161801. #else
  161802. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161803. #define FULL_COEF_BUFFER_SUPPORTED
  161804. #endif
  161805. #endif
  161806. /* Private buffer controller object */
  161807. typedef struct {
  161808. struct jpeg_c_coef_controller pub; /* public fields */
  161809. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161810. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161811. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161812. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161813. /* For single-pass compression, it's sufficient to buffer just one MCU
  161814. * (although this may prove a bit slow in practice). We allocate a
  161815. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161816. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161817. * it's not really very big; this is to keep the module interfaces unchanged
  161818. * when a large coefficient buffer is necessary.)
  161819. * In multi-pass modes, this array points to the current MCU's blocks
  161820. * within the virtual arrays.
  161821. */
  161822. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161823. /* In multi-pass modes, we need a virtual block array for each component. */
  161824. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161825. } my_coef_controller;
  161826. typedef my_coef_controller * my_coef_ptr;
  161827. /* Forward declarations */
  161828. METHODDEF(boolean) compress_data
  161829. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161830. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161831. METHODDEF(boolean) compress_first_pass
  161832. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161833. METHODDEF(boolean) compress_output
  161834. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161835. #endif
  161836. LOCAL(void)
  161837. start_iMCU_row (j_compress_ptr cinfo)
  161838. /* Reset within-iMCU-row counters for a new row */
  161839. {
  161840. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161841. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161842. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161843. * But at the bottom of the image, process only what's left.
  161844. */
  161845. if (cinfo->comps_in_scan > 1) {
  161846. coef->MCU_rows_per_iMCU_row = 1;
  161847. } else {
  161848. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161849. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161850. else
  161851. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161852. }
  161853. coef->mcu_ctr = 0;
  161854. coef->MCU_vert_offset = 0;
  161855. }
  161856. /*
  161857. * Initialize for a processing pass.
  161858. */
  161859. METHODDEF(void)
  161860. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161861. {
  161862. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161863. coef->iMCU_row_num = 0;
  161864. start_iMCU_row(cinfo);
  161865. switch (pass_mode) {
  161866. case JBUF_PASS_THRU:
  161867. if (coef->whole_image[0] != NULL)
  161868. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161869. coef->pub.compress_data = compress_data;
  161870. break;
  161871. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161872. case JBUF_SAVE_AND_PASS:
  161873. if (coef->whole_image[0] == NULL)
  161874. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161875. coef->pub.compress_data = compress_first_pass;
  161876. break;
  161877. case JBUF_CRANK_DEST:
  161878. if (coef->whole_image[0] == NULL)
  161879. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161880. coef->pub.compress_data = compress_output;
  161881. break;
  161882. #endif
  161883. default:
  161884. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161885. break;
  161886. }
  161887. }
  161888. /*
  161889. * Process some data in the single-pass case.
  161890. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161891. * per call, ie, v_samp_factor block rows for each component in the image.
  161892. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161893. *
  161894. * NB: input_buf contains a plane for each component in image,
  161895. * which we index according to the component's SOF position.
  161896. */
  161897. METHODDEF(boolean)
  161898. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161899. {
  161900. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161901. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161902. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161903. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161904. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161905. JDIMENSION ypos, xpos;
  161906. jpeg_component_info *compptr;
  161907. /* Loop to write as much as one whole iMCU row */
  161908. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161909. yoffset++) {
  161910. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161911. MCU_col_num++) {
  161912. /* Determine where data comes from in input_buf and do the DCT thing.
  161913. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161914. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161915. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161916. * specially. The data in them does not matter for image reconstruction,
  161917. * so we fill them with values that will encode to the smallest amount of
  161918. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161919. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161920. */
  161921. blkn = 0;
  161922. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161923. compptr = cinfo->cur_comp_info[ci];
  161924. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161925. : compptr->last_col_width;
  161926. xpos = MCU_col_num * compptr->MCU_sample_width;
  161927. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161928. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161929. if (coef->iMCU_row_num < last_iMCU_row ||
  161930. yoffset+yindex < compptr->last_row_height) {
  161931. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161932. input_buf[compptr->component_index],
  161933. coef->MCU_buffer[blkn],
  161934. ypos, xpos, (JDIMENSION) blockcnt);
  161935. if (blockcnt < compptr->MCU_width) {
  161936. /* Create some dummy blocks at the right edge of the image. */
  161937. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161938. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161939. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161940. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161941. }
  161942. }
  161943. } else {
  161944. /* Create a row of dummy blocks at the bottom of the image. */
  161945. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161946. compptr->MCU_width * SIZEOF(JBLOCK));
  161947. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161948. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161949. }
  161950. }
  161951. blkn += compptr->MCU_width;
  161952. ypos += DCTSIZE;
  161953. }
  161954. }
  161955. /* Try to write the MCU. In event of a suspension failure, we will
  161956. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161957. */
  161958. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161959. /* Suspension forced; update state counters and exit */
  161960. coef->MCU_vert_offset = yoffset;
  161961. coef->mcu_ctr = MCU_col_num;
  161962. return FALSE;
  161963. }
  161964. }
  161965. /* Completed an MCU row, but perhaps not an iMCU row */
  161966. coef->mcu_ctr = 0;
  161967. }
  161968. /* Completed the iMCU row, advance counters for next one */
  161969. coef->iMCU_row_num++;
  161970. start_iMCU_row(cinfo);
  161971. return TRUE;
  161972. }
  161973. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161974. /*
  161975. * Process some data in the first pass of a multi-pass case.
  161976. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161977. * per call, ie, v_samp_factor block rows for each component in the image.
  161978. * This amount of data is read from the source buffer, DCT'd and quantized,
  161979. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161980. * as needed at the right and lower edges. (The dummy blocks are constructed
  161981. * in the virtual arrays, which have been padded appropriately.) This makes
  161982. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161983. *
  161984. * We must also emit the data to the entropy encoder. This is conveniently
  161985. * done by calling compress_output() after we've loaded the current strip
  161986. * of the virtual arrays.
  161987. *
  161988. * NB: input_buf contains a plane for each component in image. All
  161989. * components are DCT'd and loaded into the virtual arrays in this pass.
  161990. * However, it may be that only a subset of the components are emitted to
  161991. * the entropy encoder during this first pass; be careful about looking
  161992. * at the scan-dependent variables (MCU dimensions, etc).
  161993. */
  161994. METHODDEF(boolean)
  161995. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161996. {
  161997. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161998. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161999. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162000. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162001. JCOEF lastDC;
  162002. jpeg_component_info *compptr;
  162003. JBLOCKARRAY buffer;
  162004. JBLOCKROW thisblockrow, lastblockrow;
  162005. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162006. ci++, compptr++) {
  162007. /* Align the virtual buffer for this component. */
  162008. buffer = (*cinfo->mem->access_virt_barray)
  162009. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162010. coef->iMCU_row_num * compptr->v_samp_factor,
  162011. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162012. /* Count non-dummy DCT block rows in this iMCU row. */
  162013. if (coef->iMCU_row_num < last_iMCU_row)
  162014. block_rows = compptr->v_samp_factor;
  162015. else {
  162016. /* NB: can't use last_row_height here, since may not be set! */
  162017. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162018. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162019. }
  162020. blocks_across = compptr->width_in_blocks;
  162021. h_samp_factor = compptr->h_samp_factor;
  162022. /* Count number of dummy blocks to be added at the right margin. */
  162023. ndummy = (int) (blocks_across % h_samp_factor);
  162024. if (ndummy > 0)
  162025. ndummy = h_samp_factor - ndummy;
  162026. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162027. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162028. */
  162029. for (block_row = 0; block_row < block_rows; block_row++) {
  162030. thisblockrow = buffer[block_row];
  162031. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162032. input_buf[ci], thisblockrow,
  162033. (JDIMENSION) (block_row * DCTSIZE),
  162034. (JDIMENSION) 0, blocks_across);
  162035. if (ndummy > 0) {
  162036. /* Create dummy blocks at the right edge of the image. */
  162037. thisblockrow += blocks_across; /* => first dummy block */
  162038. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162039. lastDC = thisblockrow[-1][0];
  162040. for (bi = 0; bi < ndummy; bi++) {
  162041. thisblockrow[bi][0] = lastDC;
  162042. }
  162043. }
  162044. }
  162045. /* If at end of image, create dummy block rows as needed.
  162046. * The tricky part here is that within each MCU, we want the DC values
  162047. * of the dummy blocks to match the last real block's DC value.
  162048. * This squeezes a few more bytes out of the resulting file...
  162049. */
  162050. if (coef->iMCU_row_num == last_iMCU_row) {
  162051. blocks_across += ndummy; /* include lower right corner */
  162052. MCUs_across = blocks_across / h_samp_factor;
  162053. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162054. block_row++) {
  162055. thisblockrow = buffer[block_row];
  162056. lastblockrow = buffer[block_row-1];
  162057. jzero_far((void FAR *) thisblockrow,
  162058. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162059. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162060. lastDC = lastblockrow[h_samp_factor-1][0];
  162061. for (bi = 0; bi < h_samp_factor; bi++) {
  162062. thisblockrow[bi][0] = lastDC;
  162063. }
  162064. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162065. lastblockrow += h_samp_factor;
  162066. }
  162067. }
  162068. }
  162069. }
  162070. /* NB: compress_output will increment iMCU_row_num if successful.
  162071. * A suspension return will result in redoing all the work above next time.
  162072. */
  162073. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162074. return compress_output(cinfo, input_buf);
  162075. }
  162076. /*
  162077. * Process some data in subsequent passes of a multi-pass case.
  162078. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162079. * per call, ie, v_samp_factor block rows for each component in the scan.
  162080. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162081. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162082. *
  162083. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162084. */
  162085. METHODDEF(boolean)
  162086. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162087. {
  162088. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162089. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162090. int blkn, ci, xindex, yindex, yoffset;
  162091. JDIMENSION start_col;
  162092. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162093. JBLOCKROW buffer_ptr;
  162094. jpeg_component_info *compptr;
  162095. /* Align the virtual buffers for the components used in this scan.
  162096. * NB: during first pass, this is safe only because the buffers will
  162097. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162098. */
  162099. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162100. compptr = cinfo->cur_comp_info[ci];
  162101. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162102. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162103. coef->iMCU_row_num * compptr->v_samp_factor,
  162104. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162105. }
  162106. /* Loop to process one whole iMCU row */
  162107. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162108. yoffset++) {
  162109. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162110. MCU_col_num++) {
  162111. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162112. blkn = 0; /* index of current DCT block within MCU */
  162113. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162114. compptr = cinfo->cur_comp_info[ci];
  162115. start_col = MCU_col_num * compptr->MCU_width;
  162116. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162117. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162118. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162119. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162120. }
  162121. }
  162122. }
  162123. /* Try to write the MCU. */
  162124. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162125. /* Suspension forced; update state counters and exit */
  162126. coef->MCU_vert_offset = yoffset;
  162127. coef->mcu_ctr = MCU_col_num;
  162128. return FALSE;
  162129. }
  162130. }
  162131. /* Completed an MCU row, but perhaps not an iMCU row */
  162132. coef->mcu_ctr = 0;
  162133. }
  162134. /* Completed the iMCU row, advance counters for next one */
  162135. coef->iMCU_row_num++;
  162136. start_iMCU_row(cinfo);
  162137. return TRUE;
  162138. }
  162139. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162140. /*
  162141. * Initialize coefficient buffer controller.
  162142. */
  162143. GLOBAL(void)
  162144. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162145. {
  162146. my_coef_ptr coef;
  162147. coef = (my_coef_ptr)
  162148. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162149. SIZEOF(my_coef_controller));
  162150. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162151. coef->pub.start_pass = start_pass_coef;
  162152. /* Create the coefficient buffer. */
  162153. if (need_full_buffer) {
  162154. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162155. /* Allocate a full-image virtual array for each component, */
  162156. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162157. int ci;
  162158. jpeg_component_info *compptr;
  162159. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162160. ci++, compptr++) {
  162161. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162162. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162163. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162164. (long) compptr->h_samp_factor),
  162165. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162166. (long) compptr->v_samp_factor),
  162167. (JDIMENSION) compptr->v_samp_factor);
  162168. }
  162169. #else
  162170. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162171. #endif
  162172. } else {
  162173. /* We only need a single-MCU buffer. */
  162174. JBLOCKROW buffer;
  162175. int i;
  162176. buffer = (JBLOCKROW)
  162177. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162178. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162179. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162180. coef->MCU_buffer[i] = buffer + i;
  162181. }
  162182. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162183. }
  162184. }
  162185. /*** End of inlined file: jccoefct.c ***/
  162186. /*** Start of inlined file: jccolor.c ***/
  162187. #define JPEG_INTERNALS
  162188. /* Private subobject */
  162189. typedef struct {
  162190. struct jpeg_color_converter pub; /* public fields */
  162191. /* Private state for RGB->YCC conversion */
  162192. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162193. } my_color_converter;
  162194. typedef my_color_converter * my_cconvert_ptr;
  162195. /**************** RGB -> YCbCr conversion: most common case **************/
  162196. /*
  162197. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162198. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162199. * The conversion equations to be implemented are therefore
  162200. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162201. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162202. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162203. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162204. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162205. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162206. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162207. * were not represented exactly. Now we sacrifice exact representation of
  162208. * maximum red and maximum blue in order to get exact grayscales.
  162209. *
  162210. * To avoid floating-point arithmetic, we represent the fractional constants
  162211. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162212. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162213. *
  162214. * For even more speed, we avoid doing any multiplications in the inner loop
  162215. * by precalculating the constants times R,G,B for all possible values.
  162216. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162217. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162218. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162219. * colorspace anyway.
  162220. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162221. * in the tables to save adding them separately in the inner loop.
  162222. */
  162223. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162224. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162225. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162226. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162227. /* We allocate one big table and divide it up into eight parts, instead of
  162228. * doing eight alloc_small requests. This lets us use a single table base
  162229. * address, which can be held in a register in the inner loops on many
  162230. * machines (more than can hold all eight addresses, anyway).
  162231. */
  162232. #define R_Y_OFF 0 /* offset to R => Y section */
  162233. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162234. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162235. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162236. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162237. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162238. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162239. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162240. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162241. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162242. /*
  162243. * Initialize for RGB->YCC colorspace conversion.
  162244. */
  162245. METHODDEF(void)
  162246. rgb_ycc_start (j_compress_ptr cinfo)
  162247. {
  162248. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162249. INT32 * rgb_ycc_tab;
  162250. INT32 i;
  162251. /* Allocate and fill in the conversion tables. */
  162252. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162253. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162254. (TABLE_SIZE * SIZEOF(INT32)));
  162255. for (i = 0; i <= MAXJSAMPLE; i++) {
  162256. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162257. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162258. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162259. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162260. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162261. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162262. * This ensures that the maximum output will round to MAXJSAMPLE
  162263. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162264. */
  162265. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162266. /* B=>Cb and R=>Cr tables are the same
  162267. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162268. */
  162269. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162270. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162271. }
  162272. }
  162273. /*
  162274. * Convert some rows of samples to the JPEG colorspace.
  162275. *
  162276. * Note that we change from the application's interleaved-pixel format
  162277. * to our internal noninterleaved, one-plane-per-component format.
  162278. * The input buffer is therefore three times as wide as the output buffer.
  162279. *
  162280. * A starting row offset is provided only for the output buffer. The caller
  162281. * can easily adjust the passed input_buf value to accommodate any row
  162282. * offset required on that side.
  162283. */
  162284. METHODDEF(void)
  162285. rgb_ycc_convert (j_compress_ptr cinfo,
  162286. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162287. JDIMENSION output_row, int num_rows)
  162288. {
  162289. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162290. register int r, g, b;
  162291. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162292. register JSAMPROW inptr;
  162293. register JSAMPROW outptr0, outptr1, outptr2;
  162294. register JDIMENSION col;
  162295. JDIMENSION num_cols = cinfo->image_width;
  162296. while (--num_rows >= 0) {
  162297. inptr = *input_buf++;
  162298. outptr0 = output_buf[0][output_row];
  162299. outptr1 = output_buf[1][output_row];
  162300. outptr2 = output_buf[2][output_row];
  162301. output_row++;
  162302. for (col = 0; col < num_cols; col++) {
  162303. r = GETJSAMPLE(inptr[RGB_RED]);
  162304. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162305. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162306. inptr += RGB_PIXELSIZE;
  162307. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162308. * must be too; we do not need an explicit range-limiting operation.
  162309. * Hence the value being shifted is never negative, and we don't
  162310. * need the general RIGHT_SHIFT macro.
  162311. */
  162312. /* Y */
  162313. outptr0[col] = (JSAMPLE)
  162314. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162315. >> SCALEBITS);
  162316. /* Cb */
  162317. outptr1[col] = (JSAMPLE)
  162318. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162319. >> SCALEBITS);
  162320. /* Cr */
  162321. outptr2[col] = (JSAMPLE)
  162322. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162323. >> SCALEBITS);
  162324. }
  162325. }
  162326. }
  162327. /**************** Cases other than RGB -> YCbCr **************/
  162328. /*
  162329. * Convert some rows of samples to the JPEG colorspace.
  162330. * This version handles RGB->grayscale conversion, which is the same
  162331. * as the RGB->Y portion of RGB->YCbCr.
  162332. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162333. */
  162334. METHODDEF(void)
  162335. rgb_gray_convert (j_compress_ptr cinfo,
  162336. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162337. JDIMENSION output_row, int num_rows)
  162338. {
  162339. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162340. register int r, g, b;
  162341. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162342. register JSAMPROW inptr;
  162343. register JSAMPROW outptr;
  162344. register JDIMENSION col;
  162345. JDIMENSION num_cols = cinfo->image_width;
  162346. while (--num_rows >= 0) {
  162347. inptr = *input_buf++;
  162348. outptr = output_buf[0][output_row];
  162349. output_row++;
  162350. for (col = 0; col < num_cols; col++) {
  162351. r = GETJSAMPLE(inptr[RGB_RED]);
  162352. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162353. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162354. inptr += RGB_PIXELSIZE;
  162355. /* Y */
  162356. outptr[col] = (JSAMPLE)
  162357. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162358. >> SCALEBITS);
  162359. }
  162360. }
  162361. }
  162362. /*
  162363. * Convert some rows of samples to the JPEG colorspace.
  162364. * This version handles Adobe-style CMYK->YCCK conversion,
  162365. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162366. * conversion as above, while passing K (black) unchanged.
  162367. * We assume rgb_ycc_start has been called.
  162368. */
  162369. METHODDEF(void)
  162370. cmyk_ycck_convert (j_compress_ptr cinfo,
  162371. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162372. JDIMENSION output_row, int num_rows)
  162373. {
  162374. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162375. register int r, g, b;
  162376. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162377. register JSAMPROW inptr;
  162378. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162379. register JDIMENSION col;
  162380. JDIMENSION num_cols = cinfo->image_width;
  162381. while (--num_rows >= 0) {
  162382. inptr = *input_buf++;
  162383. outptr0 = output_buf[0][output_row];
  162384. outptr1 = output_buf[1][output_row];
  162385. outptr2 = output_buf[2][output_row];
  162386. outptr3 = output_buf[3][output_row];
  162387. output_row++;
  162388. for (col = 0; col < num_cols; col++) {
  162389. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162390. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162391. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162392. /* K passes through as-is */
  162393. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162394. inptr += 4;
  162395. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162396. * must be too; we do not need an explicit range-limiting operation.
  162397. * Hence the value being shifted is never negative, and we don't
  162398. * need the general RIGHT_SHIFT macro.
  162399. */
  162400. /* Y */
  162401. outptr0[col] = (JSAMPLE)
  162402. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162403. >> SCALEBITS);
  162404. /* Cb */
  162405. outptr1[col] = (JSAMPLE)
  162406. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162407. >> SCALEBITS);
  162408. /* Cr */
  162409. outptr2[col] = (JSAMPLE)
  162410. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162411. >> SCALEBITS);
  162412. }
  162413. }
  162414. }
  162415. /*
  162416. * Convert some rows of samples to the JPEG colorspace.
  162417. * This version handles grayscale output with no conversion.
  162418. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162419. */
  162420. METHODDEF(void)
  162421. grayscale_convert (j_compress_ptr cinfo,
  162422. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162423. JDIMENSION output_row, int num_rows)
  162424. {
  162425. register JSAMPROW inptr;
  162426. register JSAMPROW outptr;
  162427. register JDIMENSION col;
  162428. JDIMENSION num_cols = cinfo->image_width;
  162429. int instride = cinfo->input_components;
  162430. while (--num_rows >= 0) {
  162431. inptr = *input_buf++;
  162432. outptr = output_buf[0][output_row];
  162433. output_row++;
  162434. for (col = 0; col < num_cols; col++) {
  162435. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162436. inptr += instride;
  162437. }
  162438. }
  162439. }
  162440. /*
  162441. * Convert some rows of samples to the JPEG colorspace.
  162442. * This version handles multi-component colorspaces without conversion.
  162443. * We assume input_components == num_components.
  162444. */
  162445. METHODDEF(void)
  162446. null_convert (j_compress_ptr cinfo,
  162447. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162448. JDIMENSION output_row, int num_rows)
  162449. {
  162450. register JSAMPROW inptr;
  162451. register JSAMPROW outptr;
  162452. register JDIMENSION col;
  162453. register int ci;
  162454. int nc = cinfo->num_components;
  162455. JDIMENSION num_cols = cinfo->image_width;
  162456. while (--num_rows >= 0) {
  162457. /* It seems fastest to make a separate pass for each component. */
  162458. for (ci = 0; ci < nc; ci++) {
  162459. inptr = *input_buf;
  162460. outptr = output_buf[ci][output_row];
  162461. for (col = 0; col < num_cols; col++) {
  162462. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162463. inptr += nc;
  162464. }
  162465. }
  162466. input_buf++;
  162467. output_row++;
  162468. }
  162469. }
  162470. /*
  162471. * Empty method for start_pass.
  162472. */
  162473. METHODDEF(void)
  162474. null_method (j_compress_ptr)
  162475. {
  162476. /* no work needed */
  162477. }
  162478. /*
  162479. * Module initialization routine for input colorspace conversion.
  162480. */
  162481. GLOBAL(void)
  162482. jinit_color_converter (j_compress_ptr cinfo)
  162483. {
  162484. my_cconvert_ptr cconvert;
  162485. cconvert = (my_cconvert_ptr)
  162486. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162487. SIZEOF(my_color_converter));
  162488. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162489. /* set start_pass to null method until we find out differently */
  162490. cconvert->pub.start_pass = null_method;
  162491. /* Make sure input_components agrees with in_color_space */
  162492. switch (cinfo->in_color_space) {
  162493. case JCS_GRAYSCALE:
  162494. if (cinfo->input_components != 1)
  162495. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162496. break;
  162497. case JCS_RGB:
  162498. #if RGB_PIXELSIZE != 3
  162499. if (cinfo->input_components != RGB_PIXELSIZE)
  162500. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162501. break;
  162502. #endif /* else share code with YCbCr */
  162503. case JCS_YCbCr:
  162504. if (cinfo->input_components != 3)
  162505. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162506. break;
  162507. case JCS_CMYK:
  162508. case JCS_YCCK:
  162509. if (cinfo->input_components != 4)
  162510. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162511. break;
  162512. default: /* JCS_UNKNOWN can be anything */
  162513. if (cinfo->input_components < 1)
  162514. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162515. break;
  162516. }
  162517. /* Check num_components, set conversion method based on requested space */
  162518. switch (cinfo->jpeg_color_space) {
  162519. case JCS_GRAYSCALE:
  162520. if (cinfo->num_components != 1)
  162521. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162522. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162523. cconvert->pub.color_convert = grayscale_convert;
  162524. else if (cinfo->in_color_space == JCS_RGB) {
  162525. cconvert->pub.start_pass = rgb_ycc_start;
  162526. cconvert->pub.color_convert = rgb_gray_convert;
  162527. } else if (cinfo->in_color_space == JCS_YCbCr)
  162528. cconvert->pub.color_convert = grayscale_convert;
  162529. else
  162530. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162531. break;
  162532. case JCS_RGB:
  162533. if (cinfo->num_components != 3)
  162534. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162535. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162536. cconvert->pub.color_convert = null_convert;
  162537. else
  162538. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162539. break;
  162540. case JCS_YCbCr:
  162541. if (cinfo->num_components != 3)
  162542. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162543. if (cinfo->in_color_space == JCS_RGB) {
  162544. cconvert->pub.start_pass = rgb_ycc_start;
  162545. cconvert->pub.color_convert = rgb_ycc_convert;
  162546. } else if (cinfo->in_color_space == JCS_YCbCr)
  162547. cconvert->pub.color_convert = null_convert;
  162548. else
  162549. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162550. break;
  162551. case JCS_CMYK:
  162552. if (cinfo->num_components != 4)
  162553. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162554. if (cinfo->in_color_space == JCS_CMYK)
  162555. cconvert->pub.color_convert = null_convert;
  162556. else
  162557. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162558. break;
  162559. case JCS_YCCK:
  162560. if (cinfo->num_components != 4)
  162561. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162562. if (cinfo->in_color_space == JCS_CMYK) {
  162563. cconvert->pub.start_pass = rgb_ycc_start;
  162564. cconvert->pub.color_convert = cmyk_ycck_convert;
  162565. } else if (cinfo->in_color_space == JCS_YCCK)
  162566. cconvert->pub.color_convert = null_convert;
  162567. else
  162568. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162569. break;
  162570. default: /* allow null conversion of JCS_UNKNOWN */
  162571. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162572. cinfo->num_components != cinfo->input_components)
  162573. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162574. cconvert->pub.color_convert = null_convert;
  162575. break;
  162576. }
  162577. }
  162578. /*** End of inlined file: jccolor.c ***/
  162579. #undef FIX
  162580. /*** Start of inlined file: jcdctmgr.c ***/
  162581. #define JPEG_INTERNALS
  162582. /*** Start of inlined file: jdct.h ***/
  162583. /*
  162584. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162585. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162586. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162587. * implementations use an array of type FAST_FLOAT, instead.)
  162588. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162589. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162590. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162591. * convention improves accuracy in integer implementations and saves some
  162592. * work in floating-point ones.
  162593. * Quantization of the output coefficients is done by jcdctmgr.c.
  162594. */
  162595. #ifndef __jdct_h__
  162596. #define __jdct_h__
  162597. #if BITS_IN_JSAMPLE == 8
  162598. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162599. #else
  162600. typedef INT32 DCTELEM; /* must have 32 bits */
  162601. #endif
  162602. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162603. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162604. /*
  162605. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162606. * to an output sample array. The routine must dequantize the input data as
  162607. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162608. * pointed to by compptr->dct_table. The output data is to be placed into the
  162609. * sample array starting at a specified column. (Any row offset needed will
  162610. * be applied to the array pointer before it is passed to the IDCT code.)
  162611. * Note that the number of samples emitted by the IDCT routine is
  162612. * DCT_scaled_size * DCT_scaled_size.
  162613. */
  162614. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162615. /*
  162616. * Each IDCT routine has its own ideas about the best dct_table element type.
  162617. */
  162618. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162619. #if BITS_IN_JSAMPLE == 8
  162620. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162621. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162622. #else
  162623. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162624. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162625. #endif
  162626. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162627. /*
  162628. * Each IDCT routine is responsible for range-limiting its results and
  162629. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162630. * be quite far out of range if the input data is corrupt, so a bulletproof
  162631. * range-limiting step is required. We use a mask-and-table-lookup method
  162632. * to do the combined operations quickly. See the comments with
  162633. * prepare_range_limit_table (in jdmaster.c) for more info.
  162634. */
  162635. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162636. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162637. /* Short forms of external names for systems with brain-damaged linkers. */
  162638. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162639. #define jpeg_fdct_islow jFDislow
  162640. #define jpeg_fdct_ifast jFDifast
  162641. #define jpeg_fdct_float jFDfloat
  162642. #define jpeg_idct_islow jRDislow
  162643. #define jpeg_idct_ifast jRDifast
  162644. #define jpeg_idct_float jRDfloat
  162645. #define jpeg_idct_4x4 jRD4x4
  162646. #define jpeg_idct_2x2 jRD2x2
  162647. #define jpeg_idct_1x1 jRD1x1
  162648. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162649. /* Extern declarations for the forward and inverse DCT routines. */
  162650. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162651. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162652. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162653. EXTERN(void) jpeg_idct_islow
  162654. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162655. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162656. EXTERN(void) jpeg_idct_ifast
  162657. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162658. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162659. EXTERN(void) jpeg_idct_float
  162660. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162661. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162662. EXTERN(void) jpeg_idct_4x4
  162663. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162664. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162665. EXTERN(void) jpeg_idct_2x2
  162666. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162667. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162668. EXTERN(void) jpeg_idct_1x1
  162669. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162670. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162671. /*
  162672. * Macros for handling fixed-point arithmetic; these are used by many
  162673. * but not all of the DCT/IDCT modules.
  162674. *
  162675. * All values are expected to be of type INT32.
  162676. * Fractional constants are scaled left by CONST_BITS bits.
  162677. * CONST_BITS is defined within each module using these macros,
  162678. * and may differ from one module to the next.
  162679. */
  162680. #define ONE ((INT32) 1)
  162681. #define CONST_SCALE (ONE << CONST_BITS)
  162682. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162683. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162684. * thus causing a lot of useless floating-point operations at run time.
  162685. */
  162686. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162687. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162688. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162689. * the fudge factor is correct for either sign of X.
  162690. */
  162691. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162692. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162693. * This macro is used only when the two inputs will actually be no more than
  162694. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162695. * full 32x32 multiply. This provides a useful speedup on many machines.
  162696. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162697. * in C, but some C compilers will do the right thing if you provide the
  162698. * correct combination of casts.
  162699. */
  162700. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162701. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162702. #endif
  162703. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162704. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162705. #endif
  162706. #ifndef MULTIPLY16C16 /* default definition */
  162707. #define MULTIPLY16C16(var,const) ((var) * (const))
  162708. #endif
  162709. /* Same except both inputs are variables. */
  162710. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162711. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162712. #endif
  162713. #ifndef MULTIPLY16V16 /* default definition */
  162714. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162715. #endif
  162716. #endif
  162717. /*** End of inlined file: jdct.h ***/
  162718. /* Private declarations for DCT subsystem */
  162719. /* Private subobject for this module */
  162720. typedef struct {
  162721. struct jpeg_forward_dct pub; /* public fields */
  162722. /* Pointer to the DCT routine actually in use */
  162723. forward_DCT_method_ptr do_dct;
  162724. /* The actual post-DCT divisors --- not identical to the quant table
  162725. * entries, because of scaling (especially for an unnormalized DCT).
  162726. * Each table is given in normal array order.
  162727. */
  162728. DCTELEM * divisors[NUM_QUANT_TBLS];
  162729. #ifdef DCT_FLOAT_SUPPORTED
  162730. /* Same as above for the floating-point case. */
  162731. float_DCT_method_ptr do_float_dct;
  162732. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162733. #endif
  162734. } my_fdct_controller;
  162735. typedef my_fdct_controller * my_fdct_ptr;
  162736. /*
  162737. * Initialize for a processing pass.
  162738. * Verify that all referenced Q-tables are present, and set up
  162739. * the divisor table for each one.
  162740. * In the current implementation, DCT of all components is done during
  162741. * the first pass, even if only some components will be output in the
  162742. * first scan. Hence all components should be examined here.
  162743. */
  162744. METHODDEF(void)
  162745. start_pass_fdctmgr (j_compress_ptr cinfo)
  162746. {
  162747. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162748. int ci, qtblno, i;
  162749. jpeg_component_info *compptr;
  162750. JQUANT_TBL * qtbl;
  162751. DCTELEM * dtbl;
  162752. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162753. ci++, compptr++) {
  162754. qtblno = compptr->quant_tbl_no;
  162755. /* Make sure specified quantization table is present */
  162756. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162757. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162758. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162759. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162760. /* Compute divisors for this quant table */
  162761. /* We may do this more than once for same table, but it's not a big deal */
  162762. switch (cinfo->dct_method) {
  162763. #ifdef DCT_ISLOW_SUPPORTED
  162764. case JDCT_ISLOW:
  162765. /* For LL&M IDCT method, divisors are equal to raw quantization
  162766. * coefficients multiplied by 8 (to counteract scaling).
  162767. */
  162768. if (fdct->divisors[qtblno] == NULL) {
  162769. fdct->divisors[qtblno] = (DCTELEM *)
  162770. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162771. DCTSIZE2 * SIZEOF(DCTELEM));
  162772. }
  162773. dtbl = fdct->divisors[qtblno];
  162774. for (i = 0; i < DCTSIZE2; i++) {
  162775. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162776. }
  162777. break;
  162778. #endif
  162779. #ifdef DCT_IFAST_SUPPORTED
  162780. case JDCT_IFAST:
  162781. {
  162782. /* For AA&N IDCT method, divisors are equal to quantization
  162783. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162784. * scalefactor[0] = 1
  162785. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162786. * We apply a further scale factor of 8.
  162787. */
  162788. #define CONST_BITS 14
  162789. static const INT16 aanscales[DCTSIZE2] = {
  162790. /* precomputed values scaled up by 14 bits */
  162791. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162792. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162793. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162794. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162795. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162796. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162797. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162798. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162799. };
  162800. SHIFT_TEMPS
  162801. if (fdct->divisors[qtblno] == NULL) {
  162802. fdct->divisors[qtblno] = (DCTELEM *)
  162803. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162804. DCTSIZE2 * SIZEOF(DCTELEM));
  162805. }
  162806. dtbl = fdct->divisors[qtblno];
  162807. for (i = 0; i < DCTSIZE2; i++) {
  162808. dtbl[i] = (DCTELEM)
  162809. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162810. (INT32) aanscales[i]),
  162811. CONST_BITS-3);
  162812. }
  162813. }
  162814. break;
  162815. #endif
  162816. #ifdef DCT_FLOAT_SUPPORTED
  162817. case JDCT_FLOAT:
  162818. {
  162819. /* For float AA&N IDCT method, divisors are equal to quantization
  162820. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162821. * scalefactor[0] = 1
  162822. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162823. * We apply a further scale factor of 8.
  162824. * What's actually stored is 1/divisor so that the inner loop can
  162825. * use a multiplication rather than a division.
  162826. */
  162827. FAST_FLOAT * fdtbl;
  162828. int row, col;
  162829. static const double aanscalefactor[DCTSIZE] = {
  162830. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162831. 1.0, 0.785694958, 0.541196100, 0.275899379
  162832. };
  162833. if (fdct->float_divisors[qtblno] == NULL) {
  162834. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162835. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162836. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162837. }
  162838. fdtbl = fdct->float_divisors[qtblno];
  162839. i = 0;
  162840. for (row = 0; row < DCTSIZE; row++) {
  162841. for (col = 0; col < DCTSIZE; col++) {
  162842. fdtbl[i] = (FAST_FLOAT)
  162843. (1.0 / (((double) qtbl->quantval[i] *
  162844. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162845. i++;
  162846. }
  162847. }
  162848. }
  162849. break;
  162850. #endif
  162851. default:
  162852. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162853. break;
  162854. }
  162855. }
  162856. }
  162857. /*
  162858. * Perform forward DCT on one or more blocks of a component.
  162859. *
  162860. * The input samples are taken from the sample_data[] array starting at
  162861. * position start_row/start_col, and moving to the right for any additional
  162862. * blocks. The quantized coefficients are returned in coef_blocks[].
  162863. */
  162864. METHODDEF(void)
  162865. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162866. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162867. JDIMENSION start_row, JDIMENSION start_col,
  162868. JDIMENSION num_blocks)
  162869. /* This version is used for integer DCT implementations. */
  162870. {
  162871. /* This routine is heavily used, so it's worth coding it tightly. */
  162872. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162873. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162874. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162875. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162876. JDIMENSION bi;
  162877. sample_data += start_row; /* fold in the vertical offset once */
  162878. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162879. /* Load data into workspace, applying unsigned->signed conversion */
  162880. { register DCTELEM *workspaceptr;
  162881. register JSAMPROW elemptr;
  162882. register int elemr;
  162883. workspaceptr = workspace;
  162884. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162885. elemptr = sample_data[elemr] + start_col;
  162886. #if DCTSIZE == 8 /* unroll the inner loop */
  162887. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162888. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162889. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162890. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162891. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162892. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162893. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162894. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162895. #else
  162896. { register int elemc;
  162897. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162898. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162899. }
  162900. }
  162901. #endif
  162902. }
  162903. }
  162904. /* Perform the DCT */
  162905. (*do_dct) (workspace);
  162906. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162907. { register DCTELEM temp, qval;
  162908. register int i;
  162909. register JCOEFPTR output_ptr = coef_blocks[bi];
  162910. for (i = 0; i < DCTSIZE2; i++) {
  162911. qval = divisors[i];
  162912. temp = workspace[i];
  162913. /* Divide the coefficient value by qval, ensuring proper rounding.
  162914. * Since C does not specify the direction of rounding for negative
  162915. * quotients, we have to force the dividend positive for portability.
  162916. *
  162917. * In most files, at least half of the output values will be zero
  162918. * (at default quantization settings, more like three-quarters...)
  162919. * so we should ensure that this case is fast. On many machines,
  162920. * a comparison is enough cheaper than a divide to make a special test
  162921. * a win. Since both inputs will be nonnegative, we need only test
  162922. * for a < b to discover whether a/b is 0.
  162923. * If your machine's division is fast enough, define FAST_DIVIDE.
  162924. */
  162925. #ifdef FAST_DIVIDE
  162926. #define DIVIDE_BY(a,b) a /= b
  162927. #else
  162928. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162929. #endif
  162930. if (temp < 0) {
  162931. temp = -temp;
  162932. temp += qval>>1; /* for rounding */
  162933. DIVIDE_BY(temp, qval);
  162934. temp = -temp;
  162935. } else {
  162936. temp += qval>>1; /* for rounding */
  162937. DIVIDE_BY(temp, qval);
  162938. }
  162939. output_ptr[i] = (JCOEF) temp;
  162940. }
  162941. }
  162942. }
  162943. }
  162944. #ifdef DCT_FLOAT_SUPPORTED
  162945. METHODDEF(void)
  162946. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162947. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162948. JDIMENSION start_row, JDIMENSION start_col,
  162949. JDIMENSION num_blocks)
  162950. /* This version is used for floating-point DCT implementations. */
  162951. {
  162952. /* This routine is heavily used, so it's worth coding it tightly. */
  162953. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162954. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162955. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162956. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162957. JDIMENSION bi;
  162958. sample_data += start_row; /* fold in the vertical offset once */
  162959. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162960. /* Load data into workspace, applying unsigned->signed conversion */
  162961. { register FAST_FLOAT *workspaceptr;
  162962. register JSAMPROW elemptr;
  162963. register int elemr;
  162964. workspaceptr = workspace;
  162965. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162966. elemptr = sample_data[elemr] + start_col;
  162967. #if DCTSIZE == 8 /* unroll the inner loop */
  162968. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162969. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162970. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162971. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162972. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162973. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162974. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162975. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162976. #else
  162977. { register int elemc;
  162978. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162979. *workspaceptr++ = (FAST_FLOAT)
  162980. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162981. }
  162982. }
  162983. #endif
  162984. }
  162985. }
  162986. /* Perform the DCT */
  162987. (*do_dct) (workspace);
  162988. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162989. { register FAST_FLOAT temp;
  162990. register int i;
  162991. register JCOEFPTR output_ptr = coef_blocks[bi];
  162992. for (i = 0; i < DCTSIZE2; i++) {
  162993. /* Apply the quantization and scaling factor */
  162994. temp = workspace[i] * divisors[i];
  162995. /* Round to nearest integer.
  162996. * Since C does not specify the direction of rounding for negative
  162997. * quotients, we have to force the dividend positive for portability.
  162998. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162999. * code should work for either 16-bit or 32-bit ints.
  163000. */
  163001. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163002. }
  163003. }
  163004. }
  163005. }
  163006. #endif /* DCT_FLOAT_SUPPORTED */
  163007. /*
  163008. * Initialize FDCT manager.
  163009. */
  163010. GLOBAL(void)
  163011. jinit_forward_dct (j_compress_ptr cinfo)
  163012. {
  163013. my_fdct_ptr fdct;
  163014. int i;
  163015. fdct = (my_fdct_ptr)
  163016. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163017. SIZEOF(my_fdct_controller));
  163018. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163019. fdct->pub.start_pass = start_pass_fdctmgr;
  163020. switch (cinfo->dct_method) {
  163021. #ifdef DCT_ISLOW_SUPPORTED
  163022. case JDCT_ISLOW:
  163023. fdct->pub.forward_DCT = forward_DCT;
  163024. fdct->do_dct = jpeg_fdct_islow;
  163025. break;
  163026. #endif
  163027. #ifdef DCT_IFAST_SUPPORTED
  163028. case JDCT_IFAST:
  163029. fdct->pub.forward_DCT = forward_DCT;
  163030. fdct->do_dct = jpeg_fdct_ifast;
  163031. break;
  163032. #endif
  163033. #ifdef DCT_FLOAT_SUPPORTED
  163034. case JDCT_FLOAT:
  163035. fdct->pub.forward_DCT = forward_DCT_float;
  163036. fdct->do_float_dct = jpeg_fdct_float;
  163037. break;
  163038. #endif
  163039. default:
  163040. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163041. break;
  163042. }
  163043. /* Mark divisor tables unallocated */
  163044. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163045. fdct->divisors[i] = NULL;
  163046. #ifdef DCT_FLOAT_SUPPORTED
  163047. fdct->float_divisors[i] = NULL;
  163048. #endif
  163049. }
  163050. }
  163051. /*** End of inlined file: jcdctmgr.c ***/
  163052. #undef CONST_BITS
  163053. /*** Start of inlined file: jchuff.c ***/
  163054. #define JPEG_INTERNALS
  163055. /*** Start of inlined file: jchuff.h ***/
  163056. /* The legal range of a DCT coefficient is
  163057. * -1024 .. +1023 for 8-bit data;
  163058. * -16384 .. +16383 for 12-bit data.
  163059. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163060. */
  163061. #ifndef _jchuff_h_
  163062. #define _jchuff_h_
  163063. #if BITS_IN_JSAMPLE == 8
  163064. #define MAX_COEF_BITS 10
  163065. #else
  163066. #define MAX_COEF_BITS 14
  163067. #endif
  163068. /* Derived data constructed for each Huffman table */
  163069. typedef struct {
  163070. unsigned int ehufco[256]; /* code for each symbol */
  163071. char ehufsi[256]; /* length of code for each symbol */
  163072. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163073. } c_derived_tbl;
  163074. /* Short forms of external names for systems with brain-damaged linkers. */
  163075. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163076. #define jpeg_make_c_derived_tbl jMkCDerived
  163077. #define jpeg_gen_optimal_table jGenOptTbl
  163078. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163079. /* Expand a Huffman table definition into the derived format */
  163080. EXTERN(void) jpeg_make_c_derived_tbl
  163081. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163082. c_derived_tbl ** pdtbl));
  163083. /* Generate an optimal table definition given the specified counts */
  163084. EXTERN(void) jpeg_gen_optimal_table
  163085. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163086. #endif
  163087. /*** End of inlined file: jchuff.h ***/
  163088. /* Declarations shared with jcphuff.c */
  163089. /* Expanded entropy encoder object for Huffman encoding.
  163090. *
  163091. * The savable_state subrecord contains fields that change within an MCU,
  163092. * but must not be updated permanently until we complete the MCU.
  163093. */
  163094. typedef struct {
  163095. INT32 put_buffer; /* current bit-accumulation buffer */
  163096. int put_bits; /* # of bits now in it */
  163097. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163098. } savable_state;
  163099. /* This macro is to work around compilers with missing or broken
  163100. * structure assignment. You'll need to fix this code if you have
  163101. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163102. */
  163103. #ifndef NO_STRUCT_ASSIGN
  163104. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163105. #else
  163106. #if MAX_COMPS_IN_SCAN == 4
  163107. #define ASSIGN_STATE(dest,src) \
  163108. ((dest).put_buffer = (src).put_buffer, \
  163109. (dest).put_bits = (src).put_bits, \
  163110. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163111. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163112. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163113. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163114. #endif
  163115. #endif
  163116. typedef struct {
  163117. struct jpeg_entropy_encoder pub; /* public fields */
  163118. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163119. /* These fields are NOT loaded into local working state. */
  163120. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163121. int next_restart_num; /* next restart number to write (0-7) */
  163122. /* Pointers to derived tables (these workspaces have image lifespan) */
  163123. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163124. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163125. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163126. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163127. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163128. #endif
  163129. } huff_entropy_encoder;
  163130. typedef huff_entropy_encoder * huff_entropy_ptr;
  163131. /* Working state while writing an MCU.
  163132. * This struct contains all the fields that are needed by subroutines.
  163133. */
  163134. typedef struct {
  163135. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163136. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163137. savable_state cur; /* Current bit buffer & DC state */
  163138. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163139. } working_state;
  163140. /* Forward declarations */
  163141. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163142. JBLOCKROW *MCU_data));
  163143. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163144. #ifdef ENTROPY_OPT_SUPPORTED
  163145. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163146. JBLOCKROW *MCU_data));
  163147. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163148. #endif
  163149. /*
  163150. * Initialize for a Huffman-compressed scan.
  163151. * If gather_statistics is TRUE, we do not output anything during the scan,
  163152. * just count the Huffman symbols used and generate Huffman code tables.
  163153. */
  163154. METHODDEF(void)
  163155. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163156. {
  163157. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163158. int ci, dctbl, actbl;
  163159. jpeg_component_info * compptr;
  163160. if (gather_statistics) {
  163161. #ifdef ENTROPY_OPT_SUPPORTED
  163162. entropy->pub.encode_mcu = encode_mcu_gather;
  163163. entropy->pub.finish_pass = finish_pass_gather;
  163164. #else
  163165. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163166. #endif
  163167. } else {
  163168. entropy->pub.encode_mcu = encode_mcu_huff;
  163169. entropy->pub.finish_pass = finish_pass_huff;
  163170. }
  163171. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163172. compptr = cinfo->cur_comp_info[ci];
  163173. dctbl = compptr->dc_tbl_no;
  163174. actbl = compptr->ac_tbl_no;
  163175. if (gather_statistics) {
  163176. #ifdef ENTROPY_OPT_SUPPORTED
  163177. /* Check for invalid table indexes */
  163178. /* (make_c_derived_tbl does this in the other path) */
  163179. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163180. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163181. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163182. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163183. /* Allocate and zero the statistics tables */
  163184. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163185. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163186. entropy->dc_count_ptrs[dctbl] = (long *)
  163187. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163188. 257 * SIZEOF(long));
  163189. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163190. if (entropy->ac_count_ptrs[actbl] == NULL)
  163191. entropy->ac_count_ptrs[actbl] = (long *)
  163192. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163193. 257 * SIZEOF(long));
  163194. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163195. #endif
  163196. } else {
  163197. /* Compute derived values for Huffman tables */
  163198. /* We may do this more than once for a table, but it's not expensive */
  163199. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163200. & entropy->dc_derived_tbls[dctbl]);
  163201. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163202. & entropy->ac_derived_tbls[actbl]);
  163203. }
  163204. /* Initialize DC predictions to 0 */
  163205. entropy->saved.last_dc_val[ci] = 0;
  163206. }
  163207. /* Initialize bit buffer to empty */
  163208. entropy->saved.put_buffer = 0;
  163209. entropy->saved.put_bits = 0;
  163210. /* Initialize restart stuff */
  163211. entropy->restarts_to_go = cinfo->restart_interval;
  163212. entropy->next_restart_num = 0;
  163213. }
  163214. /*
  163215. * Compute the derived values for a Huffman table.
  163216. * This routine also performs some validation checks on the table.
  163217. *
  163218. * Note this is also used by jcphuff.c.
  163219. */
  163220. GLOBAL(void)
  163221. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163222. c_derived_tbl ** pdtbl)
  163223. {
  163224. JHUFF_TBL *htbl;
  163225. c_derived_tbl *dtbl;
  163226. int p, i, l, lastp, si, maxsymbol;
  163227. char huffsize[257];
  163228. unsigned int huffcode[257];
  163229. unsigned int code;
  163230. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163231. * paralleling the order of the symbols themselves in htbl->huffval[].
  163232. */
  163233. /* Find the input Huffman table */
  163234. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163235. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163236. htbl =
  163237. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163238. if (htbl == NULL)
  163239. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163240. /* Allocate a workspace if we haven't already done so. */
  163241. if (*pdtbl == NULL)
  163242. *pdtbl = (c_derived_tbl *)
  163243. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163244. SIZEOF(c_derived_tbl));
  163245. dtbl = *pdtbl;
  163246. /* Figure C.1: make table of Huffman code length for each symbol */
  163247. p = 0;
  163248. for (l = 1; l <= 16; l++) {
  163249. i = (int) htbl->bits[l];
  163250. if (i < 0 || p + i > 256) /* protect against table overrun */
  163251. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163252. while (i--)
  163253. huffsize[p++] = (char) l;
  163254. }
  163255. huffsize[p] = 0;
  163256. lastp = p;
  163257. /* Figure C.2: generate the codes themselves */
  163258. /* We also validate that the counts represent a legal Huffman code tree. */
  163259. code = 0;
  163260. si = huffsize[0];
  163261. p = 0;
  163262. while (huffsize[p]) {
  163263. while (((int) huffsize[p]) == si) {
  163264. huffcode[p++] = code;
  163265. code++;
  163266. }
  163267. /* code is now 1 more than the last code used for codelength si; but
  163268. * it must still fit in si bits, since no code is allowed to be all ones.
  163269. */
  163270. if (((INT32) code) >= (((INT32) 1) << si))
  163271. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163272. code <<= 1;
  163273. si++;
  163274. }
  163275. /* Figure C.3: generate encoding tables */
  163276. /* These are code and size indexed by symbol value */
  163277. /* Set all codeless symbols to have code length 0;
  163278. * this lets us detect duplicate VAL entries here, and later
  163279. * allows emit_bits to detect any attempt to emit such symbols.
  163280. */
  163281. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163282. /* This is also a convenient place to check for out-of-range
  163283. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163284. * but only 0..15 for DC. (We could constrain them further
  163285. * based on data depth and mode, but this seems enough.)
  163286. */
  163287. maxsymbol = isDC ? 15 : 255;
  163288. for (p = 0; p < lastp; p++) {
  163289. i = htbl->huffval[p];
  163290. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163291. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163292. dtbl->ehufco[i] = huffcode[p];
  163293. dtbl->ehufsi[i] = huffsize[p];
  163294. }
  163295. }
  163296. /* Outputting bytes to the file */
  163297. /* Emit a byte, taking 'action' if must suspend. */
  163298. #define emit_byte(state,val,action) \
  163299. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163300. if (--(state)->free_in_buffer == 0) \
  163301. if (! dump_buffer(state)) \
  163302. { action; } }
  163303. LOCAL(boolean)
  163304. dump_buffer (working_state * state)
  163305. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163306. {
  163307. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163308. if (! (*dest->empty_output_buffer) (state->cinfo))
  163309. return FALSE;
  163310. /* After a successful buffer dump, must reset buffer pointers */
  163311. state->next_output_byte = dest->next_output_byte;
  163312. state->free_in_buffer = dest->free_in_buffer;
  163313. return TRUE;
  163314. }
  163315. /* Outputting bits to the file */
  163316. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163317. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163318. * in one call, and we never retain more than 7 bits in put_buffer
  163319. * between calls, so 24 bits are sufficient.
  163320. */
  163321. INLINE
  163322. LOCAL(boolean)
  163323. emit_bits (working_state * state, unsigned int code, int size)
  163324. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163325. {
  163326. /* This routine is heavily used, so it's worth coding tightly. */
  163327. register INT32 put_buffer = (INT32) code;
  163328. register int put_bits = state->cur.put_bits;
  163329. /* if size is 0, caller used an invalid Huffman table entry */
  163330. if (size == 0)
  163331. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163332. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163333. put_bits += size; /* new number of bits in buffer */
  163334. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163335. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163336. while (put_bits >= 8) {
  163337. int c = (int) ((put_buffer >> 16) & 0xFF);
  163338. emit_byte(state, c, return FALSE);
  163339. if (c == 0xFF) { /* need to stuff a zero byte? */
  163340. emit_byte(state, 0, return FALSE);
  163341. }
  163342. put_buffer <<= 8;
  163343. put_bits -= 8;
  163344. }
  163345. state->cur.put_buffer = put_buffer; /* update state variables */
  163346. state->cur.put_bits = put_bits;
  163347. return TRUE;
  163348. }
  163349. LOCAL(boolean)
  163350. flush_bits (working_state * state)
  163351. {
  163352. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163353. return FALSE;
  163354. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163355. state->cur.put_bits = 0;
  163356. return TRUE;
  163357. }
  163358. /* Encode a single block's worth of coefficients */
  163359. LOCAL(boolean)
  163360. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163361. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163362. {
  163363. register int temp, temp2;
  163364. register int nbits;
  163365. register int k, r, i;
  163366. /* Encode the DC coefficient difference per section F.1.2.1 */
  163367. temp = temp2 = block[0] - last_dc_val;
  163368. if (temp < 0) {
  163369. temp = -temp; /* temp is abs value of input */
  163370. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163371. /* This code assumes we are on a two's complement machine */
  163372. temp2--;
  163373. }
  163374. /* Find the number of bits needed for the magnitude of the coefficient */
  163375. nbits = 0;
  163376. while (temp) {
  163377. nbits++;
  163378. temp >>= 1;
  163379. }
  163380. /* Check for out-of-range coefficient values.
  163381. * Since we're encoding a difference, the range limit is twice as much.
  163382. */
  163383. if (nbits > MAX_COEF_BITS+1)
  163384. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163385. /* Emit the Huffman-coded symbol for the number of bits */
  163386. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163387. return FALSE;
  163388. /* Emit that number of bits of the value, if positive, */
  163389. /* or the complement of its magnitude, if negative. */
  163390. if (nbits) /* emit_bits rejects calls with size 0 */
  163391. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163392. return FALSE;
  163393. /* Encode the AC coefficients per section F.1.2.2 */
  163394. r = 0; /* r = run length of zeros */
  163395. for (k = 1; k < DCTSIZE2; k++) {
  163396. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163397. r++;
  163398. } else {
  163399. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163400. while (r > 15) {
  163401. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163402. return FALSE;
  163403. r -= 16;
  163404. }
  163405. temp2 = temp;
  163406. if (temp < 0) {
  163407. temp = -temp; /* temp is abs value of input */
  163408. /* This code assumes we are on a two's complement machine */
  163409. temp2--;
  163410. }
  163411. /* Find the number of bits needed for the magnitude of the coefficient */
  163412. nbits = 1; /* there must be at least one 1 bit */
  163413. while ((temp >>= 1))
  163414. nbits++;
  163415. /* Check for out-of-range coefficient values */
  163416. if (nbits > MAX_COEF_BITS)
  163417. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163418. /* Emit Huffman symbol for run length / number of bits */
  163419. i = (r << 4) + nbits;
  163420. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163421. return FALSE;
  163422. /* Emit that number of bits of the value, if positive, */
  163423. /* or the complement of its magnitude, if negative. */
  163424. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163425. return FALSE;
  163426. r = 0;
  163427. }
  163428. }
  163429. /* If the last coef(s) were zero, emit an end-of-block code */
  163430. if (r > 0)
  163431. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163432. return FALSE;
  163433. return TRUE;
  163434. }
  163435. /*
  163436. * Emit a restart marker & resynchronize predictions.
  163437. */
  163438. LOCAL(boolean)
  163439. emit_restart (working_state * state, int restart_num)
  163440. {
  163441. int ci;
  163442. if (! flush_bits(state))
  163443. return FALSE;
  163444. emit_byte(state, 0xFF, return FALSE);
  163445. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163446. /* Re-initialize DC predictions to 0 */
  163447. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163448. state->cur.last_dc_val[ci] = 0;
  163449. /* The restart counter is not updated until we successfully write the MCU. */
  163450. return TRUE;
  163451. }
  163452. /*
  163453. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163454. */
  163455. METHODDEF(boolean)
  163456. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163457. {
  163458. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163459. working_state state;
  163460. int blkn, ci;
  163461. jpeg_component_info * compptr;
  163462. /* Load up working state */
  163463. state.next_output_byte = cinfo->dest->next_output_byte;
  163464. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163465. ASSIGN_STATE(state.cur, entropy->saved);
  163466. state.cinfo = cinfo;
  163467. /* Emit restart marker if needed */
  163468. if (cinfo->restart_interval) {
  163469. if (entropy->restarts_to_go == 0)
  163470. if (! emit_restart(&state, entropy->next_restart_num))
  163471. return FALSE;
  163472. }
  163473. /* Encode the MCU data blocks */
  163474. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163475. ci = cinfo->MCU_membership[blkn];
  163476. compptr = cinfo->cur_comp_info[ci];
  163477. if (! encode_one_block(&state,
  163478. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163479. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163480. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163481. return FALSE;
  163482. /* Update last_dc_val */
  163483. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163484. }
  163485. /* Completed MCU, so update state */
  163486. cinfo->dest->next_output_byte = state.next_output_byte;
  163487. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163488. ASSIGN_STATE(entropy->saved, state.cur);
  163489. /* Update restart-interval state too */
  163490. if (cinfo->restart_interval) {
  163491. if (entropy->restarts_to_go == 0) {
  163492. entropy->restarts_to_go = cinfo->restart_interval;
  163493. entropy->next_restart_num++;
  163494. entropy->next_restart_num &= 7;
  163495. }
  163496. entropy->restarts_to_go--;
  163497. }
  163498. return TRUE;
  163499. }
  163500. /*
  163501. * Finish up at the end of a Huffman-compressed scan.
  163502. */
  163503. METHODDEF(void)
  163504. finish_pass_huff (j_compress_ptr cinfo)
  163505. {
  163506. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163507. working_state state;
  163508. /* Load up working state ... flush_bits needs it */
  163509. state.next_output_byte = cinfo->dest->next_output_byte;
  163510. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163511. ASSIGN_STATE(state.cur, entropy->saved);
  163512. state.cinfo = cinfo;
  163513. /* Flush out the last data */
  163514. if (! flush_bits(&state))
  163515. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163516. /* Update state */
  163517. cinfo->dest->next_output_byte = state.next_output_byte;
  163518. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163519. ASSIGN_STATE(entropy->saved, state.cur);
  163520. }
  163521. /*
  163522. * Huffman coding optimization.
  163523. *
  163524. * We first scan the supplied data and count the number of uses of each symbol
  163525. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163526. * Then we build a Huffman coding tree for the observed counts.
  163527. * Symbols which are not needed at all for the particular image are not
  163528. * assigned any code, which saves space in the DHT marker as well as in
  163529. * the compressed data.
  163530. */
  163531. #ifdef ENTROPY_OPT_SUPPORTED
  163532. /* Process a single block's worth of coefficients */
  163533. LOCAL(void)
  163534. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163535. long dc_counts[], long ac_counts[])
  163536. {
  163537. register int temp;
  163538. register int nbits;
  163539. register int k, r;
  163540. /* Encode the DC coefficient difference per section F.1.2.1 */
  163541. temp = block[0] - last_dc_val;
  163542. if (temp < 0)
  163543. temp = -temp;
  163544. /* Find the number of bits needed for the magnitude of the coefficient */
  163545. nbits = 0;
  163546. while (temp) {
  163547. nbits++;
  163548. temp >>= 1;
  163549. }
  163550. /* Check for out-of-range coefficient values.
  163551. * Since we're encoding a difference, the range limit is twice as much.
  163552. */
  163553. if (nbits > MAX_COEF_BITS+1)
  163554. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163555. /* Count the Huffman symbol for the number of bits */
  163556. dc_counts[nbits]++;
  163557. /* Encode the AC coefficients per section F.1.2.2 */
  163558. r = 0; /* r = run length of zeros */
  163559. for (k = 1; k < DCTSIZE2; k++) {
  163560. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163561. r++;
  163562. } else {
  163563. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163564. while (r > 15) {
  163565. ac_counts[0xF0]++;
  163566. r -= 16;
  163567. }
  163568. /* Find the number of bits needed for the magnitude of the coefficient */
  163569. if (temp < 0)
  163570. temp = -temp;
  163571. /* Find the number of bits needed for the magnitude of the coefficient */
  163572. nbits = 1; /* there must be at least one 1 bit */
  163573. while ((temp >>= 1))
  163574. nbits++;
  163575. /* Check for out-of-range coefficient values */
  163576. if (nbits > MAX_COEF_BITS)
  163577. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163578. /* Count Huffman symbol for run length / number of bits */
  163579. ac_counts[(r << 4) + nbits]++;
  163580. r = 0;
  163581. }
  163582. }
  163583. /* If the last coef(s) were zero, emit an end-of-block code */
  163584. if (r > 0)
  163585. ac_counts[0]++;
  163586. }
  163587. /*
  163588. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163589. * No data is actually output, so no suspension return is possible.
  163590. */
  163591. METHODDEF(boolean)
  163592. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163593. {
  163594. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163595. int blkn, ci;
  163596. jpeg_component_info * compptr;
  163597. /* Take care of restart intervals if needed */
  163598. if (cinfo->restart_interval) {
  163599. if (entropy->restarts_to_go == 0) {
  163600. /* Re-initialize DC predictions to 0 */
  163601. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163602. entropy->saved.last_dc_val[ci] = 0;
  163603. /* Update restart state */
  163604. entropy->restarts_to_go = cinfo->restart_interval;
  163605. }
  163606. entropy->restarts_to_go--;
  163607. }
  163608. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163609. ci = cinfo->MCU_membership[blkn];
  163610. compptr = cinfo->cur_comp_info[ci];
  163611. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163612. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163613. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163614. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163615. }
  163616. return TRUE;
  163617. }
  163618. /*
  163619. * Generate the best Huffman code table for the given counts, fill htbl.
  163620. * Note this is also used by jcphuff.c.
  163621. *
  163622. * The JPEG standard requires that no symbol be assigned a codeword of all
  163623. * one bits (so that padding bits added at the end of a compressed segment
  163624. * can't look like a valid code). Because of the canonical ordering of
  163625. * codewords, this just means that there must be an unused slot in the
  163626. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163627. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163628. * with count 1. In theory that's not optimal; giving it count zero but
  163629. * including it in the symbol set anyway should give a better Huffman code.
  163630. * But the theoretically better code actually seems to come out worse in
  163631. * practice, because it produces more all-ones bytes (which incur stuffed
  163632. * zero bytes in the final file). In any case the difference is tiny.
  163633. *
  163634. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163635. * If some symbols have a very small but nonzero probability, the Huffman tree
  163636. * must be adjusted to meet the code length restriction. We currently use
  163637. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163638. * optimal; it may not choose the best possible limited-length code. But
  163639. * typically only very-low-frequency symbols will be given less-than-optimal
  163640. * lengths, so the code is almost optimal. Experimental comparisons against
  163641. * an optimal limited-length-code algorithm indicate that the difference is
  163642. * microscopic --- usually less than a hundredth of a percent of total size.
  163643. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163644. */
  163645. GLOBAL(void)
  163646. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163647. {
  163648. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163649. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163650. int codesize[257]; /* codesize[k] = code length of symbol k */
  163651. int others[257]; /* next symbol in current branch of tree */
  163652. int c1, c2;
  163653. int p, i, j;
  163654. long v;
  163655. /* This algorithm is explained in section K.2 of the JPEG standard */
  163656. MEMZERO(bits, SIZEOF(bits));
  163657. MEMZERO(codesize, SIZEOF(codesize));
  163658. for (i = 0; i < 257; i++)
  163659. others[i] = -1; /* init links to empty */
  163660. freq[256] = 1; /* make sure 256 has a nonzero count */
  163661. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163662. * that no real symbol is given code-value of all ones, because 256
  163663. * will be placed last in the largest codeword category.
  163664. */
  163665. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163666. for (;;) {
  163667. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163668. /* In case of ties, take the larger symbol number */
  163669. c1 = -1;
  163670. v = 1000000000L;
  163671. for (i = 0; i <= 256; i++) {
  163672. if (freq[i] && freq[i] <= v) {
  163673. v = freq[i];
  163674. c1 = i;
  163675. }
  163676. }
  163677. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163678. /* In case of ties, take the larger symbol number */
  163679. c2 = -1;
  163680. v = 1000000000L;
  163681. for (i = 0; i <= 256; i++) {
  163682. if (freq[i] && freq[i] <= v && i != c1) {
  163683. v = freq[i];
  163684. c2 = i;
  163685. }
  163686. }
  163687. /* Done if we've merged everything into one frequency */
  163688. if (c2 < 0)
  163689. break;
  163690. /* Else merge the two counts/trees */
  163691. freq[c1] += freq[c2];
  163692. freq[c2] = 0;
  163693. /* Increment the codesize of everything in c1's tree branch */
  163694. codesize[c1]++;
  163695. while (others[c1] >= 0) {
  163696. c1 = others[c1];
  163697. codesize[c1]++;
  163698. }
  163699. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163700. /* Increment the codesize of everything in c2's tree branch */
  163701. codesize[c2]++;
  163702. while (others[c2] >= 0) {
  163703. c2 = others[c2];
  163704. codesize[c2]++;
  163705. }
  163706. }
  163707. /* Now count the number of symbols of each code length */
  163708. for (i = 0; i <= 256; i++) {
  163709. if (codesize[i]) {
  163710. /* The JPEG standard seems to think that this can't happen, */
  163711. /* but I'm paranoid... */
  163712. if (codesize[i] > MAX_CLEN)
  163713. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163714. bits[codesize[i]]++;
  163715. }
  163716. }
  163717. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163718. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163719. * Here is what the JPEG spec says about how this next bit works:
  163720. * Since symbols are paired for the longest Huffman code, the symbols are
  163721. * removed from this length category two at a time. The prefix for the pair
  163722. * (which is one bit shorter) is allocated to one of the pair; then,
  163723. * skipping the BITS entry for that prefix length, a code word from the next
  163724. * shortest nonzero BITS entry is converted into a prefix for two code words
  163725. * one bit longer.
  163726. */
  163727. for (i = MAX_CLEN; i > 16; i--) {
  163728. while (bits[i] > 0) {
  163729. j = i - 2; /* find length of new prefix to be used */
  163730. while (bits[j] == 0)
  163731. j--;
  163732. bits[i] -= 2; /* remove two symbols */
  163733. bits[i-1]++; /* one goes in this length */
  163734. bits[j+1] += 2; /* two new symbols in this length */
  163735. bits[j]--; /* symbol of this length is now a prefix */
  163736. }
  163737. }
  163738. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163739. while (bits[i] == 0) /* find largest codelength still in use */
  163740. i--;
  163741. bits[i]--;
  163742. /* Return final symbol counts (only for lengths 0..16) */
  163743. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163744. /* Return a list of the symbols sorted by code length */
  163745. /* It's not real clear to me why we don't need to consider the codelength
  163746. * changes made above, but the JPEG spec seems to think this works.
  163747. */
  163748. p = 0;
  163749. for (i = 1; i <= MAX_CLEN; i++) {
  163750. for (j = 0; j <= 255; j++) {
  163751. if (codesize[j] == i) {
  163752. htbl->huffval[p] = (UINT8) j;
  163753. p++;
  163754. }
  163755. }
  163756. }
  163757. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163758. htbl->sent_table = FALSE;
  163759. }
  163760. /*
  163761. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163762. */
  163763. METHODDEF(void)
  163764. finish_pass_gather (j_compress_ptr cinfo)
  163765. {
  163766. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163767. int ci, dctbl, actbl;
  163768. jpeg_component_info * compptr;
  163769. JHUFF_TBL **htblptr;
  163770. boolean did_dc[NUM_HUFF_TBLS];
  163771. boolean did_ac[NUM_HUFF_TBLS];
  163772. /* It's important not to apply jpeg_gen_optimal_table more than once
  163773. * per table, because it clobbers the input frequency counts!
  163774. */
  163775. MEMZERO(did_dc, SIZEOF(did_dc));
  163776. MEMZERO(did_ac, SIZEOF(did_ac));
  163777. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163778. compptr = cinfo->cur_comp_info[ci];
  163779. dctbl = compptr->dc_tbl_no;
  163780. actbl = compptr->ac_tbl_no;
  163781. if (! did_dc[dctbl]) {
  163782. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163783. if (*htblptr == NULL)
  163784. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163785. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163786. did_dc[dctbl] = TRUE;
  163787. }
  163788. if (! did_ac[actbl]) {
  163789. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163790. if (*htblptr == NULL)
  163791. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163792. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163793. did_ac[actbl] = TRUE;
  163794. }
  163795. }
  163796. }
  163797. #endif /* ENTROPY_OPT_SUPPORTED */
  163798. /*
  163799. * Module initialization routine for Huffman entropy encoding.
  163800. */
  163801. GLOBAL(void)
  163802. jinit_huff_encoder (j_compress_ptr cinfo)
  163803. {
  163804. huff_entropy_ptr entropy;
  163805. int i;
  163806. entropy = (huff_entropy_ptr)
  163807. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163808. SIZEOF(huff_entropy_encoder));
  163809. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163810. entropy->pub.start_pass = start_pass_huff;
  163811. /* Mark tables unallocated */
  163812. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163813. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163814. #ifdef ENTROPY_OPT_SUPPORTED
  163815. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163816. #endif
  163817. }
  163818. }
  163819. /*** End of inlined file: jchuff.c ***/
  163820. #undef emit_byte
  163821. /*** Start of inlined file: jcinit.c ***/
  163822. #define JPEG_INTERNALS
  163823. /*
  163824. * Master selection of compression modules.
  163825. * This is done once at the start of processing an image. We determine
  163826. * which modules will be used and give them appropriate initialization calls.
  163827. */
  163828. GLOBAL(void)
  163829. jinit_compress_master (j_compress_ptr cinfo)
  163830. {
  163831. /* Initialize master control (includes parameter checking/processing) */
  163832. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163833. /* Preprocessing */
  163834. if (! cinfo->raw_data_in) {
  163835. jinit_color_converter(cinfo);
  163836. jinit_downsampler(cinfo);
  163837. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163838. }
  163839. /* Forward DCT */
  163840. jinit_forward_dct(cinfo);
  163841. /* Entropy encoding: either Huffman or arithmetic coding. */
  163842. if (cinfo->arith_code) {
  163843. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163844. } else {
  163845. if (cinfo->progressive_mode) {
  163846. #ifdef C_PROGRESSIVE_SUPPORTED
  163847. jinit_phuff_encoder(cinfo);
  163848. #else
  163849. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163850. #endif
  163851. } else
  163852. jinit_huff_encoder(cinfo);
  163853. }
  163854. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163855. jinit_c_coef_controller(cinfo,
  163856. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163857. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163858. jinit_marker_writer(cinfo);
  163859. /* We can now tell the memory manager to allocate virtual arrays. */
  163860. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163861. /* Write the datastream header (SOI) immediately.
  163862. * Frame and scan headers are postponed till later.
  163863. * This lets application insert special markers after the SOI.
  163864. */
  163865. (*cinfo->marker->write_file_header) (cinfo);
  163866. }
  163867. /*** End of inlined file: jcinit.c ***/
  163868. /*** Start of inlined file: jcmainct.c ***/
  163869. #define JPEG_INTERNALS
  163870. /* Note: currently, there is no operating mode in which a full-image buffer
  163871. * is needed at this step. If there were, that mode could not be used with
  163872. * "raw data" input, since this module is bypassed in that case. However,
  163873. * we've left the code here for possible use in special applications.
  163874. */
  163875. #undef FULL_MAIN_BUFFER_SUPPORTED
  163876. /* Private buffer controller object */
  163877. typedef struct {
  163878. struct jpeg_c_main_controller pub; /* public fields */
  163879. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163880. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163881. boolean suspended; /* remember if we suspended output */
  163882. J_BUF_MODE pass_mode; /* current operating mode */
  163883. /* If using just a strip buffer, this points to the entire set of buffers
  163884. * (we allocate one for each component). In the full-image case, this
  163885. * points to the currently accessible strips of the virtual arrays.
  163886. */
  163887. JSAMPARRAY buffer[MAX_COMPONENTS];
  163888. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163889. /* If using full-image storage, this array holds pointers to virtual-array
  163890. * control blocks for each component. Unused if not full-image storage.
  163891. */
  163892. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163893. #endif
  163894. } my_main_controller;
  163895. typedef my_main_controller * my_main_ptr;
  163896. /* Forward declarations */
  163897. METHODDEF(void) process_data_simple_main
  163898. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163899. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163900. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163901. METHODDEF(void) process_data_buffer_main
  163902. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163903. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163904. #endif
  163905. /*
  163906. * Initialize for a processing pass.
  163907. */
  163908. METHODDEF(void)
  163909. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163910. {
  163911. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163912. /* Do nothing in raw-data mode. */
  163913. if (cinfo->raw_data_in)
  163914. return;
  163915. main_->cur_iMCU_row = 0; /* initialize counters */
  163916. main_->rowgroup_ctr = 0;
  163917. main_->suspended = FALSE;
  163918. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163919. switch (pass_mode) {
  163920. case JBUF_PASS_THRU:
  163921. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163922. if (main_->whole_image[0] != NULL)
  163923. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163924. #endif
  163925. main_->pub.process_data = process_data_simple_main;
  163926. break;
  163927. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163928. case JBUF_SAVE_SOURCE:
  163929. case JBUF_CRANK_DEST:
  163930. case JBUF_SAVE_AND_PASS:
  163931. if (main_->whole_image[0] == NULL)
  163932. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163933. main_->pub.process_data = process_data_buffer_main;
  163934. break;
  163935. #endif
  163936. default:
  163937. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163938. break;
  163939. }
  163940. }
  163941. /*
  163942. * Process some data.
  163943. * This routine handles the simple pass-through mode,
  163944. * where we have only a strip buffer.
  163945. */
  163946. METHODDEF(void)
  163947. process_data_simple_main (j_compress_ptr cinfo,
  163948. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163949. JDIMENSION in_rows_avail)
  163950. {
  163951. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163952. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163953. /* Read input data if we haven't filled the main buffer yet */
  163954. if (main_->rowgroup_ctr < DCTSIZE)
  163955. (*cinfo->prep->pre_process_data) (cinfo,
  163956. input_buf, in_row_ctr, in_rows_avail,
  163957. main_->buffer, &main_->rowgroup_ctr,
  163958. (JDIMENSION) DCTSIZE);
  163959. /* If we don't have a full iMCU row buffered, return to application for
  163960. * more data. Note that preprocessor will always pad to fill the iMCU row
  163961. * at the bottom of the image.
  163962. */
  163963. if (main_->rowgroup_ctr != DCTSIZE)
  163964. return;
  163965. /* Send the completed row to the compressor */
  163966. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163967. /* If compressor did not consume the whole row, then we must need to
  163968. * suspend processing and return to the application. In this situation
  163969. * we pretend we didn't yet consume the last input row; otherwise, if
  163970. * it happened to be the last row of the image, the application would
  163971. * think we were done.
  163972. */
  163973. if (! main_->suspended) {
  163974. (*in_row_ctr)--;
  163975. main_->suspended = TRUE;
  163976. }
  163977. return;
  163978. }
  163979. /* We did finish the row. Undo our little suspension hack if a previous
  163980. * call suspended; then mark the main buffer empty.
  163981. */
  163982. if (main_->suspended) {
  163983. (*in_row_ctr)++;
  163984. main_->suspended = FALSE;
  163985. }
  163986. main_->rowgroup_ctr = 0;
  163987. main_->cur_iMCU_row++;
  163988. }
  163989. }
  163990. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163991. /*
  163992. * Process some data.
  163993. * This routine handles all of the modes that use a full-size buffer.
  163994. */
  163995. METHODDEF(void)
  163996. process_data_buffer_main (j_compress_ptr cinfo,
  163997. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163998. JDIMENSION in_rows_avail)
  163999. {
  164000. my_main_ptr main = (my_main_ptr) cinfo->main;
  164001. int ci;
  164002. jpeg_component_info *compptr;
  164003. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164004. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164005. /* Realign the virtual buffers if at the start of an iMCU row. */
  164006. if (main->rowgroup_ctr == 0) {
  164007. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164008. ci++, compptr++) {
  164009. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164010. ((j_common_ptr) cinfo, main->whole_image[ci],
  164011. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164012. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164013. }
  164014. /* In a read pass, pretend we just read some source data. */
  164015. if (! writing) {
  164016. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164017. main->rowgroup_ctr = DCTSIZE;
  164018. }
  164019. }
  164020. /* If a write pass, read input data until the current iMCU row is full. */
  164021. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164022. if (writing) {
  164023. (*cinfo->prep->pre_process_data) (cinfo,
  164024. input_buf, in_row_ctr, in_rows_avail,
  164025. main->buffer, &main->rowgroup_ctr,
  164026. (JDIMENSION) DCTSIZE);
  164027. /* Return to application if we need more data to fill the iMCU row. */
  164028. if (main->rowgroup_ctr < DCTSIZE)
  164029. return;
  164030. }
  164031. /* Emit data, unless this is a sink-only pass. */
  164032. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164033. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164034. /* If compressor did not consume the whole row, then we must need to
  164035. * suspend processing and return to the application. In this situation
  164036. * we pretend we didn't yet consume the last input row; otherwise, if
  164037. * it happened to be the last row of the image, the application would
  164038. * think we were done.
  164039. */
  164040. if (! main->suspended) {
  164041. (*in_row_ctr)--;
  164042. main->suspended = TRUE;
  164043. }
  164044. return;
  164045. }
  164046. /* We did finish the row. Undo our little suspension hack if a previous
  164047. * call suspended; then mark the main buffer empty.
  164048. */
  164049. if (main->suspended) {
  164050. (*in_row_ctr)++;
  164051. main->suspended = FALSE;
  164052. }
  164053. }
  164054. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164055. main->rowgroup_ctr = 0;
  164056. main->cur_iMCU_row++;
  164057. }
  164058. }
  164059. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164060. /*
  164061. * Initialize main buffer controller.
  164062. */
  164063. GLOBAL(void)
  164064. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164065. {
  164066. my_main_ptr main_;
  164067. int ci;
  164068. jpeg_component_info *compptr;
  164069. main_ = (my_main_ptr)
  164070. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164071. SIZEOF(my_main_controller));
  164072. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164073. main_->pub.start_pass = start_pass_main;
  164074. /* We don't need to create a buffer in raw-data mode. */
  164075. if (cinfo->raw_data_in)
  164076. return;
  164077. /* Create the buffer. It holds downsampled data, so each component
  164078. * may be of a different size.
  164079. */
  164080. if (need_full_buffer) {
  164081. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164082. /* Allocate a full-image virtual array for each component */
  164083. /* Note we pad the bottom to a multiple of the iMCU height */
  164084. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164085. ci++, compptr++) {
  164086. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164087. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164088. compptr->width_in_blocks * DCTSIZE,
  164089. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164090. (long) compptr->v_samp_factor) * DCTSIZE,
  164091. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164092. }
  164093. #else
  164094. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164095. #endif
  164096. } else {
  164097. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164098. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164099. #endif
  164100. /* Allocate a strip buffer for each component */
  164101. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164102. ci++, compptr++) {
  164103. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164104. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164105. compptr->width_in_blocks * DCTSIZE,
  164106. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164107. }
  164108. }
  164109. }
  164110. /*** End of inlined file: jcmainct.c ***/
  164111. /*** Start of inlined file: jcmarker.c ***/
  164112. #define JPEG_INTERNALS
  164113. /* Private state */
  164114. typedef struct {
  164115. struct jpeg_marker_writer pub; /* public fields */
  164116. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164117. } my_marker_writer;
  164118. typedef my_marker_writer * my_marker_ptr;
  164119. /*
  164120. * Basic output routines.
  164121. *
  164122. * Note that we do not support suspension while writing a marker.
  164123. * Therefore, an application using suspension must ensure that there is
  164124. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164125. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164126. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164127. * modes are not supported at all with suspension, so those two are the only
  164128. * points where markers will be written.
  164129. */
  164130. LOCAL(void)
  164131. emit_byte (j_compress_ptr cinfo, int val)
  164132. /* Emit a byte */
  164133. {
  164134. struct jpeg_destination_mgr * dest = cinfo->dest;
  164135. *(dest->next_output_byte)++ = (JOCTET) val;
  164136. if (--dest->free_in_buffer == 0) {
  164137. if (! (*dest->empty_output_buffer) (cinfo))
  164138. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164139. }
  164140. }
  164141. LOCAL(void)
  164142. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164143. /* Emit a marker code */
  164144. {
  164145. emit_byte(cinfo, 0xFF);
  164146. emit_byte(cinfo, (int) mark);
  164147. }
  164148. LOCAL(void)
  164149. emit_2bytes (j_compress_ptr cinfo, int value)
  164150. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164151. {
  164152. emit_byte(cinfo, (value >> 8) & 0xFF);
  164153. emit_byte(cinfo, value & 0xFF);
  164154. }
  164155. /*
  164156. * Routines to write specific marker types.
  164157. */
  164158. LOCAL(int)
  164159. emit_dqt (j_compress_ptr cinfo, int index)
  164160. /* Emit a DQT marker */
  164161. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164162. {
  164163. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164164. int prec;
  164165. int i;
  164166. if (qtbl == NULL)
  164167. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164168. prec = 0;
  164169. for (i = 0; i < DCTSIZE2; i++) {
  164170. if (qtbl->quantval[i] > 255)
  164171. prec = 1;
  164172. }
  164173. if (! qtbl->sent_table) {
  164174. emit_marker(cinfo, M_DQT);
  164175. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164176. emit_byte(cinfo, index + (prec<<4));
  164177. for (i = 0; i < DCTSIZE2; i++) {
  164178. /* The table entries must be emitted in zigzag order. */
  164179. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164180. if (prec)
  164181. emit_byte(cinfo, (int) (qval >> 8));
  164182. emit_byte(cinfo, (int) (qval & 0xFF));
  164183. }
  164184. qtbl->sent_table = TRUE;
  164185. }
  164186. return prec;
  164187. }
  164188. LOCAL(void)
  164189. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164190. /* Emit a DHT marker */
  164191. {
  164192. JHUFF_TBL * htbl;
  164193. int length, i;
  164194. if (is_ac) {
  164195. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164196. index += 0x10; /* output index has AC bit set */
  164197. } else {
  164198. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164199. }
  164200. if (htbl == NULL)
  164201. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164202. if (! htbl->sent_table) {
  164203. emit_marker(cinfo, M_DHT);
  164204. length = 0;
  164205. for (i = 1; i <= 16; i++)
  164206. length += htbl->bits[i];
  164207. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164208. emit_byte(cinfo, index);
  164209. for (i = 1; i <= 16; i++)
  164210. emit_byte(cinfo, htbl->bits[i]);
  164211. for (i = 0; i < length; i++)
  164212. emit_byte(cinfo, htbl->huffval[i]);
  164213. htbl->sent_table = TRUE;
  164214. }
  164215. }
  164216. LOCAL(void)
  164217. emit_dac (j_compress_ptr)
  164218. /* Emit a DAC marker */
  164219. /* Since the useful info is so small, we want to emit all the tables in */
  164220. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164221. {
  164222. #ifdef C_ARITH_CODING_SUPPORTED
  164223. char dc_in_use[NUM_ARITH_TBLS];
  164224. char ac_in_use[NUM_ARITH_TBLS];
  164225. int length, i;
  164226. jpeg_component_info *compptr;
  164227. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164228. dc_in_use[i] = ac_in_use[i] = 0;
  164229. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164230. compptr = cinfo->cur_comp_info[i];
  164231. dc_in_use[compptr->dc_tbl_no] = 1;
  164232. ac_in_use[compptr->ac_tbl_no] = 1;
  164233. }
  164234. length = 0;
  164235. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164236. length += dc_in_use[i] + ac_in_use[i];
  164237. emit_marker(cinfo, M_DAC);
  164238. emit_2bytes(cinfo, length*2 + 2);
  164239. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164240. if (dc_in_use[i]) {
  164241. emit_byte(cinfo, i);
  164242. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164243. }
  164244. if (ac_in_use[i]) {
  164245. emit_byte(cinfo, i + 0x10);
  164246. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164247. }
  164248. }
  164249. #endif /* C_ARITH_CODING_SUPPORTED */
  164250. }
  164251. LOCAL(void)
  164252. emit_dri (j_compress_ptr cinfo)
  164253. /* Emit a DRI marker */
  164254. {
  164255. emit_marker(cinfo, M_DRI);
  164256. emit_2bytes(cinfo, 4); /* fixed length */
  164257. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164258. }
  164259. LOCAL(void)
  164260. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164261. /* Emit a SOF marker */
  164262. {
  164263. int ci;
  164264. jpeg_component_info *compptr;
  164265. emit_marker(cinfo, code);
  164266. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164267. /* Make sure image isn't bigger than SOF field can handle */
  164268. if ((long) cinfo->image_height > 65535L ||
  164269. (long) cinfo->image_width > 65535L)
  164270. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164271. emit_byte(cinfo, cinfo->data_precision);
  164272. emit_2bytes(cinfo, (int) cinfo->image_height);
  164273. emit_2bytes(cinfo, (int) cinfo->image_width);
  164274. emit_byte(cinfo, cinfo->num_components);
  164275. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164276. ci++, compptr++) {
  164277. emit_byte(cinfo, compptr->component_id);
  164278. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164279. emit_byte(cinfo, compptr->quant_tbl_no);
  164280. }
  164281. }
  164282. LOCAL(void)
  164283. emit_sos (j_compress_ptr cinfo)
  164284. /* Emit a SOS marker */
  164285. {
  164286. int i, td, ta;
  164287. jpeg_component_info *compptr;
  164288. emit_marker(cinfo, M_SOS);
  164289. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164290. emit_byte(cinfo, cinfo->comps_in_scan);
  164291. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164292. compptr = cinfo->cur_comp_info[i];
  164293. emit_byte(cinfo, compptr->component_id);
  164294. td = compptr->dc_tbl_no;
  164295. ta = compptr->ac_tbl_no;
  164296. if (cinfo->progressive_mode) {
  164297. /* Progressive mode: only DC or only AC tables are used in one scan;
  164298. * furthermore, Huffman coding of DC refinement uses no table at all.
  164299. * We emit 0 for unused field(s); this is recommended by the P&M text
  164300. * but does not seem to be specified in the standard.
  164301. */
  164302. if (cinfo->Ss == 0) {
  164303. ta = 0; /* DC scan */
  164304. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164305. td = 0; /* no DC table either */
  164306. } else {
  164307. td = 0; /* AC scan */
  164308. }
  164309. }
  164310. emit_byte(cinfo, (td << 4) + ta);
  164311. }
  164312. emit_byte(cinfo, cinfo->Ss);
  164313. emit_byte(cinfo, cinfo->Se);
  164314. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164315. }
  164316. LOCAL(void)
  164317. emit_jfif_app0 (j_compress_ptr cinfo)
  164318. /* Emit a JFIF-compliant APP0 marker */
  164319. {
  164320. /*
  164321. * Length of APP0 block (2 bytes)
  164322. * Block ID (4 bytes - ASCII "JFIF")
  164323. * Zero byte (1 byte to terminate the ID string)
  164324. * Version Major, Minor (2 bytes - major first)
  164325. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164326. * Xdpu (2 bytes - dots per unit horizontal)
  164327. * Ydpu (2 bytes - dots per unit vertical)
  164328. * Thumbnail X size (1 byte)
  164329. * Thumbnail Y size (1 byte)
  164330. */
  164331. emit_marker(cinfo, M_APP0);
  164332. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164333. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164334. emit_byte(cinfo, 0x46);
  164335. emit_byte(cinfo, 0x49);
  164336. emit_byte(cinfo, 0x46);
  164337. emit_byte(cinfo, 0);
  164338. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164339. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164340. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164341. emit_2bytes(cinfo, (int) cinfo->X_density);
  164342. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164343. emit_byte(cinfo, 0); /* No thumbnail image */
  164344. emit_byte(cinfo, 0);
  164345. }
  164346. LOCAL(void)
  164347. emit_adobe_app14 (j_compress_ptr cinfo)
  164348. /* Emit an Adobe APP14 marker */
  164349. {
  164350. /*
  164351. * Length of APP14 block (2 bytes)
  164352. * Block ID (5 bytes - ASCII "Adobe")
  164353. * Version Number (2 bytes - currently 100)
  164354. * Flags0 (2 bytes - currently 0)
  164355. * Flags1 (2 bytes - currently 0)
  164356. * Color transform (1 byte)
  164357. *
  164358. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164359. * now in circulation seem to use Version = 100, so that's what we write.
  164360. *
  164361. * We write the color transform byte as 1 if the JPEG color space is
  164362. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164363. * whether the encoder performed a transformation, which is pretty useless.
  164364. */
  164365. emit_marker(cinfo, M_APP14);
  164366. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164367. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164368. emit_byte(cinfo, 0x64);
  164369. emit_byte(cinfo, 0x6F);
  164370. emit_byte(cinfo, 0x62);
  164371. emit_byte(cinfo, 0x65);
  164372. emit_2bytes(cinfo, 100); /* Version */
  164373. emit_2bytes(cinfo, 0); /* Flags0 */
  164374. emit_2bytes(cinfo, 0); /* Flags1 */
  164375. switch (cinfo->jpeg_color_space) {
  164376. case JCS_YCbCr:
  164377. emit_byte(cinfo, 1); /* Color transform = 1 */
  164378. break;
  164379. case JCS_YCCK:
  164380. emit_byte(cinfo, 2); /* Color transform = 2 */
  164381. break;
  164382. default:
  164383. emit_byte(cinfo, 0); /* Color transform = 0 */
  164384. break;
  164385. }
  164386. }
  164387. /*
  164388. * These routines allow writing an arbitrary marker with parameters.
  164389. * The only intended use is to emit COM or APPn markers after calling
  164390. * write_file_header and before calling write_frame_header.
  164391. * Other uses are not guaranteed to produce desirable results.
  164392. * Counting the parameter bytes properly is the caller's responsibility.
  164393. */
  164394. METHODDEF(void)
  164395. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164396. /* Emit an arbitrary marker header */
  164397. {
  164398. if (datalen > (unsigned int) 65533) /* safety check */
  164399. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164400. emit_marker(cinfo, (JPEG_MARKER) marker);
  164401. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164402. }
  164403. METHODDEF(void)
  164404. write_marker_byte (j_compress_ptr cinfo, int val)
  164405. /* Emit one byte of marker parameters following write_marker_header */
  164406. {
  164407. emit_byte(cinfo, val);
  164408. }
  164409. /*
  164410. * Write datastream header.
  164411. * This consists of an SOI and optional APPn markers.
  164412. * We recommend use of the JFIF marker, but not the Adobe marker,
  164413. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164414. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164415. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164416. * Note that an application can write additional header markers after
  164417. * jpeg_start_compress returns.
  164418. */
  164419. METHODDEF(void)
  164420. write_file_header (j_compress_ptr cinfo)
  164421. {
  164422. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164423. emit_marker(cinfo, M_SOI); /* first the SOI */
  164424. /* SOI is defined to reset restart interval to 0 */
  164425. marker->last_restart_interval = 0;
  164426. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164427. emit_jfif_app0(cinfo);
  164428. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164429. emit_adobe_app14(cinfo);
  164430. }
  164431. /*
  164432. * Write frame header.
  164433. * This consists of DQT and SOFn markers.
  164434. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164435. * This avoids compatibility problems with incorrect implementations that
  164436. * try to error-check the quant table numbers as soon as they see the SOF.
  164437. */
  164438. METHODDEF(void)
  164439. write_frame_header (j_compress_ptr cinfo)
  164440. {
  164441. int ci, prec;
  164442. boolean is_baseline;
  164443. jpeg_component_info *compptr;
  164444. /* Emit DQT for each quantization table.
  164445. * Note that emit_dqt() suppresses any duplicate tables.
  164446. */
  164447. prec = 0;
  164448. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164449. ci++, compptr++) {
  164450. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164451. }
  164452. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164453. /* Check for a non-baseline specification.
  164454. * Note we assume that Huffman table numbers won't be changed later.
  164455. */
  164456. if (cinfo->arith_code || cinfo->progressive_mode ||
  164457. cinfo->data_precision != 8) {
  164458. is_baseline = FALSE;
  164459. } else {
  164460. is_baseline = TRUE;
  164461. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164462. ci++, compptr++) {
  164463. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164464. is_baseline = FALSE;
  164465. }
  164466. if (prec && is_baseline) {
  164467. is_baseline = FALSE;
  164468. /* If it's baseline except for quantizer size, warn the user */
  164469. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164470. }
  164471. }
  164472. /* Emit the proper SOF marker */
  164473. if (cinfo->arith_code) {
  164474. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164475. } else {
  164476. if (cinfo->progressive_mode)
  164477. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164478. else if (is_baseline)
  164479. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164480. else
  164481. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164482. }
  164483. }
  164484. /*
  164485. * Write scan header.
  164486. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164487. * Compressed data will be written following the SOS.
  164488. */
  164489. METHODDEF(void)
  164490. write_scan_header (j_compress_ptr cinfo)
  164491. {
  164492. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164493. int i;
  164494. jpeg_component_info *compptr;
  164495. if (cinfo->arith_code) {
  164496. /* Emit arith conditioning info. We may have some duplication
  164497. * if the file has multiple scans, but it's so small it's hardly
  164498. * worth worrying about.
  164499. */
  164500. emit_dac(cinfo);
  164501. } else {
  164502. /* Emit Huffman tables.
  164503. * Note that emit_dht() suppresses any duplicate tables.
  164504. */
  164505. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164506. compptr = cinfo->cur_comp_info[i];
  164507. if (cinfo->progressive_mode) {
  164508. /* Progressive mode: only DC or only AC tables are used in one scan */
  164509. if (cinfo->Ss == 0) {
  164510. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164511. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164512. } else {
  164513. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164514. }
  164515. } else {
  164516. /* Sequential mode: need both DC and AC tables */
  164517. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164518. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164519. }
  164520. }
  164521. }
  164522. /* Emit DRI if required --- note that DRI value could change for each scan.
  164523. * We avoid wasting space with unnecessary DRIs, however.
  164524. */
  164525. if (cinfo->restart_interval != marker->last_restart_interval) {
  164526. emit_dri(cinfo);
  164527. marker->last_restart_interval = cinfo->restart_interval;
  164528. }
  164529. emit_sos(cinfo);
  164530. }
  164531. /*
  164532. * Write datastream trailer.
  164533. */
  164534. METHODDEF(void)
  164535. write_file_trailer (j_compress_ptr cinfo)
  164536. {
  164537. emit_marker(cinfo, M_EOI);
  164538. }
  164539. /*
  164540. * Write an abbreviated table-specification datastream.
  164541. * This consists of SOI, DQT and DHT tables, and EOI.
  164542. * Any table that is defined and not marked sent_table = TRUE will be
  164543. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164544. */
  164545. METHODDEF(void)
  164546. write_tables_only (j_compress_ptr cinfo)
  164547. {
  164548. int i;
  164549. emit_marker(cinfo, M_SOI);
  164550. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164551. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164552. (void) emit_dqt(cinfo, i);
  164553. }
  164554. if (! cinfo->arith_code) {
  164555. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164556. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164557. emit_dht(cinfo, i, FALSE);
  164558. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164559. emit_dht(cinfo, i, TRUE);
  164560. }
  164561. }
  164562. emit_marker(cinfo, M_EOI);
  164563. }
  164564. /*
  164565. * Initialize the marker writer module.
  164566. */
  164567. GLOBAL(void)
  164568. jinit_marker_writer (j_compress_ptr cinfo)
  164569. {
  164570. my_marker_ptr marker;
  164571. /* Create the subobject */
  164572. marker = (my_marker_ptr)
  164573. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164574. SIZEOF(my_marker_writer));
  164575. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164576. /* Initialize method pointers */
  164577. marker->pub.write_file_header = write_file_header;
  164578. marker->pub.write_frame_header = write_frame_header;
  164579. marker->pub.write_scan_header = write_scan_header;
  164580. marker->pub.write_file_trailer = write_file_trailer;
  164581. marker->pub.write_tables_only = write_tables_only;
  164582. marker->pub.write_marker_header = write_marker_header;
  164583. marker->pub.write_marker_byte = write_marker_byte;
  164584. /* Initialize private state */
  164585. marker->last_restart_interval = 0;
  164586. }
  164587. /*** End of inlined file: jcmarker.c ***/
  164588. /*** Start of inlined file: jcmaster.c ***/
  164589. #define JPEG_INTERNALS
  164590. /* Private state */
  164591. typedef enum {
  164592. main_pass, /* input data, also do first output step */
  164593. huff_opt_pass, /* Huffman code optimization pass */
  164594. output_pass /* data output pass */
  164595. } c_pass_type;
  164596. typedef struct {
  164597. struct jpeg_comp_master pub; /* public fields */
  164598. c_pass_type pass_type; /* the type of the current pass */
  164599. int pass_number; /* # of passes completed */
  164600. int total_passes; /* total # of passes needed */
  164601. int scan_number; /* current index in scan_info[] */
  164602. } my_comp_master;
  164603. typedef my_comp_master * my_master_ptr;
  164604. /*
  164605. * Support routines that do various essential calculations.
  164606. */
  164607. LOCAL(void)
  164608. initial_setup (j_compress_ptr cinfo)
  164609. /* Do computations that are needed before master selection phase */
  164610. {
  164611. int ci;
  164612. jpeg_component_info *compptr;
  164613. long samplesperrow;
  164614. JDIMENSION jd_samplesperrow;
  164615. /* Sanity check on image dimensions */
  164616. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164617. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164618. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164619. /* Make sure image isn't bigger than I can handle */
  164620. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164621. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164622. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164623. /* Width of an input scanline must be representable as JDIMENSION. */
  164624. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164625. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164626. if ((long) jd_samplesperrow != samplesperrow)
  164627. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164628. /* For now, precision must match compiled-in value... */
  164629. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164630. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164631. /* Check that number of components won't exceed internal array sizes */
  164632. if (cinfo->num_components > MAX_COMPONENTS)
  164633. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164634. MAX_COMPONENTS);
  164635. /* Compute maximum sampling factors; check factor validity */
  164636. cinfo->max_h_samp_factor = 1;
  164637. cinfo->max_v_samp_factor = 1;
  164638. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164639. ci++, compptr++) {
  164640. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164641. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164642. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164643. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164644. compptr->h_samp_factor);
  164645. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164646. compptr->v_samp_factor);
  164647. }
  164648. /* Compute dimensions of components */
  164649. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164650. ci++, compptr++) {
  164651. /* Fill in the correct component_index value; don't rely on application */
  164652. compptr->component_index = ci;
  164653. /* For compression, we never do DCT scaling. */
  164654. compptr->DCT_scaled_size = DCTSIZE;
  164655. /* Size in DCT blocks */
  164656. compptr->width_in_blocks = (JDIMENSION)
  164657. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164658. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164659. compptr->height_in_blocks = (JDIMENSION)
  164660. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164661. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164662. /* Size in samples */
  164663. compptr->downsampled_width = (JDIMENSION)
  164664. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164665. (long) cinfo->max_h_samp_factor);
  164666. compptr->downsampled_height = (JDIMENSION)
  164667. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164668. (long) cinfo->max_v_samp_factor);
  164669. /* Mark component needed (this flag isn't actually used for compression) */
  164670. compptr->component_needed = TRUE;
  164671. }
  164672. /* Compute number of fully interleaved MCU rows (number of times that
  164673. * main controller will call coefficient controller).
  164674. */
  164675. cinfo->total_iMCU_rows = (JDIMENSION)
  164676. jdiv_round_up((long) cinfo->image_height,
  164677. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164678. }
  164679. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164680. LOCAL(void)
  164681. validate_script (j_compress_ptr cinfo)
  164682. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164683. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164684. */
  164685. {
  164686. const jpeg_scan_info * scanptr;
  164687. int scanno, ncomps, ci, coefi, thisi;
  164688. int Ss, Se, Ah, Al;
  164689. boolean component_sent[MAX_COMPONENTS];
  164690. #ifdef C_PROGRESSIVE_SUPPORTED
  164691. int * last_bitpos_ptr;
  164692. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164693. /* -1 until that coefficient has been seen; then last Al for it */
  164694. #endif
  164695. if (cinfo->num_scans <= 0)
  164696. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164697. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164698. * for progressive JPEG, no scan can have this.
  164699. */
  164700. scanptr = cinfo->scan_info;
  164701. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164702. #ifdef C_PROGRESSIVE_SUPPORTED
  164703. cinfo->progressive_mode = TRUE;
  164704. last_bitpos_ptr = & last_bitpos[0][0];
  164705. for (ci = 0; ci < cinfo->num_components; ci++)
  164706. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164707. *last_bitpos_ptr++ = -1;
  164708. #else
  164709. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164710. #endif
  164711. } else {
  164712. cinfo->progressive_mode = FALSE;
  164713. for (ci = 0; ci < cinfo->num_components; ci++)
  164714. component_sent[ci] = FALSE;
  164715. }
  164716. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164717. /* Validate component indexes */
  164718. ncomps = scanptr->comps_in_scan;
  164719. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164720. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164721. for (ci = 0; ci < ncomps; ci++) {
  164722. thisi = scanptr->component_index[ci];
  164723. if (thisi < 0 || thisi >= cinfo->num_components)
  164724. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164725. /* Components must appear in SOF order within each scan */
  164726. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164727. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164728. }
  164729. /* Validate progression parameters */
  164730. Ss = scanptr->Ss;
  164731. Se = scanptr->Se;
  164732. Ah = scanptr->Ah;
  164733. Al = scanptr->Al;
  164734. if (cinfo->progressive_mode) {
  164735. #ifdef C_PROGRESSIVE_SUPPORTED
  164736. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164737. * seems wrong: the upper bound ought to depend on data precision.
  164738. * Perhaps they really meant 0..N+1 for N-bit precision.
  164739. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164740. * out-of-range reconstructed DC values during the first DC scan,
  164741. * which might cause problems for some decoders.
  164742. */
  164743. #if BITS_IN_JSAMPLE == 8
  164744. #define MAX_AH_AL 10
  164745. #else
  164746. #define MAX_AH_AL 13
  164747. #endif
  164748. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164749. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164750. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164751. if (Ss == 0) {
  164752. if (Se != 0) /* DC and AC together not OK */
  164753. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164754. } else {
  164755. if (ncomps != 1) /* AC scans must be for only one component */
  164756. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164757. }
  164758. for (ci = 0; ci < ncomps; ci++) {
  164759. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164760. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164761. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164762. for (coefi = Ss; coefi <= Se; coefi++) {
  164763. if (last_bitpos_ptr[coefi] < 0) {
  164764. /* first scan of this coefficient */
  164765. if (Ah != 0)
  164766. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164767. } else {
  164768. /* not first scan */
  164769. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164770. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164771. }
  164772. last_bitpos_ptr[coefi] = Al;
  164773. }
  164774. }
  164775. #endif
  164776. } else {
  164777. /* For sequential JPEG, all progression parameters must be these: */
  164778. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164779. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164780. /* Make sure components are not sent twice */
  164781. for (ci = 0; ci < ncomps; ci++) {
  164782. thisi = scanptr->component_index[ci];
  164783. if (component_sent[thisi])
  164784. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164785. component_sent[thisi] = TRUE;
  164786. }
  164787. }
  164788. }
  164789. /* Now verify that everything got sent. */
  164790. if (cinfo->progressive_mode) {
  164791. #ifdef C_PROGRESSIVE_SUPPORTED
  164792. /* For progressive mode, we only check that at least some DC data
  164793. * got sent for each component; the spec does not require that all bits
  164794. * of all coefficients be transmitted. Would it be wiser to enforce
  164795. * transmission of all coefficient bits??
  164796. */
  164797. for (ci = 0; ci < cinfo->num_components; ci++) {
  164798. if (last_bitpos[ci][0] < 0)
  164799. ERREXIT(cinfo, JERR_MISSING_DATA);
  164800. }
  164801. #endif
  164802. } else {
  164803. for (ci = 0; ci < cinfo->num_components; ci++) {
  164804. if (! component_sent[ci])
  164805. ERREXIT(cinfo, JERR_MISSING_DATA);
  164806. }
  164807. }
  164808. }
  164809. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164810. LOCAL(void)
  164811. select_scan_parameters (j_compress_ptr cinfo)
  164812. /* Set up the scan parameters for the current scan */
  164813. {
  164814. int ci;
  164815. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164816. if (cinfo->scan_info != NULL) {
  164817. /* Prepare for current scan --- the script is already validated */
  164818. my_master_ptr master = (my_master_ptr) cinfo->master;
  164819. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164820. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164821. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164822. cinfo->cur_comp_info[ci] =
  164823. &cinfo->comp_info[scanptr->component_index[ci]];
  164824. }
  164825. cinfo->Ss = scanptr->Ss;
  164826. cinfo->Se = scanptr->Se;
  164827. cinfo->Ah = scanptr->Ah;
  164828. cinfo->Al = scanptr->Al;
  164829. }
  164830. else
  164831. #endif
  164832. {
  164833. /* Prepare for single sequential-JPEG scan containing all components */
  164834. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164835. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164836. MAX_COMPS_IN_SCAN);
  164837. cinfo->comps_in_scan = cinfo->num_components;
  164838. for (ci = 0; ci < cinfo->num_components; ci++) {
  164839. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164840. }
  164841. cinfo->Ss = 0;
  164842. cinfo->Se = DCTSIZE2-1;
  164843. cinfo->Ah = 0;
  164844. cinfo->Al = 0;
  164845. }
  164846. }
  164847. LOCAL(void)
  164848. per_scan_setup (j_compress_ptr cinfo)
  164849. /* Do computations that are needed before processing a JPEG scan */
  164850. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164851. {
  164852. int ci, mcublks, tmp;
  164853. jpeg_component_info *compptr;
  164854. if (cinfo->comps_in_scan == 1) {
  164855. /* Noninterleaved (single-component) scan */
  164856. compptr = cinfo->cur_comp_info[0];
  164857. /* Overall image size in MCUs */
  164858. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164859. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164860. /* For noninterleaved scan, always one block per MCU */
  164861. compptr->MCU_width = 1;
  164862. compptr->MCU_height = 1;
  164863. compptr->MCU_blocks = 1;
  164864. compptr->MCU_sample_width = DCTSIZE;
  164865. compptr->last_col_width = 1;
  164866. /* For noninterleaved scans, it is convenient to define last_row_height
  164867. * as the number of block rows present in the last iMCU row.
  164868. */
  164869. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164870. if (tmp == 0) tmp = compptr->v_samp_factor;
  164871. compptr->last_row_height = tmp;
  164872. /* Prepare array describing MCU composition */
  164873. cinfo->blocks_in_MCU = 1;
  164874. cinfo->MCU_membership[0] = 0;
  164875. } else {
  164876. /* Interleaved (multi-component) scan */
  164877. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164878. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164879. MAX_COMPS_IN_SCAN);
  164880. /* Overall image size in MCUs */
  164881. cinfo->MCUs_per_row = (JDIMENSION)
  164882. jdiv_round_up((long) cinfo->image_width,
  164883. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164884. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164885. jdiv_round_up((long) cinfo->image_height,
  164886. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164887. cinfo->blocks_in_MCU = 0;
  164888. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164889. compptr = cinfo->cur_comp_info[ci];
  164890. /* Sampling factors give # of blocks of component in each MCU */
  164891. compptr->MCU_width = compptr->h_samp_factor;
  164892. compptr->MCU_height = compptr->v_samp_factor;
  164893. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164894. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164895. /* Figure number of non-dummy blocks in last MCU column & row */
  164896. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164897. if (tmp == 0) tmp = compptr->MCU_width;
  164898. compptr->last_col_width = tmp;
  164899. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164900. if (tmp == 0) tmp = compptr->MCU_height;
  164901. compptr->last_row_height = tmp;
  164902. /* Prepare array describing MCU composition */
  164903. mcublks = compptr->MCU_blocks;
  164904. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164905. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164906. while (mcublks-- > 0) {
  164907. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164908. }
  164909. }
  164910. }
  164911. /* Convert restart specified in rows to actual MCU count. */
  164912. /* Note that count must fit in 16 bits, so we provide limiting. */
  164913. if (cinfo->restart_in_rows > 0) {
  164914. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164915. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164916. }
  164917. }
  164918. /*
  164919. * Per-pass setup.
  164920. * This is called at the beginning of each pass. We determine which modules
  164921. * will be active during this pass and give them appropriate start_pass calls.
  164922. * We also set is_last_pass to indicate whether any more passes will be
  164923. * required.
  164924. */
  164925. METHODDEF(void)
  164926. prepare_for_pass (j_compress_ptr cinfo)
  164927. {
  164928. my_master_ptr master = (my_master_ptr) cinfo->master;
  164929. switch (master->pass_type) {
  164930. case main_pass:
  164931. /* Initial pass: will collect input data, and do either Huffman
  164932. * optimization or data output for the first scan.
  164933. */
  164934. select_scan_parameters(cinfo);
  164935. per_scan_setup(cinfo);
  164936. if (! cinfo->raw_data_in) {
  164937. (*cinfo->cconvert->start_pass) (cinfo);
  164938. (*cinfo->downsample->start_pass) (cinfo);
  164939. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164940. }
  164941. (*cinfo->fdct->start_pass) (cinfo);
  164942. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164943. (*cinfo->coef->start_pass) (cinfo,
  164944. (master->total_passes > 1 ?
  164945. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164946. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164947. if (cinfo->optimize_coding) {
  164948. /* No immediate data output; postpone writing frame/scan headers */
  164949. master->pub.call_pass_startup = FALSE;
  164950. } else {
  164951. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164952. master->pub.call_pass_startup = TRUE;
  164953. }
  164954. break;
  164955. #ifdef ENTROPY_OPT_SUPPORTED
  164956. case huff_opt_pass:
  164957. /* Do Huffman optimization for a scan after the first one. */
  164958. select_scan_parameters(cinfo);
  164959. per_scan_setup(cinfo);
  164960. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164961. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164962. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164963. master->pub.call_pass_startup = FALSE;
  164964. break;
  164965. }
  164966. /* Special case: Huffman DC refinement scans need no Huffman table
  164967. * and therefore we can skip the optimization pass for them.
  164968. */
  164969. master->pass_type = output_pass;
  164970. master->pass_number++;
  164971. /*FALLTHROUGH*/
  164972. #endif
  164973. case output_pass:
  164974. /* Do a data-output pass. */
  164975. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164976. if (! cinfo->optimize_coding) {
  164977. select_scan_parameters(cinfo);
  164978. per_scan_setup(cinfo);
  164979. }
  164980. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164981. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164982. /* We emit frame/scan headers now */
  164983. if (master->scan_number == 0)
  164984. (*cinfo->marker->write_frame_header) (cinfo);
  164985. (*cinfo->marker->write_scan_header) (cinfo);
  164986. master->pub.call_pass_startup = FALSE;
  164987. break;
  164988. default:
  164989. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164990. }
  164991. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164992. /* Set up progress monitor's pass info if present */
  164993. if (cinfo->progress != NULL) {
  164994. cinfo->progress->completed_passes = master->pass_number;
  164995. cinfo->progress->total_passes = master->total_passes;
  164996. }
  164997. }
  164998. /*
  164999. * Special start-of-pass hook.
  165000. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165001. * In single-pass processing, we need this hook because we don't want to
  165002. * write frame/scan headers during jpeg_start_compress; we want to let the
  165003. * application write COM markers etc. between jpeg_start_compress and the
  165004. * jpeg_write_scanlines loop.
  165005. * In multi-pass processing, this routine is not used.
  165006. */
  165007. METHODDEF(void)
  165008. pass_startup (j_compress_ptr cinfo)
  165009. {
  165010. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165011. (*cinfo->marker->write_frame_header) (cinfo);
  165012. (*cinfo->marker->write_scan_header) (cinfo);
  165013. }
  165014. /*
  165015. * Finish up at end of pass.
  165016. */
  165017. METHODDEF(void)
  165018. finish_pass_master (j_compress_ptr cinfo)
  165019. {
  165020. my_master_ptr master = (my_master_ptr) cinfo->master;
  165021. /* The entropy coder always needs an end-of-pass call,
  165022. * either to analyze statistics or to flush its output buffer.
  165023. */
  165024. (*cinfo->entropy->finish_pass) (cinfo);
  165025. /* Update state for next pass */
  165026. switch (master->pass_type) {
  165027. case main_pass:
  165028. /* next pass is either output of scan 0 (after optimization)
  165029. * or output of scan 1 (if no optimization).
  165030. */
  165031. master->pass_type = output_pass;
  165032. if (! cinfo->optimize_coding)
  165033. master->scan_number++;
  165034. break;
  165035. case huff_opt_pass:
  165036. /* next pass is always output of current scan */
  165037. master->pass_type = output_pass;
  165038. break;
  165039. case output_pass:
  165040. /* next pass is either optimization or output of next scan */
  165041. if (cinfo->optimize_coding)
  165042. master->pass_type = huff_opt_pass;
  165043. master->scan_number++;
  165044. break;
  165045. }
  165046. master->pass_number++;
  165047. }
  165048. /*
  165049. * Initialize master compression control.
  165050. */
  165051. GLOBAL(void)
  165052. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165053. {
  165054. my_master_ptr master;
  165055. master = (my_master_ptr)
  165056. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165057. SIZEOF(my_comp_master));
  165058. cinfo->master = (struct jpeg_comp_master *) master;
  165059. master->pub.prepare_for_pass = prepare_for_pass;
  165060. master->pub.pass_startup = pass_startup;
  165061. master->pub.finish_pass = finish_pass_master;
  165062. master->pub.is_last_pass = FALSE;
  165063. /* Validate parameters, determine derived values */
  165064. initial_setup(cinfo);
  165065. if (cinfo->scan_info != NULL) {
  165066. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165067. validate_script(cinfo);
  165068. #else
  165069. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165070. #endif
  165071. } else {
  165072. cinfo->progressive_mode = FALSE;
  165073. cinfo->num_scans = 1;
  165074. }
  165075. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165076. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165077. /* Initialize my private state */
  165078. if (transcode_only) {
  165079. /* no main pass in transcoding */
  165080. if (cinfo->optimize_coding)
  165081. master->pass_type = huff_opt_pass;
  165082. else
  165083. master->pass_type = output_pass;
  165084. } else {
  165085. /* for normal compression, first pass is always this type: */
  165086. master->pass_type = main_pass;
  165087. }
  165088. master->scan_number = 0;
  165089. master->pass_number = 0;
  165090. if (cinfo->optimize_coding)
  165091. master->total_passes = cinfo->num_scans * 2;
  165092. else
  165093. master->total_passes = cinfo->num_scans;
  165094. }
  165095. /*** End of inlined file: jcmaster.c ***/
  165096. /*** Start of inlined file: jcomapi.c ***/
  165097. #define JPEG_INTERNALS
  165098. /*
  165099. * Abort processing of a JPEG compression or decompression operation,
  165100. * but don't destroy the object itself.
  165101. *
  165102. * For this, we merely clean up all the nonpermanent memory pools.
  165103. * Note that temp files (virtual arrays) are not allowed to belong to
  165104. * the permanent pool, so we will be able to close all temp files here.
  165105. * Closing a data source or destination, if necessary, is the application's
  165106. * responsibility.
  165107. */
  165108. GLOBAL(void)
  165109. jpeg_abort (j_common_ptr cinfo)
  165110. {
  165111. int pool;
  165112. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165113. if (cinfo->mem == NULL)
  165114. return;
  165115. /* Releasing pools in reverse order might help avoid fragmentation
  165116. * with some (brain-damaged) malloc libraries.
  165117. */
  165118. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165119. (*cinfo->mem->free_pool) (cinfo, pool);
  165120. }
  165121. /* Reset overall state for possible reuse of object */
  165122. if (cinfo->is_decompressor) {
  165123. cinfo->global_state = DSTATE_START;
  165124. /* Try to keep application from accessing now-deleted marker list.
  165125. * A bit kludgy to do it here, but this is the most central place.
  165126. */
  165127. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165128. } else {
  165129. cinfo->global_state = CSTATE_START;
  165130. }
  165131. }
  165132. /*
  165133. * Destruction of a JPEG object.
  165134. *
  165135. * Everything gets deallocated except the master jpeg_compress_struct itself
  165136. * and the error manager struct. Both of these are supplied by the application
  165137. * and must be freed, if necessary, by the application. (Often they are on
  165138. * the stack and so don't need to be freed anyway.)
  165139. * Closing a data source or destination, if necessary, is the application's
  165140. * responsibility.
  165141. */
  165142. GLOBAL(void)
  165143. jpeg_destroy (j_common_ptr cinfo)
  165144. {
  165145. /* We need only tell the memory manager to release everything. */
  165146. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165147. if (cinfo->mem != NULL)
  165148. (*cinfo->mem->self_destruct) (cinfo);
  165149. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165150. cinfo->global_state = 0; /* mark it destroyed */
  165151. }
  165152. /*
  165153. * Convenience routines for allocating quantization and Huffman tables.
  165154. * (Would jutils.c be a more reasonable place to put these?)
  165155. */
  165156. GLOBAL(JQUANT_TBL *)
  165157. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165158. {
  165159. JQUANT_TBL *tbl;
  165160. tbl = (JQUANT_TBL *)
  165161. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165162. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165163. return tbl;
  165164. }
  165165. GLOBAL(JHUFF_TBL *)
  165166. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165167. {
  165168. JHUFF_TBL *tbl;
  165169. tbl = (JHUFF_TBL *)
  165170. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165171. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165172. return tbl;
  165173. }
  165174. /*** End of inlined file: jcomapi.c ***/
  165175. /*** Start of inlined file: jcparam.c ***/
  165176. #define JPEG_INTERNALS
  165177. /*
  165178. * Quantization table setup routines
  165179. */
  165180. GLOBAL(void)
  165181. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165182. const unsigned int *basic_table,
  165183. int scale_factor, boolean force_baseline)
  165184. /* Define a quantization table equal to the basic_table times
  165185. * a scale factor (given as a percentage).
  165186. * If force_baseline is TRUE, the computed quantization table entries
  165187. * are limited to 1..255 for JPEG baseline compatibility.
  165188. */
  165189. {
  165190. JQUANT_TBL ** qtblptr;
  165191. int i;
  165192. long temp;
  165193. /* Safety check to ensure start_compress not called yet. */
  165194. if (cinfo->global_state != CSTATE_START)
  165195. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165196. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165197. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165198. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165199. if (*qtblptr == NULL)
  165200. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165201. for (i = 0; i < DCTSIZE2; i++) {
  165202. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165203. /* limit the values to the valid range */
  165204. if (temp <= 0L) temp = 1L;
  165205. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165206. if (force_baseline && temp > 255L)
  165207. temp = 255L; /* limit to baseline range if requested */
  165208. (*qtblptr)->quantval[i] = (UINT16) temp;
  165209. }
  165210. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165211. (*qtblptr)->sent_table = FALSE;
  165212. }
  165213. GLOBAL(void)
  165214. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165215. boolean force_baseline)
  165216. /* Set or change the 'quality' (quantization) setting, using default tables
  165217. * and a straight percentage-scaling quality scale. In most cases it's better
  165218. * to use jpeg_set_quality (below); this entry point is provided for
  165219. * applications that insist on a linear percentage scaling.
  165220. */
  165221. {
  165222. /* These are the sample quantization tables given in JPEG spec section K.1.
  165223. * The spec says that the values given produce "good" quality, and
  165224. * when divided by 2, "very good" quality.
  165225. */
  165226. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165227. 16, 11, 10, 16, 24, 40, 51, 61,
  165228. 12, 12, 14, 19, 26, 58, 60, 55,
  165229. 14, 13, 16, 24, 40, 57, 69, 56,
  165230. 14, 17, 22, 29, 51, 87, 80, 62,
  165231. 18, 22, 37, 56, 68, 109, 103, 77,
  165232. 24, 35, 55, 64, 81, 104, 113, 92,
  165233. 49, 64, 78, 87, 103, 121, 120, 101,
  165234. 72, 92, 95, 98, 112, 100, 103, 99
  165235. };
  165236. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165237. 17, 18, 24, 47, 99, 99, 99, 99,
  165238. 18, 21, 26, 66, 99, 99, 99, 99,
  165239. 24, 26, 56, 99, 99, 99, 99, 99,
  165240. 47, 66, 99, 99, 99, 99, 99, 99,
  165241. 99, 99, 99, 99, 99, 99, 99, 99,
  165242. 99, 99, 99, 99, 99, 99, 99, 99,
  165243. 99, 99, 99, 99, 99, 99, 99, 99,
  165244. 99, 99, 99, 99, 99, 99, 99, 99
  165245. };
  165246. /* Set up two quantization tables using the specified scaling */
  165247. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165248. scale_factor, force_baseline);
  165249. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165250. scale_factor, force_baseline);
  165251. }
  165252. GLOBAL(int)
  165253. jpeg_quality_scaling (int quality)
  165254. /* Convert a user-specified quality rating to a percentage scaling factor
  165255. * for an underlying quantization table, using our recommended scaling curve.
  165256. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165257. */
  165258. {
  165259. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165260. if (quality <= 0) quality = 1;
  165261. if (quality > 100) quality = 100;
  165262. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165263. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165264. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165265. * to make all the table entries 1 (hence, minimum quantization loss).
  165266. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165267. */
  165268. if (quality < 50)
  165269. quality = 5000 / quality;
  165270. else
  165271. quality = 200 - quality*2;
  165272. return quality;
  165273. }
  165274. GLOBAL(void)
  165275. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165276. /* Set or change the 'quality' (quantization) setting, using default tables.
  165277. * This is the standard quality-adjusting entry point for typical user
  165278. * interfaces; only those who want detailed control over quantization tables
  165279. * would use the preceding three routines directly.
  165280. */
  165281. {
  165282. /* Convert user 0-100 rating to percentage scaling */
  165283. quality = jpeg_quality_scaling(quality);
  165284. /* Set up standard quality tables */
  165285. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165286. }
  165287. /*
  165288. * Huffman table setup routines
  165289. */
  165290. LOCAL(void)
  165291. add_huff_table (j_compress_ptr cinfo,
  165292. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165293. /* Define a Huffman table */
  165294. {
  165295. int nsymbols, len;
  165296. if (*htblptr == NULL)
  165297. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165298. /* Copy the number-of-symbols-of-each-code-length counts */
  165299. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165300. /* Validate the counts. We do this here mainly so we can copy the right
  165301. * number of symbols from the val[] array, without risking marching off
  165302. * the end of memory. jchuff.c will do a more thorough test later.
  165303. */
  165304. nsymbols = 0;
  165305. for (len = 1; len <= 16; len++)
  165306. nsymbols += bits[len];
  165307. if (nsymbols < 1 || nsymbols > 256)
  165308. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165309. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165310. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165311. (*htblptr)->sent_table = FALSE;
  165312. }
  165313. LOCAL(void)
  165314. std_huff_tables (j_compress_ptr cinfo)
  165315. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165316. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165317. {
  165318. static const UINT8 bits_dc_luminance[17] =
  165319. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165320. static const UINT8 val_dc_luminance[] =
  165321. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165322. static const UINT8 bits_dc_chrominance[17] =
  165323. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165324. static const UINT8 val_dc_chrominance[] =
  165325. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165326. static const UINT8 bits_ac_luminance[17] =
  165327. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165328. static const UINT8 val_ac_luminance[] =
  165329. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165330. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165331. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165332. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165333. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165334. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165335. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165336. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165337. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165338. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165339. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165340. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165341. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165342. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165343. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165344. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165345. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165346. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165347. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165348. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165349. 0xf9, 0xfa };
  165350. static const UINT8 bits_ac_chrominance[17] =
  165351. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165352. static const UINT8 val_ac_chrominance[] =
  165353. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165354. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165355. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165356. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165357. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165358. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165359. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165360. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165361. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165362. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165363. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165364. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165365. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165366. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165367. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165368. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165369. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165370. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165371. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165372. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165373. 0xf9, 0xfa };
  165374. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165375. bits_dc_luminance, val_dc_luminance);
  165376. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165377. bits_ac_luminance, val_ac_luminance);
  165378. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165379. bits_dc_chrominance, val_dc_chrominance);
  165380. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165381. bits_ac_chrominance, val_ac_chrominance);
  165382. }
  165383. /*
  165384. * Default parameter setup for compression.
  165385. *
  165386. * Applications that don't choose to use this routine must do their
  165387. * own setup of all these parameters. Alternately, you can call this
  165388. * to establish defaults and then alter parameters selectively. This
  165389. * is the recommended approach since, if we add any new parameters,
  165390. * your code will still work (they'll be set to reasonable defaults).
  165391. */
  165392. GLOBAL(void)
  165393. jpeg_set_defaults (j_compress_ptr cinfo)
  165394. {
  165395. int i;
  165396. /* Safety check to ensure start_compress not called yet. */
  165397. if (cinfo->global_state != CSTATE_START)
  165398. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165399. /* Allocate comp_info array large enough for maximum component count.
  165400. * Array is made permanent in case application wants to compress
  165401. * multiple images at same param settings.
  165402. */
  165403. if (cinfo->comp_info == NULL)
  165404. cinfo->comp_info = (jpeg_component_info *)
  165405. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165406. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165407. /* Initialize everything not dependent on the color space */
  165408. cinfo->data_precision = BITS_IN_JSAMPLE;
  165409. /* Set up two quantization tables using default quality of 75 */
  165410. jpeg_set_quality(cinfo, 75, TRUE);
  165411. /* Set up two Huffman tables */
  165412. std_huff_tables(cinfo);
  165413. /* Initialize default arithmetic coding conditioning */
  165414. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165415. cinfo->arith_dc_L[i] = 0;
  165416. cinfo->arith_dc_U[i] = 1;
  165417. cinfo->arith_ac_K[i] = 5;
  165418. }
  165419. /* Default is no multiple-scan output */
  165420. cinfo->scan_info = NULL;
  165421. cinfo->num_scans = 0;
  165422. /* Expect normal source image, not raw downsampled data */
  165423. cinfo->raw_data_in = FALSE;
  165424. /* Use Huffman coding, not arithmetic coding, by default */
  165425. cinfo->arith_code = FALSE;
  165426. /* By default, don't do extra passes to optimize entropy coding */
  165427. cinfo->optimize_coding = FALSE;
  165428. /* The standard Huffman tables are only valid for 8-bit data precision.
  165429. * If the precision is higher, force optimization on so that usable
  165430. * tables will be computed. This test can be removed if default tables
  165431. * are supplied that are valid for the desired precision.
  165432. */
  165433. if (cinfo->data_precision > 8)
  165434. cinfo->optimize_coding = TRUE;
  165435. /* By default, use the simpler non-cosited sampling alignment */
  165436. cinfo->CCIR601_sampling = FALSE;
  165437. /* No input smoothing */
  165438. cinfo->smoothing_factor = 0;
  165439. /* DCT algorithm preference */
  165440. cinfo->dct_method = JDCT_DEFAULT;
  165441. /* No restart markers */
  165442. cinfo->restart_interval = 0;
  165443. cinfo->restart_in_rows = 0;
  165444. /* Fill in default JFIF marker parameters. Note that whether the marker
  165445. * will actually be written is determined by jpeg_set_colorspace.
  165446. *
  165447. * By default, the library emits JFIF version code 1.01.
  165448. * An application that wants to emit JFIF 1.02 extension markers should set
  165449. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165450. * to 1.02, but there may still be some decoders in use that will complain
  165451. * about that; saying 1.01 should minimize compatibility problems.
  165452. */
  165453. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165454. cinfo->JFIF_minor_version = 1;
  165455. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165456. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165457. cinfo->Y_density = 1;
  165458. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165459. jpeg_default_colorspace(cinfo);
  165460. }
  165461. /*
  165462. * Select an appropriate JPEG colorspace for in_color_space.
  165463. */
  165464. GLOBAL(void)
  165465. jpeg_default_colorspace (j_compress_ptr cinfo)
  165466. {
  165467. switch (cinfo->in_color_space) {
  165468. case JCS_GRAYSCALE:
  165469. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165470. break;
  165471. case JCS_RGB:
  165472. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165473. break;
  165474. case JCS_YCbCr:
  165475. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165476. break;
  165477. case JCS_CMYK:
  165478. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165479. break;
  165480. case JCS_YCCK:
  165481. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165482. break;
  165483. case JCS_UNKNOWN:
  165484. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165485. break;
  165486. default:
  165487. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165488. }
  165489. }
  165490. /*
  165491. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165492. */
  165493. GLOBAL(void)
  165494. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165495. {
  165496. jpeg_component_info * compptr;
  165497. int ci;
  165498. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165499. (compptr = &cinfo->comp_info[index], \
  165500. compptr->component_id = (id), \
  165501. compptr->h_samp_factor = (hsamp), \
  165502. compptr->v_samp_factor = (vsamp), \
  165503. compptr->quant_tbl_no = (quant), \
  165504. compptr->dc_tbl_no = (dctbl), \
  165505. compptr->ac_tbl_no = (actbl) )
  165506. /* Safety check to ensure start_compress not called yet. */
  165507. if (cinfo->global_state != CSTATE_START)
  165508. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165509. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165510. * tables 1 for chrominance components.
  165511. */
  165512. cinfo->jpeg_color_space = colorspace;
  165513. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165514. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165515. switch (colorspace) {
  165516. case JCS_GRAYSCALE:
  165517. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165518. cinfo->num_components = 1;
  165519. /* JFIF specifies component ID 1 */
  165520. SET_COMP(0, 1, 1,1, 0, 0,0);
  165521. break;
  165522. case JCS_RGB:
  165523. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165524. cinfo->num_components = 3;
  165525. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165526. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165527. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165528. break;
  165529. case JCS_YCbCr:
  165530. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165531. cinfo->num_components = 3;
  165532. /* JFIF specifies component IDs 1,2,3 */
  165533. /* We default to 2x2 subsamples of chrominance */
  165534. SET_COMP(0, 1, 2,2, 0, 0,0);
  165535. SET_COMP(1, 2, 1,1, 1, 1,1);
  165536. SET_COMP(2, 3, 1,1, 1, 1,1);
  165537. break;
  165538. case JCS_CMYK:
  165539. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165540. cinfo->num_components = 4;
  165541. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165542. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165543. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165544. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165545. break;
  165546. case JCS_YCCK:
  165547. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165548. cinfo->num_components = 4;
  165549. SET_COMP(0, 1, 2,2, 0, 0,0);
  165550. SET_COMP(1, 2, 1,1, 1, 1,1);
  165551. SET_COMP(2, 3, 1,1, 1, 1,1);
  165552. SET_COMP(3, 4, 2,2, 0, 0,0);
  165553. break;
  165554. case JCS_UNKNOWN:
  165555. cinfo->num_components = cinfo->input_components;
  165556. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165557. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165558. MAX_COMPONENTS);
  165559. for (ci = 0; ci < cinfo->num_components; ci++) {
  165560. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165561. }
  165562. break;
  165563. default:
  165564. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165565. }
  165566. }
  165567. #ifdef C_PROGRESSIVE_SUPPORTED
  165568. LOCAL(jpeg_scan_info *)
  165569. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165570. int Ss, int Se, int Ah, int Al)
  165571. /* Support routine: generate one scan for specified component */
  165572. {
  165573. scanptr->comps_in_scan = 1;
  165574. scanptr->component_index[0] = ci;
  165575. scanptr->Ss = Ss;
  165576. scanptr->Se = Se;
  165577. scanptr->Ah = Ah;
  165578. scanptr->Al = Al;
  165579. scanptr++;
  165580. return scanptr;
  165581. }
  165582. LOCAL(jpeg_scan_info *)
  165583. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165584. int Ss, int Se, int Ah, int Al)
  165585. /* Support routine: generate one scan for each component */
  165586. {
  165587. int ci;
  165588. for (ci = 0; ci < ncomps; ci++) {
  165589. scanptr->comps_in_scan = 1;
  165590. scanptr->component_index[0] = ci;
  165591. scanptr->Ss = Ss;
  165592. scanptr->Se = Se;
  165593. scanptr->Ah = Ah;
  165594. scanptr->Al = Al;
  165595. scanptr++;
  165596. }
  165597. return scanptr;
  165598. }
  165599. LOCAL(jpeg_scan_info *)
  165600. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165601. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165602. {
  165603. int ci;
  165604. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165605. /* Single interleaved DC scan */
  165606. scanptr->comps_in_scan = ncomps;
  165607. for (ci = 0; ci < ncomps; ci++)
  165608. scanptr->component_index[ci] = ci;
  165609. scanptr->Ss = scanptr->Se = 0;
  165610. scanptr->Ah = Ah;
  165611. scanptr->Al = Al;
  165612. scanptr++;
  165613. } else {
  165614. /* Noninterleaved DC scan for each component */
  165615. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165616. }
  165617. return scanptr;
  165618. }
  165619. /*
  165620. * Create a recommended progressive-JPEG script.
  165621. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165622. */
  165623. GLOBAL(void)
  165624. jpeg_simple_progression (j_compress_ptr cinfo)
  165625. {
  165626. int ncomps = cinfo->num_components;
  165627. int nscans;
  165628. jpeg_scan_info * scanptr;
  165629. /* Safety check to ensure start_compress not called yet. */
  165630. if (cinfo->global_state != CSTATE_START)
  165631. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165632. /* Figure space needed for script. Calculation must match code below! */
  165633. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165634. /* Custom script for YCbCr color images. */
  165635. nscans = 10;
  165636. } else {
  165637. /* All-purpose script for other color spaces. */
  165638. if (ncomps > MAX_COMPS_IN_SCAN)
  165639. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165640. else
  165641. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165642. }
  165643. /* Allocate space for script.
  165644. * We need to put it in the permanent pool in case the application performs
  165645. * multiple compressions without changing the settings. To avoid a memory
  165646. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165647. * object, we try to re-use previously allocated space, and we allocate
  165648. * enough space to handle YCbCr even if initially asked for grayscale.
  165649. */
  165650. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165651. cinfo->script_space_size = MAX(nscans, 10);
  165652. cinfo->script_space = (jpeg_scan_info *)
  165653. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165654. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165655. }
  165656. scanptr = cinfo->script_space;
  165657. cinfo->scan_info = scanptr;
  165658. cinfo->num_scans = nscans;
  165659. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165660. /* Custom script for YCbCr color images. */
  165661. /* Initial DC scan */
  165662. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165663. /* Initial AC scan: get some luma data out in a hurry */
  165664. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165665. /* Chroma data is too small to be worth expending many scans on */
  165666. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165667. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165668. /* Complete spectral selection for luma AC */
  165669. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165670. /* Refine next bit of luma AC */
  165671. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165672. /* Finish DC successive approximation */
  165673. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165674. /* Finish AC successive approximation */
  165675. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165676. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165677. /* Luma bottom bit comes last since it's usually largest scan */
  165678. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165679. } else {
  165680. /* All-purpose script for other color spaces. */
  165681. /* Successive approximation first pass */
  165682. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165683. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165684. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165685. /* Successive approximation second pass */
  165686. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165687. /* Successive approximation final pass */
  165688. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165689. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165690. }
  165691. }
  165692. #endif /* C_PROGRESSIVE_SUPPORTED */
  165693. /*** End of inlined file: jcparam.c ***/
  165694. /*** Start of inlined file: jcphuff.c ***/
  165695. #define JPEG_INTERNALS
  165696. #ifdef C_PROGRESSIVE_SUPPORTED
  165697. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165698. typedef struct {
  165699. struct jpeg_entropy_encoder pub; /* public fields */
  165700. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165701. boolean gather_statistics;
  165702. /* Bit-level coding status.
  165703. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165704. */
  165705. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165706. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165707. INT32 put_buffer; /* current bit-accumulation buffer */
  165708. int put_bits; /* # of bits now in it */
  165709. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165710. /* Coding status for DC components */
  165711. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165712. /* Coding status for AC components */
  165713. int ac_tbl_no; /* the table number of the single component */
  165714. unsigned int EOBRUN; /* run length of EOBs */
  165715. unsigned int BE; /* # of buffered correction bits before MCU */
  165716. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165717. /* packing correction bits tightly would save some space but cost time... */
  165718. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165719. int next_restart_num; /* next restart number to write (0-7) */
  165720. /* Pointers to derived tables (these workspaces have image lifespan).
  165721. * Since any one scan codes only DC or only AC, we only need one set
  165722. * of tables, not one for DC and one for AC.
  165723. */
  165724. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165725. /* Statistics tables for optimization; again, one set is enough */
  165726. long * count_ptrs[NUM_HUFF_TBLS];
  165727. } phuff_entropy_encoder;
  165728. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165729. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165730. * buffer can hold. Larger sizes may slightly improve compression, but
  165731. * 1000 is already well into the realm of overkill.
  165732. * The minimum safe size is 64 bits.
  165733. */
  165734. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165735. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165736. * We assume that int right shift is unsigned if INT32 right shift is,
  165737. * which should be safe.
  165738. */
  165739. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165740. #define ISHIFT_TEMPS int ishift_temp;
  165741. #define IRIGHT_SHIFT(x,shft) \
  165742. ((ishift_temp = (x)) < 0 ? \
  165743. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165744. (ishift_temp >> (shft)))
  165745. #else
  165746. #define ISHIFT_TEMPS
  165747. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165748. #endif
  165749. /* Forward declarations */
  165750. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165751. JBLOCKROW *MCU_data));
  165752. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165753. JBLOCKROW *MCU_data));
  165754. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165755. JBLOCKROW *MCU_data));
  165756. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165757. JBLOCKROW *MCU_data));
  165758. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165759. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165760. /*
  165761. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165762. */
  165763. METHODDEF(void)
  165764. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165765. {
  165766. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165767. boolean is_DC_band;
  165768. int ci, tbl;
  165769. jpeg_component_info * compptr;
  165770. entropy->cinfo = cinfo;
  165771. entropy->gather_statistics = gather_statistics;
  165772. is_DC_band = (cinfo->Ss == 0);
  165773. /* We assume jcmaster.c already validated the scan parameters. */
  165774. /* Select execution routines */
  165775. if (cinfo->Ah == 0) {
  165776. if (is_DC_band)
  165777. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165778. else
  165779. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165780. } else {
  165781. if (is_DC_band)
  165782. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165783. else {
  165784. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165785. /* AC refinement needs a correction bit buffer */
  165786. if (entropy->bit_buffer == NULL)
  165787. entropy->bit_buffer = (char *)
  165788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165789. MAX_CORR_BITS * SIZEOF(char));
  165790. }
  165791. }
  165792. if (gather_statistics)
  165793. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165794. else
  165795. entropy->pub.finish_pass = finish_pass_phuff;
  165796. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165797. * for AC coefficients.
  165798. */
  165799. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165800. compptr = cinfo->cur_comp_info[ci];
  165801. /* Initialize DC predictions to 0 */
  165802. entropy->last_dc_val[ci] = 0;
  165803. /* Get table index */
  165804. if (is_DC_band) {
  165805. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165806. continue;
  165807. tbl = compptr->dc_tbl_no;
  165808. } else {
  165809. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165810. }
  165811. if (gather_statistics) {
  165812. /* Check for invalid table index */
  165813. /* (make_c_derived_tbl does this in the other path) */
  165814. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165815. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165816. /* Allocate and zero the statistics tables */
  165817. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165818. if (entropy->count_ptrs[tbl] == NULL)
  165819. entropy->count_ptrs[tbl] = (long *)
  165820. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165821. 257 * SIZEOF(long));
  165822. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165823. } else {
  165824. /* Compute derived values for Huffman table */
  165825. /* We may do this more than once for a table, but it's not expensive */
  165826. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165827. & entropy->derived_tbls[tbl]);
  165828. }
  165829. }
  165830. /* Initialize AC stuff */
  165831. entropy->EOBRUN = 0;
  165832. entropy->BE = 0;
  165833. /* Initialize bit buffer to empty */
  165834. entropy->put_buffer = 0;
  165835. entropy->put_bits = 0;
  165836. /* Initialize restart stuff */
  165837. entropy->restarts_to_go = cinfo->restart_interval;
  165838. entropy->next_restart_num = 0;
  165839. }
  165840. /* Outputting bytes to the file.
  165841. * NB: these must be called only when actually outputting,
  165842. * that is, entropy->gather_statistics == FALSE.
  165843. */
  165844. /* Emit a byte */
  165845. #define emit_byte(entropy,val) \
  165846. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165847. if (--(entropy)->free_in_buffer == 0) \
  165848. dump_buffer_p(entropy); }
  165849. LOCAL(void)
  165850. dump_buffer_p (phuff_entropy_ptr entropy)
  165851. /* Empty the output buffer; we do not support suspension in this module. */
  165852. {
  165853. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165854. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165855. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165856. /* After a successful buffer dump, must reset buffer pointers */
  165857. entropy->next_output_byte = dest->next_output_byte;
  165858. entropy->free_in_buffer = dest->free_in_buffer;
  165859. }
  165860. /* Outputting bits to the file */
  165861. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165862. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165863. * in one call, and we never retain more than 7 bits in put_buffer
  165864. * between calls, so 24 bits are sufficient.
  165865. */
  165866. INLINE
  165867. LOCAL(void)
  165868. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165869. /* Emit some bits, unless we are in gather mode */
  165870. {
  165871. /* This routine is heavily used, so it's worth coding tightly. */
  165872. register INT32 put_buffer = (INT32) code;
  165873. register int put_bits = entropy->put_bits;
  165874. /* if size is 0, caller used an invalid Huffman table entry */
  165875. if (size == 0)
  165876. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165877. if (entropy->gather_statistics)
  165878. return; /* do nothing if we're only getting stats */
  165879. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165880. put_bits += size; /* new number of bits in buffer */
  165881. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165882. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165883. while (put_bits >= 8) {
  165884. int c = (int) ((put_buffer >> 16) & 0xFF);
  165885. emit_byte(entropy, c);
  165886. if (c == 0xFF) { /* need to stuff a zero byte? */
  165887. emit_byte(entropy, 0);
  165888. }
  165889. put_buffer <<= 8;
  165890. put_bits -= 8;
  165891. }
  165892. entropy->put_buffer = put_buffer; /* update variables */
  165893. entropy->put_bits = put_bits;
  165894. }
  165895. LOCAL(void)
  165896. flush_bits_p (phuff_entropy_ptr entropy)
  165897. {
  165898. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165899. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165900. entropy->put_bits = 0;
  165901. }
  165902. /*
  165903. * Emit (or just count) a Huffman symbol.
  165904. */
  165905. INLINE
  165906. LOCAL(void)
  165907. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165908. {
  165909. if (entropy->gather_statistics)
  165910. entropy->count_ptrs[tbl_no][symbol]++;
  165911. else {
  165912. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165913. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165914. }
  165915. }
  165916. /*
  165917. * Emit bits from a correction bit buffer.
  165918. */
  165919. LOCAL(void)
  165920. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165921. unsigned int nbits)
  165922. {
  165923. if (entropy->gather_statistics)
  165924. return; /* no real work */
  165925. while (nbits > 0) {
  165926. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165927. bufstart++;
  165928. nbits--;
  165929. }
  165930. }
  165931. /*
  165932. * Emit any pending EOBRUN symbol.
  165933. */
  165934. LOCAL(void)
  165935. emit_eobrun (phuff_entropy_ptr entropy)
  165936. {
  165937. register int temp, nbits;
  165938. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165939. temp = entropy->EOBRUN;
  165940. nbits = 0;
  165941. while ((temp >>= 1))
  165942. nbits++;
  165943. /* safety check: shouldn't happen given limited correction-bit buffer */
  165944. if (nbits > 14)
  165945. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165946. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165947. if (nbits)
  165948. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165949. entropy->EOBRUN = 0;
  165950. /* Emit any buffered correction bits */
  165951. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165952. entropy->BE = 0;
  165953. }
  165954. }
  165955. /*
  165956. * Emit a restart marker & resynchronize predictions.
  165957. */
  165958. LOCAL(void)
  165959. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165960. {
  165961. int ci;
  165962. emit_eobrun(entropy);
  165963. if (! entropy->gather_statistics) {
  165964. flush_bits_p(entropy);
  165965. emit_byte(entropy, 0xFF);
  165966. emit_byte(entropy, JPEG_RST0 + restart_num);
  165967. }
  165968. if (entropy->cinfo->Ss == 0) {
  165969. /* Re-initialize DC predictions to 0 */
  165970. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165971. entropy->last_dc_val[ci] = 0;
  165972. } else {
  165973. /* Re-initialize all AC-related fields to 0 */
  165974. entropy->EOBRUN = 0;
  165975. entropy->BE = 0;
  165976. }
  165977. }
  165978. /*
  165979. * MCU encoding for DC initial scan (either spectral selection,
  165980. * or first pass of successive approximation).
  165981. */
  165982. METHODDEF(boolean)
  165983. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165984. {
  165985. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165986. register int temp, temp2;
  165987. register int nbits;
  165988. int blkn, ci;
  165989. int Al = cinfo->Al;
  165990. JBLOCKROW block;
  165991. jpeg_component_info * compptr;
  165992. ISHIFT_TEMPS
  165993. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165994. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165995. /* Emit restart marker if needed */
  165996. if (cinfo->restart_interval)
  165997. if (entropy->restarts_to_go == 0)
  165998. emit_restart_p(entropy, entropy->next_restart_num);
  165999. /* Encode the MCU data blocks */
  166000. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166001. block = MCU_data[blkn];
  166002. ci = cinfo->MCU_membership[blkn];
  166003. compptr = cinfo->cur_comp_info[ci];
  166004. /* Compute the DC value after the required point transform by Al.
  166005. * This is simply an arithmetic right shift.
  166006. */
  166007. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166008. /* DC differences are figured on the point-transformed values. */
  166009. temp = temp2 - entropy->last_dc_val[ci];
  166010. entropy->last_dc_val[ci] = temp2;
  166011. /* Encode the DC coefficient difference per section G.1.2.1 */
  166012. temp2 = temp;
  166013. if (temp < 0) {
  166014. temp = -temp; /* temp is abs value of input */
  166015. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166016. /* This code assumes we are on a two's complement machine */
  166017. temp2--;
  166018. }
  166019. /* Find the number of bits needed for the magnitude of the coefficient */
  166020. nbits = 0;
  166021. while (temp) {
  166022. nbits++;
  166023. temp >>= 1;
  166024. }
  166025. /* Check for out-of-range coefficient values.
  166026. * Since we're encoding a difference, the range limit is twice as much.
  166027. */
  166028. if (nbits > MAX_COEF_BITS+1)
  166029. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166030. /* Count/emit the Huffman-coded symbol for the number of bits */
  166031. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166032. /* Emit that number of bits of the value, if positive, */
  166033. /* or the complement of its magnitude, if negative. */
  166034. if (nbits) /* emit_bits rejects calls with size 0 */
  166035. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166036. }
  166037. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166038. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166039. /* Update restart-interval state too */
  166040. if (cinfo->restart_interval) {
  166041. if (entropy->restarts_to_go == 0) {
  166042. entropy->restarts_to_go = cinfo->restart_interval;
  166043. entropy->next_restart_num++;
  166044. entropy->next_restart_num &= 7;
  166045. }
  166046. entropy->restarts_to_go--;
  166047. }
  166048. return TRUE;
  166049. }
  166050. /*
  166051. * MCU encoding for AC initial scan (either spectral selection,
  166052. * or first pass of successive approximation).
  166053. */
  166054. METHODDEF(boolean)
  166055. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166056. {
  166057. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166058. register int temp, temp2;
  166059. register int nbits;
  166060. register int r, k;
  166061. int Se = cinfo->Se;
  166062. int Al = cinfo->Al;
  166063. JBLOCKROW block;
  166064. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166065. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166066. /* Emit restart marker if needed */
  166067. if (cinfo->restart_interval)
  166068. if (entropy->restarts_to_go == 0)
  166069. emit_restart_p(entropy, entropy->next_restart_num);
  166070. /* Encode the MCU data block */
  166071. block = MCU_data[0];
  166072. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166073. r = 0; /* r = run length of zeros */
  166074. for (k = cinfo->Ss; k <= Se; k++) {
  166075. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166076. r++;
  166077. continue;
  166078. }
  166079. /* We must apply the point transform by Al. For AC coefficients this
  166080. * is an integer division with rounding towards 0. To do this portably
  166081. * in C, we shift after obtaining the absolute value; so the code is
  166082. * interwoven with finding the abs value (temp) and output bits (temp2).
  166083. */
  166084. if (temp < 0) {
  166085. temp = -temp; /* temp is abs value of input */
  166086. temp >>= Al; /* apply the point transform */
  166087. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166088. temp2 = ~temp;
  166089. } else {
  166090. temp >>= Al; /* apply the point transform */
  166091. temp2 = temp;
  166092. }
  166093. /* Watch out for case that nonzero coef is zero after point transform */
  166094. if (temp == 0) {
  166095. r++;
  166096. continue;
  166097. }
  166098. /* Emit any pending EOBRUN */
  166099. if (entropy->EOBRUN > 0)
  166100. emit_eobrun(entropy);
  166101. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166102. while (r > 15) {
  166103. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166104. r -= 16;
  166105. }
  166106. /* Find the number of bits needed for the magnitude of the coefficient */
  166107. nbits = 1; /* there must be at least one 1 bit */
  166108. while ((temp >>= 1))
  166109. nbits++;
  166110. /* Check for out-of-range coefficient values */
  166111. if (nbits > MAX_COEF_BITS)
  166112. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166113. /* Count/emit Huffman symbol for run length / number of bits */
  166114. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166115. /* Emit that number of bits of the value, if positive, */
  166116. /* or the complement of its magnitude, if negative. */
  166117. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166118. r = 0; /* reset zero run length */
  166119. }
  166120. if (r > 0) { /* If there are trailing zeroes, */
  166121. entropy->EOBRUN++; /* count an EOB */
  166122. if (entropy->EOBRUN == 0x7FFF)
  166123. emit_eobrun(entropy); /* force it out to avoid overflow */
  166124. }
  166125. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166126. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166127. /* Update restart-interval state too */
  166128. if (cinfo->restart_interval) {
  166129. if (entropy->restarts_to_go == 0) {
  166130. entropy->restarts_to_go = cinfo->restart_interval;
  166131. entropy->next_restart_num++;
  166132. entropy->next_restart_num &= 7;
  166133. }
  166134. entropy->restarts_to_go--;
  166135. }
  166136. return TRUE;
  166137. }
  166138. /*
  166139. * MCU encoding for DC successive approximation refinement scan.
  166140. * Note: we assume such scans can be multi-component, although the spec
  166141. * is not very clear on the point.
  166142. */
  166143. METHODDEF(boolean)
  166144. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166145. {
  166146. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166147. register int temp;
  166148. int blkn;
  166149. int Al = cinfo->Al;
  166150. JBLOCKROW block;
  166151. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166152. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166153. /* Emit restart marker if needed */
  166154. if (cinfo->restart_interval)
  166155. if (entropy->restarts_to_go == 0)
  166156. emit_restart_p(entropy, entropy->next_restart_num);
  166157. /* Encode the MCU data blocks */
  166158. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166159. block = MCU_data[blkn];
  166160. /* We simply emit the Al'th bit of the DC coefficient value. */
  166161. temp = (*block)[0];
  166162. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166163. }
  166164. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166165. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166166. /* Update restart-interval state too */
  166167. if (cinfo->restart_interval) {
  166168. if (entropy->restarts_to_go == 0) {
  166169. entropy->restarts_to_go = cinfo->restart_interval;
  166170. entropy->next_restart_num++;
  166171. entropy->next_restart_num &= 7;
  166172. }
  166173. entropy->restarts_to_go--;
  166174. }
  166175. return TRUE;
  166176. }
  166177. /*
  166178. * MCU encoding for AC successive approximation refinement scan.
  166179. */
  166180. METHODDEF(boolean)
  166181. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166182. {
  166183. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166184. register int temp;
  166185. register int r, k;
  166186. int EOB;
  166187. char *BR_buffer;
  166188. unsigned int BR;
  166189. int Se = cinfo->Se;
  166190. int Al = cinfo->Al;
  166191. JBLOCKROW block;
  166192. int absvalues[DCTSIZE2];
  166193. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166194. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166195. /* Emit restart marker if needed */
  166196. if (cinfo->restart_interval)
  166197. if (entropy->restarts_to_go == 0)
  166198. emit_restart_p(entropy, entropy->next_restart_num);
  166199. /* Encode the MCU data block */
  166200. block = MCU_data[0];
  166201. /* It is convenient to make a pre-pass to determine the transformed
  166202. * coefficients' absolute values and the EOB position.
  166203. */
  166204. EOB = 0;
  166205. for (k = cinfo->Ss; k <= Se; k++) {
  166206. temp = (*block)[jpeg_natural_order[k]];
  166207. /* We must apply the point transform by Al. For AC coefficients this
  166208. * is an integer division with rounding towards 0. To do this portably
  166209. * in C, we shift after obtaining the absolute value.
  166210. */
  166211. if (temp < 0)
  166212. temp = -temp; /* temp is abs value of input */
  166213. temp >>= Al; /* apply the point transform */
  166214. absvalues[k] = temp; /* save abs value for main pass */
  166215. if (temp == 1)
  166216. EOB = k; /* EOB = index of last newly-nonzero coef */
  166217. }
  166218. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166219. r = 0; /* r = run length of zeros */
  166220. BR = 0; /* BR = count of buffered bits added now */
  166221. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166222. for (k = cinfo->Ss; k <= Se; k++) {
  166223. if ((temp = absvalues[k]) == 0) {
  166224. r++;
  166225. continue;
  166226. }
  166227. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166228. while (r > 15 && k <= EOB) {
  166229. /* emit any pending EOBRUN and the BE correction bits */
  166230. emit_eobrun(entropy);
  166231. /* Emit ZRL */
  166232. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166233. r -= 16;
  166234. /* Emit buffered correction bits that must be associated with ZRL */
  166235. emit_buffered_bits(entropy, BR_buffer, BR);
  166236. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166237. BR = 0;
  166238. }
  166239. /* If the coef was previously nonzero, it only needs a correction bit.
  166240. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166241. * that we also need to test r > 15. But if r > 15, we can only get here
  166242. * if k > EOB, which implies that this coefficient is not 1.
  166243. */
  166244. if (temp > 1) {
  166245. /* The correction bit is the next bit of the absolute value. */
  166246. BR_buffer[BR++] = (char) (temp & 1);
  166247. continue;
  166248. }
  166249. /* Emit any pending EOBRUN and the BE correction bits */
  166250. emit_eobrun(entropy);
  166251. /* Count/emit Huffman symbol for run length / number of bits */
  166252. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166253. /* Emit output bit for newly-nonzero coef */
  166254. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166255. emit_bits_p(entropy, (unsigned int) temp, 1);
  166256. /* Emit buffered correction bits that must be associated with this code */
  166257. emit_buffered_bits(entropy, BR_buffer, BR);
  166258. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166259. BR = 0;
  166260. r = 0; /* reset zero run length */
  166261. }
  166262. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166263. entropy->EOBRUN++; /* count an EOB */
  166264. entropy->BE += BR; /* concat my correction bits to older ones */
  166265. /* We force out the EOB if we risk either:
  166266. * 1. overflow of the EOB counter;
  166267. * 2. overflow of the correction bit buffer during the next MCU.
  166268. */
  166269. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166270. emit_eobrun(entropy);
  166271. }
  166272. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166273. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166274. /* Update restart-interval state too */
  166275. if (cinfo->restart_interval) {
  166276. if (entropy->restarts_to_go == 0) {
  166277. entropy->restarts_to_go = cinfo->restart_interval;
  166278. entropy->next_restart_num++;
  166279. entropy->next_restart_num &= 7;
  166280. }
  166281. entropy->restarts_to_go--;
  166282. }
  166283. return TRUE;
  166284. }
  166285. /*
  166286. * Finish up at the end of a Huffman-compressed progressive scan.
  166287. */
  166288. METHODDEF(void)
  166289. finish_pass_phuff (j_compress_ptr cinfo)
  166290. {
  166291. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166292. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166293. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166294. /* Flush out any buffered data */
  166295. emit_eobrun(entropy);
  166296. flush_bits_p(entropy);
  166297. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166298. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166299. }
  166300. /*
  166301. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166302. */
  166303. METHODDEF(void)
  166304. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166305. {
  166306. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166307. boolean is_DC_band;
  166308. int ci, tbl;
  166309. jpeg_component_info * compptr;
  166310. JHUFF_TBL **htblptr;
  166311. boolean did[NUM_HUFF_TBLS];
  166312. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166313. emit_eobrun(entropy);
  166314. is_DC_band = (cinfo->Ss == 0);
  166315. /* It's important not to apply jpeg_gen_optimal_table more than once
  166316. * per table, because it clobbers the input frequency counts!
  166317. */
  166318. MEMZERO(did, SIZEOF(did));
  166319. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166320. compptr = cinfo->cur_comp_info[ci];
  166321. if (is_DC_band) {
  166322. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166323. continue;
  166324. tbl = compptr->dc_tbl_no;
  166325. } else {
  166326. tbl = compptr->ac_tbl_no;
  166327. }
  166328. if (! did[tbl]) {
  166329. if (is_DC_band)
  166330. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166331. else
  166332. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166333. if (*htblptr == NULL)
  166334. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166335. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166336. did[tbl] = TRUE;
  166337. }
  166338. }
  166339. }
  166340. /*
  166341. * Module initialization routine for progressive Huffman entropy encoding.
  166342. */
  166343. GLOBAL(void)
  166344. jinit_phuff_encoder (j_compress_ptr cinfo)
  166345. {
  166346. phuff_entropy_ptr entropy;
  166347. int i;
  166348. entropy = (phuff_entropy_ptr)
  166349. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166350. SIZEOF(phuff_entropy_encoder));
  166351. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166352. entropy->pub.start_pass = start_pass_phuff;
  166353. /* Mark tables unallocated */
  166354. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166355. entropy->derived_tbls[i] = NULL;
  166356. entropy->count_ptrs[i] = NULL;
  166357. }
  166358. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166359. }
  166360. #endif /* C_PROGRESSIVE_SUPPORTED */
  166361. /*** End of inlined file: jcphuff.c ***/
  166362. /*** Start of inlined file: jcprepct.c ***/
  166363. #define JPEG_INTERNALS
  166364. /* At present, jcsample.c can request context rows only for smoothing.
  166365. * In the future, we might also need context rows for CCIR601 sampling
  166366. * or other more-complex downsampling procedures. The code to support
  166367. * context rows should be compiled only if needed.
  166368. */
  166369. #ifdef INPUT_SMOOTHING_SUPPORTED
  166370. #define CONTEXT_ROWS_SUPPORTED
  166371. #endif
  166372. /*
  166373. * For the simple (no-context-row) case, we just need to buffer one
  166374. * row group's worth of pixels for the downsampling step. At the bottom of
  166375. * the image, we pad to a full row group by replicating the last pixel row.
  166376. * The downsampler's last output row is then replicated if needed to pad
  166377. * out to a full iMCU row.
  166378. *
  166379. * When providing context rows, we must buffer three row groups' worth of
  166380. * pixels. Three row groups are physically allocated, but the row pointer
  166381. * arrays are made five row groups high, with the extra pointers above and
  166382. * below "wrapping around" to point to the last and first real row groups.
  166383. * This allows the downsampler to access the proper context rows.
  166384. * At the top and bottom of the image, we create dummy context rows by
  166385. * copying the first or last real pixel row. This copying could be avoided
  166386. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166387. * trouble on the compression side.
  166388. */
  166389. /* Private buffer controller object */
  166390. typedef struct {
  166391. struct jpeg_c_prep_controller pub; /* public fields */
  166392. /* Downsampling input buffer. This buffer holds color-converted data
  166393. * until we have enough to do a downsample step.
  166394. */
  166395. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166396. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166397. int next_buf_row; /* index of next row to store in color_buf */
  166398. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166399. int this_row_group; /* starting row index of group to process */
  166400. int next_buf_stop; /* downsample when we reach this index */
  166401. #endif
  166402. } my_prep_controller;
  166403. typedef my_prep_controller * my_prep_ptr;
  166404. /*
  166405. * Initialize for a processing pass.
  166406. */
  166407. METHODDEF(void)
  166408. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166409. {
  166410. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166411. if (pass_mode != JBUF_PASS_THRU)
  166412. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166413. /* Initialize total-height counter for detecting bottom of image */
  166414. prep->rows_to_go = cinfo->image_height;
  166415. /* Mark the conversion buffer empty */
  166416. prep->next_buf_row = 0;
  166417. #ifdef CONTEXT_ROWS_SUPPORTED
  166418. /* Preset additional state variables for context mode.
  166419. * These aren't used in non-context mode, so we needn't test which mode.
  166420. */
  166421. prep->this_row_group = 0;
  166422. /* Set next_buf_stop to stop after two row groups have been read in. */
  166423. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166424. #endif
  166425. }
  166426. /*
  166427. * Expand an image vertically from height input_rows to height output_rows,
  166428. * by duplicating the bottom row.
  166429. */
  166430. LOCAL(void)
  166431. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166432. int input_rows, int output_rows)
  166433. {
  166434. register int row;
  166435. for (row = input_rows; row < output_rows; row++) {
  166436. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166437. 1, num_cols);
  166438. }
  166439. }
  166440. /*
  166441. * Process some data in the simple no-context case.
  166442. *
  166443. * Preprocessor output data is counted in "row groups". A row group
  166444. * is defined to be v_samp_factor sample rows of each component.
  166445. * Downsampling will produce this much data from each max_v_samp_factor
  166446. * input rows.
  166447. */
  166448. METHODDEF(void)
  166449. pre_process_data (j_compress_ptr cinfo,
  166450. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166451. JDIMENSION in_rows_avail,
  166452. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166453. JDIMENSION out_row_groups_avail)
  166454. {
  166455. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166456. int numrows, ci;
  166457. JDIMENSION inrows;
  166458. jpeg_component_info * compptr;
  166459. while (*in_row_ctr < in_rows_avail &&
  166460. *out_row_group_ctr < out_row_groups_avail) {
  166461. /* Do color conversion to fill the conversion buffer. */
  166462. inrows = in_rows_avail - *in_row_ctr;
  166463. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166464. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166465. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166466. prep->color_buf,
  166467. (JDIMENSION) prep->next_buf_row,
  166468. numrows);
  166469. *in_row_ctr += numrows;
  166470. prep->next_buf_row += numrows;
  166471. prep->rows_to_go -= numrows;
  166472. /* If at bottom of image, pad to fill the conversion buffer. */
  166473. if (prep->rows_to_go == 0 &&
  166474. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166475. for (ci = 0; ci < cinfo->num_components; ci++) {
  166476. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166477. prep->next_buf_row, cinfo->max_v_samp_factor);
  166478. }
  166479. prep->next_buf_row = cinfo->max_v_samp_factor;
  166480. }
  166481. /* If we've filled the conversion buffer, empty it. */
  166482. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166483. (*cinfo->downsample->downsample) (cinfo,
  166484. prep->color_buf, (JDIMENSION) 0,
  166485. output_buf, *out_row_group_ctr);
  166486. prep->next_buf_row = 0;
  166487. (*out_row_group_ctr)++;
  166488. }
  166489. /* If at bottom of image, pad the output to a full iMCU height.
  166490. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166491. */
  166492. if (prep->rows_to_go == 0 &&
  166493. *out_row_group_ctr < out_row_groups_avail) {
  166494. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166495. ci++, compptr++) {
  166496. expand_bottom_edge(output_buf[ci],
  166497. compptr->width_in_blocks * DCTSIZE,
  166498. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166499. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166500. }
  166501. *out_row_group_ctr = out_row_groups_avail;
  166502. break; /* can exit outer loop without test */
  166503. }
  166504. }
  166505. }
  166506. #ifdef CONTEXT_ROWS_SUPPORTED
  166507. /*
  166508. * Process some data in the context case.
  166509. */
  166510. METHODDEF(void)
  166511. pre_process_context (j_compress_ptr cinfo,
  166512. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166513. JDIMENSION in_rows_avail,
  166514. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166515. JDIMENSION out_row_groups_avail)
  166516. {
  166517. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166518. int numrows, ci;
  166519. int buf_height = cinfo->max_v_samp_factor * 3;
  166520. JDIMENSION inrows;
  166521. while (*out_row_group_ctr < out_row_groups_avail) {
  166522. if (*in_row_ctr < in_rows_avail) {
  166523. /* Do color conversion to fill the conversion buffer. */
  166524. inrows = in_rows_avail - *in_row_ctr;
  166525. numrows = prep->next_buf_stop - prep->next_buf_row;
  166526. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166527. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166528. prep->color_buf,
  166529. (JDIMENSION) prep->next_buf_row,
  166530. numrows);
  166531. /* Pad at top of image, if first time through */
  166532. if (prep->rows_to_go == cinfo->image_height) {
  166533. for (ci = 0; ci < cinfo->num_components; ci++) {
  166534. int row;
  166535. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166536. jcopy_sample_rows(prep->color_buf[ci], 0,
  166537. prep->color_buf[ci], -row,
  166538. 1, cinfo->image_width);
  166539. }
  166540. }
  166541. }
  166542. *in_row_ctr += numrows;
  166543. prep->next_buf_row += numrows;
  166544. prep->rows_to_go -= numrows;
  166545. } else {
  166546. /* Return for more data, unless we are at the bottom of the image. */
  166547. if (prep->rows_to_go != 0)
  166548. break;
  166549. /* When at bottom of image, pad to fill the conversion buffer. */
  166550. if (prep->next_buf_row < prep->next_buf_stop) {
  166551. for (ci = 0; ci < cinfo->num_components; ci++) {
  166552. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166553. prep->next_buf_row, prep->next_buf_stop);
  166554. }
  166555. prep->next_buf_row = prep->next_buf_stop;
  166556. }
  166557. }
  166558. /* If we've gotten enough data, downsample a row group. */
  166559. if (prep->next_buf_row == prep->next_buf_stop) {
  166560. (*cinfo->downsample->downsample) (cinfo,
  166561. prep->color_buf,
  166562. (JDIMENSION) prep->this_row_group,
  166563. output_buf, *out_row_group_ctr);
  166564. (*out_row_group_ctr)++;
  166565. /* Advance pointers with wraparound as necessary. */
  166566. prep->this_row_group += cinfo->max_v_samp_factor;
  166567. if (prep->this_row_group >= buf_height)
  166568. prep->this_row_group = 0;
  166569. if (prep->next_buf_row >= buf_height)
  166570. prep->next_buf_row = 0;
  166571. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166572. }
  166573. }
  166574. }
  166575. /*
  166576. * Create the wrapped-around downsampling input buffer needed for context mode.
  166577. */
  166578. LOCAL(void)
  166579. create_context_buffer (j_compress_ptr cinfo)
  166580. {
  166581. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166582. int rgroup_height = cinfo->max_v_samp_factor;
  166583. int ci, i;
  166584. jpeg_component_info * compptr;
  166585. JSAMPARRAY true_buffer, fake_buffer;
  166586. /* Grab enough space for fake row pointers for all the components;
  166587. * we need five row groups' worth of pointers for each component.
  166588. */
  166589. fake_buffer = (JSAMPARRAY)
  166590. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166591. (cinfo->num_components * 5 * rgroup_height) *
  166592. SIZEOF(JSAMPROW));
  166593. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166594. ci++, compptr++) {
  166595. /* Allocate the actual buffer space (3 row groups) for this component.
  166596. * We make the buffer wide enough to allow the downsampler to edge-expand
  166597. * horizontally within the buffer, if it so chooses.
  166598. */
  166599. true_buffer = (*cinfo->mem->alloc_sarray)
  166600. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166601. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166602. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166603. (JDIMENSION) (3 * rgroup_height));
  166604. /* Copy true buffer row pointers into the middle of the fake row array */
  166605. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166606. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166607. /* Fill in the above and below wraparound pointers */
  166608. for (i = 0; i < rgroup_height; i++) {
  166609. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166610. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166611. }
  166612. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166613. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166614. }
  166615. }
  166616. #endif /* CONTEXT_ROWS_SUPPORTED */
  166617. /*
  166618. * Initialize preprocessing controller.
  166619. */
  166620. GLOBAL(void)
  166621. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166622. {
  166623. my_prep_ptr prep;
  166624. int ci;
  166625. jpeg_component_info * compptr;
  166626. if (need_full_buffer) /* safety check */
  166627. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166628. prep = (my_prep_ptr)
  166629. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166630. SIZEOF(my_prep_controller));
  166631. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166632. prep->pub.start_pass = start_pass_prep;
  166633. /* Allocate the color conversion buffer.
  166634. * We make the buffer wide enough to allow the downsampler to edge-expand
  166635. * horizontally within the buffer, if it so chooses.
  166636. */
  166637. if (cinfo->downsample->need_context_rows) {
  166638. /* Set up to provide context rows */
  166639. #ifdef CONTEXT_ROWS_SUPPORTED
  166640. prep->pub.pre_process_data = pre_process_context;
  166641. create_context_buffer(cinfo);
  166642. #else
  166643. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166644. #endif
  166645. } else {
  166646. /* No context, just make it tall enough for one row group */
  166647. prep->pub.pre_process_data = pre_process_data;
  166648. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166649. ci++, compptr++) {
  166650. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166651. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166652. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166653. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166654. (JDIMENSION) cinfo->max_v_samp_factor);
  166655. }
  166656. }
  166657. }
  166658. /*** End of inlined file: jcprepct.c ***/
  166659. /*** Start of inlined file: jcsample.c ***/
  166660. #define JPEG_INTERNALS
  166661. /* Pointer to routine to downsample a single component */
  166662. typedef JMETHOD(void, downsample1_ptr,
  166663. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166664. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166665. /* Private subobject */
  166666. typedef struct {
  166667. struct jpeg_downsampler pub; /* public fields */
  166668. /* Downsampling method pointers, one per component */
  166669. downsample1_ptr methods[MAX_COMPONENTS];
  166670. } my_downsampler;
  166671. typedef my_downsampler * my_downsample_ptr;
  166672. /*
  166673. * Initialize for a downsampling pass.
  166674. */
  166675. METHODDEF(void)
  166676. start_pass_downsample (j_compress_ptr)
  166677. {
  166678. /* no work for now */
  166679. }
  166680. /*
  166681. * Expand a component horizontally from width input_cols to width output_cols,
  166682. * by duplicating the rightmost samples.
  166683. */
  166684. LOCAL(void)
  166685. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166686. JDIMENSION input_cols, JDIMENSION output_cols)
  166687. {
  166688. register JSAMPROW ptr;
  166689. register JSAMPLE pixval;
  166690. register int count;
  166691. int row;
  166692. int numcols = (int) (output_cols - input_cols);
  166693. if (numcols > 0) {
  166694. for (row = 0; row < num_rows; row++) {
  166695. ptr = image_data[row] + input_cols;
  166696. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166697. for (count = numcols; count > 0; count--)
  166698. *ptr++ = pixval;
  166699. }
  166700. }
  166701. }
  166702. /*
  166703. * Do downsampling for a whole row group (all components).
  166704. *
  166705. * In this version we simply downsample each component independently.
  166706. */
  166707. METHODDEF(void)
  166708. sep_downsample (j_compress_ptr cinfo,
  166709. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166710. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166711. {
  166712. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166713. int ci;
  166714. jpeg_component_info * compptr;
  166715. JSAMPARRAY in_ptr, out_ptr;
  166716. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166717. ci++, compptr++) {
  166718. in_ptr = input_buf[ci] + in_row_index;
  166719. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166720. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166721. }
  166722. }
  166723. /*
  166724. * Downsample pixel values of a single component.
  166725. * One row group is processed per call.
  166726. * This version handles arbitrary integral sampling ratios, without smoothing.
  166727. * Note that this version is not actually used for customary sampling ratios.
  166728. */
  166729. METHODDEF(void)
  166730. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166731. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166732. {
  166733. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166734. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166735. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166736. JSAMPROW inptr, outptr;
  166737. INT32 outvalue;
  166738. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166739. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166740. numpix = h_expand * v_expand;
  166741. numpix2 = numpix/2;
  166742. /* Expand input data enough to let all the output samples be generated
  166743. * by the standard loop. Special-casing padded output would be more
  166744. * efficient.
  166745. */
  166746. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166747. cinfo->image_width, output_cols * h_expand);
  166748. inrow = 0;
  166749. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166750. outptr = output_data[outrow];
  166751. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166752. outcol++, outcol_h += h_expand) {
  166753. outvalue = 0;
  166754. for (v = 0; v < v_expand; v++) {
  166755. inptr = input_data[inrow+v] + outcol_h;
  166756. for (h = 0; h < h_expand; h++) {
  166757. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166758. }
  166759. }
  166760. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166761. }
  166762. inrow += v_expand;
  166763. }
  166764. }
  166765. /*
  166766. * Downsample pixel values of a single component.
  166767. * This version handles the special case of a full-size component,
  166768. * without smoothing.
  166769. */
  166770. METHODDEF(void)
  166771. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166772. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166773. {
  166774. /* Copy the data */
  166775. jcopy_sample_rows(input_data, 0, output_data, 0,
  166776. cinfo->max_v_samp_factor, cinfo->image_width);
  166777. /* Edge-expand */
  166778. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166779. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166780. }
  166781. /*
  166782. * Downsample pixel values of a single component.
  166783. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166784. * without smoothing.
  166785. *
  166786. * A note about the "bias" calculations: when rounding fractional values to
  166787. * integer, we do not want to always round 0.5 up to the next integer.
  166788. * If we did that, we'd introduce a noticeable bias towards larger values.
  166789. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166790. * alternate pixel locations (a simple ordered dither pattern).
  166791. */
  166792. METHODDEF(void)
  166793. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166794. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166795. {
  166796. int outrow;
  166797. JDIMENSION outcol;
  166798. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166799. register JSAMPROW inptr, outptr;
  166800. register int bias;
  166801. /* Expand input data enough to let all the output samples be generated
  166802. * by the standard loop. Special-casing padded output would be more
  166803. * efficient.
  166804. */
  166805. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166806. cinfo->image_width, output_cols * 2);
  166807. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166808. outptr = output_data[outrow];
  166809. inptr = input_data[outrow];
  166810. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166811. for (outcol = 0; outcol < output_cols; outcol++) {
  166812. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166813. + bias) >> 1);
  166814. bias ^= 1; /* 0=>1, 1=>0 */
  166815. inptr += 2;
  166816. }
  166817. }
  166818. }
  166819. /*
  166820. * Downsample pixel values of a single component.
  166821. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166822. * without smoothing.
  166823. */
  166824. METHODDEF(void)
  166825. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166826. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166827. {
  166828. int inrow, outrow;
  166829. JDIMENSION outcol;
  166830. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166831. register JSAMPROW inptr0, inptr1, outptr;
  166832. register int bias;
  166833. /* Expand input data enough to let all the output samples be generated
  166834. * by the standard loop. Special-casing padded output would be more
  166835. * efficient.
  166836. */
  166837. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166838. cinfo->image_width, output_cols * 2);
  166839. inrow = 0;
  166840. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166841. outptr = output_data[outrow];
  166842. inptr0 = input_data[inrow];
  166843. inptr1 = input_data[inrow+1];
  166844. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166845. for (outcol = 0; outcol < output_cols; outcol++) {
  166846. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166847. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166848. + bias) >> 2);
  166849. bias ^= 3; /* 1=>2, 2=>1 */
  166850. inptr0 += 2; inptr1 += 2;
  166851. }
  166852. inrow += 2;
  166853. }
  166854. }
  166855. #ifdef INPUT_SMOOTHING_SUPPORTED
  166856. /*
  166857. * Downsample pixel values of a single component.
  166858. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166859. * with smoothing. One row of context is required.
  166860. */
  166861. METHODDEF(void)
  166862. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166863. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166864. {
  166865. int inrow, outrow;
  166866. JDIMENSION colctr;
  166867. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166868. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166869. INT32 membersum, neighsum, memberscale, neighscale;
  166870. /* Expand input data enough to let all the output samples be generated
  166871. * by the standard loop. Special-casing padded output would be more
  166872. * efficient.
  166873. */
  166874. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166875. cinfo->image_width, output_cols * 2);
  166876. /* We don't bother to form the individual "smoothed" input pixel values;
  166877. * we can directly compute the output which is the average of the four
  166878. * smoothed values. Each of the four member pixels contributes a fraction
  166879. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166880. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166881. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166882. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166883. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166884. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166885. * factors are scaled by 2^16 = 65536.
  166886. * Also recall that SF = smoothing_factor / 1024.
  166887. */
  166888. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166889. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166890. inrow = 0;
  166891. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166892. outptr = output_data[outrow];
  166893. inptr0 = input_data[inrow];
  166894. inptr1 = input_data[inrow+1];
  166895. above_ptr = input_data[inrow-1];
  166896. below_ptr = input_data[inrow+2];
  166897. /* Special case for first column: pretend column -1 is same as column 0 */
  166898. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166899. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166900. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166901. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166902. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166903. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166904. neighsum += neighsum;
  166905. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166906. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166907. membersum = membersum * memberscale + neighsum * neighscale;
  166908. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166909. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166910. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166911. /* sum of pixels directly mapped to this output element */
  166912. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166913. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166914. /* sum of edge-neighbor pixels */
  166915. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166916. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166917. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166918. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166919. /* The edge-neighbors count twice as much as corner-neighbors */
  166920. neighsum += neighsum;
  166921. /* Add in the corner-neighbors */
  166922. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166923. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166924. /* form final output scaled up by 2^16 */
  166925. membersum = membersum * memberscale + neighsum * neighscale;
  166926. /* round, descale and output it */
  166927. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166928. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166929. }
  166930. /* Special case for last column */
  166931. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166932. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166933. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166934. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166935. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166936. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166937. neighsum += neighsum;
  166938. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166939. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166940. membersum = membersum * memberscale + neighsum * neighscale;
  166941. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166942. inrow += 2;
  166943. }
  166944. }
  166945. /*
  166946. * Downsample pixel values of a single component.
  166947. * This version handles the special case of a full-size component,
  166948. * with smoothing. One row of context is required.
  166949. */
  166950. METHODDEF(void)
  166951. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166952. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166953. {
  166954. int outrow;
  166955. JDIMENSION colctr;
  166956. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166957. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166958. INT32 membersum, neighsum, memberscale, neighscale;
  166959. int colsum, lastcolsum, nextcolsum;
  166960. /* Expand input data enough to let all the output samples be generated
  166961. * by the standard loop. Special-casing padded output would be more
  166962. * efficient.
  166963. */
  166964. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166965. cinfo->image_width, output_cols);
  166966. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166967. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166968. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166969. * Also recall that SF = smoothing_factor / 1024.
  166970. */
  166971. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166972. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166973. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166974. outptr = output_data[outrow];
  166975. inptr = input_data[outrow];
  166976. above_ptr = input_data[outrow-1];
  166977. below_ptr = input_data[outrow+1];
  166978. /* Special case for first column */
  166979. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166980. GETJSAMPLE(*inptr);
  166981. membersum = GETJSAMPLE(*inptr++);
  166982. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166983. GETJSAMPLE(*inptr);
  166984. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166985. membersum = membersum * memberscale + neighsum * neighscale;
  166986. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166987. lastcolsum = colsum; colsum = nextcolsum;
  166988. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166989. membersum = GETJSAMPLE(*inptr++);
  166990. above_ptr++; below_ptr++;
  166991. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166992. GETJSAMPLE(*inptr);
  166993. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166994. membersum = membersum * memberscale + neighsum * neighscale;
  166995. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166996. lastcolsum = colsum; colsum = nextcolsum;
  166997. }
  166998. /* Special case for last column */
  166999. membersum = GETJSAMPLE(*inptr);
  167000. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167001. membersum = membersum * memberscale + neighsum * neighscale;
  167002. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167003. }
  167004. }
  167005. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167006. /*
  167007. * Module initialization routine for downsampling.
  167008. * Note that we must select a routine for each component.
  167009. */
  167010. GLOBAL(void)
  167011. jinit_downsampler (j_compress_ptr cinfo)
  167012. {
  167013. my_downsample_ptr downsample;
  167014. int ci;
  167015. jpeg_component_info * compptr;
  167016. boolean smoothok = TRUE;
  167017. downsample = (my_downsample_ptr)
  167018. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167019. SIZEOF(my_downsampler));
  167020. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167021. downsample->pub.start_pass = start_pass_downsample;
  167022. downsample->pub.downsample = sep_downsample;
  167023. downsample->pub.need_context_rows = FALSE;
  167024. if (cinfo->CCIR601_sampling)
  167025. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167026. /* Verify we can handle the sampling factors, and set up method pointers */
  167027. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167028. ci++, compptr++) {
  167029. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167030. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167031. #ifdef INPUT_SMOOTHING_SUPPORTED
  167032. if (cinfo->smoothing_factor) {
  167033. downsample->methods[ci] = fullsize_smooth_downsample;
  167034. downsample->pub.need_context_rows = TRUE;
  167035. } else
  167036. #endif
  167037. downsample->methods[ci] = fullsize_downsample;
  167038. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167039. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167040. smoothok = FALSE;
  167041. downsample->methods[ci] = h2v1_downsample;
  167042. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167043. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167044. #ifdef INPUT_SMOOTHING_SUPPORTED
  167045. if (cinfo->smoothing_factor) {
  167046. downsample->methods[ci] = h2v2_smooth_downsample;
  167047. downsample->pub.need_context_rows = TRUE;
  167048. } else
  167049. #endif
  167050. downsample->methods[ci] = h2v2_downsample;
  167051. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167052. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167053. smoothok = FALSE;
  167054. downsample->methods[ci] = int_downsample;
  167055. } else
  167056. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167057. }
  167058. #ifdef INPUT_SMOOTHING_SUPPORTED
  167059. if (cinfo->smoothing_factor && !smoothok)
  167060. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167061. #endif
  167062. }
  167063. /*** End of inlined file: jcsample.c ***/
  167064. /*** Start of inlined file: jctrans.c ***/
  167065. #define JPEG_INTERNALS
  167066. /* Forward declarations */
  167067. LOCAL(void) transencode_master_selection
  167068. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167069. LOCAL(void) transencode_coef_controller
  167070. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167071. /*
  167072. * Compression initialization for writing raw-coefficient data.
  167073. * Before calling this, all parameters and a data destination must be set up.
  167074. * Call jpeg_finish_compress() to actually write the data.
  167075. *
  167076. * The number of passed virtual arrays must match cinfo->num_components.
  167077. * Note that the virtual arrays need not be filled or even realized at
  167078. * the time write_coefficients is called; indeed, if the virtual arrays
  167079. * were requested from this compression object's memory manager, they
  167080. * typically will be realized during this routine and filled afterwards.
  167081. */
  167082. GLOBAL(void)
  167083. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167084. {
  167085. if (cinfo->global_state != CSTATE_START)
  167086. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167087. /* Mark all tables to be written */
  167088. jpeg_suppress_tables(cinfo, FALSE);
  167089. /* (Re)initialize error mgr and destination modules */
  167090. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167091. (*cinfo->dest->init_destination) (cinfo);
  167092. /* Perform master selection of active modules */
  167093. transencode_master_selection(cinfo, coef_arrays);
  167094. /* Wait for jpeg_finish_compress() call */
  167095. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167096. cinfo->global_state = CSTATE_WRCOEFS;
  167097. }
  167098. /*
  167099. * Initialize the compression object with default parameters,
  167100. * then copy from the source object all parameters needed for lossless
  167101. * transcoding. Parameters that can be varied without loss (such as
  167102. * scan script and Huffman optimization) are left in their default states.
  167103. */
  167104. GLOBAL(void)
  167105. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167106. j_compress_ptr dstinfo)
  167107. {
  167108. JQUANT_TBL ** qtblptr;
  167109. jpeg_component_info *incomp, *outcomp;
  167110. JQUANT_TBL *c_quant, *slot_quant;
  167111. int tblno, ci, coefi;
  167112. /* Safety check to ensure start_compress not called yet. */
  167113. if (dstinfo->global_state != CSTATE_START)
  167114. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167115. /* Copy fundamental image dimensions */
  167116. dstinfo->image_width = srcinfo->image_width;
  167117. dstinfo->image_height = srcinfo->image_height;
  167118. dstinfo->input_components = srcinfo->num_components;
  167119. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167120. /* Initialize all parameters to default values */
  167121. jpeg_set_defaults(dstinfo);
  167122. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167123. * Fix it to get the right header markers for the image colorspace.
  167124. */
  167125. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167126. dstinfo->data_precision = srcinfo->data_precision;
  167127. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167128. /* Copy the source's quantization tables. */
  167129. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167130. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167131. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167132. if (*qtblptr == NULL)
  167133. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167134. MEMCOPY((*qtblptr)->quantval,
  167135. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167136. SIZEOF((*qtblptr)->quantval));
  167137. (*qtblptr)->sent_table = FALSE;
  167138. }
  167139. }
  167140. /* Copy the source's per-component info.
  167141. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167142. */
  167143. dstinfo->num_components = srcinfo->num_components;
  167144. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167145. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167146. MAX_COMPONENTS);
  167147. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167148. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167149. outcomp->component_id = incomp->component_id;
  167150. outcomp->h_samp_factor = incomp->h_samp_factor;
  167151. outcomp->v_samp_factor = incomp->v_samp_factor;
  167152. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167153. /* Make sure saved quantization table for component matches the qtable
  167154. * slot. If not, the input file re-used this qtable slot.
  167155. * IJG encoder currently cannot duplicate this.
  167156. */
  167157. tblno = outcomp->quant_tbl_no;
  167158. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167159. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167160. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167161. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167162. c_quant = incomp->quant_table;
  167163. if (c_quant != NULL) {
  167164. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167165. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167166. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167167. }
  167168. }
  167169. /* Note: we do not copy the source's Huffman table assignments;
  167170. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167171. */
  167172. }
  167173. /* Also copy JFIF version and resolution information, if available.
  167174. * Strictly speaking this isn't "critical" info, but it's nearly
  167175. * always appropriate to copy it if available. In particular,
  167176. * if the application chooses to copy JFIF 1.02 extension markers from
  167177. * the source file, we need to copy the version to make sure we don't
  167178. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167179. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167180. */
  167181. if (srcinfo->saw_JFIF_marker) {
  167182. if (srcinfo->JFIF_major_version == 1) {
  167183. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167184. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167185. }
  167186. dstinfo->density_unit = srcinfo->density_unit;
  167187. dstinfo->X_density = srcinfo->X_density;
  167188. dstinfo->Y_density = srcinfo->Y_density;
  167189. }
  167190. }
  167191. /*
  167192. * Master selection of compression modules for transcoding.
  167193. * This substitutes for jcinit.c's initialization of the full compressor.
  167194. */
  167195. LOCAL(void)
  167196. transencode_master_selection (j_compress_ptr cinfo,
  167197. jvirt_barray_ptr * coef_arrays)
  167198. {
  167199. /* Although we don't actually use input_components for transcoding,
  167200. * jcmaster.c's initial_setup will complain if input_components is 0.
  167201. */
  167202. cinfo->input_components = 1;
  167203. /* Initialize master control (includes parameter checking/processing) */
  167204. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167205. /* Entropy encoding: either Huffman or arithmetic coding. */
  167206. if (cinfo->arith_code) {
  167207. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167208. } else {
  167209. if (cinfo->progressive_mode) {
  167210. #ifdef C_PROGRESSIVE_SUPPORTED
  167211. jinit_phuff_encoder(cinfo);
  167212. #else
  167213. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167214. #endif
  167215. } else
  167216. jinit_huff_encoder(cinfo);
  167217. }
  167218. /* We need a special coefficient buffer controller. */
  167219. transencode_coef_controller(cinfo, coef_arrays);
  167220. jinit_marker_writer(cinfo);
  167221. /* We can now tell the memory manager to allocate virtual arrays. */
  167222. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167223. /* Write the datastream header (SOI, JFIF) immediately.
  167224. * Frame and scan headers are postponed till later.
  167225. * This lets application insert special markers after the SOI.
  167226. */
  167227. (*cinfo->marker->write_file_header) (cinfo);
  167228. }
  167229. /*
  167230. * The rest of this file is a special implementation of the coefficient
  167231. * buffer controller. This is similar to jccoefct.c, but it handles only
  167232. * output from presupplied virtual arrays. Furthermore, we generate any
  167233. * dummy padding blocks on-the-fly rather than expecting them to be present
  167234. * in the arrays.
  167235. */
  167236. /* Private buffer controller object */
  167237. typedef struct {
  167238. struct jpeg_c_coef_controller pub; /* public fields */
  167239. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167240. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167241. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167242. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167243. /* Virtual block array for each component. */
  167244. jvirt_barray_ptr * whole_image;
  167245. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167246. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167247. } my_coef_controller2;
  167248. typedef my_coef_controller2 * my_coef_ptr2;
  167249. LOCAL(void)
  167250. start_iMCU_row2 (j_compress_ptr cinfo)
  167251. /* Reset within-iMCU-row counters for a new row */
  167252. {
  167253. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167254. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167255. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167256. * But at the bottom of the image, process only what's left.
  167257. */
  167258. if (cinfo->comps_in_scan > 1) {
  167259. coef->MCU_rows_per_iMCU_row = 1;
  167260. } else {
  167261. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167262. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167263. else
  167264. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167265. }
  167266. coef->mcu_ctr = 0;
  167267. coef->MCU_vert_offset = 0;
  167268. }
  167269. /*
  167270. * Initialize for a processing pass.
  167271. */
  167272. METHODDEF(void)
  167273. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167274. {
  167275. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167276. if (pass_mode != JBUF_CRANK_DEST)
  167277. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167278. coef->iMCU_row_num = 0;
  167279. start_iMCU_row2(cinfo);
  167280. }
  167281. /*
  167282. * Process some data.
  167283. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167284. * per call, ie, v_samp_factor block rows for each component in the scan.
  167285. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167286. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167287. *
  167288. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167289. */
  167290. METHODDEF(boolean)
  167291. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167292. {
  167293. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167294. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167295. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167296. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167297. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167298. JDIMENSION start_col;
  167299. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167300. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167301. JBLOCKROW buffer_ptr;
  167302. jpeg_component_info *compptr;
  167303. /* Align the virtual buffers for the components used in this scan. */
  167304. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167305. compptr = cinfo->cur_comp_info[ci];
  167306. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167307. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167308. coef->iMCU_row_num * compptr->v_samp_factor,
  167309. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167310. }
  167311. /* Loop to process one whole iMCU row */
  167312. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167313. yoffset++) {
  167314. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167315. MCU_col_num++) {
  167316. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167317. blkn = 0; /* index of current DCT block within MCU */
  167318. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167319. compptr = cinfo->cur_comp_info[ci];
  167320. start_col = MCU_col_num * compptr->MCU_width;
  167321. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167322. : compptr->last_col_width;
  167323. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167324. if (coef->iMCU_row_num < last_iMCU_row ||
  167325. yindex+yoffset < compptr->last_row_height) {
  167326. /* Fill in pointers to real blocks in this row */
  167327. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167328. for (xindex = 0; xindex < blockcnt; xindex++)
  167329. MCU_buffer[blkn++] = buffer_ptr++;
  167330. } else {
  167331. /* At bottom of image, need a whole row of dummy blocks */
  167332. xindex = 0;
  167333. }
  167334. /* Fill in any dummy blocks needed in this row.
  167335. * Dummy blocks are filled in the same way as in jccoefct.c:
  167336. * all zeroes in the AC entries, DC entries equal to previous
  167337. * block's DC value. The init routine has already zeroed the
  167338. * AC entries, so we need only set the DC entries correctly.
  167339. */
  167340. for (; xindex < compptr->MCU_width; xindex++) {
  167341. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167342. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167343. blkn++;
  167344. }
  167345. }
  167346. }
  167347. /* Try to write the MCU. */
  167348. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167349. /* Suspension forced; update state counters and exit */
  167350. coef->MCU_vert_offset = yoffset;
  167351. coef->mcu_ctr = MCU_col_num;
  167352. return FALSE;
  167353. }
  167354. }
  167355. /* Completed an MCU row, but perhaps not an iMCU row */
  167356. coef->mcu_ctr = 0;
  167357. }
  167358. /* Completed the iMCU row, advance counters for next one */
  167359. coef->iMCU_row_num++;
  167360. start_iMCU_row2(cinfo);
  167361. return TRUE;
  167362. }
  167363. /*
  167364. * Initialize coefficient buffer controller.
  167365. *
  167366. * Each passed coefficient array must be the right size for that
  167367. * coefficient: width_in_blocks wide and height_in_blocks high,
  167368. * with unitheight at least v_samp_factor.
  167369. */
  167370. LOCAL(void)
  167371. transencode_coef_controller (j_compress_ptr cinfo,
  167372. jvirt_barray_ptr * coef_arrays)
  167373. {
  167374. my_coef_ptr2 coef;
  167375. JBLOCKROW buffer;
  167376. int i;
  167377. coef = (my_coef_ptr2)
  167378. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167379. SIZEOF(my_coef_controller2));
  167380. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167381. coef->pub.start_pass = start_pass_coef2;
  167382. coef->pub.compress_data = compress_output2;
  167383. /* Save pointer to virtual arrays */
  167384. coef->whole_image = coef_arrays;
  167385. /* Allocate and pre-zero space for dummy DCT blocks. */
  167386. buffer = (JBLOCKROW)
  167387. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167388. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167389. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167390. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167391. coef->dummy_buffer[i] = buffer + i;
  167392. }
  167393. }
  167394. /*** End of inlined file: jctrans.c ***/
  167395. /*** Start of inlined file: jdapistd.c ***/
  167396. #define JPEG_INTERNALS
  167397. /* Forward declarations */
  167398. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167399. /*
  167400. * Decompression initialization.
  167401. * jpeg_read_header must be completed before calling this.
  167402. *
  167403. * If a multipass operating mode was selected, this will do all but the
  167404. * last pass, and thus may take a great deal of time.
  167405. *
  167406. * Returns FALSE if suspended. The return value need be inspected only if
  167407. * a suspending data source is used.
  167408. */
  167409. GLOBAL(boolean)
  167410. jpeg_start_decompress (j_decompress_ptr cinfo)
  167411. {
  167412. if (cinfo->global_state == DSTATE_READY) {
  167413. /* First call: initialize master control, select active modules */
  167414. jinit_master_decompress(cinfo);
  167415. if (cinfo->buffered_image) {
  167416. /* No more work here; expecting jpeg_start_output next */
  167417. cinfo->global_state = DSTATE_BUFIMAGE;
  167418. return TRUE;
  167419. }
  167420. cinfo->global_state = DSTATE_PRELOAD;
  167421. }
  167422. if (cinfo->global_state == DSTATE_PRELOAD) {
  167423. /* If file has multiple scans, absorb them all into the coef buffer */
  167424. if (cinfo->inputctl->has_multiple_scans) {
  167425. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167426. for (;;) {
  167427. int retcode;
  167428. /* Call progress monitor hook if present */
  167429. if (cinfo->progress != NULL)
  167430. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167431. /* Absorb some more input */
  167432. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167433. if (retcode == JPEG_SUSPENDED)
  167434. return FALSE;
  167435. if (retcode == JPEG_REACHED_EOI)
  167436. break;
  167437. /* Advance progress counter if appropriate */
  167438. if (cinfo->progress != NULL &&
  167439. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167440. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167441. /* jdmaster underestimated number of scans; ratchet up one scan */
  167442. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167443. }
  167444. }
  167445. }
  167446. #else
  167447. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167448. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167449. }
  167450. cinfo->output_scan_number = cinfo->input_scan_number;
  167451. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167452. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167453. /* Perform any dummy output passes, and set up for the final pass */
  167454. return output_pass_setup(cinfo);
  167455. }
  167456. /*
  167457. * Set up for an output pass, and perform any dummy pass(es) needed.
  167458. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167459. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167460. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167461. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167462. */
  167463. LOCAL(boolean)
  167464. output_pass_setup (j_decompress_ptr cinfo)
  167465. {
  167466. if (cinfo->global_state != DSTATE_PRESCAN) {
  167467. /* First call: do pass setup */
  167468. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167469. cinfo->output_scanline = 0;
  167470. cinfo->global_state = DSTATE_PRESCAN;
  167471. }
  167472. /* Loop over any required dummy passes */
  167473. while (cinfo->master->is_dummy_pass) {
  167474. #ifdef QUANT_2PASS_SUPPORTED
  167475. /* Crank through the dummy pass */
  167476. while (cinfo->output_scanline < cinfo->output_height) {
  167477. JDIMENSION last_scanline;
  167478. /* Call progress monitor hook if present */
  167479. if (cinfo->progress != NULL) {
  167480. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167481. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167482. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167483. }
  167484. /* Process some data */
  167485. last_scanline = cinfo->output_scanline;
  167486. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167487. &cinfo->output_scanline, (JDIMENSION) 0);
  167488. if (cinfo->output_scanline == last_scanline)
  167489. return FALSE; /* No progress made, must suspend */
  167490. }
  167491. /* Finish up dummy pass, and set up for another one */
  167492. (*cinfo->master->finish_output_pass) (cinfo);
  167493. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167494. cinfo->output_scanline = 0;
  167495. #else
  167496. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167497. #endif /* QUANT_2PASS_SUPPORTED */
  167498. }
  167499. /* Ready for application to drive output pass through
  167500. * jpeg_read_scanlines or jpeg_read_raw_data.
  167501. */
  167502. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167503. return TRUE;
  167504. }
  167505. /*
  167506. * Read some scanlines of data from the JPEG decompressor.
  167507. *
  167508. * The return value will be the number of lines actually read.
  167509. * This may be less than the number requested in several cases,
  167510. * including bottom of image, data source suspension, and operating
  167511. * modes that emit multiple scanlines at a time.
  167512. *
  167513. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167514. * this likely signals an application programmer error. However,
  167515. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167516. */
  167517. GLOBAL(JDIMENSION)
  167518. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167519. JDIMENSION max_lines)
  167520. {
  167521. JDIMENSION row_ctr;
  167522. if (cinfo->global_state != DSTATE_SCANNING)
  167523. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167524. if (cinfo->output_scanline >= cinfo->output_height) {
  167525. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167526. return 0;
  167527. }
  167528. /* Call progress monitor hook if present */
  167529. if (cinfo->progress != NULL) {
  167530. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167531. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167532. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167533. }
  167534. /* Process some data */
  167535. row_ctr = 0;
  167536. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167537. cinfo->output_scanline += row_ctr;
  167538. return row_ctr;
  167539. }
  167540. /*
  167541. * Alternate entry point to read raw data.
  167542. * Processes exactly one iMCU row per call, unless suspended.
  167543. */
  167544. GLOBAL(JDIMENSION)
  167545. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167546. JDIMENSION max_lines)
  167547. {
  167548. JDIMENSION lines_per_iMCU_row;
  167549. if (cinfo->global_state != DSTATE_RAW_OK)
  167550. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167551. if (cinfo->output_scanline >= cinfo->output_height) {
  167552. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167553. return 0;
  167554. }
  167555. /* Call progress monitor hook if present */
  167556. if (cinfo->progress != NULL) {
  167557. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167558. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167559. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167560. }
  167561. /* Verify that at least one iMCU row can be returned. */
  167562. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167563. if (max_lines < lines_per_iMCU_row)
  167564. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167565. /* Decompress directly into user's buffer. */
  167566. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167567. return 0; /* suspension forced, can do nothing more */
  167568. /* OK, we processed one iMCU row. */
  167569. cinfo->output_scanline += lines_per_iMCU_row;
  167570. return lines_per_iMCU_row;
  167571. }
  167572. /* Additional entry points for buffered-image mode. */
  167573. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167574. /*
  167575. * Initialize for an output pass in buffered-image mode.
  167576. */
  167577. GLOBAL(boolean)
  167578. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167579. {
  167580. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167581. cinfo->global_state != DSTATE_PRESCAN)
  167582. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167583. /* Limit scan number to valid range */
  167584. if (scan_number <= 0)
  167585. scan_number = 1;
  167586. if (cinfo->inputctl->eoi_reached &&
  167587. scan_number > cinfo->input_scan_number)
  167588. scan_number = cinfo->input_scan_number;
  167589. cinfo->output_scan_number = scan_number;
  167590. /* Perform any dummy output passes, and set up for the real pass */
  167591. return output_pass_setup(cinfo);
  167592. }
  167593. /*
  167594. * Finish up after an output pass in buffered-image mode.
  167595. *
  167596. * Returns FALSE if suspended. The return value need be inspected only if
  167597. * a suspending data source is used.
  167598. */
  167599. GLOBAL(boolean)
  167600. jpeg_finish_output (j_decompress_ptr cinfo)
  167601. {
  167602. if ((cinfo->global_state == DSTATE_SCANNING ||
  167603. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167604. /* Terminate this pass. */
  167605. /* We do not require the whole pass to have been completed. */
  167606. (*cinfo->master->finish_output_pass) (cinfo);
  167607. cinfo->global_state = DSTATE_BUFPOST;
  167608. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167609. /* BUFPOST = repeat call after a suspension, anything else is error */
  167610. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167611. }
  167612. /* Read markers looking for SOS or EOI */
  167613. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167614. ! cinfo->inputctl->eoi_reached) {
  167615. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167616. return FALSE; /* Suspend, come back later */
  167617. }
  167618. cinfo->global_state = DSTATE_BUFIMAGE;
  167619. return TRUE;
  167620. }
  167621. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167622. /*** End of inlined file: jdapistd.c ***/
  167623. /*** Start of inlined file: jdapimin.c ***/
  167624. #define JPEG_INTERNALS
  167625. /*
  167626. * Initialization of a JPEG decompression object.
  167627. * The error manager must already be set up (in case memory manager fails).
  167628. */
  167629. GLOBAL(void)
  167630. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167631. {
  167632. int i;
  167633. /* Guard against version mismatches between library and caller. */
  167634. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167635. if (version != JPEG_LIB_VERSION)
  167636. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167637. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167638. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167639. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167640. /* For debugging purposes, we zero the whole master structure.
  167641. * But the application has already set the err pointer, and may have set
  167642. * client_data, so we have to save and restore those fields.
  167643. * Note: if application hasn't set client_data, tools like Purify may
  167644. * complain here.
  167645. */
  167646. {
  167647. struct jpeg_error_mgr * err = cinfo->err;
  167648. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167649. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167650. cinfo->err = err;
  167651. cinfo->client_data = client_data;
  167652. }
  167653. cinfo->is_decompressor = TRUE;
  167654. /* Initialize a memory manager instance for this object */
  167655. jinit_memory_mgr((j_common_ptr) cinfo);
  167656. /* Zero out pointers to permanent structures. */
  167657. cinfo->progress = NULL;
  167658. cinfo->src = NULL;
  167659. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167660. cinfo->quant_tbl_ptrs[i] = NULL;
  167661. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167662. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167663. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167664. }
  167665. /* Initialize marker processor so application can override methods
  167666. * for COM, APPn markers before calling jpeg_read_header.
  167667. */
  167668. cinfo->marker_list = NULL;
  167669. jinit_marker_reader(cinfo);
  167670. /* And initialize the overall input controller. */
  167671. jinit_input_controller(cinfo);
  167672. /* OK, I'm ready */
  167673. cinfo->global_state = DSTATE_START;
  167674. }
  167675. /*
  167676. * Destruction of a JPEG decompression object
  167677. */
  167678. GLOBAL(void)
  167679. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167680. {
  167681. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167682. }
  167683. /*
  167684. * Abort processing of a JPEG decompression operation,
  167685. * but don't destroy the object itself.
  167686. */
  167687. GLOBAL(void)
  167688. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167689. {
  167690. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167691. }
  167692. /*
  167693. * Set default decompression parameters.
  167694. */
  167695. LOCAL(void)
  167696. default_decompress_parms (j_decompress_ptr cinfo)
  167697. {
  167698. /* Guess the input colorspace, and set output colorspace accordingly. */
  167699. /* (Wish JPEG committee had provided a real way to specify this...) */
  167700. /* Note application may override our guesses. */
  167701. switch (cinfo->num_components) {
  167702. case 1:
  167703. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167704. cinfo->out_color_space = JCS_GRAYSCALE;
  167705. break;
  167706. case 3:
  167707. if (cinfo->saw_JFIF_marker) {
  167708. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167709. } else if (cinfo->saw_Adobe_marker) {
  167710. switch (cinfo->Adobe_transform) {
  167711. case 0:
  167712. cinfo->jpeg_color_space = JCS_RGB;
  167713. break;
  167714. case 1:
  167715. cinfo->jpeg_color_space = JCS_YCbCr;
  167716. break;
  167717. default:
  167718. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167719. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167720. break;
  167721. }
  167722. } else {
  167723. /* Saw no special markers, try to guess from the component IDs */
  167724. int cid0 = cinfo->comp_info[0].component_id;
  167725. int cid1 = cinfo->comp_info[1].component_id;
  167726. int cid2 = cinfo->comp_info[2].component_id;
  167727. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167728. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167729. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167730. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167731. else {
  167732. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167733. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167734. }
  167735. }
  167736. /* Always guess RGB is proper output colorspace. */
  167737. cinfo->out_color_space = JCS_RGB;
  167738. break;
  167739. case 4:
  167740. if (cinfo->saw_Adobe_marker) {
  167741. switch (cinfo->Adobe_transform) {
  167742. case 0:
  167743. cinfo->jpeg_color_space = JCS_CMYK;
  167744. break;
  167745. case 2:
  167746. cinfo->jpeg_color_space = JCS_YCCK;
  167747. break;
  167748. default:
  167749. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167750. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167751. break;
  167752. }
  167753. } else {
  167754. /* No special markers, assume straight CMYK. */
  167755. cinfo->jpeg_color_space = JCS_CMYK;
  167756. }
  167757. cinfo->out_color_space = JCS_CMYK;
  167758. break;
  167759. default:
  167760. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167761. cinfo->out_color_space = JCS_UNKNOWN;
  167762. break;
  167763. }
  167764. /* Set defaults for other decompression parameters. */
  167765. cinfo->scale_num = 1; /* 1:1 scaling */
  167766. cinfo->scale_denom = 1;
  167767. cinfo->output_gamma = 1.0;
  167768. cinfo->buffered_image = FALSE;
  167769. cinfo->raw_data_out = FALSE;
  167770. cinfo->dct_method = JDCT_DEFAULT;
  167771. cinfo->do_fancy_upsampling = TRUE;
  167772. cinfo->do_block_smoothing = TRUE;
  167773. cinfo->quantize_colors = FALSE;
  167774. /* We set these in case application only sets quantize_colors. */
  167775. cinfo->dither_mode = JDITHER_FS;
  167776. #ifdef QUANT_2PASS_SUPPORTED
  167777. cinfo->two_pass_quantize = TRUE;
  167778. #else
  167779. cinfo->two_pass_quantize = FALSE;
  167780. #endif
  167781. cinfo->desired_number_of_colors = 256;
  167782. cinfo->colormap = NULL;
  167783. /* Initialize for no mode change in buffered-image mode. */
  167784. cinfo->enable_1pass_quant = FALSE;
  167785. cinfo->enable_external_quant = FALSE;
  167786. cinfo->enable_2pass_quant = FALSE;
  167787. }
  167788. /*
  167789. * Decompression startup: read start of JPEG datastream to see what's there.
  167790. * Need only initialize JPEG object and supply a data source before calling.
  167791. *
  167792. * This routine will read as far as the first SOS marker (ie, actual start of
  167793. * compressed data), and will save all tables and parameters in the JPEG
  167794. * object. It will also initialize the decompression parameters to default
  167795. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167796. * adjust the decompression parameters and then call jpeg_start_decompress.
  167797. * (Or, if the application only wanted to determine the image parameters,
  167798. * the data need not be decompressed. In that case, call jpeg_abort or
  167799. * jpeg_destroy to release any temporary space.)
  167800. * If an abbreviated (tables only) datastream is presented, the routine will
  167801. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167802. * re-use the JPEG object to read the abbreviated image datastream(s).
  167803. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167804. * The JPEG_SUSPENDED return code only occurs if the data source module
  167805. * requests suspension of the decompressor. In this case the application
  167806. * should load more source data and then re-call jpeg_read_header to resume
  167807. * processing.
  167808. * If a non-suspending data source is used and require_image is TRUE, then the
  167809. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167810. *
  167811. * This routine is now just a front end to jpeg_consume_input, with some
  167812. * extra error checking.
  167813. */
  167814. GLOBAL(int)
  167815. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167816. {
  167817. int retcode;
  167818. if (cinfo->global_state != DSTATE_START &&
  167819. cinfo->global_state != DSTATE_INHEADER)
  167820. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167821. retcode = jpeg_consume_input(cinfo);
  167822. switch (retcode) {
  167823. case JPEG_REACHED_SOS:
  167824. retcode = JPEG_HEADER_OK;
  167825. break;
  167826. case JPEG_REACHED_EOI:
  167827. if (require_image) /* Complain if application wanted an image */
  167828. ERREXIT(cinfo, JERR_NO_IMAGE);
  167829. /* Reset to start state; it would be safer to require the application to
  167830. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167831. * A side effect is to free any temporary memory (there shouldn't be any).
  167832. */
  167833. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167834. retcode = JPEG_HEADER_TABLES_ONLY;
  167835. break;
  167836. case JPEG_SUSPENDED:
  167837. /* no work */
  167838. break;
  167839. }
  167840. return retcode;
  167841. }
  167842. /*
  167843. * Consume data in advance of what the decompressor requires.
  167844. * This can be called at any time once the decompressor object has
  167845. * been created and a data source has been set up.
  167846. *
  167847. * This routine is essentially a state machine that handles a couple
  167848. * of critical state-transition actions, namely initial setup and
  167849. * transition from header scanning to ready-for-start_decompress.
  167850. * All the actual input is done via the input controller's consume_input
  167851. * method.
  167852. */
  167853. GLOBAL(int)
  167854. jpeg_consume_input (j_decompress_ptr cinfo)
  167855. {
  167856. int retcode = JPEG_SUSPENDED;
  167857. /* NB: every possible DSTATE value should be listed in this switch */
  167858. switch (cinfo->global_state) {
  167859. case DSTATE_START:
  167860. /* Start-of-datastream actions: reset appropriate modules */
  167861. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167862. /* Initialize application's data source module */
  167863. (*cinfo->src->init_source) (cinfo);
  167864. cinfo->global_state = DSTATE_INHEADER;
  167865. /*FALLTHROUGH*/
  167866. case DSTATE_INHEADER:
  167867. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167868. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167869. /* Set up default parameters based on header data */
  167870. default_decompress_parms(cinfo);
  167871. /* Set global state: ready for start_decompress */
  167872. cinfo->global_state = DSTATE_READY;
  167873. }
  167874. break;
  167875. case DSTATE_READY:
  167876. /* Can't advance past first SOS until start_decompress is called */
  167877. retcode = JPEG_REACHED_SOS;
  167878. break;
  167879. case DSTATE_PRELOAD:
  167880. case DSTATE_PRESCAN:
  167881. case DSTATE_SCANNING:
  167882. case DSTATE_RAW_OK:
  167883. case DSTATE_BUFIMAGE:
  167884. case DSTATE_BUFPOST:
  167885. case DSTATE_STOPPING:
  167886. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167887. break;
  167888. default:
  167889. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167890. }
  167891. return retcode;
  167892. }
  167893. /*
  167894. * Have we finished reading the input file?
  167895. */
  167896. GLOBAL(boolean)
  167897. jpeg_input_complete (j_decompress_ptr cinfo)
  167898. {
  167899. /* Check for valid jpeg object */
  167900. if (cinfo->global_state < DSTATE_START ||
  167901. cinfo->global_state > DSTATE_STOPPING)
  167902. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167903. return cinfo->inputctl->eoi_reached;
  167904. }
  167905. /*
  167906. * Is there more than one scan?
  167907. */
  167908. GLOBAL(boolean)
  167909. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167910. {
  167911. /* Only valid after jpeg_read_header completes */
  167912. if (cinfo->global_state < DSTATE_READY ||
  167913. cinfo->global_state > DSTATE_STOPPING)
  167914. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167915. return cinfo->inputctl->has_multiple_scans;
  167916. }
  167917. /*
  167918. * Finish JPEG decompression.
  167919. *
  167920. * This will normally just verify the file trailer and release temp storage.
  167921. *
  167922. * Returns FALSE if suspended. The return value need be inspected only if
  167923. * a suspending data source is used.
  167924. */
  167925. GLOBAL(boolean)
  167926. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167927. {
  167928. if ((cinfo->global_state == DSTATE_SCANNING ||
  167929. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167930. /* Terminate final pass of non-buffered mode */
  167931. if (cinfo->output_scanline < cinfo->output_height)
  167932. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167933. (*cinfo->master->finish_output_pass) (cinfo);
  167934. cinfo->global_state = DSTATE_STOPPING;
  167935. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167936. /* Finishing after a buffered-image operation */
  167937. cinfo->global_state = DSTATE_STOPPING;
  167938. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167939. /* STOPPING = repeat call after a suspension, anything else is error */
  167940. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167941. }
  167942. /* Read until EOI */
  167943. while (! cinfo->inputctl->eoi_reached) {
  167944. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167945. return FALSE; /* Suspend, come back later */
  167946. }
  167947. /* Do final cleanup */
  167948. (*cinfo->src->term_source) (cinfo);
  167949. /* We can use jpeg_abort to release memory and reset global_state */
  167950. jpeg_abort((j_common_ptr) cinfo);
  167951. return TRUE;
  167952. }
  167953. /*** End of inlined file: jdapimin.c ***/
  167954. /*** Start of inlined file: jdatasrc.c ***/
  167955. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167956. /*** Start of inlined file: jerror.h ***/
  167957. /*
  167958. * To define the enum list of message codes, include this file without
  167959. * defining macro JMESSAGE. To create a message string table, include it
  167960. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167961. */
  167962. #ifndef JMESSAGE
  167963. #ifndef JERROR_H
  167964. /* First time through, define the enum list */
  167965. #define JMAKE_ENUM_LIST
  167966. #else
  167967. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167968. #define JMESSAGE(code,string)
  167969. #endif /* JERROR_H */
  167970. #endif /* JMESSAGE */
  167971. #ifdef JMAKE_ENUM_LIST
  167972. typedef enum {
  167973. #define JMESSAGE(code,string) code ,
  167974. #endif /* JMAKE_ENUM_LIST */
  167975. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167976. /* For maintenance convenience, list is alphabetical by message code name */
  167977. JMESSAGE(JERR_ARITH_NOTIMPL,
  167978. "Sorry, there are legal restrictions on arithmetic coding")
  167979. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167980. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167981. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167982. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167983. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167984. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167985. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167986. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167987. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167988. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167989. JMESSAGE(JERR_BAD_LIB_VERSION,
  167990. "Wrong JPEG library version: library is %d, caller expects %d")
  167991. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167992. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167993. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167994. JMESSAGE(JERR_BAD_PROGRESSION,
  167995. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167996. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167997. "Invalid progressive parameters at scan script entry %d")
  167998. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167999. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168000. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168001. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168002. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168003. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168004. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168005. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168006. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168007. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168008. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168009. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168010. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168011. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168012. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168013. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168014. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168015. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168016. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168017. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168018. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168019. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168020. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168021. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168022. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168023. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168024. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168025. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168026. "Cannot transcode due to multiple use of quantization table %d")
  168027. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168028. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168029. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168030. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168031. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168032. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168033. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168034. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168035. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168036. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168037. JMESSAGE(JERR_QUANT_COMPONENTS,
  168038. "Cannot quantize more than %d color components")
  168039. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168040. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168041. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168042. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168043. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168044. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168045. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168046. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168047. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168048. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168049. JMESSAGE(JERR_TFILE_WRITE,
  168050. "Write failed on temporary file --- out of disk space?")
  168051. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168052. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168053. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168054. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168055. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168056. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168057. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168058. JMESSAGE(JMSG_VERSION, JVERSION)
  168059. JMESSAGE(JTRC_16BIT_TABLES,
  168060. "Caution: quantization tables are too coarse for baseline JPEG")
  168061. JMESSAGE(JTRC_ADOBE,
  168062. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168063. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168064. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168065. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168066. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168067. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168068. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168069. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168070. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168071. JMESSAGE(JTRC_EOI, "End Of Image")
  168072. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168073. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168074. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168075. "Warning: thumbnail image size does not match data length %u")
  168076. JMESSAGE(JTRC_JFIF_EXTENSION,
  168077. "JFIF extension marker: type 0x%02x, length %u")
  168078. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168079. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168080. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168081. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168082. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168083. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168084. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168085. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168086. JMESSAGE(JTRC_RST, "RST%d")
  168087. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168088. "Smoothing not supported with nonstandard sampling ratios")
  168089. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168090. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168091. JMESSAGE(JTRC_SOI, "Start of Image")
  168092. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168093. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168094. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168095. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168096. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168097. JMESSAGE(JTRC_THUMB_JPEG,
  168098. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168099. JMESSAGE(JTRC_THUMB_PALETTE,
  168100. "JFIF extension marker: palette thumbnail image, length %u")
  168101. JMESSAGE(JTRC_THUMB_RGB,
  168102. "JFIF extension marker: RGB thumbnail image, length %u")
  168103. JMESSAGE(JTRC_UNKNOWN_IDS,
  168104. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168105. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168106. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168107. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168108. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168109. "Inconsistent progression sequence for component %d coefficient %d")
  168110. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168111. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168112. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168113. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168114. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168115. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168116. JMESSAGE(JWRN_MUST_RESYNC,
  168117. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168118. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168119. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168120. #ifdef JMAKE_ENUM_LIST
  168121. JMSG_LASTMSGCODE
  168122. } J_MESSAGE_CODE;
  168123. #undef JMAKE_ENUM_LIST
  168124. #endif /* JMAKE_ENUM_LIST */
  168125. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168126. #undef JMESSAGE
  168127. #ifndef JERROR_H
  168128. #define JERROR_H
  168129. /* Macros to simplify using the error and trace message stuff */
  168130. /* The first parameter is either type of cinfo pointer */
  168131. /* Fatal errors (print message and exit) */
  168132. #define ERREXIT(cinfo,code) \
  168133. ((cinfo)->err->msg_code = (code), \
  168134. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168135. #define ERREXIT1(cinfo,code,p1) \
  168136. ((cinfo)->err->msg_code = (code), \
  168137. (cinfo)->err->msg_parm.i[0] = (p1), \
  168138. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168139. #define ERREXIT2(cinfo,code,p1,p2) \
  168140. ((cinfo)->err->msg_code = (code), \
  168141. (cinfo)->err->msg_parm.i[0] = (p1), \
  168142. (cinfo)->err->msg_parm.i[1] = (p2), \
  168143. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168144. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168145. ((cinfo)->err->msg_code = (code), \
  168146. (cinfo)->err->msg_parm.i[0] = (p1), \
  168147. (cinfo)->err->msg_parm.i[1] = (p2), \
  168148. (cinfo)->err->msg_parm.i[2] = (p3), \
  168149. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168150. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168151. ((cinfo)->err->msg_code = (code), \
  168152. (cinfo)->err->msg_parm.i[0] = (p1), \
  168153. (cinfo)->err->msg_parm.i[1] = (p2), \
  168154. (cinfo)->err->msg_parm.i[2] = (p3), \
  168155. (cinfo)->err->msg_parm.i[3] = (p4), \
  168156. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168157. #define ERREXITS(cinfo,code,str) \
  168158. ((cinfo)->err->msg_code = (code), \
  168159. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168160. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168161. #define MAKESTMT(stuff) do { stuff } while (0)
  168162. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168163. #define WARNMS(cinfo,code) \
  168164. ((cinfo)->err->msg_code = (code), \
  168165. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168166. #define WARNMS1(cinfo,code,p1) \
  168167. ((cinfo)->err->msg_code = (code), \
  168168. (cinfo)->err->msg_parm.i[0] = (p1), \
  168169. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168170. #define WARNMS2(cinfo,code,p1,p2) \
  168171. ((cinfo)->err->msg_code = (code), \
  168172. (cinfo)->err->msg_parm.i[0] = (p1), \
  168173. (cinfo)->err->msg_parm.i[1] = (p2), \
  168174. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168175. /* Informational/debugging messages */
  168176. #define TRACEMS(cinfo,lvl,code) \
  168177. ((cinfo)->err->msg_code = (code), \
  168178. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168179. #define TRACEMS1(cinfo,lvl,code,p1) \
  168180. ((cinfo)->err->msg_code = (code), \
  168181. (cinfo)->err->msg_parm.i[0] = (p1), \
  168182. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168183. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168184. ((cinfo)->err->msg_code = (code), \
  168185. (cinfo)->err->msg_parm.i[0] = (p1), \
  168186. (cinfo)->err->msg_parm.i[1] = (p2), \
  168187. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168188. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168189. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168190. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168191. (cinfo)->err->msg_code = (code); \
  168192. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168193. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168194. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168195. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168196. (cinfo)->err->msg_code = (code); \
  168197. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168198. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168199. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168200. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168201. _mp[4] = (p5); \
  168202. (cinfo)->err->msg_code = (code); \
  168203. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168204. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168205. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168206. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168207. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168208. (cinfo)->err->msg_code = (code); \
  168209. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168210. #define TRACEMSS(cinfo,lvl,code,str) \
  168211. ((cinfo)->err->msg_code = (code), \
  168212. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168213. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168214. #endif /* JERROR_H */
  168215. /*** End of inlined file: jerror.h ***/
  168216. /* Expanded data source object for stdio input */
  168217. typedef struct {
  168218. struct jpeg_source_mgr pub; /* public fields */
  168219. FILE * infile; /* source stream */
  168220. JOCTET * buffer; /* start of buffer */
  168221. boolean start_of_file; /* have we gotten any data yet? */
  168222. } my_source_mgr;
  168223. typedef my_source_mgr * my_src_ptr;
  168224. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168225. /*
  168226. * Initialize source --- called by jpeg_read_header
  168227. * before any data is actually read.
  168228. */
  168229. METHODDEF(void)
  168230. init_source (j_decompress_ptr cinfo)
  168231. {
  168232. my_src_ptr src = (my_src_ptr) cinfo->src;
  168233. /* We reset the empty-input-file flag for each image,
  168234. * but we don't clear the input buffer.
  168235. * This is correct behavior for reading a series of images from one source.
  168236. */
  168237. src->start_of_file = TRUE;
  168238. }
  168239. /*
  168240. * Fill the input buffer --- called whenever buffer is emptied.
  168241. *
  168242. * In typical applications, this should read fresh data into the buffer
  168243. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168244. * reset the pointer & count to the start of the buffer, and return TRUE
  168245. * indicating that the buffer has been reloaded. It is not necessary to
  168246. * fill the buffer entirely, only to obtain at least one more byte.
  168247. *
  168248. * There is no such thing as an EOF return. If the end of the file has been
  168249. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168250. * the buffer. In most cases, generating a warning message and inserting a
  168251. * fake EOI marker is the best course of action --- this will allow the
  168252. * decompressor to output however much of the image is there. However,
  168253. * the resulting error message is misleading if the real problem is an empty
  168254. * input file, so we handle that case specially.
  168255. *
  168256. * In applications that need to be able to suspend compression due to input
  168257. * not being available yet, a FALSE return indicates that no more data can be
  168258. * obtained right now, but more may be forthcoming later. In this situation,
  168259. * the decompressor will return to its caller (with an indication of the
  168260. * number of scanlines it has read, if any). The application should resume
  168261. * decompression after it has loaded more data into the input buffer. Note
  168262. * that there are substantial restrictions on the use of suspension --- see
  168263. * the documentation.
  168264. *
  168265. * When suspending, the decompressor will back up to a convenient restart point
  168266. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168267. * indicate where the restart point will be if the current call returns FALSE.
  168268. * Data beyond this point must be rescanned after resumption, so move it to
  168269. * the front of the buffer rather than discarding it.
  168270. */
  168271. METHODDEF(boolean)
  168272. fill_input_buffer (j_decompress_ptr cinfo)
  168273. {
  168274. my_src_ptr src = (my_src_ptr) cinfo->src;
  168275. size_t nbytes;
  168276. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168277. if (nbytes <= 0) {
  168278. if (src->start_of_file) /* Treat empty input file as fatal error */
  168279. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168280. WARNMS(cinfo, JWRN_JPEG_EOF);
  168281. /* Insert a fake EOI marker */
  168282. src->buffer[0] = (JOCTET) 0xFF;
  168283. src->buffer[1] = (JOCTET) JPEG_EOI;
  168284. nbytes = 2;
  168285. }
  168286. src->pub.next_input_byte = src->buffer;
  168287. src->pub.bytes_in_buffer = nbytes;
  168288. src->start_of_file = FALSE;
  168289. return TRUE;
  168290. }
  168291. /*
  168292. * Skip data --- used to skip over a potentially large amount of
  168293. * uninteresting data (such as an APPn marker).
  168294. *
  168295. * Writers of suspendable-input applications must note that skip_input_data
  168296. * is not granted the right to give a suspension return. If the skip extends
  168297. * beyond the data currently in the buffer, the buffer can be marked empty so
  168298. * that the next read will cause a fill_input_buffer call that can suspend.
  168299. * Arranging for additional bytes to be discarded before reloading the input
  168300. * buffer is the application writer's problem.
  168301. */
  168302. METHODDEF(void)
  168303. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168304. {
  168305. my_src_ptr src = (my_src_ptr) cinfo->src;
  168306. /* Just a dumb implementation for now. Could use fseek() except
  168307. * it doesn't work on pipes. Not clear that being smart is worth
  168308. * any trouble anyway --- large skips are infrequent.
  168309. */
  168310. if (num_bytes > 0) {
  168311. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168312. num_bytes -= (long) src->pub.bytes_in_buffer;
  168313. (void) fill_input_buffer(cinfo);
  168314. /* note we assume that fill_input_buffer will never return FALSE,
  168315. * so suspension need not be handled.
  168316. */
  168317. }
  168318. src->pub.next_input_byte += (size_t) num_bytes;
  168319. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168320. }
  168321. }
  168322. /*
  168323. * An additional method that can be provided by data source modules is the
  168324. * resync_to_restart method for error recovery in the presence of RST markers.
  168325. * For the moment, this source module just uses the default resync method
  168326. * provided by the JPEG library. That method assumes that no backtracking
  168327. * is possible.
  168328. */
  168329. /*
  168330. * Terminate source --- called by jpeg_finish_decompress
  168331. * after all data has been read. Often a no-op.
  168332. *
  168333. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168334. * application must deal with any cleanup that should happen even
  168335. * for error exit.
  168336. */
  168337. METHODDEF(void)
  168338. term_source (j_decompress_ptr)
  168339. {
  168340. /* no work necessary here */
  168341. }
  168342. /*
  168343. * Prepare for input from a stdio stream.
  168344. * The caller must have already opened the stream, and is responsible
  168345. * for closing it after finishing decompression.
  168346. */
  168347. GLOBAL(void)
  168348. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168349. {
  168350. my_src_ptr src;
  168351. /* The source object and input buffer are made permanent so that a series
  168352. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168353. * only before the first one. (If we discarded the buffer at the end of
  168354. * one image, we'd likely lose the start of the next one.)
  168355. * This makes it unsafe to use this manager and a different source
  168356. * manager serially with the same JPEG object. Caveat programmer.
  168357. */
  168358. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168359. cinfo->src = (struct jpeg_source_mgr *)
  168360. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168361. SIZEOF(my_source_mgr));
  168362. src = (my_src_ptr) cinfo->src;
  168363. src->buffer = (JOCTET *)
  168364. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168365. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168366. }
  168367. src = (my_src_ptr) cinfo->src;
  168368. src->pub.init_source = init_source;
  168369. src->pub.fill_input_buffer = fill_input_buffer;
  168370. src->pub.skip_input_data = skip_input_data;
  168371. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168372. src->pub.term_source = term_source;
  168373. src->infile = infile;
  168374. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168375. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168376. }
  168377. /*** End of inlined file: jdatasrc.c ***/
  168378. /*** Start of inlined file: jdcoefct.c ***/
  168379. #define JPEG_INTERNALS
  168380. /* Block smoothing is only applicable for progressive JPEG, so: */
  168381. #ifndef D_PROGRESSIVE_SUPPORTED
  168382. #undef BLOCK_SMOOTHING_SUPPORTED
  168383. #endif
  168384. /* Private buffer controller object */
  168385. typedef struct {
  168386. struct jpeg_d_coef_controller pub; /* public fields */
  168387. /* These variables keep track of the current location of the input side. */
  168388. /* cinfo->input_iMCU_row is also used for this. */
  168389. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168390. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168391. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168392. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168393. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168394. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168395. * and let the entropy decoder write into that workspace each time.
  168396. * (On 80x86, the workspace is FAR even though it's not really very big;
  168397. * this is to keep the module interfaces unchanged when a large coefficient
  168398. * buffer is necessary.)
  168399. * In multi-pass modes, this array points to the current MCU's blocks
  168400. * within the virtual arrays; it is used only by the input side.
  168401. */
  168402. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168403. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168404. /* In multi-pass modes, we need a virtual block array for each component. */
  168405. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168406. #endif
  168407. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168408. /* When doing block smoothing, we latch coefficient Al values here */
  168409. int * coef_bits_latch;
  168410. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168411. #endif
  168412. } my_coef_controller3;
  168413. typedef my_coef_controller3 * my_coef_ptr3;
  168414. /* Forward declarations */
  168415. METHODDEF(int) decompress_onepass
  168416. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168417. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168418. METHODDEF(int) decompress_data
  168419. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168420. #endif
  168421. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168422. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168423. METHODDEF(int) decompress_smooth_data
  168424. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168425. #endif
  168426. LOCAL(void)
  168427. start_iMCU_row3 (j_decompress_ptr cinfo)
  168428. /* Reset within-iMCU-row counters for a new row (input side) */
  168429. {
  168430. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168431. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168432. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168433. * But at the bottom of the image, process only what's left.
  168434. */
  168435. if (cinfo->comps_in_scan > 1) {
  168436. coef->MCU_rows_per_iMCU_row = 1;
  168437. } else {
  168438. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168439. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168440. else
  168441. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168442. }
  168443. coef->MCU_ctr = 0;
  168444. coef->MCU_vert_offset = 0;
  168445. }
  168446. /*
  168447. * Initialize for an input processing pass.
  168448. */
  168449. METHODDEF(void)
  168450. start_input_pass (j_decompress_ptr cinfo)
  168451. {
  168452. cinfo->input_iMCU_row = 0;
  168453. start_iMCU_row3(cinfo);
  168454. }
  168455. /*
  168456. * Initialize for an output processing pass.
  168457. */
  168458. METHODDEF(void)
  168459. start_output_pass (j_decompress_ptr cinfo)
  168460. {
  168461. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168462. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168463. /* If multipass, check to see whether to use block smoothing on this pass */
  168464. if (coef->pub.coef_arrays != NULL) {
  168465. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168466. coef->pub.decompress_data = decompress_smooth_data;
  168467. else
  168468. coef->pub.decompress_data = decompress_data;
  168469. }
  168470. #endif
  168471. cinfo->output_iMCU_row = 0;
  168472. }
  168473. /*
  168474. * Decompress and return some data in the single-pass case.
  168475. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168476. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168477. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168478. *
  168479. * NB: output_buf contains a plane for each component in image,
  168480. * which we index according to the component's SOF position.
  168481. */
  168482. METHODDEF(int)
  168483. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168484. {
  168485. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168486. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168487. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168488. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168489. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168490. JSAMPARRAY output_ptr;
  168491. JDIMENSION start_col, output_col;
  168492. jpeg_component_info *compptr;
  168493. inverse_DCT_method_ptr inverse_DCT;
  168494. /* Loop to process as much as one whole iMCU row */
  168495. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168496. yoffset++) {
  168497. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168498. MCU_col_num++) {
  168499. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168500. jzero_far((void FAR *) coef->MCU_buffer[0],
  168501. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168502. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168503. /* Suspension forced; update state counters and exit */
  168504. coef->MCU_vert_offset = yoffset;
  168505. coef->MCU_ctr = MCU_col_num;
  168506. return JPEG_SUSPENDED;
  168507. }
  168508. /* Determine where data should go in output_buf and do the IDCT thing.
  168509. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168510. * incremented past them!). Note the inner loop relies on having
  168511. * allocated the MCU_buffer[] blocks sequentially.
  168512. */
  168513. blkn = 0; /* index of current DCT block within MCU */
  168514. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168515. compptr = cinfo->cur_comp_info[ci];
  168516. /* Don't bother to IDCT an uninteresting component. */
  168517. if (! compptr->component_needed) {
  168518. blkn += compptr->MCU_blocks;
  168519. continue;
  168520. }
  168521. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168522. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168523. : compptr->last_col_width;
  168524. output_ptr = output_buf[compptr->component_index] +
  168525. yoffset * compptr->DCT_scaled_size;
  168526. start_col = MCU_col_num * compptr->MCU_sample_width;
  168527. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168528. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168529. yoffset+yindex < compptr->last_row_height) {
  168530. output_col = start_col;
  168531. for (xindex = 0; xindex < useful_width; xindex++) {
  168532. (*inverse_DCT) (cinfo, compptr,
  168533. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168534. output_ptr, output_col);
  168535. output_col += compptr->DCT_scaled_size;
  168536. }
  168537. }
  168538. blkn += compptr->MCU_width;
  168539. output_ptr += compptr->DCT_scaled_size;
  168540. }
  168541. }
  168542. }
  168543. /* Completed an MCU row, but perhaps not an iMCU row */
  168544. coef->MCU_ctr = 0;
  168545. }
  168546. /* Completed the iMCU row, advance counters for next one */
  168547. cinfo->output_iMCU_row++;
  168548. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168549. start_iMCU_row3(cinfo);
  168550. return JPEG_ROW_COMPLETED;
  168551. }
  168552. /* Completed the scan */
  168553. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168554. return JPEG_SCAN_COMPLETED;
  168555. }
  168556. /*
  168557. * Dummy consume-input routine for single-pass operation.
  168558. */
  168559. METHODDEF(int)
  168560. dummy_consume_data (j_decompress_ptr)
  168561. {
  168562. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168563. }
  168564. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168565. /*
  168566. * Consume input data and store it in the full-image coefficient buffer.
  168567. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168568. * ie, v_samp_factor block rows for each component in the scan.
  168569. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168570. */
  168571. METHODDEF(int)
  168572. consume_data (j_decompress_ptr cinfo)
  168573. {
  168574. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168575. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168576. int blkn, ci, xindex, yindex, yoffset;
  168577. JDIMENSION start_col;
  168578. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168579. JBLOCKROW buffer_ptr;
  168580. jpeg_component_info *compptr;
  168581. /* Align the virtual buffers for the components used in this scan. */
  168582. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168583. compptr = cinfo->cur_comp_info[ci];
  168584. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168585. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168586. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168587. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168588. /* Note: entropy decoder expects buffer to be zeroed,
  168589. * but this is handled automatically by the memory manager
  168590. * because we requested a pre-zeroed array.
  168591. */
  168592. }
  168593. /* Loop to process one whole iMCU row */
  168594. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168595. yoffset++) {
  168596. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168597. MCU_col_num++) {
  168598. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168599. blkn = 0; /* index of current DCT block within MCU */
  168600. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168601. compptr = cinfo->cur_comp_info[ci];
  168602. start_col = MCU_col_num * compptr->MCU_width;
  168603. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168604. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168605. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168606. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168607. }
  168608. }
  168609. }
  168610. /* Try to fetch the MCU. */
  168611. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168612. /* Suspension forced; update state counters and exit */
  168613. coef->MCU_vert_offset = yoffset;
  168614. coef->MCU_ctr = MCU_col_num;
  168615. return JPEG_SUSPENDED;
  168616. }
  168617. }
  168618. /* Completed an MCU row, but perhaps not an iMCU row */
  168619. coef->MCU_ctr = 0;
  168620. }
  168621. /* Completed the iMCU row, advance counters for next one */
  168622. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168623. start_iMCU_row3(cinfo);
  168624. return JPEG_ROW_COMPLETED;
  168625. }
  168626. /* Completed the scan */
  168627. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168628. return JPEG_SCAN_COMPLETED;
  168629. }
  168630. /*
  168631. * Decompress and return some data in the multi-pass case.
  168632. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168633. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168634. *
  168635. * NB: output_buf contains a plane for each component in image.
  168636. */
  168637. METHODDEF(int)
  168638. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168639. {
  168640. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168641. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168642. JDIMENSION block_num;
  168643. int ci, block_row, block_rows;
  168644. JBLOCKARRAY buffer;
  168645. JBLOCKROW buffer_ptr;
  168646. JSAMPARRAY output_ptr;
  168647. JDIMENSION output_col;
  168648. jpeg_component_info *compptr;
  168649. inverse_DCT_method_ptr inverse_DCT;
  168650. /* Force some input to be done if we are getting ahead of the input. */
  168651. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168652. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168653. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168654. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168655. return JPEG_SUSPENDED;
  168656. }
  168657. /* OK, output from the virtual arrays. */
  168658. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168659. ci++, compptr++) {
  168660. /* Don't bother to IDCT an uninteresting component. */
  168661. if (! compptr->component_needed)
  168662. continue;
  168663. /* Align the virtual buffer for this component. */
  168664. buffer = (*cinfo->mem->access_virt_barray)
  168665. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168666. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168667. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168668. /* Count non-dummy DCT block rows in this iMCU row. */
  168669. if (cinfo->output_iMCU_row < last_iMCU_row)
  168670. block_rows = compptr->v_samp_factor;
  168671. else {
  168672. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168673. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168674. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168675. }
  168676. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168677. output_ptr = output_buf[ci];
  168678. /* Loop over all DCT blocks to be processed. */
  168679. for (block_row = 0; block_row < block_rows; block_row++) {
  168680. buffer_ptr = buffer[block_row];
  168681. output_col = 0;
  168682. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168683. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168684. output_ptr, output_col);
  168685. buffer_ptr++;
  168686. output_col += compptr->DCT_scaled_size;
  168687. }
  168688. output_ptr += compptr->DCT_scaled_size;
  168689. }
  168690. }
  168691. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168692. return JPEG_ROW_COMPLETED;
  168693. return JPEG_SCAN_COMPLETED;
  168694. }
  168695. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168696. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168697. /*
  168698. * This code applies interblock smoothing as described by section K.8
  168699. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168700. * the DC values of a DCT block and its 8 neighboring blocks.
  168701. * We apply smoothing only for progressive JPEG decoding, and only if
  168702. * the coefficients it can estimate are not yet known to full precision.
  168703. */
  168704. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168705. #define Q01_POS 1
  168706. #define Q10_POS 8
  168707. #define Q20_POS 16
  168708. #define Q11_POS 9
  168709. #define Q02_POS 2
  168710. /*
  168711. * Determine whether block smoothing is applicable and safe.
  168712. * We also latch the current states of the coef_bits[] entries for the
  168713. * AC coefficients; otherwise, if the input side of the decompressor
  168714. * advances into a new scan, we might think the coefficients are known
  168715. * more accurately than they really are.
  168716. */
  168717. LOCAL(boolean)
  168718. smoothing_ok (j_decompress_ptr cinfo)
  168719. {
  168720. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168721. boolean smoothing_useful = FALSE;
  168722. int ci, coefi;
  168723. jpeg_component_info *compptr;
  168724. JQUANT_TBL * qtable;
  168725. int * coef_bits;
  168726. int * coef_bits_latch;
  168727. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168728. return FALSE;
  168729. /* Allocate latch area if not already done */
  168730. if (coef->coef_bits_latch == NULL)
  168731. coef->coef_bits_latch = (int *)
  168732. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168733. cinfo->num_components *
  168734. (SAVED_COEFS * SIZEOF(int)));
  168735. coef_bits_latch = coef->coef_bits_latch;
  168736. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168737. ci++, compptr++) {
  168738. /* All components' quantization values must already be latched. */
  168739. if ((qtable = compptr->quant_table) == NULL)
  168740. return FALSE;
  168741. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168742. if (qtable->quantval[0] == 0 ||
  168743. qtable->quantval[Q01_POS] == 0 ||
  168744. qtable->quantval[Q10_POS] == 0 ||
  168745. qtable->quantval[Q20_POS] == 0 ||
  168746. qtable->quantval[Q11_POS] == 0 ||
  168747. qtable->quantval[Q02_POS] == 0)
  168748. return FALSE;
  168749. /* DC values must be at least partly known for all components. */
  168750. coef_bits = cinfo->coef_bits[ci];
  168751. if (coef_bits[0] < 0)
  168752. return FALSE;
  168753. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168754. for (coefi = 1; coefi <= 5; coefi++) {
  168755. coef_bits_latch[coefi] = coef_bits[coefi];
  168756. if (coef_bits[coefi] != 0)
  168757. smoothing_useful = TRUE;
  168758. }
  168759. coef_bits_latch += SAVED_COEFS;
  168760. }
  168761. return smoothing_useful;
  168762. }
  168763. /*
  168764. * Variant of decompress_data for use when doing block smoothing.
  168765. */
  168766. METHODDEF(int)
  168767. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168768. {
  168769. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168770. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168771. JDIMENSION block_num, last_block_column;
  168772. int ci, block_row, block_rows, access_rows;
  168773. JBLOCKARRAY buffer;
  168774. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168775. JSAMPARRAY output_ptr;
  168776. JDIMENSION output_col;
  168777. jpeg_component_info *compptr;
  168778. inverse_DCT_method_ptr inverse_DCT;
  168779. boolean first_row, last_row;
  168780. JBLOCK workspace;
  168781. int *coef_bits;
  168782. JQUANT_TBL *quanttbl;
  168783. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168784. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168785. int Al, pred;
  168786. /* Force some input to be done if we are getting ahead of the input. */
  168787. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168788. ! cinfo->inputctl->eoi_reached) {
  168789. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168790. /* If input is working on current scan, we ordinarily want it to
  168791. * have completed the current row. But if input scan is DC,
  168792. * we want it to keep one row ahead so that next block row's DC
  168793. * values are up to date.
  168794. */
  168795. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168796. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168797. break;
  168798. }
  168799. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168800. return JPEG_SUSPENDED;
  168801. }
  168802. /* OK, output from the virtual arrays. */
  168803. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168804. ci++, compptr++) {
  168805. /* Don't bother to IDCT an uninteresting component. */
  168806. if (! compptr->component_needed)
  168807. continue;
  168808. /* Count non-dummy DCT block rows in this iMCU row. */
  168809. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168810. block_rows = compptr->v_samp_factor;
  168811. access_rows = block_rows * 2; /* this and next iMCU row */
  168812. last_row = FALSE;
  168813. } else {
  168814. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168815. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168816. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168817. access_rows = block_rows; /* this iMCU row only */
  168818. last_row = TRUE;
  168819. }
  168820. /* Align the virtual buffer for this component. */
  168821. if (cinfo->output_iMCU_row > 0) {
  168822. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168823. buffer = (*cinfo->mem->access_virt_barray)
  168824. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168825. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168826. (JDIMENSION) access_rows, FALSE);
  168827. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168828. first_row = FALSE;
  168829. } else {
  168830. buffer = (*cinfo->mem->access_virt_barray)
  168831. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168832. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168833. first_row = TRUE;
  168834. }
  168835. /* Fetch component-dependent info */
  168836. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168837. quanttbl = compptr->quant_table;
  168838. Q00 = quanttbl->quantval[0];
  168839. Q01 = quanttbl->quantval[Q01_POS];
  168840. Q10 = quanttbl->quantval[Q10_POS];
  168841. Q20 = quanttbl->quantval[Q20_POS];
  168842. Q11 = quanttbl->quantval[Q11_POS];
  168843. Q02 = quanttbl->quantval[Q02_POS];
  168844. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168845. output_ptr = output_buf[ci];
  168846. /* Loop over all DCT blocks to be processed. */
  168847. for (block_row = 0; block_row < block_rows; block_row++) {
  168848. buffer_ptr = buffer[block_row];
  168849. if (first_row && block_row == 0)
  168850. prev_block_row = buffer_ptr;
  168851. else
  168852. prev_block_row = buffer[block_row-1];
  168853. if (last_row && block_row == block_rows-1)
  168854. next_block_row = buffer_ptr;
  168855. else
  168856. next_block_row = buffer[block_row+1];
  168857. /* We fetch the surrounding DC values using a sliding-register approach.
  168858. * Initialize all nine here so as to do the right thing on narrow pics.
  168859. */
  168860. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168861. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168862. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168863. output_col = 0;
  168864. last_block_column = compptr->width_in_blocks - 1;
  168865. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168866. /* Fetch current DCT block into workspace so we can modify it. */
  168867. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168868. /* Update DC values */
  168869. if (block_num < last_block_column) {
  168870. DC3 = (int) prev_block_row[1][0];
  168871. DC6 = (int) buffer_ptr[1][0];
  168872. DC9 = (int) next_block_row[1][0];
  168873. }
  168874. /* Compute coefficient estimates per K.8.
  168875. * An estimate is applied only if coefficient is still zero,
  168876. * and is not known to be fully accurate.
  168877. */
  168878. /* AC01 */
  168879. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168880. num = 36 * Q00 * (DC4 - DC6);
  168881. if (num >= 0) {
  168882. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168883. if (Al > 0 && pred >= (1<<Al))
  168884. pred = (1<<Al)-1;
  168885. } else {
  168886. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168887. if (Al > 0 && pred >= (1<<Al))
  168888. pred = (1<<Al)-1;
  168889. pred = -pred;
  168890. }
  168891. workspace[1] = (JCOEF) pred;
  168892. }
  168893. /* AC10 */
  168894. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168895. num = 36 * Q00 * (DC2 - DC8);
  168896. if (num >= 0) {
  168897. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168898. if (Al > 0 && pred >= (1<<Al))
  168899. pred = (1<<Al)-1;
  168900. } else {
  168901. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168902. if (Al > 0 && pred >= (1<<Al))
  168903. pred = (1<<Al)-1;
  168904. pred = -pred;
  168905. }
  168906. workspace[8] = (JCOEF) pred;
  168907. }
  168908. /* AC20 */
  168909. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168910. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168911. if (num >= 0) {
  168912. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168913. if (Al > 0 && pred >= (1<<Al))
  168914. pred = (1<<Al)-1;
  168915. } else {
  168916. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168917. if (Al > 0 && pred >= (1<<Al))
  168918. pred = (1<<Al)-1;
  168919. pred = -pred;
  168920. }
  168921. workspace[16] = (JCOEF) pred;
  168922. }
  168923. /* AC11 */
  168924. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168925. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168926. if (num >= 0) {
  168927. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168928. if (Al > 0 && pred >= (1<<Al))
  168929. pred = (1<<Al)-1;
  168930. } else {
  168931. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168932. if (Al > 0 && pred >= (1<<Al))
  168933. pred = (1<<Al)-1;
  168934. pred = -pred;
  168935. }
  168936. workspace[9] = (JCOEF) pred;
  168937. }
  168938. /* AC02 */
  168939. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168940. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168941. if (num >= 0) {
  168942. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168943. if (Al > 0 && pred >= (1<<Al))
  168944. pred = (1<<Al)-1;
  168945. } else {
  168946. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168947. if (Al > 0 && pred >= (1<<Al))
  168948. pred = (1<<Al)-1;
  168949. pred = -pred;
  168950. }
  168951. workspace[2] = (JCOEF) pred;
  168952. }
  168953. /* OK, do the IDCT */
  168954. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168955. output_ptr, output_col);
  168956. /* Advance for next column */
  168957. DC1 = DC2; DC2 = DC3;
  168958. DC4 = DC5; DC5 = DC6;
  168959. DC7 = DC8; DC8 = DC9;
  168960. buffer_ptr++, prev_block_row++, next_block_row++;
  168961. output_col += compptr->DCT_scaled_size;
  168962. }
  168963. output_ptr += compptr->DCT_scaled_size;
  168964. }
  168965. }
  168966. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168967. return JPEG_ROW_COMPLETED;
  168968. return JPEG_SCAN_COMPLETED;
  168969. }
  168970. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168971. /*
  168972. * Initialize coefficient buffer controller.
  168973. */
  168974. GLOBAL(void)
  168975. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168976. {
  168977. my_coef_ptr3 coef;
  168978. coef = (my_coef_ptr3)
  168979. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168980. SIZEOF(my_coef_controller3));
  168981. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168982. coef->pub.start_input_pass = start_input_pass;
  168983. coef->pub.start_output_pass = start_output_pass;
  168984. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168985. coef->coef_bits_latch = NULL;
  168986. #endif
  168987. /* Create the coefficient buffer. */
  168988. if (need_full_buffer) {
  168989. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168990. /* Allocate a full-image virtual array for each component, */
  168991. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168992. /* Note we ask for a pre-zeroed array. */
  168993. int ci, access_rows;
  168994. jpeg_component_info *compptr;
  168995. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168996. ci++, compptr++) {
  168997. access_rows = compptr->v_samp_factor;
  168998. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168999. /* If block smoothing could be used, need a bigger window */
  169000. if (cinfo->progressive_mode)
  169001. access_rows *= 3;
  169002. #endif
  169003. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169004. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169005. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169006. (long) compptr->h_samp_factor),
  169007. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169008. (long) compptr->v_samp_factor),
  169009. (JDIMENSION) access_rows);
  169010. }
  169011. coef->pub.consume_data = consume_data;
  169012. coef->pub.decompress_data = decompress_data;
  169013. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169014. #else
  169015. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169016. #endif
  169017. } else {
  169018. /* We only need a single-MCU buffer. */
  169019. JBLOCKROW buffer;
  169020. int i;
  169021. buffer = (JBLOCKROW)
  169022. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169023. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169024. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169025. coef->MCU_buffer[i] = buffer + i;
  169026. }
  169027. coef->pub.consume_data = dummy_consume_data;
  169028. coef->pub.decompress_data = decompress_onepass;
  169029. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169030. }
  169031. }
  169032. /*** End of inlined file: jdcoefct.c ***/
  169033. #undef FIX
  169034. /*** Start of inlined file: jdcolor.c ***/
  169035. #define JPEG_INTERNALS
  169036. /* Private subobject */
  169037. typedef struct {
  169038. struct jpeg_color_deconverter pub; /* public fields */
  169039. /* Private state for YCC->RGB conversion */
  169040. int * Cr_r_tab; /* => table for Cr to R conversion */
  169041. int * Cb_b_tab; /* => table for Cb to B conversion */
  169042. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169043. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169044. } my_color_deconverter2;
  169045. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169046. /**************** YCbCr -> RGB conversion: most common case **************/
  169047. /*
  169048. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169049. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169050. * The conversion equations to be implemented are therefore
  169051. * R = Y + 1.40200 * Cr
  169052. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169053. * B = Y + 1.77200 * Cb
  169054. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169055. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169056. *
  169057. * To avoid floating-point arithmetic, we represent the fractional constants
  169058. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169059. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169060. * Notice that Y, being an integral input, does not contribute any fraction
  169061. * so it need not participate in the rounding.
  169062. *
  169063. * For even more speed, we avoid doing any multiplications in the inner loop
  169064. * by precalculating the constants times Cb and Cr for all possible values.
  169065. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169066. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169067. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169068. * colorspace anyway.
  169069. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169070. * values for the G calculation are left scaled up, since we must add them
  169071. * together before rounding.
  169072. */
  169073. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169074. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169075. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169076. /*
  169077. * Initialize tables for YCC->RGB colorspace conversion.
  169078. */
  169079. LOCAL(void)
  169080. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169081. {
  169082. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169083. int i;
  169084. INT32 x;
  169085. SHIFT_TEMPS
  169086. cconvert->Cr_r_tab = (int *)
  169087. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169088. (MAXJSAMPLE+1) * SIZEOF(int));
  169089. cconvert->Cb_b_tab = (int *)
  169090. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169091. (MAXJSAMPLE+1) * SIZEOF(int));
  169092. cconvert->Cr_g_tab = (INT32 *)
  169093. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169094. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169095. cconvert->Cb_g_tab = (INT32 *)
  169096. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169097. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169098. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169099. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169100. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169101. /* Cr=>R value is nearest int to 1.40200 * x */
  169102. cconvert->Cr_r_tab[i] = (int)
  169103. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169104. /* Cb=>B value is nearest int to 1.77200 * x */
  169105. cconvert->Cb_b_tab[i] = (int)
  169106. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169107. /* Cr=>G value is scaled-up -0.71414 * x */
  169108. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169109. /* Cb=>G value is scaled-up -0.34414 * x */
  169110. /* We also add in ONE_HALF so that need not do it in inner loop */
  169111. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169112. }
  169113. }
  169114. /*
  169115. * Convert some rows of samples to the output colorspace.
  169116. *
  169117. * Note that we change from noninterleaved, one-plane-per-component format
  169118. * to interleaved-pixel format. The output buffer is therefore three times
  169119. * as wide as the input buffer.
  169120. * A starting row offset is provided only for the input buffer. The caller
  169121. * can easily adjust the passed output_buf value to accommodate any row
  169122. * offset required on that side.
  169123. */
  169124. METHODDEF(void)
  169125. ycc_rgb_convert (j_decompress_ptr cinfo,
  169126. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169127. JSAMPARRAY output_buf, int num_rows)
  169128. {
  169129. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169130. register int y, cb, cr;
  169131. register JSAMPROW outptr;
  169132. register JSAMPROW inptr0, inptr1, inptr2;
  169133. register JDIMENSION col;
  169134. JDIMENSION num_cols = cinfo->output_width;
  169135. /* copy these pointers into registers if possible */
  169136. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169137. register int * Crrtab = cconvert->Cr_r_tab;
  169138. register int * Cbbtab = cconvert->Cb_b_tab;
  169139. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169140. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169141. SHIFT_TEMPS
  169142. while (--num_rows >= 0) {
  169143. inptr0 = input_buf[0][input_row];
  169144. inptr1 = input_buf[1][input_row];
  169145. inptr2 = input_buf[2][input_row];
  169146. input_row++;
  169147. outptr = *output_buf++;
  169148. for (col = 0; col < num_cols; col++) {
  169149. y = GETJSAMPLE(inptr0[col]);
  169150. cb = GETJSAMPLE(inptr1[col]);
  169151. cr = GETJSAMPLE(inptr2[col]);
  169152. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169153. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169154. outptr[RGB_GREEN] = range_limit[y +
  169155. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169156. SCALEBITS))];
  169157. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169158. outptr += RGB_PIXELSIZE;
  169159. }
  169160. }
  169161. }
  169162. /**************** Cases other than YCbCr -> RGB **************/
  169163. /*
  169164. * Color conversion for no colorspace change: just copy the data,
  169165. * converting from separate-planes to interleaved representation.
  169166. */
  169167. METHODDEF(void)
  169168. null_convert2 (j_decompress_ptr cinfo,
  169169. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169170. JSAMPARRAY output_buf, int num_rows)
  169171. {
  169172. register JSAMPROW inptr, outptr;
  169173. register JDIMENSION count;
  169174. register int num_components = cinfo->num_components;
  169175. JDIMENSION num_cols = cinfo->output_width;
  169176. int ci;
  169177. while (--num_rows >= 0) {
  169178. for (ci = 0; ci < num_components; ci++) {
  169179. inptr = input_buf[ci][input_row];
  169180. outptr = output_buf[0] + ci;
  169181. for (count = num_cols; count > 0; count--) {
  169182. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169183. outptr += num_components;
  169184. }
  169185. }
  169186. input_row++;
  169187. output_buf++;
  169188. }
  169189. }
  169190. /*
  169191. * Color conversion for grayscale: just copy the data.
  169192. * This also works for YCbCr -> grayscale conversion, in which
  169193. * we just copy the Y (luminance) component and ignore chrominance.
  169194. */
  169195. METHODDEF(void)
  169196. grayscale_convert2 (j_decompress_ptr cinfo,
  169197. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169198. JSAMPARRAY output_buf, int num_rows)
  169199. {
  169200. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169201. num_rows, cinfo->output_width);
  169202. }
  169203. /*
  169204. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169205. * This is provided to support applications that don't want to cope
  169206. * with grayscale as a separate case.
  169207. */
  169208. METHODDEF(void)
  169209. gray_rgb_convert (j_decompress_ptr cinfo,
  169210. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169211. JSAMPARRAY output_buf, int num_rows)
  169212. {
  169213. register JSAMPROW inptr, outptr;
  169214. register JDIMENSION col;
  169215. JDIMENSION num_cols = cinfo->output_width;
  169216. while (--num_rows >= 0) {
  169217. inptr = input_buf[0][input_row++];
  169218. outptr = *output_buf++;
  169219. for (col = 0; col < num_cols; col++) {
  169220. /* We can dispense with GETJSAMPLE() here */
  169221. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169222. outptr += RGB_PIXELSIZE;
  169223. }
  169224. }
  169225. }
  169226. /*
  169227. * Adobe-style YCCK->CMYK conversion.
  169228. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169229. * conversion as above, while passing K (black) unchanged.
  169230. * We assume build_ycc_rgb_table has been called.
  169231. */
  169232. METHODDEF(void)
  169233. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169234. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169235. JSAMPARRAY output_buf, int num_rows)
  169236. {
  169237. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169238. register int y, cb, cr;
  169239. register JSAMPROW outptr;
  169240. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169241. register JDIMENSION col;
  169242. JDIMENSION num_cols = cinfo->output_width;
  169243. /* copy these pointers into registers if possible */
  169244. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169245. register int * Crrtab = cconvert->Cr_r_tab;
  169246. register int * Cbbtab = cconvert->Cb_b_tab;
  169247. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169248. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169249. SHIFT_TEMPS
  169250. while (--num_rows >= 0) {
  169251. inptr0 = input_buf[0][input_row];
  169252. inptr1 = input_buf[1][input_row];
  169253. inptr2 = input_buf[2][input_row];
  169254. inptr3 = input_buf[3][input_row];
  169255. input_row++;
  169256. outptr = *output_buf++;
  169257. for (col = 0; col < num_cols; col++) {
  169258. y = GETJSAMPLE(inptr0[col]);
  169259. cb = GETJSAMPLE(inptr1[col]);
  169260. cr = GETJSAMPLE(inptr2[col]);
  169261. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169262. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169263. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169264. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169265. SCALEBITS)))];
  169266. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169267. /* K passes through unchanged */
  169268. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169269. outptr += 4;
  169270. }
  169271. }
  169272. }
  169273. /*
  169274. * Empty method for start_pass.
  169275. */
  169276. METHODDEF(void)
  169277. start_pass_dcolor (j_decompress_ptr)
  169278. {
  169279. /* no work needed */
  169280. }
  169281. /*
  169282. * Module initialization routine for output colorspace conversion.
  169283. */
  169284. GLOBAL(void)
  169285. jinit_color_deconverter (j_decompress_ptr cinfo)
  169286. {
  169287. my_cconvert_ptr2 cconvert;
  169288. int ci;
  169289. cconvert = (my_cconvert_ptr2)
  169290. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169291. SIZEOF(my_color_deconverter2));
  169292. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169293. cconvert->pub.start_pass = start_pass_dcolor;
  169294. /* Make sure num_components agrees with jpeg_color_space */
  169295. switch (cinfo->jpeg_color_space) {
  169296. case JCS_GRAYSCALE:
  169297. if (cinfo->num_components != 1)
  169298. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169299. break;
  169300. case JCS_RGB:
  169301. case JCS_YCbCr:
  169302. if (cinfo->num_components != 3)
  169303. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169304. break;
  169305. case JCS_CMYK:
  169306. case JCS_YCCK:
  169307. if (cinfo->num_components != 4)
  169308. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169309. break;
  169310. default: /* JCS_UNKNOWN can be anything */
  169311. if (cinfo->num_components < 1)
  169312. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169313. break;
  169314. }
  169315. /* Set out_color_components and conversion method based on requested space.
  169316. * Also clear the component_needed flags for any unused components,
  169317. * so that earlier pipeline stages can avoid useless computation.
  169318. */
  169319. switch (cinfo->out_color_space) {
  169320. case JCS_GRAYSCALE:
  169321. cinfo->out_color_components = 1;
  169322. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169323. cinfo->jpeg_color_space == JCS_YCbCr) {
  169324. cconvert->pub.color_convert = grayscale_convert2;
  169325. /* For color->grayscale conversion, only the Y (0) component is needed */
  169326. for (ci = 1; ci < cinfo->num_components; ci++)
  169327. cinfo->comp_info[ci].component_needed = FALSE;
  169328. } else
  169329. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169330. break;
  169331. case JCS_RGB:
  169332. cinfo->out_color_components = RGB_PIXELSIZE;
  169333. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169334. cconvert->pub.color_convert = ycc_rgb_convert;
  169335. build_ycc_rgb_table(cinfo);
  169336. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169337. cconvert->pub.color_convert = gray_rgb_convert;
  169338. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169339. cconvert->pub.color_convert = null_convert2;
  169340. } else
  169341. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169342. break;
  169343. case JCS_CMYK:
  169344. cinfo->out_color_components = 4;
  169345. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169346. cconvert->pub.color_convert = ycck_cmyk_convert;
  169347. build_ycc_rgb_table(cinfo);
  169348. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169349. cconvert->pub.color_convert = null_convert2;
  169350. } else
  169351. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169352. break;
  169353. default:
  169354. /* Permit null conversion to same output space */
  169355. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169356. cinfo->out_color_components = cinfo->num_components;
  169357. cconvert->pub.color_convert = null_convert2;
  169358. } else /* unsupported non-null conversion */
  169359. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169360. break;
  169361. }
  169362. if (cinfo->quantize_colors)
  169363. cinfo->output_components = 1; /* single colormapped output component */
  169364. else
  169365. cinfo->output_components = cinfo->out_color_components;
  169366. }
  169367. /*** End of inlined file: jdcolor.c ***/
  169368. #undef FIX
  169369. /*** Start of inlined file: jddctmgr.c ***/
  169370. #define JPEG_INTERNALS
  169371. /*
  169372. * The decompressor input side (jdinput.c) saves away the appropriate
  169373. * quantization table for each component at the start of the first scan
  169374. * involving that component. (This is necessary in order to correctly
  169375. * decode files that reuse Q-table slots.)
  169376. * When we are ready to make an output pass, the saved Q-table is converted
  169377. * to a multiplier table that will actually be used by the IDCT routine.
  169378. * The multiplier table contents are IDCT-method-dependent. To support
  169379. * application changes in IDCT method between scans, we can remake the
  169380. * multiplier tables if necessary.
  169381. * In buffered-image mode, the first output pass may occur before any data
  169382. * has been seen for some components, and thus before their Q-tables have
  169383. * been saved away. To handle this case, multiplier tables are preset
  169384. * to zeroes; the result of the IDCT will be a neutral gray level.
  169385. */
  169386. /* Private subobject for this module */
  169387. typedef struct {
  169388. struct jpeg_inverse_dct pub; /* public fields */
  169389. /* This array contains the IDCT method code that each multiplier table
  169390. * is currently set up for, or -1 if it's not yet set up.
  169391. * The actual multiplier tables are pointed to by dct_table in the
  169392. * per-component comp_info structures.
  169393. */
  169394. int cur_method[MAX_COMPONENTS];
  169395. } my_idct_controller;
  169396. typedef my_idct_controller * my_idct_ptr;
  169397. /* Allocated multiplier tables: big enough for any supported variant */
  169398. typedef union {
  169399. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169400. #ifdef DCT_IFAST_SUPPORTED
  169401. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169402. #endif
  169403. #ifdef DCT_FLOAT_SUPPORTED
  169404. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169405. #endif
  169406. } multiplier_table;
  169407. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169408. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169409. */
  169410. #ifdef DCT_ISLOW_SUPPORTED
  169411. #define PROVIDE_ISLOW_TABLES
  169412. #else
  169413. #ifdef IDCT_SCALING_SUPPORTED
  169414. #define PROVIDE_ISLOW_TABLES
  169415. #endif
  169416. #endif
  169417. /*
  169418. * Prepare for an output pass.
  169419. * Here we select the proper IDCT routine for each component and build
  169420. * a matching multiplier table.
  169421. */
  169422. METHODDEF(void)
  169423. start_pass (j_decompress_ptr cinfo)
  169424. {
  169425. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169426. int ci, i;
  169427. jpeg_component_info *compptr;
  169428. int method = 0;
  169429. inverse_DCT_method_ptr method_ptr = NULL;
  169430. JQUANT_TBL * qtbl;
  169431. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169432. ci++, compptr++) {
  169433. /* Select the proper IDCT routine for this component's scaling */
  169434. switch (compptr->DCT_scaled_size) {
  169435. #ifdef IDCT_SCALING_SUPPORTED
  169436. case 1:
  169437. method_ptr = jpeg_idct_1x1;
  169438. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169439. break;
  169440. case 2:
  169441. method_ptr = jpeg_idct_2x2;
  169442. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169443. break;
  169444. case 4:
  169445. method_ptr = jpeg_idct_4x4;
  169446. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169447. break;
  169448. #endif
  169449. case DCTSIZE:
  169450. switch (cinfo->dct_method) {
  169451. #ifdef DCT_ISLOW_SUPPORTED
  169452. case JDCT_ISLOW:
  169453. method_ptr = jpeg_idct_islow;
  169454. method = JDCT_ISLOW;
  169455. break;
  169456. #endif
  169457. #ifdef DCT_IFAST_SUPPORTED
  169458. case JDCT_IFAST:
  169459. method_ptr = jpeg_idct_ifast;
  169460. method = JDCT_IFAST;
  169461. break;
  169462. #endif
  169463. #ifdef DCT_FLOAT_SUPPORTED
  169464. case JDCT_FLOAT:
  169465. method_ptr = jpeg_idct_float;
  169466. method = JDCT_FLOAT;
  169467. break;
  169468. #endif
  169469. default:
  169470. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169471. break;
  169472. }
  169473. break;
  169474. default:
  169475. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169476. break;
  169477. }
  169478. idct->pub.inverse_DCT[ci] = method_ptr;
  169479. /* Create multiplier table from quant table.
  169480. * However, we can skip this if the component is uninteresting
  169481. * or if we already built the table. Also, if no quant table
  169482. * has yet been saved for the component, we leave the
  169483. * multiplier table all-zero; we'll be reading zeroes from the
  169484. * coefficient controller's buffer anyway.
  169485. */
  169486. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169487. continue;
  169488. qtbl = compptr->quant_table;
  169489. if (qtbl == NULL) /* happens if no data yet for component */
  169490. continue;
  169491. idct->cur_method[ci] = method;
  169492. switch (method) {
  169493. #ifdef PROVIDE_ISLOW_TABLES
  169494. case JDCT_ISLOW:
  169495. {
  169496. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169497. * coefficients, but are stored as ints to ensure access efficiency.
  169498. */
  169499. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169500. for (i = 0; i < DCTSIZE2; i++) {
  169501. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169502. }
  169503. }
  169504. break;
  169505. #endif
  169506. #ifdef DCT_IFAST_SUPPORTED
  169507. case JDCT_IFAST:
  169508. {
  169509. /* For AA&N IDCT method, multipliers are equal to quantization
  169510. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169511. * scalefactor[0] = 1
  169512. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169513. * For integer operation, the multiplier table is to be scaled by
  169514. * IFAST_SCALE_BITS.
  169515. */
  169516. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169517. #define CONST_BITS 14
  169518. static const INT16 aanscales[DCTSIZE2] = {
  169519. /* precomputed values scaled up by 14 bits */
  169520. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169521. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169522. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169523. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169524. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169525. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169526. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169527. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169528. };
  169529. SHIFT_TEMPS
  169530. for (i = 0; i < DCTSIZE2; i++) {
  169531. ifmtbl[i] = (IFAST_MULT_TYPE)
  169532. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169533. (INT32) aanscales[i]),
  169534. CONST_BITS-IFAST_SCALE_BITS);
  169535. }
  169536. }
  169537. break;
  169538. #endif
  169539. #ifdef DCT_FLOAT_SUPPORTED
  169540. case JDCT_FLOAT:
  169541. {
  169542. /* For float AA&N IDCT method, multipliers are equal to quantization
  169543. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169544. * scalefactor[0] = 1
  169545. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169546. */
  169547. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169548. int row, col;
  169549. static const double aanscalefactor[DCTSIZE] = {
  169550. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169551. 1.0, 0.785694958, 0.541196100, 0.275899379
  169552. };
  169553. i = 0;
  169554. for (row = 0; row < DCTSIZE; row++) {
  169555. for (col = 0; col < DCTSIZE; col++) {
  169556. fmtbl[i] = (FLOAT_MULT_TYPE)
  169557. ((double) qtbl->quantval[i] *
  169558. aanscalefactor[row] * aanscalefactor[col]);
  169559. i++;
  169560. }
  169561. }
  169562. }
  169563. break;
  169564. #endif
  169565. default:
  169566. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169567. break;
  169568. }
  169569. }
  169570. }
  169571. /*
  169572. * Initialize IDCT manager.
  169573. */
  169574. GLOBAL(void)
  169575. jinit_inverse_dct (j_decompress_ptr cinfo)
  169576. {
  169577. my_idct_ptr idct;
  169578. int ci;
  169579. jpeg_component_info *compptr;
  169580. idct = (my_idct_ptr)
  169581. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169582. SIZEOF(my_idct_controller));
  169583. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169584. idct->pub.start_pass = start_pass;
  169585. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169586. ci++, compptr++) {
  169587. /* Allocate and pre-zero a multiplier table for each component */
  169588. compptr->dct_table =
  169589. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169590. SIZEOF(multiplier_table));
  169591. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169592. /* Mark multiplier table not yet set up for any method */
  169593. idct->cur_method[ci] = -1;
  169594. }
  169595. }
  169596. /*** End of inlined file: jddctmgr.c ***/
  169597. #undef CONST_BITS
  169598. #undef ASSIGN_STATE
  169599. /*** Start of inlined file: jdhuff.c ***/
  169600. #define JPEG_INTERNALS
  169601. /*** Start of inlined file: jdhuff.h ***/
  169602. /* Short forms of external names for systems with brain-damaged linkers. */
  169603. #ifndef __jdhuff_h__
  169604. #define __jdhuff_h__
  169605. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169606. #define jpeg_make_d_derived_tbl jMkDDerived
  169607. #define jpeg_fill_bit_buffer jFilBitBuf
  169608. #define jpeg_huff_decode jHufDecode
  169609. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169610. /* Derived data constructed for each Huffman table */
  169611. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169612. typedef struct {
  169613. /* Basic tables: (element [0] of each array is unused) */
  169614. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169615. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169616. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169617. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169618. * the smallest code of length k; so given a code of length k, the
  169619. * corresponding symbol is huffval[code + valoffset[k]]
  169620. */
  169621. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169622. JHUFF_TBL *pub;
  169623. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169624. * the input data stream. If the next Huffman code is no more
  169625. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169626. * the corresponding symbol directly from these tables.
  169627. */
  169628. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169629. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169630. } d_derived_tbl;
  169631. /* Expand a Huffman table definition into the derived format */
  169632. EXTERN(void) jpeg_make_d_derived_tbl
  169633. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169634. d_derived_tbl ** pdtbl));
  169635. /*
  169636. * Fetching the next N bits from the input stream is a time-critical operation
  169637. * for the Huffman decoders. We implement it with a combination of inline
  169638. * macros and out-of-line subroutines. Note that N (the number of bits
  169639. * demanded at one time) never exceeds 15 for JPEG use.
  169640. *
  169641. * We read source bytes into get_buffer and dole out bits as needed.
  169642. * If get_buffer already contains enough bits, they are fetched in-line
  169643. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169644. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169645. * as full as possible (not just to the number of bits needed; this
  169646. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169647. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169648. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169649. * at least the requested number of bits --- dummy zeroes are inserted if
  169650. * necessary.
  169651. */
  169652. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169653. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169654. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169655. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169656. * appropriately should be a win. Unfortunately we can't define the size
  169657. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169658. * because not all machines measure sizeof in 8-bit bytes.
  169659. */
  169660. typedef struct { /* Bitreading state saved across MCUs */
  169661. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169662. int bits_left; /* # of unused bits in it */
  169663. } bitread_perm_state;
  169664. typedef struct { /* Bitreading working state within an MCU */
  169665. /* Current data source location */
  169666. /* We need a copy, rather than munging the original, in case of suspension */
  169667. const JOCTET * next_input_byte; /* => next byte to read from source */
  169668. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169669. /* Bit input buffer --- note these values are kept in register variables,
  169670. * not in this struct, inside the inner loops.
  169671. */
  169672. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169673. int bits_left; /* # of unused bits in it */
  169674. /* Pointer needed by jpeg_fill_bit_buffer. */
  169675. j_decompress_ptr cinfo; /* back link to decompress master record */
  169676. } bitread_working_state;
  169677. /* Macros to declare and load/save bitread local variables. */
  169678. #define BITREAD_STATE_VARS \
  169679. register bit_buf_type get_buffer; \
  169680. register int bits_left; \
  169681. bitread_working_state br_state
  169682. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169683. br_state.cinfo = cinfop; \
  169684. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169685. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169686. get_buffer = permstate.get_buffer; \
  169687. bits_left = permstate.bits_left;
  169688. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169689. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169690. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169691. permstate.get_buffer = get_buffer; \
  169692. permstate.bits_left = bits_left
  169693. /*
  169694. * These macros provide the in-line portion of bit fetching.
  169695. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169696. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169697. * The variables get_buffer and bits_left are assumed to be locals,
  169698. * but the state struct might not be (jpeg_huff_decode needs this).
  169699. * CHECK_BIT_BUFFER(state,n,action);
  169700. * Ensure there are N bits in get_buffer; if suspend, take action.
  169701. * val = GET_BITS(n);
  169702. * Fetch next N bits.
  169703. * val = PEEK_BITS(n);
  169704. * Fetch next N bits without removing them from the buffer.
  169705. * DROP_BITS(n);
  169706. * Discard next N bits.
  169707. * The value N should be a simple variable, not an expression, because it
  169708. * is evaluated multiple times.
  169709. */
  169710. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169711. { if (bits_left < (nbits)) { \
  169712. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169713. { action; } \
  169714. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169715. #define GET_BITS(nbits) \
  169716. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169717. #define PEEK_BITS(nbits) \
  169718. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169719. #define DROP_BITS(nbits) \
  169720. (bits_left -= (nbits))
  169721. /* Load up the bit buffer to a depth of at least nbits */
  169722. EXTERN(boolean) jpeg_fill_bit_buffer
  169723. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169724. register int bits_left, int nbits));
  169725. /*
  169726. * Code for extracting next Huffman-coded symbol from input bit stream.
  169727. * Again, this is time-critical and we make the main paths be macros.
  169728. *
  169729. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169730. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169731. * or fewer bits long. The few overlength codes are handled with a loop,
  169732. * which need not be inline code.
  169733. *
  169734. * Notes about the HUFF_DECODE macro:
  169735. * 1. Near the end of the data segment, we may fail to get enough bits
  169736. * for a lookahead. In that case, we do it the hard way.
  169737. * 2. If the lookahead table contains no entry, the next code must be
  169738. * more than HUFF_LOOKAHEAD bits long.
  169739. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169740. */
  169741. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169742. { register int nb, look; \
  169743. if (bits_left < HUFF_LOOKAHEAD) { \
  169744. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169745. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169746. if (bits_left < HUFF_LOOKAHEAD) { \
  169747. nb = 1; goto slowlabel; \
  169748. } \
  169749. } \
  169750. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169751. if ((nb = htbl->look_nbits[look]) != 0) { \
  169752. DROP_BITS(nb); \
  169753. result = htbl->look_sym[look]; \
  169754. } else { \
  169755. nb = HUFF_LOOKAHEAD+1; \
  169756. slowlabel: \
  169757. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169758. { failaction; } \
  169759. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169760. } \
  169761. }
  169762. /* Out-of-line case for Huffman code fetching */
  169763. EXTERN(int) jpeg_huff_decode
  169764. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169765. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169766. #endif
  169767. /*** End of inlined file: jdhuff.h ***/
  169768. /* Declarations shared with jdphuff.c */
  169769. /*
  169770. * Expanded entropy decoder object for Huffman decoding.
  169771. *
  169772. * The savable_state subrecord contains fields that change within an MCU,
  169773. * but must not be updated permanently until we complete the MCU.
  169774. */
  169775. typedef struct {
  169776. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169777. } savable_state2;
  169778. /* This macro is to work around compilers with missing or broken
  169779. * structure assignment. You'll need to fix this code if you have
  169780. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169781. */
  169782. #ifndef NO_STRUCT_ASSIGN
  169783. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169784. #else
  169785. #if MAX_COMPS_IN_SCAN == 4
  169786. #define ASSIGN_STATE(dest,src) \
  169787. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169788. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169789. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169790. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169791. #endif
  169792. #endif
  169793. typedef struct {
  169794. struct jpeg_entropy_decoder pub; /* public fields */
  169795. /* These fields are loaded into local variables at start of each MCU.
  169796. * In case of suspension, we exit WITHOUT updating them.
  169797. */
  169798. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169799. savable_state2 saved; /* Other state at start of MCU */
  169800. /* These fields are NOT loaded into local working state. */
  169801. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169802. /* Pointers to derived tables (these workspaces have image lifespan) */
  169803. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169804. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169805. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169806. /* Pointers to derived tables to be used for each block within an MCU */
  169807. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169808. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169809. /* Whether we care about the DC and AC coefficient values for each block */
  169810. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169811. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169812. } huff_entropy_decoder2;
  169813. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169814. /*
  169815. * Initialize for a Huffman-compressed scan.
  169816. */
  169817. METHODDEF(void)
  169818. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169819. {
  169820. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169821. int ci, blkn, dctbl, actbl;
  169822. jpeg_component_info * compptr;
  169823. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169824. * This ought to be an error condition, but we make it a warning because
  169825. * there are some baseline files out there with all zeroes in these bytes.
  169826. */
  169827. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169828. cinfo->Ah != 0 || cinfo->Al != 0)
  169829. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169830. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169831. compptr = cinfo->cur_comp_info[ci];
  169832. dctbl = compptr->dc_tbl_no;
  169833. actbl = compptr->ac_tbl_no;
  169834. /* Compute derived values for Huffman tables */
  169835. /* We may do this more than once for a table, but it's not expensive */
  169836. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169837. & entropy->dc_derived_tbls[dctbl]);
  169838. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169839. & entropy->ac_derived_tbls[actbl]);
  169840. /* Initialize DC predictions to 0 */
  169841. entropy->saved.last_dc_val[ci] = 0;
  169842. }
  169843. /* Precalculate decoding info for each block in an MCU of this scan */
  169844. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169845. ci = cinfo->MCU_membership[blkn];
  169846. compptr = cinfo->cur_comp_info[ci];
  169847. /* Precalculate which table to use for each block */
  169848. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169849. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169850. /* Decide whether we really care about the coefficient values */
  169851. if (compptr->component_needed) {
  169852. entropy->dc_needed[blkn] = TRUE;
  169853. /* we don't need the ACs if producing a 1/8th-size image */
  169854. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169855. } else {
  169856. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169857. }
  169858. }
  169859. /* Initialize bitread state variables */
  169860. entropy->bitstate.bits_left = 0;
  169861. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169862. entropy->pub.insufficient_data = FALSE;
  169863. /* Initialize restart counter */
  169864. entropy->restarts_to_go = cinfo->restart_interval;
  169865. }
  169866. /*
  169867. * Compute the derived values for a Huffman table.
  169868. * This routine also performs some validation checks on the table.
  169869. *
  169870. * Note this is also used by jdphuff.c.
  169871. */
  169872. GLOBAL(void)
  169873. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169874. d_derived_tbl ** pdtbl)
  169875. {
  169876. JHUFF_TBL *htbl;
  169877. d_derived_tbl *dtbl;
  169878. int p, i, l, si, numsymbols;
  169879. int lookbits, ctr;
  169880. char huffsize[257];
  169881. unsigned int huffcode[257];
  169882. unsigned int code;
  169883. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169884. * paralleling the order of the symbols themselves in htbl->huffval[].
  169885. */
  169886. /* Find the input Huffman table */
  169887. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169888. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169889. htbl =
  169890. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169891. if (htbl == NULL)
  169892. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169893. /* Allocate a workspace if we haven't already done so. */
  169894. if (*pdtbl == NULL)
  169895. *pdtbl = (d_derived_tbl *)
  169896. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169897. SIZEOF(d_derived_tbl));
  169898. dtbl = *pdtbl;
  169899. dtbl->pub = htbl; /* fill in back link */
  169900. /* Figure C.1: make table of Huffman code length for each symbol */
  169901. p = 0;
  169902. for (l = 1; l <= 16; l++) {
  169903. i = (int) htbl->bits[l];
  169904. if (i < 0 || p + i > 256) /* protect against table overrun */
  169905. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169906. while (i--)
  169907. huffsize[p++] = (char) l;
  169908. }
  169909. huffsize[p] = 0;
  169910. numsymbols = p;
  169911. /* Figure C.2: generate the codes themselves */
  169912. /* We also validate that the counts represent a legal Huffman code tree. */
  169913. code = 0;
  169914. si = huffsize[0];
  169915. p = 0;
  169916. while (huffsize[p]) {
  169917. while (((int) huffsize[p]) == si) {
  169918. huffcode[p++] = code;
  169919. code++;
  169920. }
  169921. /* code is now 1 more than the last code used for codelength si; but
  169922. * it must still fit in si bits, since no code is allowed to be all ones.
  169923. */
  169924. if (((INT32) code) >= (((INT32) 1) << si))
  169925. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169926. code <<= 1;
  169927. si++;
  169928. }
  169929. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169930. p = 0;
  169931. for (l = 1; l <= 16; l++) {
  169932. if (htbl->bits[l]) {
  169933. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169934. * minus the minimum code of length l
  169935. */
  169936. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169937. p += htbl->bits[l];
  169938. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169939. } else {
  169940. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169941. }
  169942. }
  169943. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169944. /* Compute lookahead tables to speed up decoding.
  169945. * First we set all the table entries to 0, indicating "too long";
  169946. * then we iterate through the Huffman codes that are short enough and
  169947. * fill in all the entries that correspond to bit sequences starting
  169948. * with that code.
  169949. */
  169950. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169951. p = 0;
  169952. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169953. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169954. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169955. /* Generate left-justified code followed by all possible bit sequences */
  169956. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169957. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169958. dtbl->look_nbits[lookbits] = l;
  169959. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169960. lookbits++;
  169961. }
  169962. }
  169963. }
  169964. /* Validate symbols as being reasonable.
  169965. * For AC tables, we make no check, but accept all byte values 0..255.
  169966. * For DC tables, we require the symbols to be in range 0..15.
  169967. * (Tighter bounds could be applied depending on the data depth and mode,
  169968. * but this is sufficient to ensure safe decoding.)
  169969. */
  169970. if (isDC) {
  169971. for (i = 0; i < numsymbols; i++) {
  169972. int sym = htbl->huffval[i];
  169973. if (sym < 0 || sym > 15)
  169974. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169975. }
  169976. }
  169977. }
  169978. /*
  169979. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169980. * See jdhuff.h for info about usage.
  169981. * Note: current values of get_buffer and bits_left are passed as parameters,
  169982. * but are returned in the corresponding fields of the state struct.
  169983. *
  169984. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169985. * of get_buffer to be used. (On machines with wider words, an even larger
  169986. * buffer could be used.) However, on some machines 32-bit shifts are
  169987. * quite slow and take time proportional to the number of places shifted.
  169988. * (This is true with most PC compilers, for instance.) In this case it may
  169989. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169990. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169991. */
  169992. #ifdef SLOW_SHIFT_32
  169993. #define MIN_GET_BITS 15 /* minimum allowable value */
  169994. #else
  169995. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169996. #endif
  169997. GLOBAL(boolean)
  169998. jpeg_fill_bit_buffer (bitread_working_state * state,
  169999. register bit_buf_type get_buffer, register int bits_left,
  170000. int nbits)
  170001. /* Load up the bit buffer to a depth of at least nbits */
  170002. {
  170003. /* Copy heavily used state fields into locals (hopefully registers) */
  170004. register const JOCTET * next_input_byte = state->next_input_byte;
  170005. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170006. j_decompress_ptr cinfo = state->cinfo;
  170007. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170008. /* (It is assumed that no request will be for more than that many bits.) */
  170009. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170010. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170011. while (bits_left < MIN_GET_BITS) {
  170012. register int c;
  170013. /* Attempt to read a byte */
  170014. if (bytes_in_buffer == 0) {
  170015. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170016. return FALSE;
  170017. next_input_byte = cinfo->src->next_input_byte;
  170018. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170019. }
  170020. bytes_in_buffer--;
  170021. c = GETJOCTET(*next_input_byte++);
  170022. /* If it's 0xFF, check and discard stuffed zero byte */
  170023. if (c == 0xFF) {
  170024. /* Loop here to discard any padding FF's on terminating marker,
  170025. * so that we can save a valid unread_marker value. NOTE: we will
  170026. * accept multiple FF's followed by a 0 as meaning a single FF data
  170027. * byte. This data pattern is not valid according to the standard.
  170028. */
  170029. do {
  170030. if (bytes_in_buffer == 0) {
  170031. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170032. return FALSE;
  170033. next_input_byte = cinfo->src->next_input_byte;
  170034. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170035. }
  170036. bytes_in_buffer--;
  170037. c = GETJOCTET(*next_input_byte++);
  170038. } while (c == 0xFF);
  170039. if (c == 0) {
  170040. /* Found FF/00, which represents an FF data byte */
  170041. c = 0xFF;
  170042. } else {
  170043. /* Oops, it's actually a marker indicating end of compressed data.
  170044. * Save the marker code for later use.
  170045. * Fine point: it might appear that we should save the marker into
  170046. * bitread working state, not straight into permanent state. But
  170047. * once we have hit a marker, we cannot need to suspend within the
  170048. * current MCU, because we will read no more bytes from the data
  170049. * source. So it is OK to update permanent state right away.
  170050. */
  170051. cinfo->unread_marker = c;
  170052. /* See if we need to insert some fake zero bits. */
  170053. goto no_more_bytes;
  170054. }
  170055. }
  170056. /* OK, load c into get_buffer */
  170057. get_buffer = (get_buffer << 8) | c;
  170058. bits_left += 8;
  170059. } /* end while */
  170060. } else {
  170061. no_more_bytes:
  170062. /* We get here if we've read the marker that terminates the compressed
  170063. * data segment. There should be enough bits in the buffer register
  170064. * to satisfy the request; if so, no problem.
  170065. */
  170066. if (nbits > bits_left) {
  170067. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170068. * the data stream, so that we can produce some kind of image.
  170069. * We use a nonvolatile flag to ensure that only one warning message
  170070. * appears per data segment.
  170071. */
  170072. if (! cinfo->entropy->insufficient_data) {
  170073. WARNMS(cinfo, JWRN_HIT_MARKER);
  170074. cinfo->entropy->insufficient_data = TRUE;
  170075. }
  170076. /* Fill the buffer with zero bits */
  170077. get_buffer <<= MIN_GET_BITS - bits_left;
  170078. bits_left = MIN_GET_BITS;
  170079. }
  170080. }
  170081. /* Unload the local registers */
  170082. state->next_input_byte = next_input_byte;
  170083. state->bytes_in_buffer = bytes_in_buffer;
  170084. state->get_buffer = get_buffer;
  170085. state->bits_left = bits_left;
  170086. return TRUE;
  170087. }
  170088. /*
  170089. * Out-of-line code for Huffman code decoding.
  170090. * See jdhuff.h for info about usage.
  170091. */
  170092. GLOBAL(int)
  170093. jpeg_huff_decode (bitread_working_state * state,
  170094. register bit_buf_type get_buffer, register int bits_left,
  170095. d_derived_tbl * htbl, int min_bits)
  170096. {
  170097. register int l = min_bits;
  170098. register INT32 code;
  170099. /* HUFF_DECODE has determined that the code is at least min_bits */
  170100. /* bits long, so fetch that many bits in one swoop. */
  170101. CHECK_BIT_BUFFER(*state, l, return -1);
  170102. code = GET_BITS(l);
  170103. /* Collect the rest of the Huffman code one bit at a time. */
  170104. /* This is per Figure F.16 in the JPEG spec. */
  170105. while (code > htbl->maxcode[l]) {
  170106. code <<= 1;
  170107. CHECK_BIT_BUFFER(*state, 1, return -1);
  170108. code |= GET_BITS(1);
  170109. l++;
  170110. }
  170111. /* Unload the local registers */
  170112. state->get_buffer = get_buffer;
  170113. state->bits_left = bits_left;
  170114. /* With garbage input we may reach the sentinel value l = 17. */
  170115. if (l > 16) {
  170116. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170117. return 0; /* fake a zero as the safest result */
  170118. }
  170119. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170120. }
  170121. /*
  170122. * Check for a restart marker & resynchronize decoder.
  170123. * Returns FALSE if must suspend.
  170124. */
  170125. LOCAL(boolean)
  170126. process_restart (j_decompress_ptr cinfo)
  170127. {
  170128. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170129. int ci;
  170130. /* Throw away any unused bits remaining in bit buffer; */
  170131. /* include any full bytes in next_marker's count of discarded bytes */
  170132. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170133. entropy->bitstate.bits_left = 0;
  170134. /* Advance past the RSTn marker */
  170135. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170136. return FALSE;
  170137. /* Re-initialize DC predictions to 0 */
  170138. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170139. entropy->saved.last_dc_val[ci] = 0;
  170140. /* Reset restart counter */
  170141. entropy->restarts_to_go = cinfo->restart_interval;
  170142. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170143. * against a marker. In that case we will end up treating the next data
  170144. * segment as empty, and we can avoid producing bogus output pixels by
  170145. * leaving the flag set.
  170146. */
  170147. if (cinfo->unread_marker == 0)
  170148. entropy->pub.insufficient_data = FALSE;
  170149. return TRUE;
  170150. }
  170151. /*
  170152. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170153. * The coefficients are reordered from zigzag order into natural array order,
  170154. * but are not dequantized.
  170155. *
  170156. * The i'th block of the MCU is stored into the block pointed to by
  170157. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170158. * (Wholesale zeroing is usually a little faster than retail...)
  170159. *
  170160. * Returns FALSE if data source requested suspension. In that case no
  170161. * changes have been made to permanent state. (Exception: some output
  170162. * coefficients may already have been assigned. This is harmless for
  170163. * this module, since we'll just re-assign them on the next call.)
  170164. */
  170165. METHODDEF(boolean)
  170166. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170167. {
  170168. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170169. int blkn;
  170170. BITREAD_STATE_VARS;
  170171. savable_state2 state;
  170172. /* Process restart marker if needed; may have to suspend */
  170173. if (cinfo->restart_interval) {
  170174. if (entropy->restarts_to_go == 0)
  170175. if (! process_restart(cinfo))
  170176. return FALSE;
  170177. }
  170178. /* If we've run out of data, just leave the MCU set to zeroes.
  170179. * This way, we return uniform gray for the remainder of the segment.
  170180. */
  170181. if (! entropy->pub.insufficient_data) {
  170182. /* Load up working state */
  170183. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170184. ASSIGN_STATE(state, entropy->saved);
  170185. /* Outer loop handles each block in the MCU */
  170186. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170187. JBLOCKROW block = MCU_data[blkn];
  170188. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170189. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170190. register int s, k, r;
  170191. /* Decode a single block's worth of coefficients */
  170192. /* Section F.2.2.1: decode the DC coefficient difference */
  170193. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170194. if (s) {
  170195. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170196. r = GET_BITS(s);
  170197. s = HUFF_EXTEND(r, s);
  170198. }
  170199. if (entropy->dc_needed[blkn]) {
  170200. /* Convert DC difference to actual value, update last_dc_val */
  170201. int ci = cinfo->MCU_membership[blkn];
  170202. s += state.last_dc_val[ci];
  170203. state.last_dc_val[ci] = s;
  170204. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170205. (*block)[0] = (JCOEF) s;
  170206. }
  170207. if (entropy->ac_needed[blkn]) {
  170208. /* Section F.2.2.2: decode the AC coefficients */
  170209. /* Since zeroes are skipped, output area must be cleared beforehand */
  170210. for (k = 1; k < DCTSIZE2; k++) {
  170211. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170212. r = s >> 4;
  170213. s &= 15;
  170214. if (s) {
  170215. k += r;
  170216. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170217. r = GET_BITS(s);
  170218. s = HUFF_EXTEND(r, s);
  170219. /* Output coefficient in natural (dezigzagged) order.
  170220. * Note: the extra entries in jpeg_natural_order[] will save us
  170221. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170222. */
  170223. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170224. } else {
  170225. if (r != 15)
  170226. break;
  170227. k += 15;
  170228. }
  170229. }
  170230. } else {
  170231. /* Section F.2.2.2: decode the AC coefficients */
  170232. /* In this path we just discard the values */
  170233. for (k = 1; k < DCTSIZE2; k++) {
  170234. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170235. r = s >> 4;
  170236. s &= 15;
  170237. if (s) {
  170238. k += r;
  170239. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170240. DROP_BITS(s);
  170241. } else {
  170242. if (r != 15)
  170243. break;
  170244. k += 15;
  170245. }
  170246. }
  170247. }
  170248. }
  170249. /* Completed MCU, so update state */
  170250. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170251. ASSIGN_STATE(entropy->saved, state);
  170252. }
  170253. /* Account for restart interval (no-op if not using restarts) */
  170254. entropy->restarts_to_go--;
  170255. return TRUE;
  170256. }
  170257. /*
  170258. * Module initialization routine for Huffman entropy decoding.
  170259. */
  170260. GLOBAL(void)
  170261. jinit_huff_decoder (j_decompress_ptr cinfo)
  170262. {
  170263. huff_entropy_ptr2 entropy;
  170264. int i;
  170265. entropy = (huff_entropy_ptr2)
  170266. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170267. SIZEOF(huff_entropy_decoder2));
  170268. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170269. entropy->pub.start_pass = start_pass_huff_decoder;
  170270. entropy->pub.decode_mcu = decode_mcu;
  170271. /* Mark tables unallocated */
  170272. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170273. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170274. }
  170275. }
  170276. /*** End of inlined file: jdhuff.c ***/
  170277. /*** Start of inlined file: jdinput.c ***/
  170278. #define JPEG_INTERNALS
  170279. /* Private state */
  170280. typedef struct {
  170281. struct jpeg_input_controller pub; /* public fields */
  170282. boolean inheaders; /* TRUE until first SOS is reached */
  170283. } my_input_controller;
  170284. typedef my_input_controller * my_inputctl_ptr;
  170285. /* Forward declarations */
  170286. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170287. /*
  170288. * Routines to calculate various quantities related to the size of the image.
  170289. */
  170290. LOCAL(void)
  170291. initial_setup2 (j_decompress_ptr cinfo)
  170292. /* Called once, when first SOS marker is reached */
  170293. {
  170294. int ci;
  170295. jpeg_component_info *compptr;
  170296. /* Make sure image isn't bigger than I can handle */
  170297. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170298. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170299. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170300. /* For now, precision must match compiled-in value... */
  170301. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170302. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170303. /* Check that number of components won't exceed internal array sizes */
  170304. if (cinfo->num_components > MAX_COMPONENTS)
  170305. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170306. MAX_COMPONENTS);
  170307. /* Compute maximum sampling factors; check factor validity */
  170308. cinfo->max_h_samp_factor = 1;
  170309. cinfo->max_v_samp_factor = 1;
  170310. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170311. ci++, compptr++) {
  170312. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170313. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170314. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170315. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170316. compptr->h_samp_factor);
  170317. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170318. compptr->v_samp_factor);
  170319. }
  170320. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170321. * In the full decompressor, this will be overridden by jdmaster.c;
  170322. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170323. */
  170324. cinfo->min_DCT_scaled_size = DCTSIZE;
  170325. /* Compute dimensions of components */
  170326. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170327. ci++, compptr++) {
  170328. compptr->DCT_scaled_size = DCTSIZE;
  170329. /* Size in DCT blocks */
  170330. compptr->width_in_blocks = (JDIMENSION)
  170331. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170332. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170333. compptr->height_in_blocks = (JDIMENSION)
  170334. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170335. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170336. /* downsampled_width and downsampled_height will also be overridden by
  170337. * jdmaster.c if we are doing full decompression. The transcoder library
  170338. * doesn't use these values, but the calling application might.
  170339. */
  170340. /* Size in samples */
  170341. compptr->downsampled_width = (JDIMENSION)
  170342. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170343. (long) cinfo->max_h_samp_factor);
  170344. compptr->downsampled_height = (JDIMENSION)
  170345. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170346. (long) cinfo->max_v_samp_factor);
  170347. /* Mark component needed, until color conversion says otherwise */
  170348. compptr->component_needed = TRUE;
  170349. /* Mark no quantization table yet saved for component */
  170350. compptr->quant_table = NULL;
  170351. }
  170352. /* Compute number of fully interleaved MCU rows. */
  170353. cinfo->total_iMCU_rows = (JDIMENSION)
  170354. jdiv_round_up((long) cinfo->image_height,
  170355. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170356. /* Decide whether file contains multiple scans */
  170357. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170358. cinfo->inputctl->has_multiple_scans = TRUE;
  170359. else
  170360. cinfo->inputctl->has_multiple_scans = FALSE;
  170361. }
  170362. LOCAL(void)
  170363. per_scan_setup2 (j_decompress_ptr cinfo)
  170364. /* Do computations that are needed before processing a JPEG scan */
  170365. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170366. {
  170367. int ci, mcublks, tmp;
  170368. jpeg_component_info *compptr;
  170369. if (cinfo->comps_in_scan == 1) {
  170370. /* Noninterleaved (single-component) scan */
  170371. compptr = cinfo->cur_comp_info[0];
  170372. /* Overall image size in MCUs */
  170373. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170374. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170375. /* For noninterleaved scan, always one block per MCU */
  170376. compptr->MCU_width = 1;
  170377. compptr->MCU_height = 1;
  170378. compptr->MCU_blocks = 1;
  170379. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170380. compptr->last_col_width = 1;
  170381. /* For noninterleaved scans, it is convenient to define last_row_height
  170382. * as the number of block rows present in the last iMCU row.
  170383. */
  170384. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170385. if (tmp == 0) tmp = compptr->v_samp_factor;
  170386. compptr->last_row_height = tmp;
  170387. /* Prepare array describing MCU composition */
  170388. cinfo->blocks_in_MCU = 1;
  170389. cinfo->MCU_membership[0] = 0;
  170390. } else {
  170391. /* Interleaved (multi-component) scan */
  170392. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170393. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170394. MAX_COMPS_IN_SCAN);
  170395. /* Overall image size in MCUs */
  170396. cinfo->MCUs_per_row = (JDIMENSION)
  170397. jdiv_round_up((long) cinfo->image_width,
  170398. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170399. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170400. jdiv_round_up((long) cinfo->image_height,
  170401. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170402. cinfo->blocks_in_MCU = 0;
  170403. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170404. compptr = cinfo->cur_comp_info[ci];
  170405. /* Sampling factors give # of blocks of component in each MCU */
  170406. compptr->MCU_width = compptr->h_samp_factor;
  170407. compptr->MCU_height = compptr->v_samp_factor;
  170408. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170409. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170410. /* Figure number of non-dummy blocks in last MCU column & row */
  170411. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170412. if (tmp == 0) tmp = compptr->MCU_width;
  170413. compptr->last_col_width = tmp;
  170414. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170415. if (tmp == 0) tmp = compptr->MCU_height;
  170416. compptr->last_row_height = tmp;
  170417. /* Prepare array describing MCU composition */
  170418. mcublks = compptr->MCU_blocks;
  170419. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170420. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170421. while (mcublks-- > 0) {
  170422. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170423. }
  170424. }
  170425. }
  170426. }
  170427. /*
  170428. * Save away a copy of the Q-table referenced by each component present
  170429. * in the current scan, unless already saved during a prior scan.
  170430. *
  170431. * In a multiple-scan JPEG file, the encoder could assign different components
  170432. * the same Q-table slot number, but change table definitions between scans
  170433. * so that each component uses a different Q-table. (The IJG encoder is not
  170434. * currently capable of doing this, but other encoders might.) Since we want
  170435. * to be able to dequantize all the components at the end of the file, this
  170436. * means that we have to save away the table actually used for each component.
  170437. * We do this by copying the table at the start of the first scan containing
  170438. * the component.
  170439. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170440. * slot between scans of a component using that slot. If the encoder does so
  170441. * anyway, this decoder will simply use the Q-table values that were current
  170442. * at the start of the first scan for the component.
  170443. *
  170444. * The decompressor output side looks only at the saved quant tables,
  170445. * not at the current Q-table slots.
  170446. */
  170447. LOCAL(void)
  170448. latch_quant_tables (j_decompress_ptr cinfo)
  170449. {
  170450. int ci, qtblno;
  170451. jpeg_component_info *compptr;
  170452. JQUANT_TBL * qtbl;
  170453. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170454. compptr = cinfo->cur_comp_info[ci];
  170455. /* No work if we already saved Q-table for this component */
  170456. if (compptr->quant_table != NULL)
  170457. continue;
  170458. /* Make sure specified quantization table is present */
  170459. qtblno = compptr->quant_tbl_no;
  170460. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170461. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170462. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170463. /* OK, save away the quantization table */
  170464. qtbl = (JQUANT_TBL *)
  170465. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170466. SIZEOF(JQUANT_TBL));
  170467. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170468. compptr->quant_table = qtbl;
  170469. }
  170470. }
  170471. /*
  170472. * Initialize the input modules to read a scan of compressed data.
  170473. * The first call to this is done by jdmaster.c after initializing
  170474. * the entire decompressor (during jpeg_start_decompress).
  170475. * Subsequent calls come from consume_markers, below.
  170476. */
  170477. METHODDEF(void)
  170478. start_input_pass2 (j_decompress_ptr cinfo)
  170479. {
  170480. per_scan_setup2(cinfo);
  170481. latch_quant_tables(cinfo);
  170482. (*cinfo->entropy->start_pass) (cinfo);
  170483. (*cinfo->coef->start_input_pass) (cinfo);
  170484. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170485. }
  170486. /*
  170487. * Finish up after inputting a compressed-data scan.
  170488. * This is called by the coefficient controller after it's read all
  170489. * the expected data of the scan.
  170490. */
  170491. METHODDEF(void)
  170492. finish_input_pass (j_decompress_ptr cinfo)
  170493. {
  170494. cinfo->inputctl->consume_input = consume_markers;
  170495. }
  170496. /*
  170497. * Read JPEG markers before, between, or after compressed-data scans.
  170498. * Change state as necessary when a new scan is reached.
  170499. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170500. *
  170501. * The consume_input method pointer points either here or to the
  170502. * coefficient controller's consume_data routine, depending on whether
  170503. * we are reading a compressed data segment or inter-segment markers.
  170504. */
  170505. METHODDEF(int)
  170506. consume_markers (j_decompress_ptr cinfo)
  170507. {
  170508. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170509. int val;
  170510. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170511. return JPEG_REACHED_EOI;
  170512. val = (*cinfo->marker->read_markers) (cinfo);
  170513. switch (val) {
  170514. case JPEG_REACHED_SOS: /* Found SOS */
  170515. if (inputctl->inheaders) { /* 1st SOS */
  170516. initial_setup2(cinfo);
  170517. inputctl->inheaders = FALSE;
  170518. /* Note: start_input_pass must be called by jdmaster.c
  170519. * before any more input can be consumed. jdapimin.c is
  170520. * responsible for enforcing this sequencing.
  170521. */
  170522. } else { /* 2nd or later SOS marker */
  170523. if (! inputctl->pub.has_multiple_scans)
  170524. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170525. start_input_pass2(cinfo);
  170526. }
  170527. break;
  170528. case JPEG_REACHED_EOI: /* Found EOI */
  170529. inputctl->pub.eoi_reached = TRUE;
  170530. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170531. if (cinfo->marker->saw_SOF)
  170532. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170533. } else {
  170534. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170535. * if user set output_scan_number larger than number of scans.
  170536. */
  170537. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170538. cinfo->output_scan_number = cinfo->input_scan_number;
  170539. }
  170540. break;
  170541. case JPEG_SUSPENDED:
  170542. break;
  170543. }
  170544. return val;
  170545. }
  170546. /*
  170547. * Reset state to begin a fresh datastream.
  170548. */
  170549. METHODDEF(void)
  170550. reset_input_controller (j_decompress_ptr cinfo)
  170551. {
  170552. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170553. inputctl->pub.consume_input = consume_markers;
  170554. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170555. inputctl->pub.eoi_reached = FALSE;
  170556. inputctl->inheaders = TRUE;
  170557. /* Reset other modules */
  170558. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170559. (*cinfo->marker->reset_marker_reader) (cinfo);
  170560. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170561. cinfo->coef_bits = NULL;
  170562. }
  170563. /*
  170564. * Initialize the input controller module.
  170565. * This is called only once, when the decompression object is created.
  170566. */
  170567. GLOBAL(void)
  170568. jinit_input_controller (j_decompress_ptr cinfo)
  170569. {
  170570. my_inputctl_ptr inputctl;
  170571. /* Create subobject in permanent pool */
  170572. inputctl = (my_inputctl_ptr)
  170573. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170574. SIZEOF(my_input_controller));
  170575. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170576. /* Initialize method pointers */
  170577. inputctl->pub.consume_input = consume_markers;
  170578. inputctl->pub.reset_input_controller = reset_input_controller;
  170579. inputctl->pub.start_input_pass = start_input_pass2;
  170580. inputctl->pub.finish_input_pass = finish_input_pass;
  170581. /* Initialize state: can't use reset_input_controller since we don't
  170582. * want to try to reset other modules yet.
  170583. */
  170584. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170585. inputctl->pub.eoi_reached = FALSE;
  170586. inputctl->inheaders = TRUE;
  170587. }
  170588. /*** End of inlined file: jdinput.c ***/
  170589. /*** Start of inlined file: jdmainct.c ***/
  170590. #define JPEG_INTERNALS
  170591. /*
  170592. * In the current system design, the main buffer need never be a full-image
  170593. * buffer; any full-height buffers will be found inside the coefficient or
  170594. * postprocessing controllers. Nonetheless, the main controller is not
  170595. * trivial. Its responsibility is to provide context rows for upsampling/
  170596. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170597. *
  170598. * Postprocessor input data is counted in "row groups". A row group
  170599. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170600. * sample rows of each component. (We require DCT_scaled_size values to be
  170601. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170602. * values will likely be powers of two, so we actually have the stronger
  170603. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170604. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170605. * row group (times any additional scale factor that the upsampler is
  170606. * applying).
  170607. *
  170608. * The coefficient controller will deliver data to us one iMCU row at a time;
  170609. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170610. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170611. * to one row of MCUs when the image is fully interleaved.) Note that the
  170612. * number of sample rows varies across components, but the number of row
  170613. * groups does not. Some garbage sample rows may be included in the last iMCU
  170614. * row at the bottom of the image.
  170615. *
  170616. * Depending on the vertical scaling algorithm used, the upsampler may need
  170617. * access to the sample row(s) above and below its current input row group.
  170618. * The upsampler is required to set need_context_rows TRUE at global selection
  170619. * time if so. When need_context_rows is FALSE, this controller can simply
  170620. * obtain one iMCU row at a time from the coefficient controller and dole it
  170621. * out as row groups to the postprocessor.
  170622. *
  170623. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170624. * passed to postprocessing contains at least one row group's worth of samples
  170625. * above and below the row group(s) being processed. Note that the context
  170626. * rows "above" the first passed row group appear at negative row offsets in
  170627. * the passed buffer. At the top and bottom of the image, the required
  170628. * context rows are manufactured by duplicating the first or last real sample
  170629. * row; this avoids having special cases in the upsampling inner loops.
  170630. *
  170631. * The amount of context is fixed at one row group just because that's a
  170632. * convenient number for this controller to work with. The existing
  170633. * upsamplers really only need one sample row of context. An upsampler
  170634. * supporting arbitrary output rescaling might wish for more than one row
  170635. * group of context when shrinking the image; tough, we don't handle that.
  170636. * (This is justified by the assumption that downsizing will be handled mostly
  170637. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170638. * the upsample step needn't be much less than one.)
  170639. *
  170640. * To provide the desired context, we have to retain the last two row groups
  170641. * of one iMCU row while reading in the next iMCU row. (The last row group
  170642. * can't be processed until we have another row group for its below-context,
  170643. * and so we have to save the next-to-last group too for its above-context.)
  170644. * We could do this most simply by copying data around in our buffer, but
  170645. * that'd be very slow. We can avoid copying any data by creating a rather
  170646. * strange pointer structure. Here's how it works. We allocate a workspace
  170647. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170648. * of row groups per iMCU row). We create two sets of redundant pointers to
  170649. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170650. * pointer lists look like this:
  170651. * M+1 M-1
  170652. * master pointer --> 0 master pointer --> 0
  170653. * 1 1
  170654. * ... ...
  170655. * M-3 M-3
  170656. * M-2 M
  170657. * M-1 M+1
  170658. * M M-2
  170659. * M+1 M-1
  170660. * 0 0
  170661. * We read alternate iMCU rows using each master pointer; thus the last two
  170662. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170663. * The pointer lists are set up so that the required context rows appear to
  170664. * be adjacent to the proper places when we pass the pointer lists to the
  170665. * upsampler.
  170666. *
  170667. * The above pictures describe the normal state of the pointer lists.
  170668. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170669. * the first or last sample row as necessary (this is cheaper than copying
  170670. * sample rows around).
  170671. *
  170672. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170673. * situation each iMCU row provides only one row group so the buffering logic
  170674. * must be different (eg, we must read two iMCU rows before we can emit the
  170675. * first row group). For now, we simply do not support providing context
  170676. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170677. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170678. * want it quick and dirty, so a context-free upsampler is sufficient.
  170679. */
  170680. /* Private buffer controller object */
  170681. typedef struct {
  170682. struct jpeg_d_main_controller pub; /* public fields */
  170683. /* Pointer to allocated workspace (M or M+2 row groups). */
  170684. JSAMPARRAY buffer[MAX_COMPONENTS];
  170685. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170686. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170687. /* Remaining fields are only used in the context case. */
  170688. /* These are the master pointers to the funny-order pointer lists. */
  170689. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170690. int whichptr; /* indicates which pointer set is now in use */
  170691. int context_state; /* process_data state machine status */
  170692. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170693. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170694. } my_main_controller4;
  170695. typedef my_main_controller4 * my_main_ptr4;
  170696. /* context_state values: */
  170697. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170698. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170699. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170700. /* Forward declarations */
  170701. METHODDEF(void) process_data_simple_main2
  170702. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170703. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170704. METHODDEF(void) process_data_context_main
  170705. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170706. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170707. #ifdef QUANT_2PASS_SUPPORTED
  170708. METHODDEF(void) process_data_crank_post
  170709. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170710. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170711. #endif
  170712. LOCAL(void)
  170713. alloc_funny_pointers (j_decompress_ptr cinfo)
  170714. /* Allocate space for the funny pointer lists.
  170715. * This is done only once, not once per pass.
  170716. */
  170717. {
  170718. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170719. int ci, rgroup;
  170720. int M = cinfo->min_DCT_scaled_size;
  170721. jpeg_component_info *compptr;
  170722. JSAMPARRAY xbuf;
  170723. /* Get top-level space for component array pointers.
  170724. * We alloc both arrays with one call to save a few cycles.
  170725. */
  170726. main_->xbuffer[0] = (JSAMPIMAGE)
  170727. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170728. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170729. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170730. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170731. ci++, compptr++) {
  170732. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170733. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170734. /* Get space for pointer lists --- M+4 row groups in each list.
  170735. * We alloc both pointer lists with one call to save a few cycles.
  170736. */
  170737. xbuf = (JSAMPARRAY)
  170738. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170739. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170740. xbuf += rgroup; /* want one row group at negative offsets */
  170741. main_->xbuffer[0][ci] = xbuf;
  170742. xbuf += rgroup * (M + 4);
  170743. main_->xbuffer[1][ci] = xbuf;
  170744. }
  170745. }
  170746. LOCAL(void)
  170747. make_funny_pointers (j_decompress_ptr cinfo)
  170748. /* Create the funny pointer lists discussed in the comments above.
  170749. * The actual workspace is already allocated (in main->buffer),
  170750. * and the space for the pointer lists is allocated too.
  170751. * This routine just fills in the curiously ordered lists.
  170752. * This will be repeated at the beginning of each pass.
  170753. */
  170754. {
  170755. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170756. int ci, i, rgroup;
  170757. int M = cinfo->min_DCT_scaled_size;
  170758. jpeg_component_info *compptr;
  170759. JSAMPARRAY buf, xbuf0, xbuf1;
  170760. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170761. ci++, compptr++) {
  170762. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170763. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170764. xbuf0 = main_->xbuffer[0][ci];
  170765. xbuf1 = main_->xbuffer[1][ci];
  170766. /* First copy the workspace pointers as-is */
  170767. buf = main_->buffer[ci];
  170768. for (i = 0; i < rgroup * (M + 2); i++) {
  170769. xbuf0[i] = xbuf1[i] = buf[i];
  170770. }
  170771. /* In the second list, put the last four row groups in swapped order */
  170772. for (i = 0; i < rgroup * 2; i++) {
  170773. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170774. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170775. }
  170776. /* The wraparound pointers at top and bottom will be filled later
  170777. * (see set_wraparound_pointers, below). Initially we want the "above"
  170778. * pointers to duplicate the first actual data line. This only needs
  170779. * to happen in xbuffer[0].
  170780. */
  170781. for (i = 0; i < rgroup; i++) {
  170782. xbuf0[i - rgroup] = xbuf0[0];
  170783. }
  170784. }
  170785. }
  170786. LOCAL(void)
  170787. set_wraparound_pointers (j_decompress_ptr cinfo)
  170788. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170789. * This changes the pointer list state from top-of-image to the normal state.
  170790. */
  170791. {
  170792. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170793. int ci, i, rgroup;
  170794. int M = cinfo->min_DCT_scaled_size;
  170795. jpeg_component_info *compptr;
  170796. JSAMPARRAY xbuf0, xbuf1;
  170797. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170798. ci++, compptr++) {
  170799. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170800. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170801. xbuf0 = main_->xbuffer[0][ci];
  170802. xbuf1 = main_->xbuffer[1][ci];
  170803. for (i = 0; i < rgroup; i++) {
  170804. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170805. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170806. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170807. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170808. }
  170809. }
  170810. }
  170811. LOCAL(void)
  170812. set_bottom_pointers (j_decompress_ptr cinfo)
  170813. /* Change the pointer lists to duplicate the last sample row at the bottom
  170814. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170815. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170816. */
  170817. {
  170818. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170819. int ci, i, rgroup, iMCUheight, rows_left;
  170820. jpeg_component_info *compptr;
  170821. JSAMPARRAY xbuf;
  170822. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170823. ci++, compptr++) {
  170824. /* Count sample rows in one iMCU row and in one row group */
  170825. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170826. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170827. /* Count nondummy sample rows remaining for this component */
  170828. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170829. if (rows_left == 0) rows_left = iMCUheight;
  170830. /* Count nondummy row groups. Should get same answer for each component,
  170831. * so we need only do it once.
  170832. */
  170833. if (ci == 0) {
  170834. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170835. }
  170836. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170837. * last partial rowgroup and ensures at least one full rowgroup of context.
  170838. */
  170839. xbuf = main_->xbuffer[main_->whichptr][ci];
  170840. for (i = 0; i < rgroup * 2; i++) {
  170841. xbuf[rows_left + i] = xbuf[rows_left-1];
  170842. }
  170843. }
  170844. }
  170845. /*
  170846. * Initialize for a processing pass.
  170847. */
  170848. METHODDEF(void)
  170849. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170850. {
  170851. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170852. switch (pass_mode) {
  170853. case JBUF_PASS_THRU:
  170854. if (cinfo->upsample->need_context_rows) {
  170855. main_->pub.process_data = process_data_context_main;
  170856. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170857. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170858. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170859. main_->iMCU_row_ctr = 0;
  170860. } else {
  170861. /* Simple case with no context needed */
  170862. main_->pub.process_data = process_data_simple_main2;
  170863. }
  170864. main_->buffer_full = FALSE; /* Mark buffer empty */
  170865. main_->rowgroup_ctr = 0;
  170866. break;
  170867. #ifdef QUANT_2PASS_SUPPORTED
  170868. case JBUF_CRANK_DEST:
  170869. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170870. main_->pub.process_data = process_data_crank_post;
  170871. break;
  170872. #endif
  170873. default:
  170874. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170875. break;
  170876. }
  170877. }
  170878. /*
  170879. * Process some data.
  170880. * This handles the simple case where no context is required.
  170881. */
  170882. METHODDEF(void)
  170883. process_data_simple_main2 (j_decompress_ptr cinfo,
  170884. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170885. JDIMENSION out_rows_avail)
  170886. {
  170887. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170888. JDIMENSION rowgroups_avail;
  170889. /* Read input data if we haven't filled the main buffer yet */
  170890. if (! main_->buffer_full) {
  170891. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170892. return; /* suspension forced, can do nothing more */
  170893. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170894. }
  170895. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170896. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170897. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170898. * to the postprocessor. The postprocessor has to check for bottom
  170899. * of image anyway (at row resolution), so no point in us doing it too.
  170900. */
  170901. /* Feed the postprocessor */
  170902. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170903. &main_->rowgroup_ctr, rowgroups_avail,
  170904. output_buf, out_row_ctr, out_rows_avail);
  170905. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170906. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170907. main_->buffer_full = FALSE;
  170908. main_->rowgroup_ctr = 0;
  170909. }
  170910. }
  170911. /*
  170912. * Process some data.
  170913. * This handles the case where context rows must be provided.
  170914. */
  170915. METHODDEF(void)
  170916. process_data_context_main (j_decompress_ptr cinfo,
  170917. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170918. JDIMENSION out_rows_avail)
  170919. {
  170920. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170921. /* Read input data if we haven't filled the main buffer yet */
  170922. if (! main_->buffer_full) {
  170923. if (! (*cinfo->coef->decompress_data) (cinfo,
  170924. main_->xbuffer[main_->whichptr]))
  170925. return; /* suspension forced, can do nothing more */
  170926. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170927. main_->iMCU_row_ctr++; /* count rows received */
  170928. }
  170929. /* Postprocessor typically will not swallow all the input data it is handed
  170930. * in one call (due to filling the output buffer first). Must be prepared
  170931. * to exit and restart. This switch lets us keep track of how far we got.
  170932. * Note that each case falls through to the next on successful completion.
  170933. */
  170934. switch (main_->context_state) {
  170935. case CTX_POSTPONED_ROW:
  170936. /* Call postprocessor using previously set pointers for postponed row */
  170937. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170938. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170939. output_buf, out_row_ctr, out_rows_avail);
  170940. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170941. return; /* Need to suspend */
  170942. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170943. if (*out_row_ctr >= out_rows_avail)
  170944. return; /* Postprocessor exactly filled output buf */
  170945. /*FALLTHROUGH*/
  170946. case CTX_PREPARE_FOR_IMCU:
  170947. /* Prepare to process first M-1 row groups of this iMCU row */
  170948. main_->rowgroup_ctr = 0;
  170949. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170950. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170951. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170952. */
  170953. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170954. set_bottom_pointers(cinfo);
  170955. main_->context_state = CTX_PROCESS_IMCU;
  170956. /*FALLTHROUGH*/
  170957. case CTX_PROCESS_IMCU:
  170958. /* Call postprocessor using previously set pointers */
  170959. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170960. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170961. output_buf, out_row_ctr, out_rows_avail);
  170962. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170963. return; /* Need to suspend */
  170964. /* After the first iMCU, change wraparound pointers to normal state */
  170965. if (main_->iMCU_row_ctr == 1)
  170966. set_wraparound_pointers(cinfo);
  170967. /* Prepare to load new iMCU row using other xbuffer list */
  170968. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170969. main_->buffer_full = FALSE;
  170970. /* Still need to process last row group of this iMCU row, */
  170971. /* which is saved at index M+1 of the other xbuffer */
  170972. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170973. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170974. main_->context_state = CTX_POSTPONED_ROW;
  170975. }
  170976. }
  170977. /*
  170978. * Process some data.
  170979. * Final pass of two-pass quantization: just call the postprocessor.
  170980. * Source data will be the postprocessor controller's internal buffer.
  170981. */
  170982. #ifdef QUANT_2PASS_SUPPORTED
  170983. METHODDEF(void)
  170984. process_data_crank_post (j_decompress_ptr cinfo,
  170985. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170986. JDIMENSION out_rows_avail)
  170987. {
  170988. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170989. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170990. output_buf, out_row_ctr, out_rows_avail);
  170991. }
  170992. #endif /* QUANT_2PASS_SUPPORTED */
  170993. /*
  170994. * Initialize main buffer controller.
  170995. */
  170996. GLOBAL(void)
  170997. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170998. {
  170999. my_main_ptr4 main_;
  171000. int ci, rgroup, ngroups;
  171001. jpeg_component_info *compptr;
  171002. main_ = (my_main_ptr4)
  171003. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171004. SIZEOF(my_main_controller4));
  171005. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171006. main_->pub.start_pass = start_pass_main2;
  171007. if (need_full_buffer) /* shouldn't happen */
  171008. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171009. /* Allocate the workspace.
  171010. * ngroups is the number of row groups we need.
  171011. */
  171012. if (cinfo->upsample->need_context_rows) {
  171013. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171014. ERREXIT(cinfo, JERR_NOTIMPL);
  171015. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171016. ngroups = cinfo->min_DCT_scaled_size + 2;
  171017. } else {
  171018. ngroups = cinfo->min_DCT_scaled_size;
  171019. }
  171020. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171021. ci++, compptr++) {
  171022. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171023. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171024. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171025. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171026. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171027. (JDIMENSION) (rgroup * ngroups));
  171028. }
  171029. }
  171030. /*** End of inlined file: jdmainct.c ***/
  171031. /*** Start of inlined file: jdmarker.c ***/
  171032. #define JPEG_INTERNALS
  171033. /* Private state */
  171034. typedef struct {
  171035. struct jpeg_marker_reader pub; /* public fields */
  171036. /* Application-overridable marker processing methods */
  171037. jpeg_marker_parser_method process_COM;
  171038. jpeg_marker_parser_method process_APPn[16];
  171039. /* Limit on marker data length to save for each marker type */
  171040. unsigned int length_limit_COM;
  171041. unsigned int length_limit_APPn[16];
  171042. /* Status of COM/APPn marker saving */
  171043. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171044. unsigned int bytes_read; /* data bytes read so far in marker */
  171045. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171046. } my_marker_reader;
  171047. typedef my_marker_reader * my_marker_ptr2;
  171048. /*
  171049. * Macros for fetching data from the data source module.
  171050. *
  171051. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171052. * the current restart point; we update them only when we have reached a
  171053. * suitable place to restart if a suspension occurs.
  171054. */
  171055. /* Declare and initialize local copies of input pointer/count */
  171056. #define INPUT_VARS(cinfo) \
  171057. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171058. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171059. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171060. /* Unload the local copies --- do this only at a restart boundary */
  171061. #define INPUT_SYNC(cinfo) \
  171062. ( datasrc->next_input_byte = next_input_byte, \
  171063. datasrc->bytes_in_buffer = bytes_in_buffer )
  171064. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171065. #define INPUT_RELOAD(cinfo) \
  171066. ( next_input_byte = datasrc->next_input_byte, \
  171067. bytes_in_buffer = datasrc->bytes_in_buffer )
  171068. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171069. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171070. * but we must reload the local copies after a successful fill.
  171071. */
  171072. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171073. if (bytes_in_buffer == 0) { \
  171074. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171075. { action; } \
  171076. INPUT_RELOAD(cinfo); \
  171077. }
  171078. /* Read a byte into variable V.
  171079. * If must suspend, take the specified action (typically "return FALSE").
  171080. */
  171081. #define INPUT_BYTE(cinfo,V,action) \
  171082. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171083. bytes_in_buffer--; \
  171084. V = GETJOCTET(*next_input_byte++); )
  171085. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171086. * V should be declared unsigned int or perhaps INT32.
  171087. */
  171088. #define INPUT_2BYTES(cinfo,V,action) \
  171089. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171090. bytes_in_buffer--; \
  171091. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171092. MAKE_BYTE_AVAIL(cinfo,action); \
  171093. bytes_in_buffer--; \
  171094. V += GETJOCTET(*next_input_byte++); )
  171095. /*
  171096. * Routines to process JPEG markers.
  171097. *
  171098. * Entry condition: JPEG marker itself has been read and its code saved
  171099. * in cinfo->unread_marker; input restart point is just after the marker.
  171100. *
  171101. * Exit: if return TRUE, have read and processed any parameters, and have
  171102. * updated the restart point to point after the parameters.
  171103. * If return FALSE, was forced to suspend before reaching end of
  171104. * marker parameters; restart point has not been moved. Same routine
  171105. * will be called again after application supplies more input data.
  171106. *
  171107. * This approach to suspension assumes that all of a marker's parameters
  171108. * can fit into a single input bufferload. This should hold for "normal"
  171109. * markers. Some COM/APPn markers might have large parameter segments
  171110. * that might not fit. If we are simply dropping such a marker, we use
  171111. * skip_input_data to get past it, and thereby put the problem on the
  171112. * source manager's shoulders. If we are saving the marker's contents
  171113. * into memory, we use a slightly different convention: when forced to
  171114. * suspend, the marker processor updates the restart point to the end of
  171115. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171116. * On resumption, cinfo->unread_marker still contains the marker code,
  171117. * but the data source will point to the next chunk of marker data.
  171118. * The marker processor must retain internal state to deal with this.
  171119. *
  171120. * Note that we don't bother to avoid duplicate trace messages if a
  171121. * suspension occurs within marker parameters. Other side effects
  171122. * require more care.
  171123. */
  171124. LOCAL(boolean)
  171125. get_soi (j_decompress_ptr cinfo)
  171126. /* Process an SOI marker */
  171127. {
  171128. int i;
  171129. TRACEMS(cinfo, 1, JTRC_SOI);
  171130. if (cinfo->marker->saw_SOI)
  171131. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171132. /* Reset all parameters that are defined to be reset by SOI */
  171133. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171134. cinfo->arith_dc_L[i] = 0;
  171135. cinfo->arith_dc_U[i] = 1;
  171136. cinfo->arith_ac_K[i] = 5;
  171137. }
  171138. cinfo->restart_interval = 0;
  171139. /* Set initial assumptions for colorspace etc */
  171140. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171141. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171142. cinfo->saw_JFIF_marker = FALSE;
  171143. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171144. cinfo->JFIF_minor_version = 1;
  171145. cinfo->density_unit = 0;
  171146. cinfo->X_density = 1;
  171147. cinfo->Y_density = 1;
  171148. cinfo->saw_Adobe_marker = FALSE;
  171149. cinfo->Adobe_transform = 0;
  171150. cinfo->marker->saw_SOI = TRUE;
  171151. return TRUE;
  171152. }
  171153. LOCAL(boolean)
  171154. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171155. /* Process a SOFn marker */
  171156. {
  171157. INT32 length;
  171158. int c, ci;
  171159. jpeg_component_info * compptr;
  171160. INPUT_VARS(cinfo);
  171161. cinfo->progressive_mode = is_prog;
  171162. cinfo->arith_code = is_arith;
  171163. INPUT_2BYTES(cinfo, length, return FALSE);
  171164. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171165. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171166. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171167. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171168. length -= 8;
  171169. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171170. (int) cinfo->image_width, (int) cinfo->image_height,
  171171. cinfo->num_components);
  171172. if (cinfo->marker->saw_SOF)
  171173. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171174. /* We don't support files in which the image height is initially specified */
  171175. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171176. /* might as well have a general sanity check. */
  171177. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171178. || cinfo->num_components <= 0)
  171179. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171180. if (length != (cinfo->num_components * 3))
  171181. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171182. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171183. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171184. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171185. cinfo->num_components * SIZEOF(jpeg_component_info));
  171186. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171187. ci++, compptr++) {
  171188. compptr->component_index = ci;
  171189. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171190. INPUT_BYTE(cinfo, c, return FALSE);
  171191. compptr->h_samp_factor = (c >> 4) & 15;
  171192. compptr->v_samp_factor = (c ) & 15;
  171193. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171194. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171195. compptr->component_id, compptr->h_samp_factor,
  171196. compptr->v_samp_factor, compptr->quant_tbl_no);
  171197. }
  171198. cinfo->marker->saw_SOF = TRUE;
  171199. INPUT_SYNC(cinfo);
  171200. return TRUE;
  171201. }
  171202. LOCAL(boolean)
  171203. get_sos (j_decompress_ptr cinfo)
  171204. /* Process a SOS marker */
  171205. {
  171206. INT32 length;
  171207. int i, ci, n, c, cc;
  171208. jpeg_component_info * compptr;
  171209. INPUT_VARS(cinfo);
  171210. if (! cinfo->marker->saw_SOF)
  171211. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171212. INPUT_2BYTES(cinfo, length, return FALSE);
  171213. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171214. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171215. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171216. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171217. cinfo->comps_in_scan = n;
  171218. /* Collect the component-spec parameters */
  171219. for (i = 0; i < n; i++) {
  171220. INPUT_BYTE(cinfo, cc, return FALSE);
  171221. INPUT_BYTE(cinfo, c, return FALSE);
  171222. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171223. ci++, compptr++) {
  171224. if (cc == compptr->component_id)
  171225. goto id_found;
  171226. }
  171227. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171228. id_found:
  171229. cinfo->cur_comp_info[i] = compptr;
  171230. compptr->dc_tbl_no = (c >> 4) & 15;
  171231. compptr->ac_tbl_no = (c ) & 15;
  171232. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171233. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171234. }
  171235. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171236. INPUT_BYTE(cinfo, c, return FALSE);
  171237. cinfo->Ss = c;
  171238. INPUT_BYTE(cinfo, c, return FALSE);
  171239. cinfo->Se = c;
  171240. INPUT_BYTE(cinfo, c, return FALSE);
  171241. cinfo->Ah = (c >> 4) & 15;
  171242. cinfo->Al = (c ) & 15;
  171243. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171244. cinfo->Ah, cinfo->Al);
  171245. /* Prepare to scan data & restart markers */
  171246. cinfo->marker->next_restart_num = 0;
  171247. /* Count another SOS marker */
  171248. cinfo->input_scan_number++;
  171249. INPUT_SYNC(cinfo);
  171250. return TRUE;
  171251. }
  171252. #ifdef D_ARITH_CODING_SUPPORTED
  171253. LOCAL(boolean)
  171254. get_dac (j_decompress_ptr cinfo)
  171255. /* Process a DAC marker */
  171256. {
  171257. INT32 length;
  171258. int index, val;
  171259. INPUT_VARS(cinfo);
  171260. INPUT_2BYTES(cinfo, length, return FALSE);
  171261. length -= 2;
  171262. while (length > 0) {
  171263. INPUT_BYTE(cinfo, index, return FALSE);
  171264. INPUT_BYTE(cinfo, val, return FALSE);
  171265. length -= 2;
  171266. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171267. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171268. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171269. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171270. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171271. } else { /* define DC table */
  171272. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171273. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171274. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171275. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171276. }
  171277. }
  171278. if (length != 0)
  171279. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171280. INPUT_SYNC(cinfo);
  171281. return TRUE;
  171282. }
  171283. #else /* ! D_ARITH_CODING_SUPPORTED */
  171284. #define get_dac(cinfo) skip_variable(cinfo)
  171285. #endif /* D_ARITH_CODING_SUPPORTED */
  171286. LOCAL(boolean)
  171287. get_dht (j_decompress_ptr cinfo)
  171288. /* Process a DHT marker */
  171289. {
  171290. INT32 length;
  171291. UINT8 bits[17];
  171292. UINT8 huffval[256];
  171293. int i, index, count;
  171294. JHUFF_TBL **htblptr;
  171295. INPUT_VARS(cinfo);
  171296. INPUT_2BYTES(cinfo, length, return FALSE);
  171297. length -= 2;
  171298. while (length > 16) {
  171299. INPUT_BYTE(cinfo, index, return FALSE);
  171300. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171301. bits[0] = 0;
  171302. count = 0;
  171303. for (i = 1; i <= 16; i++) {
  171304. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171305. count += bits[i];
  171306. }
  171307. length -= 1 + 16;
  171308. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171309. bits[1], bits[2], bits[3], bits[4],
  171310. bits[5], bits[6], bits[7], bits[8]);
  171311. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171312. bits[9], bits[10], bits[11], bits[12],
  171313. bits[13], bits[14], bits[15], bits[16]);
  171314. /* Here we just do minimal validation of the counts to avoid walking
  171315. * off the end of our table space. jdhuff.c will check more carefully.
  171316. */
  171317. if (count > 256 || ((INT32) count) > length)
  171318. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171319. for (i = 0; i < count; i++)
  171320. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171321. length -= count;
  171322. if (index & 0x10) { /* AC table definition */
  171323. index -= 0x10;
  171324. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171325. } else { /* DC table definition */
  171326. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171327. }
  171328. if (index < 0 || index >= NUM_HUFF_TBLS)
  171329. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171330. if (*htblptr == NULL)
  171331. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171332. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171333. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171334. }
  171335. if (length != 0)
  171336. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171337. INPUT_SYNC(cinfo);
  171338. return TRUE;
  171339. }
  171340. LOCAL(boolean)
  171341. get_dqt (j_decompress_ptr cinfo)
  171342. /* Process a DQT marker */
  171343. {
  171344. INT32 length;
  171345. int n, i, prec;
  171346. unsigned int tmp;
  171347. JQUANT_TBL *quant_ptr;
  171348. INPUT_VARS(cinfo);
  171349. INPUT_2BYTES(cinfo, length, return FALSE);
  171350. length -= 2;
  171351. while (length > 0) {
  171352. INPUT_BYTE(cinfo, n, return FALSE);
  171353. prec = n >> 4;
  171354. n &= 0x0F;
  171355. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171356. if (n >= NUM_QUANT_TBLS)
  171357. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171358. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171359. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171360. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171361. for (i = 0; i < DCTSIZE2; i++) {
  171362. if (prec)
  171363. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171364. else
  171365. INPUT_BYTE(cinfo, tmp, return FALSE);
  171366. /* We convert the zigzag-order table to natural array order. */
  171367. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171368. }
  171369. if (cinfo->err->trace_level >= 2) {
  171370. for (i = 0; i < DCTSIZE2; i += 8) {
  171371. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171372. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171373. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171374. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171375. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171376. }
  171377. }
  171378. length -= DCTSIZE2+1;
  171379. if (prec) length -= DCTSIZE2;
  171380. }
  171381. if (length != 0)
  171382. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171383. INPUT_SYNC(cinfo);
  171384. return TRUE;
  171385. }
  171386. LOCAL(boolean)
  171387. get_dri (j_decompress_ptr cinfo)
  171388. /* Process a DRI marker */
  171389. {
  171390. INT32 length;
  171391. unsigned int tmp;
  171392. INPUT_VARS(cinfo);
  171393. INPUT_2BYTES(cinfo, length, return FALSE);
  171394. if (length != 4)
  171395. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171396. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171397. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171398. cinfo->restart_interval = tmp;
  171399. INPUT_SYNC(cinfo);
  171400. return TRUE;
  171401. }
  171402. /*
  171403. * Routines for processing APPn and COM markers.
  171404. * These are either saved in memory or discarded, per application request.
  171405. * APP0 and APP14 are specially checked to see if they are
  171406. * JFIF and Adobe markers, respectively.
  171407. */
  171408. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171409. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171410. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171411. LOCAL(void)
  171412. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171413. unsigned int datalen, INT32 remaining)
  171414. /* Examine first few bytes from an APP0.
  171415. * Take appropriate action if it is a JFIF marker.
  171416. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171417. */
  171418. {
  171419. INT32 totallen = (INT32) datalen + remaining;
  171420. if (datalen >= APP0_DATA_LEN &&
  171421. GETJOCTET(data[0]) == 0x4A &&
  171422. GETJOCTET(data[1]) == 0x46 &&
  171423. GETJOCTET(data[2]) == 0x49 &&
  171424. GETJOCTET(data[3]) == 0x46 &&
  171425. GETJOCTET(data[4]) == 0) {
  171426. /* Found JFIF APP0 marker: save info */
  171427. cinfo->saw_JFIF_marker = TRUE;
  171428. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171429. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171430. cinfo->density_unit = GETJOCTET(data[7]);
  171431. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171432. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171433. /* Check version.
  171434. * Major version must be 1, anything else signals an incompatible change.
  171435. * (We used to treat this as an error, but now it's a nonfatal warning,
  171436. * because some bozo at Hijaak couldn't read the spec.)
  171437. * Minor version should be 0..2, but process anyway if newer.
  171438. */
  171439. if (cinfo->JFIF_major_version != 1)
  171440. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171441. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171442. /* Generate trace messages */
  171443. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171444. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171445. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171446. /* Validate thumbnail dimensions and issue appropriate messages */
  171447. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171448. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171449. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171450. totallen -= APP0_DATA_LEN;
  171451. if (totallen !=
  171452. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171453. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171454. } else if (datalen >= 6 &&
  171455. GETJOCTET(data[0]) == 0x4A &&
  171456. GETJOCTET(data[1]) == 0x46 &&
  171457. GETJOCTET(data[2]) == 0x58 &&
  171458. GETJOCTET(data[3]) == 0x58 &&
  171459. GETJOCTET(data[4]) == 0) {
  171460. /* Found JFIF "JFXX" extension APP0 marker */
  171461. /* The library doesn't actually do anything with these,
  171462. * but we try to produce a helpful trace message.
  171463. */
  171464. switch (GETJOCTET(data[5])) {
  171465. case 0x10:
  171466. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171467. break;
  171468. case 0x11:
  171469. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171470. break;
  171471. case 0x13:
  171472. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171473. break;
  171474. default:
  171475. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171476. GETJOCTET(data[5]), (int) totallen);
  171477. break;
  171478. }
  171479. } else {
  171480. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171481. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171482. }
  171483. }
  171484. LOCAL(void)
  171485. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171486. unsigned int datalen, INT32 remaining)
  171487. /* Examine first few bytes from an APP14.
  171488. * Take appropriate action if it is an Adobe marker.
  171489. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171490. */
  171491. {
  171492. unsigned int version, flags0, flags1, transform;
  171493. if (datalen >= APP14_DATA_LEN &&
  171494. GETJOCTET(data[0]) == 0x41 &&
  171495. GETJOCTET(data[1]) == 0x64 &&
  171496. GETJOCTET(data[2]) == 0x6F &&
  171497. GETJOCTET(data[3]) == 0x62 &&
  171498. GETJOCTET(data[4]) == 0x65) {
  171499. /* Found Adobe APP14 marker */
  171500. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171501. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171502. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171503. transform = GETJOCTET(data[11]);
  171504. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171505. cinfo->saw_Adobe_marker = TRUE;
  171506. cinfo->Adobe_transform = (UINT8) transform;
  171507. } else {
  171508. /* Start of APP14 does not match "Adobe", or too short */
  171509. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171510. }
  171511. }
  171512. METHODDEF(boolean)
  171513. get_interesting_appn (j_decompress_ptr cinfo)
  171514. /* Process an APP0 or APP14 marker without saving it */
  171515. {
  171516. INT32 length;
  171517. JOCTET b[APPN_DATA_LEN];
  171518. unsigned int i, numtoread;
  171519. INPUT_VARS(cinfo);
  171520. INPUT_2BYTES(cinfo, length, return FALSE);
  171521. length -= 2;
  171522. /* get the interesting part of the marker data */
  171523. if (length >= APPN_DATA_LEN)
  171524. numtoread = APPN_DATA_LEN;
  171525. else if (length > 0)
  171526. numtoread = (unsigned int) length;
  171527. else
  171528. numtoread = 0;
  171529. for (i = 0; i < numtoread; i++)
  171530. INPUT_BYTE(cinfo, b[i], return FALSE);
  171531. length -= numtoread;
  171532. /* process it */
  171533. switch (cinfo->unread_marker) {
  171534. case M_APP0:
  171535. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171536. break;
  171537. case M_APP14:
  171538. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171539. break;
  171540. default:
  171541. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171542. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171543. break;
  171544. }
  171545. /* skip any remaining data -- could be lots */
  171546. INPUT_SYNC(cinfo);
  171547. if (length > 0)
  171548. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171549. return TRUE;
  171550. }
  171551. #ifdef SAVE_MARKERS_SUPPORTED
  171552. METHODDEF(boolean)
  171553. save_marker (j_decompress_ptr cinfo)
  171554. /* Save an APPn or COM marker into the marker list */
  171555. {
  171556. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171557. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171558. unsigned int bytes_read, data_length;
  171559. JOCTET FAR * data;
  171560. INT32 length = 0;
  171561. INPUT_VARS(cinfo);
  171562. if (cur_marker == NULL) {
  171563. /* begin reading a marker */
  171564. INPUT_2BYTES(cinfo, length, return FALSE);
  171565. length -= 2;
  171566. if (length >= 0) { /* watch out for bogus length word */
  171567. /* figure out how much we want to save */
  171568. unsigned int limit;
  171569. if (cinfo->unread_marker == (int) M_COM)
  171570. limit = marker->length_limit_COM;
  171571. else
  171572. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171573. if ((unsigned int) length < limit)
  171574. limit = (unsigned int) length;
  171575. /* allocate and initialize the marker item */
  171576. cur_marker = (jpeg_saved_marker_ptr)
  171577. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171578. SIZEOF(struct jpeg_marker_struct) + limit);
  171579. cur_marker->next = NULL;
  171580. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171581. cur_marker->original_length = (unsigned int) length;
  171582. cur_marker->data_length = limit;
  171583. /* data area is just beyond the jpeg_marker_struct */
  171584. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171585. marker->cur_marker = cur_marker;
  171586. marker->bytes_read = 0;
  171587. bytes_read = 0;
  171588. data_length = limit;
  171589. } else {
  171590. /* deal with bogus length word */
  171591. bytes_read = data_length = 0;
  171592. data = NULL;
  171593. }
  171594. } else {
  171595. /* resume reading a marker */
  171596. bytes_read = marker->bytes_read;
  171597. data_length = cur_marker->data_length;
  171598. data = cur_marker->data + bytes_read;
  171599. }
  171600. while (bytes_read < data_length) {
  171601. INPUT_SYNC(cinfo); /* move the restart point to here */
  171602. marker->bytes_read = bytes_read;
  171603. /* If there's not at least one byte in buffer, suspend */
  171604. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171605. /* Copy bytes with reasonable rapidity */
  171606. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171607. *data++ = *next_input_byte++;
  171608. bytes_in_buffer--;
  171609. bytes_read++;
  171610. }
  171611. }
  171612. /* Done reading what we want to read */
  171613. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171614. /* Add new marker to end of list */
  171615. if (cinfo->marker_list == NULL) {
  171616. cinfo->marker_list = cur_marker;
  171617. } else {
  171618. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171619. while (prev->next != NULL)
  171620. prev = prev->next;
  171621. prev->next = cur_marker;
  171622. }
  171623. /* Reset pointer & calc remaining data length */
  171624. data = cur_marker->data;
  171625. length = cur_marker->original_length - data_length;
  171626. }
  171627. /* Reset to initial state for next marker */
  171628. marker->cur_marker = NULL;
  171629. /* Process the marker if interesting; else just make a generic trace msg */
  171630. switch (cinfo->unread_marker) {
  171631. case M_APP0:
  171632. examine_app0(cinfo, data, data_length, length);
  171633. break;
  171634. case M_APP14:
  171635. examine_app14(cinfo, data, data_length, length);
  171636. break;
  171637. default:
  171638. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171639. (int) (data_length + length));
  171640. break;
  171641. }
  171642. /* skip any remaining data -- could be lots */
  171643. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171644. if (length > 0)
  171645. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171646. return TRUE;
  171647. }
  171648. #endif /* SAVE_MARKERS_SUPPORTED */
  171649. METHODDEF(boolean)
  171650. skip_variable (j_decompress_ptr cinfo)
  171651. /* Skip over an unknown or uninteresting variable-length marker */
  171652. {
  171653. INT32 length;
  171654. INPUT_VARS(cinfo);
  171655. INPUT_2BYTES(cinfo, length, return FALSE);
  171656. length -= 2;
  171657. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171658. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171659. if (length > 0)
  171660. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171661. return TRUE;
  171662. }
  171663. /*
  171664. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171665. * Returns FALSE if had to suspend before reaching a marker;
  171666. * in that case cinfo->unread_marker is unchanged.
  171667. *
  171668. * Note that the result might not be a valid marker code,
  171669. * but it will never be 0 or FF.
  171670. */
  171671. LOCAL(boolean)
  171672. next_marker (j_decompress_ptr cinfo)
  171673. {
  171674. int c;
  171675. INPUT_VARS(cinfo);
  171676. for (;;) {
  171677. INPUT_BYTE(cinfo, c, return FALSE);
  171678. /* Skip any non-FF bytes.
  171679. * This may look a bit inefficient, but it will not occur in a valid file.
  171680. * We sync after each discarded byte so that a suspending data source
  171681. * can discard the byte from its buffer.
  171682. */
  171683. while (c != 0xFF) {
  171684. cinfo->marker->discarded_bytes++;
  171685. INPUT_SYNC(cinfo);
  171686. INPUT_BYTE(cinfo, c, return FALSE);
  171687. }
  171688. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171689. * pad bytes, so don't count them in discarded_bytes. We assume there
  171690. * will not be so many consecutive FF bytes as to overflow a suspending
  171691. * data source's input buffer.
  171692. */
  171693. do {
  171694. INPUT_BYTE(cinfo, c, return FALSE);
  171695. } while (c == 0xFF);
  171696. if (c != 0)
  171697. break; /* found a valid marker, exit loop */
  171698. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171699. * Discard it and loop back to try again.
  171700. */
  171701. cinfo->marker->discarded_bytes += 2;
  171702. INPUT_SYNC(cinfo);
  171703. }
  171704. if (cinfo->marker->discarded_bytes != 0) {
  171705. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171706. cinfo->marker->discarded_bytes = 0;
  171707. }
  171708. cinfo->unread_marker = c;
  171709. INPUT_SYNC(cinfo);
  171710. return TRUE;
  171711. }
  171712. LOCAL(boolean)
  171713. first_marker (j_decompress_ptr cinfo)
  171714. /* Like next_marker, but used to obtain the initial SOI marker. */
  171715. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171716. * we might well scan an entire input file before realizing it ain't JPEG.
  171717. * If an application wants to process non-JFIF files, it must seek to the
  171718. * SOI before calling the JPEG library.
  171719. */
  171720. {
  171721. int c, c2;
  171722. INPUT_VARS(cinfo);
  171723. INPUT_BYTE(cinfo, c, return FALSE);
  171724. INPUT_BYTE(cinfo, c2, return FALSE);
  171725. if (c != 0xFF || c2 != (int) M_SOI)
  171726. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171727. cinfo->unread_marker = c2;
  171728. INPUT_SYNC(cinfo);
  171729. return TRUE;
  171730. }
  171731. /*
  171732. * Read markers until SOS or EOI.
  171733. *
  171734. * Returns same codes as are defined for jpeg_consume_input:
  171735. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171736. */
  171737. METHODDEF(int)
  171738. read_markers (j_decompress_ptr cinfo)
  171739. {
  171740. /* Outer loop repeats once for each marker. */
  171741. for (;;) {
  171742. /* Collect the marker proper, unless we already did. */
  171743. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171744. if (cinfo->unread_marker == 0) {
  171745. if (! cinfo->marker->saw_SOI) {
  171746. if (! first_marker(cinfo))
  171747. return JPEG_SUSPENDED;
  171748. } else {
  171749. if (! next_marker(cinfo))
  171750. return JPEG_SUSPENDED;
  171751. }
  171752. }
  171753. /* At this point cinfo->unread_marker contains the marker code and the
  171754. * input point is just past the marker proper, but before any parameters.
  171755. * A suspension will cause us to return with this state still true.
  171756. */
  171757. switch (cinfo->unread_marker) {
  171758. case M_SOI:
  171759. if (! get_soi(cinfo))
  171760. return JPEG_SUSPENDED;
  171761. break;
  171762. case M_SOF0: /* Baseline */
  171763. case M_SOF1: /* Extended sequential, Huffman */
  171764. if (! get_sof(cinfo, FALSE, FALSE))
  171765. return JPEG_SUSPENDED;
  171766. break;
  171767. case M_SOF2: /* Progressive, Huffman */
  171768. if (! get_sof(cinfo, TRUE, FALSE))
  171769. return JPEG_SUSPENDED;
  171770. break;
  171771. case M_SOF9: /* Extended sequential, arithmetic */
  171772. if (! get_sof(cinfo, FALSE, TRUE))
  171773. return JPEG_SUSPENDED;
  171774. break;
  171775. case M_SOF10: /* Progressive, arithmetic */
  171776. if (! get_sof(cinfo, TRUE, TRUE))
  171777. return JPEG_SUSPENDED;
  171778. break;
  171779. /* Currently unsupported SOFn types */
  171780. case M_SOF3: /* Lossless, Huffman */
  171781. case M_SOF5: /* Differential sequential, Huffman */
  171782. case M_SOF6: /* Differential progressive, Huffman */
  171783. case M_SOF7: /* Differential lossless, Huffman */
  171784. case M_JPG: /* Reserved for JPEG extensions */
  171785. case M_SOF11: /* Lossless, arithmetic */
  171786. case M_SOF13: /* Differential sequential, arithmetic */
  171787. case M_SOF14: /* Differential progressive, arithmetic */
  171788. case M_SOF15: /* Differential lossless, arithmetic */
  171789. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171790. break;
  171791. case M_SOS:
  171792. if (! get_sos(cinfo))
  171793. return JPEG_SUSPENDED;
  171794. cinfo->unread_marker = 0; /* processed the marker */
  171795. return JPEG_REACHED_SOS;
  171796. case M_EOI:
  171797. TRACEMS(cinfo, 1, JTRC_EOI);
  171798. cinfo->unread_marker = 0; /* processed the marker */
  171799. return JPEG_REACHED_EOI;
  171800. case M_DAC:
  171801. if (! get_dac(cinfo))
  171802. return JPEG_SUSPENDED;
  171803. break;
  171804. case M_DHT:
  171805. if (! get_dht(cinfo))
  171806. return JPEG_SUSPENDED;
  171807. break;
  171808. case M_DQT:
  171809. if (! get_dqt(cinfo))
  171810. return JPEG_SUSPENDED;
  171811. break;
  171812. case M_DRI:
  171813. if (! get_dri(cinfo))
  171814. return JPEG_SUSPENDED;
  171815. break;
  171816. case M_APP0:
  171817. case M_APP1:
  171818. case M_APP2:
  171819. case M_APP3:
  171820. case M_APP4:
  171821. case M_APP5:
  171822. case M_APP6:
  171823. case M_APP7:
  171824. case M_APP8:
  171825. case M_APP9:
  171826. case M_APP10:
  171827. case M_APP11:
  171828. case M_APP12:
  171829. case M_APP13:
  171830. case M_APP14:
  171831. case M_APP15:
  171832. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171833. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171834. return JPEG_SUSPENDED;
  171835. break;
  171836. case M_COM:
  171837. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171838. return JPEG_SUSPENDED;
  171839. break;
  171840. case M_RST0: /* these are all parameterless */
  171841. case M_RST1:
  171842. case M_RST2:
  171843. case M_RST3:
  171844. case M_RST4:
  171845. case M_RST5:
  171846. case M_RST6:
  171847. case M_RST7:
  171848. case M_TEM:
  171849. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171850. break;
  171851. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171852. if (! skip_variable(cinfo))
  171853. return JPEG_SUSPENDED;
  171854. break;
  171855. default: /* must be DHP, EXP, JPGn, or RESn */
  171856. /* For now, we treat the reserved markers as fatal errors since they are
  171857. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171858. * Once the JPEG 3 version-number marker is well defined, this code
  171859. * ought to change!
  171860. */
  171861. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171862. break;
  171863. }
  171864. /* Successfully processed marker, so reset state variable */
  171865. cinfo->unread_marker = 0;
  171866. } /* end loop */
  171867. }
  171868. /*
  171869. * Read a restart marker, which is expected to appear next in the datastream;
  171870. * if the marker is not there, take appropriate recovery action.
  171871. * Returns FALSE if suspension is required.
  171872. *
  171873. * This is called by the entropy decoder after it has read an appropriate
  171874. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171875. * has already read a marker from the data source. Under normal conditions
  171876. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171877. * it holds a marker which the decoder will be unable to read past.
  171878. */
  171879. METHODDEF(boolean)
  171880. read_restart_marker (j_decompress_ptr cinfo)
  171881. {
  171882. /* Obtain a marker unless we already did. */
  171883. /* Note that next_marker will complain if it skips any data. */
  171884. if (cinfo->unread_marker == 0) {
  171885. if (! next_marker(cinfo))
  171886. return FALSE;
  171887. }
  171888. if (cinfo->unread_marker ==
  171889. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171890. /* Normal case --- swallow the marker and let entropy decoder continue */
  171891. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171892. cinfo->unread_marker = 0;
  171893. } else {
  171894. /* Uh-oh, the restart markers have been messed up. */
  171895. /* Let the data source manager determine how to resync. */
  171896. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171897. cinfo->marker->next_restart_num))
  171898. return FALSE;
  171899. }
  171900. /* Update next-restart state */
  171901. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171902. return TRUE;
  171903. }
  171904. /*
  171905. * This is the default resync_to_restart method for data source managers
  171906. * to use if they don't have any better approach. Some data source managers
  171907. * may be able to back up, or may have additional knowledge about the data
  171908. * which permits a more intelligent recovery strategy; such managers would
  171909. * presumably supply their own resync method.
  171910. *
  171911. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171912. * the restart marker it was expecting. (This code is *not* used unless
  171913. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171914. * the marker code actually found (might be anything, except 0 or FF).
  171915. * The desired restart marker number (0..7) is passed as a parameter.
  171916. * This routine is supposed to apply whatever error recovery strategy seems
  171917. * appropriate in order to position the input stream to the next data segment.
  171918. * Note that cinfo->unread_marker is treated as a marker appearing before
  171919. * the current data-source input point; usually it should be reset to zero
  171920. * before returning.
  171921. * Returns FALSE if suspension is required.
  171922. *
  171923. * This implementation is substantially constrained by wanting to treat the
  171924. * input as a data stream; this means we can't back up. Therefore, we have
  171925. * only the following actions to work with:
  171926. * 1. Simply discard the marker and let the entropy decoder resume at next
  171927. * byte of file.
  171928. * 2. Read forward until we find another marker, discarding intervening
  171929. * data. (In theory we could look ahead within the current bufferload,
  171930. * without having to discard data if we don't find the desired marker.
  171931. * This idea is not implemented here, in part because it makes behavior
  171932. * dependent on buffer size and chance buffer-boundary positions.)
  171933. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171934. * This will cause the entropy decoder to process an empty data segment,
  171935. * inserting dummy zeroes, and then we will reprocess the marker.
  171936. *
  171937. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171938. * appropriate if the found marker is a future restart marker (indicating
  171939. * that we have missed the desired restart marker, probably because it got
  171940. * corrupted).
  171941. * We apply #2 or #3 if the found marker is a restart marker no more than
  171942. * two counts behind or ahead of the expected one. We also apply #2 if the
  171943. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171944. * If the found marker is a restart marker more than 2 counts away, we do #1
  171945. * (too much risk that the marker is erroneous; with luck we will be able to
  171946. * resync at some future point).
  171947. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171948. * overrunning the end of a scan. An implementation limited to single-scan
  171949. * files might find it better to apply #2 for markers other than EOI, since
  171950. * any other marker would have to be bogus data in that case.
  171951. */
  171952. GLOBAL(boolean)
  171953. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171954. {
  171955. int marker = cinfo->unread_marker;
  171956. int action = 1;
  171957. /* Always put up a warning. */
  171958. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171959. /* Outer loop handles repeated decision after scanning forward. */
  171960. for (;;) {
  171961. if (marker < (int) M_SOF0)
  171962. action = 2; /* invalid marker */
  171963. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171964. action = 3; /* valid non-restart marker */
  171965. else {
  171966. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171967. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171968. action = 3; /* one of the next two expected restarts */
  171969. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171970. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171971. action = 2; /* a prior restart, so advance */
  171972. else
  171973. action = 1; /* desired restart or too far away */
  171974. }
  171975. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171976. switch (action) {
  171977. case 1:
  171978. /* Discard marker and let entropy decoder resume processing. */
  171979. cinfo->unread_marker = 0;
  171980. return TRUE;
  171981. case 2:
  171982. /* Scan to the next marker, and repeat the decision loop. */
  171983. if (! next_marker(cinfo))
  171984. return FALSE;
  171985. marker = cinfo->unread_marker;
  171986. break;
  171987. case 3:
  171988. /* Return without advancing past this marker. */
  171989. /* Entropy decoder will be forced to process an empty segment. */
  171990. return TRUE;
  171991. }
  171992. } /* end loop */
  171993. }
  171994. /*
  171995. * Reset marker processing state to begin a fresh datastream.
  171996. */
  171997. METHODDEF(void)
  171998. reset_marker_reader (j_decompress_ptr cinfo)
  171999. {
  172000. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172001. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172002. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172003. cinfo->unread_marker = 0; /* no pending marker */
  172004. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172005. marker->pub.saw_SOF = FALSE;
  172006. marker->pub.discarded_bytes = 0;
  172007. marker->cur_marker = NULL;
  172008. }
  172009. /*
  172010. * Initialize the marker reader module.
  172011. * This is called only once, when the decompression object is created.
  172012. */
  172013. GLOBAL(void)
  172014. jinit_marker_reader (j_decompress_ptr cinfo)
  172015. {
  172016. my_marker_ptr2 marker;
  172017. int i;
  172018. /* Create subobject in permanent pool */
  172019. marker = (my_marker_ptr2)
  172020. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172021. SIZEOF(my_marker_reader));
  172022. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172023. /* Initialize public method pointers */
  172024. marker->pub.reset_marker_reader = reset_marker_reader;
  172025. marker->pub.read_markers = read_markers;
  172026. marker->pub.read_restart_marker = read_restart_marker;
  172027. /* Initialize COM/APPn processing.
  172028. * By default, we examine and then discard APP0 and APP14,
  172029. * but simply discard COM and all other APPn.
  172030. */
  172031. marker->process_COM = skip_variable;
  172032. marker->length_limit_COM = 0;
  172033. for (i = 0; i < 16; i++) {
  172034. marker->process_APPn[i] = skip_variable;
  172035. marker->length_limit_APPn[i] = 0;
  172036. }
  172037. marker->process_APPn[0] = get_interesting_appn;
  172038. marker->process_APPn[14] = get_interesting_appn;
  172039. /* Reset marker processing state */
  172040. reset_marker_reader(cinfo);
  172041. }
  172042. /*
  172043. * Control saving of COM and APPn markers into marker_list.
  172044. */
  172045. #ifdef SAVE_MARKERS_SUPPORTED
  172046. GLOBAL(void)
  172047. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172048. unsigned int length_limit)
  172049. {
  172050. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172051. long maxlength;
  172052. jpeg_marker_parser_method processor;
  172053. /* Length limit mustn't be larger than what we can allocate
  172054. * (should only be a concern in a 16-bit environment).
  172055. */
  172056. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172057. if (((long) length_limit) > maxlength)
  172058. length_limit = (unsigned int) maxlength;
  172059. /* Choose processor routine to use.
  172060. * APP0/APP14 have special requirements.
  172061. */
  172062. if (length_limit) {
  172063. processor = save_marker;
  172064. /* If saving APP0/APP14, save at least enough for our internal use. */
  172065. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172066. length_limit = APP0_DATA_LEN;
  172067. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172068. length_limit = APP14_DATA_LEN;
  172069. } else {
  172070. processor = skip_variable;
  172071. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172072. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172073. processor = get_interesting_appn;
  172074. }
  172075. if (marker_code == (int) M_COM) {
  172076. marker->process_COM = processor;
  172077. marker->length_limit_COM = length_limit;
  172078. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172079. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172080. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172081. } else
  172082. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172083. }
  172084. #endif /* SAVE_MARKERS_SUPPORTED */
  172085. /*
  172086. * Install a special processing method for COM or APPn markers.
  172087. */
  172088. GLOBAL(void)
  172089. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172090. jpeg_marker_parser_method routine)
  172091. {
  172092. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172093. if (marker_code == (int) M_COM)
  172094. marker->process_COM = routine;
  172095. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172096. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172097. else
  172098. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172099. }
  172100. /*** End of inlined file: jdmarker.c ***/
  172101. /*** Start of inlined file: jdmaster.c ***/
  172102. #define JPEG_INTERNALS
  172103. /* Private state */
  172104. typedef struct {
  172105. struct jpeg_decomp_master pub; /* public fields */
  172106. int pass_number; /* # of passes completed */
  172107. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172108. /* Saved references to initialized quantizer modules,
  172109. * in case we need to switch modes.
  172110. */
  172111. struct jpeg_color_quantizer * quantizer_1pass;
  172112. struct jpeg_color_quantizer * quantizer_2pass;
  172113. } my_decomp_master;
  172114. typedef my_decomp_master * my_master_ptr6;
  172115. /*
  172116. * Determine whether merged upsample/color conversion should be used.
  172117. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172118. */
  172119. LOCAL(boolean)
  172120. use_merged_upsample (j_decompress_ptr cinfo)
  172121. {
  172122. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172123. /* Merging is the equivalent of plain box-filter upsampling */
  172124. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172125. return FALSE;
  172126. /* jdmerge.c only supports YCC=>RGB color conversion */
  172127. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172128. cinfo->out_color_space != JCS_RGB ||
  172129. cinfo->out_color_components != RGB_PIXELSIZE)
  172130. return FALSE;
  172131. /* and it only handles 2h1v or 2h2v sampling ratios */
  172132. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172133. cinfo->comp_info[1].h_samp_factor != 1 ||
  172134. cinfo->comp_info[2].h_samp_factor != 1 ||
  172135. cinfo->comp_info[0].v_samp_factor > 2 ||
  172136. cinfo->comp_info[1].v_samp_factor != 1 ||
  172137. cinfo->comp_info[2].v_samp_factor != 1)
  172138. return FALSE;
  172139. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172140. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172141. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172142. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172143. return FALSE;
  172144. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172145. return TRUE; /* by golly, it'll work... */
  172146. #else
  172147. return FALSE;
  172148. #endif
  172149. }
  172150. /*
  172151. * Compute output image dimensions and related values.
  172152. * NOTE: this is exported for possible use by application.
  172153. * Hence it mustn't do anything that can't be done twice.
  172154. * Also note that it may be called before the master module is initialized!
  172155. */
  172156. GLOBAL(void)
  172157. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172158. /* Do computations that are needed before master selection phase */
  172159. {
  172160. #ifdef IDCT_SCALING_SUPPORTED
  172161. int ci;
  172162. jpeg_component_info *compptr;
  172163. #endif
  172164. /* Prevent application from calling me at wrong times */
  172165. if (cinfo->global_state != DSTATE_READY)
  172166. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172167. #ifdef IDCT_SCALING_SUPPORTED
  172168. /* Compute actual output image dimensions and DCT scaling choices. */
  172169. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172170. /* Provide 1/8 scaling */
  172171. cinfo->output_width = (JDIMENSION)
  172172. jdiv_round_up((long) cinfo->image_width, 8L);
  172173. cinfo->output_height = (JDIMENSION)
  172174. jdiv_round_up((long) cinfo->image_height, 8L);
  172175. cinfo->min_DCT_scaled_size = 1;
  172176. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172177. /* Provide 1/4 scaling */
  172178. cinfo->output_width = (JDIMENSION)
  172179. jdiv_round_up((long) cinfo->image_width, 4L);
  172180. cinfo->output_height = (JDIMENSION)
  172181. jdiv_round_up((long) cinfo->image_height, 4L);
  172182. cinfo->min_DCT_scaled_size = 2;
  172183. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172184. /* Provide 1/2 scaling */
  172185. cinfo->output_width = (JDIMENSION)
  172186. jdiv_round_up((long) cinfo->image_width, 2L);
  172187. cinfo->output_height = (JDIMENSION)
  172188. jdiv_round_up((long) cinfo->image_height, 2L);
  172189. cinfo->min_DCT_scaled_size = 4;
  172190. } else {
  172191. /* Provide 1/1 scaling */
  172192. cinfo->output_width = cinfo->image_width;
  172193. cinfo->output_height = cinfo->image_height;
  172194. cinfo->min_DCT_scaled_size = DCTSIZE;
  172195. }
  172196. /* In selecting the actual DCT scaling for each component, we try to
  172197. * scale up the chroma components via IDCT scaling rather than upsampling.
  172198. * This saves time if the upsampler gets to use 1:1 scaling.
  172199. * Note this code assumes that the supported DCT scalings are powers of 2.
  172200. */
  172201. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172202. ci++, compptr++) {
  172203. int ssize = cinfo->min_DCT_scaled_size;
  172204. while (ssize < DCTSIZE &&
  172205. (compptr->h_samp_factor * ssize * 2 <=
  172206. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172207. (compptr->v_samp_factor * ssize * 2 <=
  172208. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172209. ssize = ssize * 2;
  172210. }
  172211. compptr->DCT_scaled_size = ssize;
  172212. }
  172213. /* Recompute downsampled dimensions of components;
  172214. * application needs to know these if using raw downsampled data.
  172215. */
  172216. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172217. ci++, compptr++) {
  172218. /* Size in samples, after IDCT scaling */
  172219. compptr->downsampled_width = (JDIMENSION)
  172220. jdiv_round_up((long) cinfo->image_width *
  172221. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172222. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172223. compptr->downsampled_height = (JDIMENSION)
  172224. jdiv_round_up((long) cinfo->image_height *
  172225. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172226. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172227. }
  172228. #else /* !IDCT_SCALING_SUPPORTED */
  172229. /* Hardwire it to "no scaling" */
  172230. cinfo->output_width = cinfo->image_width;
  172231. cinfo->output_height = cinfo->image_height;
  172232. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172233. * and has computed unscaled downsampled_width and downsampled_height.
  172234. */
  172235. #endif /* IDCT_SCALING_SUPPORTED */
  172236. /* Report number of components in selected colorspace. */
  172237. /* Probably this should be in the color conversion module... */
  172238. switch (cinfo->out_color_space) {
  172239. case JCS_GRAYSCALE:
  172240. cinfo->out_color_components = 1;
  172241. break;
  172242. case JCS_RGB:
  172243. #if RGB_PIXELSIZE != 3
  172244. cinfo->out_color_components = RGB_PIXELSIZE;
  172245. break;
  172246. #endif /* else share code with YCbCr */
  172247. case JCS_YCbCr:
  172248. cinfo->out_color_components = 3;
  172249. break;
  172250. case JCS_CMYK:
  172251. case JCS_YCCK:
  172252. cinfo->out_color_components = 4;
  172253. break;
  172254. default: /* else must be same colorspace as in file */
  172255. cinfo->out_color_components = cinfo->num_components;
  172256. break;
  172257. }
  172258. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172259. cinfo->out_color_components);
  172260. /* See if upsampler will want to emit more than one row at a time */
  172261. if (use_merged_upsample(cinfo))
  172262. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172263. else
  172264. cinfo->rec_outbuf_height = 1;
  172265. }
  172266. /*
  172267. * Several decompression processes need to range-limit values to the range
  172268. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172269. * due to noise introduced by quantization, roundoff error, etc. These
  172270. * processes are inner loops and need to be as fast as possible. On most
  172271. * machines, particularly CPUs with pipelines or instruction prefetch,
  172272. * a (subscript-check-less) C table lookup
  172273. * x = sample_range_limit[x];
  172274. * is faster than explicit tests
  172275. * if (x < 0) x = 0;
  172276. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172277. * These processes all use a common table prepared by the routine below.
  172278. *
  172279. * For most steps we can mathematically guarantee that the initial value
  172280. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172281. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172282. * limiting step (just after the IDCT), a wildly out-of-range value is
  172283. * possible if the input data is corrupt. To avoid any chance of indexing
  172284. * off the end of memory and getting a bad-pointer trap, we perform the
  172285. * post-IDCT limiting thus:
  172286. * x = range_limit[x & MASK];
  172287. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172288. * samples. Under normal circumstances this is more than enough range and
  172289. * a correct output will be generated; with bogus input data the mask will
  172290. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172291. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172292. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172293. * So the post-IDCT limiting table ends up looking like this:
  172294. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172295. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172296. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172297. * 0,1,...,CENTERJSAMPLE-1
  172298. * Negative inputs select values from the upper half of the table after
  172299. * masking.
  172300. *
  172301. * We can save some space by overlapping the start of the post-IDCT table
  172302. * with the simpler range limiting table. The post-IDCT table begins at
  172303. * sample_range_limit + CENTERJSAMPLE.
  172304. *
  172305. * Note that the table is allocated in near data space on PCs; it's small
  172306. * enough and used often enough to justify this.
  172307. */
  172308. LOCAL(void)
  172309. prepare_range_limit_table (j_decompress_ptr cinfo)
  172310. /* Allocate and fill in the sample_range_limit table */
  172311. {
  172312. JSAMPLE * table;
  172313. int i;
  172314. table = (JSAMPLE *)
  172315. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172316. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172317. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172318. cinfo->sample_range_limit = table;
  172319. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172320. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172321. /* Main part of "simple" table: limit[x] = x */
  172322. for (i = 0; i <= MAXJSAMPLE; i++)
  172323. table[i] = (JSAMPLE) i;
  172324. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172325. /* End of simple table, rest of first half of post-IDCT table */
  172326. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172327. table[i] = MAXJSAMPLE;
  172328. /* Second half of post-IDCT table */
  172329. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172330. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172331. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172332. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172333. }
  172334. /*
  172335. * Master selection of decompression modules.
  172336. * This is done once at jpeg_start_decompress time. We determine
  172337. * which modules will be used and give them appropriate initialization calls.
  172338. * We also initialize the decompressor input side to begin consuming data.
  172339. *
  172340. * Since jpeg_read_header has finished, we know what is in the SOF
  172341. * and (first) SOS markers. We also have all the application parameter
  172342. * settings.
  172343. */
  172344. LOCAL(void)
  172345. master_selection (j_decompress_ptr cinfo)
  172346. {
  172347. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172348. boolean use_c_buffer;
  172349. long samplesperrow;
  172350. JDIMENSION jd_samplesperrow;
  172351. /* Initialize dimensions and other stuff */
  172352. jpeg_calc_output_dimensions(cinfo);
  172353. prepare_range_limit_table(cinfo);
  172354. /* Width of an output scanline must be representable as JDIMENSION. */
  172355. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172356. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172357. if ((long) jd_samplesperrow != samplesperrow)
  172358. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172359. /* Initialize my private state */
  172360. master->pass_number = 0;
  172361. master->using_merged_upsample = use_merged_upsample(cinfo);
  172362. /* Color quantizer selection */
  172363. master->quantizer_1pass = NULL;
  172364. master->quantizer_2pass = NULL;
  172365. /* No mode changes if not using buffered-image mode. */
  172366. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172367. cinfo->enable_1pass_quant = FALSE;
  172368. cinfo->enable_external_quant = FALSE;
  172369. cinfo->enable_2pass_quant = FALSE;
  172370. }
  172371. if (cinfo->quantize_colors) {
  172372. if (cinfo->raw_data_out)
  172373. ERREXIT(cinfo, JERR_NOTIMPL);
  172374. /* 2-pass quantizer only works in 3-component color space. */
  172375. if (cinfo->out_color_components != 3) {
  172376. cinfo->enable_1pass_quant = TRUE;
  172377. cinfo->enable_external_quant = FALSE;
  172378. cinfo->enable_2pass_quant = FALSE;
  172379. cinfo->colormap = NULL;
  172380. } else if (cinfo->colormap != NULL) {
  172381. cinfo->enable_external_quant = TRUE;
  172382. } else if (cinfo->two_pass_quantize) {
  172383. cinfo->enable_2pass_quant = TRUE;
  172384. } else {
  172385. cinfo->enable_1pass_quant = TRUE;
  172386. }
  172387. if (cinfo->enable_1pass_quant) {
  172388. #ifdef QUANT_1PASS_SUPPORTED
  172389. jinit_1pass_quantizer(cinfo);
  172390. master->quantizer_1pass = cinfo->cquantize;
  172391. #else
  172392. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172393. #endif
  172394. }
  172395. /* We use the 2-pass code to map to external colormaps. */
  172396. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172397. #ifdef QUANT_2PASS_SUPPORTED
  172398. jinit_2pass_quantizer(cinfo);
  172399. master->quantizer_2pass = cinfo->cquantize;
  172400. #else
  172401. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172402. #endif
  172403. }
  172404. /* If both quantizers are initialized, the 2-pass one is left active;
  172405. * this is necessary for starting with quantization to an external map.
  172406. */
  172407. }
  172408. /* Post-processing: in particular, color conversion first */
  172409. if (! cinfo->raw_data_out) {
  172410. if (master->using_merged_upsample) {
  172411. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172412. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172413. #else
  172414. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172415. #endif
  172416. } else {
  172417. jinit_color_deconverter(cinfo);
  172418. jinit_upsampler(cinfo);
  172419. }
  172420. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172421. }
  172422. /* Inverse DCT */
  172423. jinit_inverse_dct(cinfo);
  172424. /* Entropy decoding: either Huffman or arithmetic coding. */
  172425. if (cinfo->arith_code) {
  172426. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172427. } else {
  172428. if (cinfo->progressive_mode) {
  172429. #ifdef D_PROGRESSIVE_SUPPORTED
  172430. jinit_phuff_decoder(cinfo);
  172431. #else
  172432. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172433. #endif
  172434. } else
  172435. jinit_huff_decoder(cinfo);
  172436. }
  172437. /* Initialize principal buffer controllers. */
  172438. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172439. jinit_d_coef_controller(cinfo, use_c_buffer);
  172440. if (! cinfo->raw_data_out)
  172441. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172442. /* We can now tell the memory manager to allocate virtual arrays. */
  172443. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172444. /* Initialize input side of decompressor to consume first scan. */
  172445. (*cinfo->inputctl->start_input_pass) (cinfo);
  172446. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172447. /* If jpeg_start_decompress will read the whole file, initialize
  172448. * progress monitoring appropriately. The input step is counted
  172449. * as one pass.
  172450. */
  172451. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172452. cinfo->inputctl->has_multiple_scans) {
  172453. int nscans;
  172454. /* Estimate number of scans to set pass_limit. */
  172455. if (cinfo->progressive_mode) {
  172456. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172457. nscans = 2 + 3 * cinfo->num_components;
  172458. } else {
  172459. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172460. nscans = cinfo->num_components;
  172461. }
  172462. cinfo->progress->pass_counter = 0L;
  172463. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172464. cinfo->progress->completed_passes = 0;
  172465. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172466. /* Count the input pass as done */
  172467. master->pass_number++;
  172468. }
  172469. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172470. }
  172471. /*
  172472. * Per-pass setup.
  172473. * This is called at the beginning of each output pass. We determine which
  172474. * modules will be active during this pass and give them appropriate
  172475. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172476. * is a "real" output pass or a dummy pass for color quantization.
  172477. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172478. */
  172479. METHODDEF(void)
  172480. prepare_for_output_pass (j_decompress_ptr cinfo)
  172481. {
  172482. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172483. if (master->pub.is_dummy_pass) {
  172484. #ifdef QUANT_2PASS_SUPPORTED
  172485. /* Final pass of 2-pass quantization */
  172486. master->pub.is_dummy_pass = FALSE;
  172487. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172488. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172489. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172490. #else
  172491. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172492. #endif /* QUANT_2PASS_SUPPORTED */
  172493. } else {
  172494. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172495. /* Select new quantization method */
  172496. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172497. cinfo->cquantize = master->quantizer_2pass;
  172498. master->pub.is_dummy_pass = TRUE;
  172499. } else if (cinfo->enable_1pass_quant) {
  172500. cinfo->cquantize = master->quantizer_1pass;
  172501. } else {
  172502. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172503. }
  172504. }
  172505. (*cinfo->idct->start_pass) (cinfo);
  172506. (*cinfo->coef->start_output_pass) (cinfo);
  172507. if (! cinfo->raw_data_out) {
  172508. if (! master->using_merged_upsample)
  172509. (*cinfo->cconvert->start_pass) (cinfo);
  172510. (*cinfo->upsample->start_pass) (cinfo);
  172511. if (cinfo->quantize_colors)
  172512. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172513. (*cinfo->post->start_pass) (cinfo,
  172514. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172515. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172516. }
  172517. }
  172518. /* Set up progress monitor's pass info if present */
  172519. if (cinfo->progress != NULL) {
  172520. cinfo->progress->completed_passes = master->pass_number;
  172521. cinfo->progress->total_passes = master->pass_number +
  172522. (master->pub.is_dummy_pass ? 2 : 1);
  172523. /* In buffered-image mode, we assume one more output pass if EOI not
  172524. * yet reached, but no more passes if EOI has been reached.
  172525. */
  172526. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172527. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172528. }
  172529. }
  172530. }
  172531. /*
  172532. * Finish up at end of an output pass.
  172533. */
  172534. METHODDEF(void)
  172535. finish_output_pass (j_decompress_ptr cinfo)
  172536. {
  172537. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172538. if (cinfo->quantize_colors)
  172539. (*cinfo->cquantize->finish_pass) (cinfo);
  172540. master->pass_number++;
  172541. }
  172542. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172543. /*
  172544. * Switch to a new external colormap between output passes.
  172545. */
  172546. GLOBAL(void)
  172547. jpeg_new_colormap (j_decompress_ptr cinfo)
  172548. {
  172549. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172550. /* Prevent application from calling me at wrong times */
  172551. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172552. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172553. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172554. cinfo->colormap != NULL) {
  172555. /* Select 2-pass quantizer for external colormap use */
  172556. cinfo->cquantize = master->quantizer_2pass;
  172557. /* Notify quantizer of colormap change */
  172558. (*cinfo->cquantize->new_color_map) (cinfo);
  172559. master->pub.is_dummy_pass = FALSE; /* just in case */
  172560. } else
  172561. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172562. }
  172563. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172564. /*
  172565. * Initialize master decompression control and select active modules.
  172566. * This is performed at the start of jpeg_start_decompress.
  172567. */
  172568. GLOBAL(void)
  172569. jinit_master_decompress (j_decompress_ptr cinfo)
  172570. {
  172571. my_master_ptr6 master;
  172572. master = (my_master_ptr6)
  172573. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172574. SIZEOF(my_decomp_master));
  172575. cinfo->master = (struct jpeg_decomp_master *) master;
  172576. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172577. master->pub.finish_output_pass = finish_output_pass;
  172578. master->pub.is_dummy_pass = FALSE;
  172579. master_selection(cinfo);
  172580. }
  172581. /*** End of inlined file: jdmaster.c ***/
  172582. #undef FIX
  172583. /*** Start of inlined file: jdmerge.c ***/
  172584. #define JPEG_INTERNALS
  172585. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172586. /* Private subobject */
  172587. typedef struct {
  172588. struct jpeg_upsampler pub; /* public fields */
  172589. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172590. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172591. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172592. JSAMPARRAY output_buf));
  172593. /* Private state for YCC->RGB conversion */
  172594. int * Cr_r_tab; /* => table for Cr to R conversion */
  172595. int * Cb_b_tab; /* => table for Cb to B conversion */
  172596. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172597. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172598. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172599. * We need a "spare" row buffer to hold the second output row if the
  172600. * application provides just a one-row buffer; we also use the spare
  172601. * to discard the dummy last row if the image height is odd.
  172602. */
  172603. JSAMPROW spare_row;
  172604. boolean spare_full; /* T if spare buffer is occupied */
  172605. JDIMENSION out_row_width; /* samples per output row */
  172606. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172607. } my_upsampler;
  172608. typedef my_upsampler * my_upsample_ptr;
  172609. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172610. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172611. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172612. /*
  172613. * Initialize tables for YCC->RGB colorspace conversion.
  172614. * This is taken directly from jdcolor.c; see that file for more info.
  172615. */
  172616. LOCAL(void)
  172617. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172618. {
  172619. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172620. int i;
  172621. INT32 x;
  172622. SHIFT_TEMPS
  172623. upsample->Cr_r_tab = (int *)
  172624. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172625. (MAXJSAMPLE+1) * SIZEOF(int));
  172626. upsample->Cb_b_tab = (int *)
  172627. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172628. (MAXJSAMPLE+1) * SIZEOF(int));
  172629. upsample->Cr_g_tab = (INT32 *)
  172630. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172631. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172632. upsample->Cb_g_tab = (INT32 *)
  172633. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172634. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172635. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172636. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172637. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172638. /* Cr=>R value is nearest int to 1.40200 * x */
  172639. upsample->Cr_r_tab[i] = (int)
  172640. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172641. /* Cb=>B value is nearest int to 1.77200 * x */
  172642. upsample->Cb_b_tab[i] = (int)
  172643. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172644. /* Cr=>G value is scaled-up -0.71414 * x */
  172645. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172646. /* Cb=>G value is scaled-up -0.34414 * x */
  172647. /* We also add in ONE_HALF so that need not do it in inner loop */
  172648. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172649. }
  172650. }
  172651. /*
  172652. * Initialize for an upsampling pass.
  172653. */
  172654. METHODDEF(void)
  172655. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172656. {
  172657. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172658. /* Mark the spare buffer empty */
  172659. upsample->spare_full = FALSE;
  172660. /* Initialize total-height counter for detecting bottom of image */
  172661. upsample->rows_to_go = cinfo->output_height;
  172662. }
  172663. /*
  172664. * Control routine to do upsampling (and color conversion).
  172665. *
  172666. * The control routine just handles the row buffering considerations.
  172667. */
  172668. METHODDEF(void)
  172669. merged_2v_upsample (j_decompress_ptr cinfo,
  172670. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172671. JDIMENSION,
  172672. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172673. JDIMENSION out_rows_avail)
  172674. /* 2:1 vertical sampling case: may need a spare row. */
  172675. {
  172676. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172677. JSAMPROW work_ptrs[2];
  172678. JDIMENSION num_rows; /* number of rows returned to caller */
  172679. if (upsample->spare_full) {
  172680. /* If we have a spare row saved from a previous cycle, just return it. */
  172681. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172682. 1, upsample->out_row_width);
  172683. num_rows = 1;
  172684. upsample->spare_full = FALSE;
  172685. } else {
  172686. /* Figure number of rows to return to caller. */
  172687. num_rows = 2;
  172688. /* Not more than the distance to the end of the image. */
  172689. if (num_rows > upsample->rows_to_go)
  172690. num_rows = upsample->rows_to_go;
  172691. /* And not more than what the client can accept: */
  172692. out_rows_avail -= *out_row_ctr;
  172693. if (num_rows > out_rows_avail)
  172694. num_rows = out_rows_avail;
  172695. /* Create output pointer array for upsampler. */
  172696. work_ptrs[0] = output_buf[*out_row_ctr];
  172697. if (num_rows > 1) {
  172698. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172699. } else {
  172700. work_ptrs[1] = upsample->spare_row;
  172701. upsample->spare_full = TRUE;
  172702. }
  172703. /* Now do the upsampling. */
  172704. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172705. }
  172706. /* Adjust counts */
  172707. *out_row_ctr += num_rows;
  172708. upsample->rows_to_go -= num_rows;
  172709. /* When the buffer is emptied, declare this input row group consumed */
  172710. if (! upsample->spare_full)
  172711. (*in_row_group_ctr)++;
  172712. }
  172713. METHODDEF(void)
  172714. merged_1v_upsample (j_decompress_ptr cinfo,
  172715. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172716. JDIMENSION,
  172717. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172718. JDIMENSION)
  172719. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172720. {
  172721. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172722. /* Just do the upsampling. */
  172723. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172724. output_buf + *out_row_ctr);
  172725. /* Adjust counts */
  172726. (*out_row_ctr)++;
  172727. (*in_row_group_ctr)++;
  172728. }
  172729. /*
  172730. * These are the routines invoked by the control routines to do
  172731. * the actual upsampling/conversion. One row group is processed per call.
  172732. *
  172733. * Note: since we may be writing directly into application-supplied buffers,
  172734. * we have to be honest about the output width; we can't assume the buffer
  172735. * has been rounded up to an even width.
  172736. */
  172737. /*
  172738. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172739. */
  172740. METHODDEF(void)
  172741. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172742. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172743. JSAMPARRAY output_buf)
  172744. {
  172745. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172746. register int y, cred, cgreen, cblue;
  172747. int cb, cr;
  172748. register JSAMPROW outptr;
  172749. JSAMPROW inptr0, inptr1, inptr2;
  172750. JDIMENSION col;
  172751. /* copy these pointers into registers if possible */
  172752. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172753. int * Crrtab = upsample->Cr_r_tab;
  172754. int * Cbbtab = upsample->Cb_b_tab;
  172755. INT32 * Crgtab = upsample->Cr_g_tab;
  172756. INT32 * Cbgtab = upsample->Cb_g_tab;
  172757. SHIFT_TEMPS
  172758. inptr0 = input_buf[0][in_row_group_ctr];
  172759. inptr1 = input_buf[1][in_row_group_ctr];
  172760. inptr2 = input_buf[2][in_row_group_ctr];
  172761. outptr = output_buf[0];
  172762. /* Loop for each pair of output pixels */
  172763. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172764. /* Do the chroma part of the calculation */
  172765. cb = GETJSAMPLE(*inptr1++);
  172766. cr = GETJSAMPLE(*inptr2++);
  172767. cred = Crrtab[cr];
  172768. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172769. cblue = Cbbtab[cb];
  172770. /* Fetch 2 Y values and emit 2 pixels */
  172771. y = GETJSAMPLE(*inptr0++);
  172772. outptr[RGB_RED] = range_limit[y + cred];
  172773. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172774. outptr[RGB_BLUE] = range_limit[y + cblue];
  172775. outptr += RGB_PIXELSIZE;
  172776. y = GETJSAMPLE(*inptr0++);
  172777. outptr[RGB_RED] = range_limit[y + cred];
  172778. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172779. outptr[RGB_BLUE] = range_limit[y + cblue];
  172780. outptr += RGB_PIXELSIZE;
  172781. }
  172782. /* If image width is odd, do the last output column separately */
  172783. if (cinfo->output_width & 1) {
  172784. cb = GETJSAMPLE(*inptr1);
  172785. cr = GETJSAMPLE(*inptr2);
  172786. cred = Crrtab[cr];
  172787. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172788. cblue = Cbbtab[cb];
  172789. y = GETJSAMPLE(*inptr0);
  172790. outptr[RGB_RED] = range_limit[y + cred];
  172791. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172792. outptr[RGB_BLUE] = range_limit[y + cblue];
  172793. }
  172794. }
  172795. /*
  172796. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172797. */
  172798. METHODDEF(void)
  172799. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172800. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172801. JSAMPARRAY output_buf)
  172802. {
  172803. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172804. register int y, cred, cgreen, cblue;
  172805. int cb, cr;
  172806. register JSAMPROW outptr0, outptr1;
  172807. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172808. JDIMENSION col;
  172809. /* copy these pointers into registers if possible */
  172810. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172811. int * Crrtab = upsample->Cr_r_tab;
  172812. int * Cbbtab = upsample->Cb_b_tab;
  172813. INT32 * Crgtab = upsample->Cr_g_tab;
  172814. INT32 * Cbgtab = upsample->Cb_g_tab;
  172815. SHIFT_TEMPS
  172816. inptr00 = input_buf[0][in_row_group_ctr*2];
  172817. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172818. inptr1 = input_buf[1][in_row_group_ctr];
  172819. inptr2 = input_buf[2][in_row_group_ctr];
  172820. outptr0 = output_buf[0];
  172821. outptr1 = output_buf[1];
  172822. /* Loop for each group of output pixels */
  172823. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172824. /* Do the chroma part of the calculation */
  172825. cb = GETJSAMPLE(*inptr1++);
  172826. cr = GETJSAMPLE(*inptr2++);
  172827. cred = Crrtab[cr];
  172828. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172829. cblue = Cbbtab[cb];
  172830. /* Fetch 4 Y values and emit 4 pixels */
  172831. y = GETJSAMPLE(*inptr00++);
  172832. outptr0[RGB_RED] = range_limit[y + cred];
  172833. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172834. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172835. outptr0 += RGB_PIXELSIZE;
  172836. y = GETJSAMPLE(*inptr00++);
  172837. outptr0[RGB_RED] = range_limit[y + cred];
  172838. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172839. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172840. outptr0 += RGB_PIXELSIZE;
  172841. y = GETJSAMPLE(*inptr01++);
  172842. outptr1[RGB_RED] = range_limit[y + cred];
  172843. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172844. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172845. outptr1 += RGB_PIXELSIZE;
  172846. y = GETJSAMPLE(*inptr01++);
  172847. outptr1[RGB_RED] = range_limit[y + cred];
  172848. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172849. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172850. outptr1 += RGB_PIXELSIZE;
  172851. }
  172852. /* If image width is odd, do the last output column separately */
  172853. if (cinfo->output_width & 1) {
  172854. cb = GETJSAMPLE(*inptr1);
  172855. cr = GETJSAMPLE(*inptr2);
  172856. cred = Crrtab[cr];
  172857. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172858. cblue = Cbbtab[cb];
  172859. y = GETJSAMPLE(*inptr00);
  172860. outptr0[RGB_RED] = range_limit[y + cred];
  172861. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172862. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172863. y = GETJSAMPLE(*inptr01);
  172864. outptr1[RGB_RED] = range_limit[y + cred];
  172865. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172866. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172867. }
  172868. }
  172869. /*
  172870. * Module initialization routine for merged upsampling/color conversion.
  172871. *
  172872. * NB: this is called under the conditions determined by use_merged_upsample()
  172873. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172874. * of this module; no safety checks are made here.
  172875. */
  172876. GLOBAL(void)
  172877. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172878. {
  172879. my_upsample_ptr upsample;
  172880. upsample = (my_upsample_ptr)
  172881. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172882. SIZEOF(my_upsampler));
  172883. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172884. upsample->pub.start_pass = start_pass_merged_upsample;
  172885. upsample->pub.need_context_rows = FALSE;
  172886. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172887. if (cinfo->max_v_samp_factor == 2) {
  172888. upsample->pub.upsample = merged_2v_upsample;
  172889. upsample->upmethod = h2v2_merged_upsample;
  172890. /* Allocate a spare row buffer */
  172891. upsample->spare_row = (JSAMPROW)
  172892. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172893. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172894. } else {
  172895. upsample->pub.upsample = merged_1v_upsample;
  172896. upsample->upmethod = h2v1_merged_upsample;
  172897. /* No spare row needed */
  172898. upsample->spare_row = NULL;
  172899. }
  172900. build_ycc_rgb_table2(cinfo);
  172901. }
  172902. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172903. /*** End of inlined file: jdmerge.c ***/
  172904. #undef ASSIGN_STATE
  172905. /*** Start of inlined file: jdphuff.c ***/
  172906. #define JPEG_INTERNALS
  172907. #ifdef D_PROGRESSIVE_SUPPORTED
  172908. /*
  172909. * Expanded entropy decoder object for progressive Huffman decoding.
  172910. *
  172911. * The savable_state subrecord contains fields that change within an MCU,
  172912. * but must not be updated permanently until we complete the MCU.
  172913. */
  172914. typedef struct {
  172915. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172916. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172917. } savable_state3;
  172918. /* This macro is to work around compilers with missing or broken
  172919. * structure assignment. You'll need to fix this code if you have
  172920. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172921. */
  172922. #ifndef NO_STRUCT_ASSIGN
  172923. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172924. #else
  172925. #if MAX_COMPS_IN_SCAN == 4
  172926. #define ASSIGN_STATE(dest,src) \
  172927. ((dest).EOBRUN = (src).EOBRUN, \
  172928. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172929. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172930. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172931. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172932. #endif
  172933. #endif
  172934. typedef struct {
  172935. struct jpeg_entropy_decoder pub; /* public fields */
  172936. /* These fields are loaded into local variables at start of each MCU.
  172937. * In case of suspension, we exit WITHOUT updating them.
  172938. */
  172939. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172940. savable_state3 saved; /* Other state at start of MCU */
  172941. /* These fields are NOT loaded into local working state. */
  172942. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172943. /* Pointers to derived tables (these workspaces have image lifespan) */
  172944. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172945. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172946. } phuff_entropy_decoder;
  172947. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172948. /* Forward declarations */
  172949. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172950. JBLOCKROW *MCU_data));
  172951. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172952. JBLOCKROW *MCU_data));
  172953. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172954. JBLOCKROW *MCU_data));
  172955. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172956. JBLOCKROW *MCU_data));
  172957. /*
  172958. * Initialize for a Huffman-compressed scan.
  172959. */
  172960. METHODDEF(void)
  172961. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172962. {
  172963. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172964. boolean is_DC_band, bad;
  172965. int ci, coefi, tbl;
  172966. int *coef_bit_ptr;
  172967. jpeg_component_info * compptr;
  172968. is_DC_band = (cinfo->Ss == 0);
  172969. /* Validate scan parameters */
  172970. bad = FALSE;
  172971. if (is_DC_band) {
  172972. if (cinfo->Se != 0)
  172973. bad = TRUE;
  172974. } else {
  172975. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172976. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172977. bad = TRUE;
  172978. /* AC scans may have only one component */
  172979. if (cinfo->comps_in_scan != 1)
  172980. bad = TRUE;
  172981. }
  172982. if (cinfo->Ah != 0) {
  172983. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172984. if (cinfo->Al != cinfo->Ah-1)
  172985. bad = TRUE;
  172986. }
  172987. if (cinfo->Al > 13) /* need not check for < 0 */
  172988. bad = TRUE;
  172989. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172990. * but the spec doesn't say so, and we try to be liberal about what we
  172991. * accept. Note: large Al values could result in out-of-range DC
  172992. * coefficients during early scans, leading to bizarre displays due to
  172993. * overflows in the IDCT math. But we won't crash.
  172994. */
  172995. if (bad)
  172996. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172997. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172998. /* Update progression status, and verify that scan order is legal.
  172999. * Note that inter-scan inconsistencies are treated as warnings
  173000. * not fatal errors ... not clear if this is right way to behave.
  173001. */
  173002. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173003. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173004. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173005. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173006. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173007. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173008. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173009. if (cinfo->Ah != expected)
  173010. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173011. coef_bit_ptr[coefi] = cinfo->Al;
  173012. }
  173013. }
  173014. /* Select MCU decoding routine */
  173015. if (cinfo->Ah == 0) {
  173016. if (is_DC_band)
  173017. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173018. else
  173019. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173020. } else {
  173021. if (is_DC_band)
  173022. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173023. else
  173024. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173025. }
  173026. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173027. compptr = cinfo->cur_comp_info[ci];
  173028. /* Make sure requested tables are present, and compute derived tables.
  173029. * We may build same derived table more than once, but it's not expensive.
  173030. */
  173031. if (is_DC_band) {
  173032. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173033. tbl = compptr->dc_tbl_no;
  173034. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173035. & entropy->derived_tbls[tbl]);
  173036. }
  173037. } else {
  173038. tbl = compptr->ac_tbl_no;
  173039. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173040. & entropy->derived_tbls[tbl]);
  173041. /* remember the single active table */
  173042. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173043. }
  173044. /* Initialize DC predictions to 0 */
  173045. entropy->saved.last_dc_val[ci] = 0;
  173046. }
  173047. /* Initialize bitread state variables */
  173048. entropy->bitstate.bits_left = 0;
  173049. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173050. entropy->pub.insufficient_data = FALSE;
  173051. /* Initialize private state variables */
  173052. entropy->saved.EOBRUN = 0;
  173053. /* Initialize restart counter */
  173054. entropy->restarts_to_go = cinfo->restart_interval;
  173055. }
  173056. /*
  173057. * Check for a restart marker & resynchronize decoder.
  173058. * Returns FALSE if must suspend.
  173059. */
  173060. LOCAL(boolean)
  173061. process_restartp (j_decompress_ptr cinfo)
  173062. {
  173063. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173064. int ci;
  173065. /* Throw away any unused bits remaining in bit buffer; */
  173066. /* include any full bytes in next_marker's count of discarded bytes */
  173067. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173068. entropy->bitstate.bits_left = 0;
  173069. /* Advance past the RSTn marker */
  173070. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173071. return FALSE;
  173072. /* Re-initialize DC predictions to 0 */
  173073. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173074. entropy->saved.last_dc_val[ci] = 0;
  173075. /* Re-init EOB run count, too */
  173076. entropy->saved.EOBRUN = 0;
  173077. /* Reset restart counter */
  173078. entropy->restarts_to_go = cinfo->restart_interval;
  173079. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173080. * against a marker. In that case we will end up treating the next data
  173081. * segment as empty, and we can avoid producing bogus output pixels by
  173082. * leaving the flag set.
  173083. */
  173084. if (cinfo->unread_marker == 0)
  173085. entropy->pub.insufficient_data = FALSE;
  173086. return TRUE;
  173087. }
  173088. /*
  173089. * Huffman MCU decoding.
  173090. * Each of these routines decodes and returns one MCU's worth of
  173091. * Huffman-compressed coefficients.
  173092. * The coefficients are reordered from zigzag order into natural array order,
  173093. * but are not dequantized.
  173094. *
  173095. * The i'th block of the MCU is stored into the block pointed to by
  173096. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173097. *
  173098. * We return FALSE if data source requested suspension. In that case no
  173099. * changes have been made to permanent state. (Exception: some output
  173100. * coefficients may already have been assigned. This is harmless for
  173101. * spectral selection, since we'll just re-assign them on the next call.
  173102. * Successive approximation AC refinement has to be more careful, however.)
  173103. */
  173104. /*
  173105. * MCU decoding for DC initial scan (either spectral selection,
  173106. * or first pass of successive approximation).
  173107. */
  173108. METHODDEF(boolean)
  173109. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173110. {
  173111. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173112. int Al = cinfo->Al;
  173113. register int s, r;
  173114. int blkn, ci;
  173115. JBLOCKROW block;
  173116. BITREAD_STATE_VARS;
  173117. savable_state3 state;
  173118. d_derived_tbl * tbl;
  173119. jpeg_component_info * compptr;
  173120. /* Process restart marker if needed; may have to suspend */
  173121. if (cinfo->restart_interval) {
  173122. if (entropy->restarts_to_go == 0)
  173123. if (! process_restartp(cinfo))
  173124. return FALSE;
  173125. }
  173126. /* If we've run out of data, just leave the MCU set to zeroes.
  173127. * This way, we return uniform gray for the remainder of the segment.
  173128. */
  173129. if (! entropy->pub.insufficient_data) {
  173130. /* Load up working state */
  173131. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173132. ASSIGN_STATE(state, entropy->saved);
  173133. /* Outer loop handles each block in the MCU */
  173134. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173135. block = MCU_data[blkn];
  173136. ci = cinfo->MCU_membership[blkn];
  173137. compptr = cinfo->cur_comp_info[ci];
  173138. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173139. /* Decode a single block's worth of coefficients */
  173140. /* Section F.2.2.1: decode the DC coefficient difference */
  173141. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173142. if (s) {
  173143. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173144. r = GET_BITS(s);
  173145. s = HUFF_EXTEND(r, s);
  173146. }
  173147. /* Convert DC difference to actual value, update last_dc_val */
  173148. s += state.last_dc_val[ci];
  173149. state.last_dc_val[ci] = s;
  173150. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173151. (*block)[0] = (JCOEF) (s << Al);
  173152. }
  173153. /* Completed MCU, so update state */
  173154. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173155. ASSIGN_STATE(entropy->saved, state);
  173156. }
  173157. /* Account for restart interval (no-op if not using restarts) */
  173158. entropy->restarts_to_go--;
  173159. return TRUE;
  173160. }
  173161. /*
  173162. * MCU decoding for AC initial scan (either spectral selection,
  173163. * or first pass of successive approximation).
  173164. */
  173165. METHODDEF(boolean)
  173166. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173167. {
  173168. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173169. int Se = cinfo->Se;
  173170. int Al = cinfo->Al;
  173171. register int s, k, r;
  173172. unsigned int EOBRUN;
  173173. JBLOCKROW block;
  173174. BITREAD_STATE_VARS;
  173175. d_derived_tbl * tbl;
  173176. /* Process restart marker if needed; may have to suspend */
  173177. if (cinfo->restart_interval) {
  173178. if (entropy->restarts_to_go == 0)
  173179. if (! process_restartp(cinfo))
  173180. return FALSE;
  173181. }
  173182. /* If we've run out of data, just leave the MCU set to zeroes.
  173183. * This way, we return uniform gray for the remainder of the segment.
  173184. */
  173185. if (! entropy->pub.insufficient_data) {
  173186. /* Load up working state.
  173187. * We can avoid loading/saving bitread state if in an EOB run.
  173188. */
  173189. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173190. /* There is always only one block per MCU */
  173191. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173192. EOBRUN--; /* ...process it now (we do nothing) */
  173193. else {
  173194. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173195. block = MCU_data[0];
  173196. tbl = entropy->ac_derived_tbl;
  173197. for (k = cinfo->Ss; k <= Se; k++) {
  173198. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173199. r = s >> 4;
  173200. s &= 15;
  173201. if (s) {
  173202. k += r;
  173203. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173204. r = GET_BITS(s);
  173205. s = HUFF_EXTEND(r, s);
  173206. /* Scale and output coefficient in natural (dezigzagged) order */
  173207. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173208. } else {
  173209. if (r == 15) { /* ZRL */
  173210. k += 15; /* skip 15 zeroes in band */
  173211. } else { /* EOBr, run length is 2^r + appended bits */
  173212. EOBRUN = 1 << r;
  173213. if (r) { /* EOBr, r > 0 */
  173214. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173215. r = GET_BITS(r);
  173216. EOBRUN += r;
  173217. }
  173218. EOBRUN--; /* this band is processed at this moment */
  173219. break; /* force end-of-band */
  173220. }
  173221. }
  173222. }
  173223. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173224. }
  173225. /* Completed MCU, so update state */
  173226. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173227. }
  173228. /* Account for restart interval (no-op if not using restarts) */
  173229. entropy->restarts_to_go--;
  173230. return TRUE;
  173231. }
  173232. /*
  173233. * MCU decoding for DC successive approximation refinement scan.
  173234. * Note: we assume such scans can be multi-component, although the spec
  173235. * is not very clear on the point.
  173236. */
  173237. METHODDEF(boolean)
  173238. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173239. {
  173240. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173241. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173242. int blkn;
  173243. JBLOCKROW block;
  173244. BITREAD_STATE_VARS;
  173245. /* Process restart marker if needed; may have to suspend */
  173246. if (cinfo->restart_interval) {
  173247. if (entropy->restarts_to_go == 0)
  173248. if (! process_restartp(cinfo))
  173249. return FALSE;
  173250. }
  173251. /* Not worth the cycles to check insufficient_data here,
  173252. * since we will not change the data anyway if we read zeroes.
  173253. */
  173254. /* Load up working state */
  173255. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173256. /* Outer loop handles each block in the MCU */
  173257. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173258. block = MCU_data[blkn];
  173259. /* Encoded data is simply the next bit of the two's-complement DC value */
  173260. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173261. if (GET_BITS(1))
  173262. (*block)[0] |= p1;
  173263. /* Note: since we use |=, repeating the assignment later is safe */
  173264. }
  173265. /* Completed MCU, so update state */
  173266. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173267. /* Account for restart interval (no-op if not using restarts) */
  173268. entropy->restarts_to_go--;
  173269. return TRUE;
  173270. }
  173271. /*
  173272. * MCU decoding for AC successive approximation refinement scan.
  173273. */
  173274. METHODDEF(boolean)
  173275. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173276. {
  173277. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173278. int Se = cinfo->Se;
  173279. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173280. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173281. register int s, k, r;
  173282. unsigned int EOBRUN;
  173283. JBLOCKROW block;
  173284. JCOEFPTR thiscoef;
  173285. BITREAD_STATE_VARS;
  173286. d_derived_tbl * tbl;
  173287. int num_newnz;
  173288. int newnz_pos[DCTSIZE2];
  173289. /* Process restart marker if needed; may have to suspend */
  173290. if (cinfo->restart_interval) {
  173291. if (entropy->restarts_to_go == 0)
  173292. if (! process_restartp(cinfo))
  173293. return FALSE;
  173294. }
  173295. /* If we've run out of data, don't modify the MCU.
  173296. */
  173297. if (! entropy->pub.insufficient_data) {
  173298. /* Load up working state */
  173299. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173300. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173301. /* There is always only one block per MCU */
  173302. block = MCU_data[0];
  173303. tbl = entropy->ac_derived_tbl;
  173304. /* If we are forced to suspend, we must undo the assignments to any newly
  173305. * nonzero coefficients in the block, because otherwise we'd get confused
  173306. * next time about which coefficients were already nonzero.
  173307. * But we need not undo addition of bits to already-nonzero coefficients;
  173308. * instead, we can test the current bit to see if we already did it.
  173309. */
  173310. num_newnz = 0;
  173311. /* initialize coefficient loop counter to start of band */
  173312. k = cinfo->Ss;
  173313. if (EOBRUN == 0) {
  173314. for (; k <= Se; k++) {
  173315. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173316. r = s >> 4;
  173317. s &= 15;
  173318. if (s) {
  173319. if (s != 1) /* size of new coef should always be 1 */
  173320. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173321. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173322. if (GET_BITS(1))
  173323. s = p1; /* newly nonzero coef is positive */
  173324. else
  173325. s = m1; /* newly nonzero coef is negative */
  173326. } else {
  173327. if (r != 15) {
  173328. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173329. if (r) {
  173330. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173331. r = GET_BITS(r);
  173332. EOBRUN += r;
  173333. }
  173334. break; /* rest of block is handled by EOB logic */
  173335. }
  173336. /* note s = 0 for processing ZRL */
  173337. }
  173338. /* Advance over already-nonzero coefs and r still-zero coefs,
  173339. * appending correction bits to the nonzeroes. A correction bit is 1
  173340. * if the absolute value of the coefficient must be increased.
  173341. */
  173342. do {
  173343. thiscoef = *block + jpeg_natural_order[k];
  173344. if (*thiscoef != 0) {
  173345. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173346. if (GET_BITS(1)) {
  173347. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173348. if (*thiscoef >= 0)
  173349. *thiscoef += p1;
  173350. else
  173351. *thiscoef += m1;
  173352. }
  173353. }
  173354. } else {
  173355. if (--r < 0)
  173356. break; /* reached target zero coefficient */
  173357. }
  173358. k++;
  173359. } while (k <= Se);
  173360. if (s) {
  173361. int pos = jpeg_natural_order[k];
  173362. /* Output newly nonzero coefficient */
  173363. (*block)[pos] = (JCOEF) s;
  173364. /* Remember its position in case we have to suspend */
  173365. newnz_pos[num_newnz++] = pos;
  173366. }
  173367. }
  173368. }
  173369. if (EOBRUN > 0) {
  173370. /* Scan any remaining coefficient positions after the end-of-band
  173371. * (the last newly nonzero coefficient, if any). Append a correction
  173372. * bit to each already-nonzero coefficient. A correction bit is 1
  173373. * if the absolute value of the coefficient must be increased.
  173374. */
  173375. for (; k <= Se; k++) {
  173376. thiscoef = *block + jpeg_natural_order[k];
  173377. if (*thiscoef != 0) {
  173378. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173379. if (GET_BITS(1)) {
  173380. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173381. if (*thiscoef >= 0)
  173382. *thiscoef += p1;
  173383. else
  173384. *thiscoef += m1;
  173385. }
  173386. }
  173387. }
  173388. }
  173389. /* Count one block completed in EOB run */
  173390. EOBRUN--;
  173391. }
  173392. /* Completed MCU, so update state */
  173393. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173394. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173395. }
  173396. /* Account for restart interval (no-op if not using restarts) */
  173397. entropy->restarts_to_go--;
  173398. return TRUE;
  173399. undoit:
  173400. /* Re-zero any output coefficients that we made newly nonzero */
  173401. while (num_newnz > 0)
  173402. (*block)[newnz_pos[--num_newnz]] = 0;
  173403. return FALSE;
  173404. }
  173405. /*
  173406. * Module initialization routine for progressive Huffman entropy decoding.
  173407. */
  173408. GLOBAL(void)
  173409. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173410. {
  173411. phuff_entropy_ptr2 entropy;
  173412. int *coef_bit_ptr;
  173413. int ci, i;
  173414. entropy = (phuff_entropy_ptr2)
  173415. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173416. SIZEOF(phuff_entropy_decoder));
  173417. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173418. entropy->pub.start_pass = start_pass_phuff_decoder;
  173419. /* Mark derived tables unallocated */
  173420. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173421. entropy->derived_tbls[i] = NULL;
  173422. }
  173423. /* Create progression status table */
  173424. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173425. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173426. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173427. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173428. for (ci = 0; ci < cinfo->num_components; ci++)
  173429. for (i = 0; i < DCTSIZE2; i++)
  173430. *coef_bit_ptr++ = -1;
  173431. }
  173432. #endif /* D_PROGRESSIVE_SUPPORTED */
  173433. /*** End of inlined file: jdphuff.c ***/
  173434. /*** Start of inlined file: jdpostct.c ***/
  173435. #define JPEG_INTERNALS
  173436. /* Private buffer controller object */
  173437. typedef struct {
  173438. struct jpeg_d_post_controller pub; /* public fields */
  173439. /* Color quantization source buffer: this holds output data from
  173440. * the upsample/color conversion step to be passed to the quantizer.
  173441. * For two-pass color quantization, we need a full-image buffer;
  173442. * for one-pass operation, a strip buffer is sufficient.
  173443. */
  173444. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173445. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173446. JDIMENSION strip_height; /* buffer size in rows */
  173447. /* for two-pass mode only: */
  173448. JDIMENSION starting_row; /* row # of first row in current strip */
  173449. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173450. } my_post_controller;
  173451. typedef my_post_controller * my_post_ptr;
  173452. /* Forward declarations */
  173453. METHODDEF(void) post_process_1pass
  173454. JPP((j_decompress_ptr cinfo,
  173455. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173456. JDIMENSION in_row_groups_avail,
  173457. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173458. JDIMENSION out_rows_avail));
  173459. #ifdef QUANT_2PASS_SUPPORTED
  173460. METHODDEF(void) post_process_prepass
  173461. JPP((j_decompress_ptr cinfo,
  173462. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173463. JDIMENSION in_row_groups_avail,
  173464. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173465. JDIMENSION out_rows_avail));
  173466. METHODDEF(void) post_process_2pass
  173467. JPP((j_decompress_ptr cinfo,
  173468. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173469. JDIMENSION in_row_groups_avail,
  173470. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173471. JDIMENSION out_rows_avail));
  173472. #endif
  173473. /*
  173474. * Initialize for a processing pass.
  173475. */
  173476. METHODDEF(void)
  173477. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173478. {
  173479. my_post_ptr post = (my_post_ptr) cinfo->post;
  173480. switch (pass_mode) {
  173481. case JBUF_PASS_THRU:
  173482. if (cinfo->quantize_colors) {
  173483. /* Single-pass processing with color quantization. */
  173484. post->pub.post_process_data = post_process_1pass;
  173485. /* We could be doing buffered-image output before starting a 2-pass
  173486. * color quantization; in that case, jinit_d_post_controller did not
  173487. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173488. */
  173489. if (post->buffer == NULL) {
  173490. post->buffer = (*cinfo->mem->access_virt_sarray)
  173491. ((j_common_ptr) cinfo, post->whole_image,
  173492. (JDIMENSION) 0, post->strip_height, TRUE);
  173493. }
  173494. } else {
  173495. /* For single-pass processing without color quantization,
  173496. * I have no work to do; just call the upsampler directly.
  173497. */
  173498. post->pub.post_process_data = cinfo->upsample->upsample;
  173499. }
  173500. break;
  173501. #ifdef QUANT_2PASS_SUPPORTED
  173502. case JBUF_SAVE_AND_PASS:
  173503. /* First pass of 2-pass quantization */
  173504. if (post->whole_image == NULL)
  173505. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173506. post->pub.post_process_data = post_process_prepass;
  173507. break;
  173508. case JBUF_CRANK_DEST:
  173509. /* Second pass of 2-pass quantization */
  173510. if (post->whole_image == NULL)
  173511. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173512. post->pub.post_process_data = post_process_2pass;
  173513. break;
  173514. #endif /* QUANT_2PASS_SUPPORTED */
  173515. default:
  173516. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173517. break;
  173518. }
  173519. post->starting_row = post->next_row = 0;
  173520. }
  173521. /*
  173522. * Process some data in the one-pass (strip buffer) case.
  173523. * This is used for color precision reduction as well as one-pass quantization.
  173524. */
  173525. METHODDEF(void)
  173526. post_process_1pass (j_decompress_ptr cinfo,
  173527. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173528. JDIMENSION in_row_groups_avail,
  173529. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173530. JDIMENSION out_rows_avail)
  173531. {
  173532. my_post_ptr post = (my_post_ptr) cinfo->post;
  173533. JDIMENSION num_rows, max_rows;
  173534. /* Fill the buffer, but not more than what we can dump out in one go. */
  173535. /* Note we rely on the upsampler to detect bottom of image. */
  173536. max_rows = out_rows_avail - *out_row_ctr;
  173537. if (max_rows > post->strip_height)
  173538. max_rows = post->strip_height;
  173539. num_rows = 0;
  173540. (*cinfo->upsample->upsample) (cinfo,
  173541. input_buf, in_row_group_ctr, in_row_groups_avail,
  173542. post->buffer, &num_rows, max_rows);
  173543. /* Quantize and emit data. */
  173544. (*cinfo->cquantize->color_quantize) (cinfo,
  173545. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173546. *out_row_ctr += num_rows;
  173547. }
  173548. #ifdef QUANT_2PASS_SUPPORTED
  173549. /*
  173550. * Process some data in the first pass of 2-pass quantization.
  173551. */
  173552. METHODDEF(void)
  173553. post_process_prepass (j_decompress_ptr cinfo,
  173554. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173555. JDIMENSION in_row_groups_avail,
  173556. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173557. JDIMENSION)
  173558. {
  173559. my_post_ptr post = (my_post_ptr) cinfo->post;
  173560. JDIMENSION old_next_row, num_rows;
  173561. /* Reposition virtual buffer if at start of strip. */
  173562. if (post->next_row == 0) {
  173563. post->buffer = (*cinfo->mem->access_virt_sarray)
  173564. ((j_common_ptr) cinfo, post->whole_image,
  173565. post->starting_row, post->strip_height, TRUE);
  173566. }
  173567. /* Upsample some data (up to a strip height's worth). */
  173568. old_next_row = post->next_row;
  173569. (*cinfo->upsample->upsample) (cinfo,
  173570. input_buf, in_row_group_ctr, in_row_groups_avail,
  173571. post->buffer, &post->next_row, post->strip_height);
  173572. /* Allow quantizer to scan new data. No data is emitted, */
  173573. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173574. if (post->next_row > old_next_row) {
  173575. num_rows = post->next_row - old_next_row;
  173576. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173577. (JSAMPARRAY) NULL, (int) num_rows);
  173578. *out_row_ctr += num_rows;
  173579. }
  173580. /* Advance if we filled the strip. */
  173581. if (post->next_row >= post->strip_height) {
  173582. post->starting_row += post->strip_height;
  173583. post->next_row = 0;
  173584. }
  173585. }
  173586. /*
  173587. * Process some data in the second pass of 2-pass quantization.
  173588. */
  173589. METHODDEF(void)
  173590. post_process_2pass (j_decompress_ptr cinfo,
  173591. JSAMPIMAGE, JDIMENSION *,
  173592. JDIMENSION,
  173593. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173594. JDIMENSION out_rows_avail)
  173595. {
  173596. my_post_ptr post = (my_post_ptr) cinfo->post;
  173597. JDIMENSION num_rows, max_rows;
  173598. /* Reposition virtual buffer if at start of strip. */
  173599. if (post->next_row == 0) {
  173600. post->buffer = (*cinfo->mem->access_virt_sarray)
  173601. ((j_common_ptr) cinfo, post->whole_image,
  173602. post->starting_row, post->strip_height, FALSE);
  173603. }
  173604. /* Determine number of rows to emit. */
  173605. num_rows = post->strip_height - post->next_row; /* available in strip */
  173606. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173607. if (num_rows > max_rows)
  173608. num_rows = max_rows;
  173609. /* We have to check bottom of image here, can't depend on upsampler. */
  173610. max_rows = cinfo->output_height - post->starting_row;
  173611. if (num_rows > max_rows)
  173612. num_rows = max_rows;
  173613. /* Quantize and emit data. */
  173614. (*cinfo->cquantize->color_quantize) (cinfo,
  173615. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173616. (int) num_rows);
  173617. *out_row_ctr += num_rows;
  173618. /* Advance if we filled the strip. */
  173619. post->next_row += num_rows;
  173620. if (post->next_row >= post->strip_height) {
  173621. post->starting_row += post->strip_height;
  173622. post->next_row = 0;
  173623. }
  173624. }
  173625. #endif /* QUANT_2PASS_SUPPORTED */
  173626. /*
  173627. * Initialize postprocessing controller.
  173628. */
  173629. GLOBAL(void)
  173630. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173631. {
  173632. my_post_ptr post;
  173633. post = (my_post_ptr)
  173634. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173635. SIZEOF(my_post_controller));
  173636. cinfo->post = (struct jpeg_d_post_controller *) post;
  173637. post->pub.start_pass = start_pass_dpost;
  173638. post->whole_image = NULL; /* flag for no virtual arrays */
  173639. post->buffer = NULL; /* flag for no strip buffer */
  173640. /* Create the quantization buffer, if needed */
  173641. if (cinfo->quantize_colors) {
  173642. /* The buffer strip height is max_v_samp_factor, which is typically
  173643. * an efficient number of rows for upsampling to return.
  173644. * (In the presence of output rescaling, we might want to be smarter?)
  173645. */
  173646. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173647. if (need_full_buffer) {
  173648. /* Two-pass color quantization: need full-image storage. */
  173649. /* We round up the number of rows to a multiple of the strip height. */
  173650. #ifdef QUANT_2PASS_SUPPORTED
  173651. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173652. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173653. cinfo->output_width * cinfo->out_color_components,
  173654. (JDIMENSION) jround_up((long) cinfo->output_height,
  173655. (long) post->strip_height),
  173656. post->strip_height);
  173657. #else
  173658. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173659. #endif /* QUANT_2PASS_SUPPORTED */
  173660. } else {
  173661. /* One-pass color quantization: just make a strip buffer. */
  173662. post->buffer = (*cinfo->mem->alloc_sarray)
  173663. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173664. cinfo->output_width * cinfo->out_color_components,
  173665. post->strip_height);
  173666. }
  173667. }
  173668. }
  173669. /*** End of inlined file: jdpostct.c ***/
  173670. #undef FIX
  173671. /*** Start of inlined file: jdsample.c ***/
  173672. #define JPEG_INTERNALS
  173673. /* Pointer to routine to upsample a single component */
  173674. typedef JMETHOD(void, upsample1_ptr,
  173675. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173676. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173677. /* Private subobject */
  173678. typedef struct {
  173679. struct jpeg_upsampler pub; /* public fields */
  173680. /* Color conversion buffer. When using separate upsampling and color
  173681. * conversion steps, this buffer holds one upsampled row group until it
  173682. * has been color converted and output.
  173683. * Note: we do not allocate any storage for component(s) which are full-size,
  173684. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173685. * simply set to point to the input data array, thereby avoiding copying.
  173686. */
  173687. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173688. /* Per-component upsampling method pointers */
  173689. upsample1_ptr methods[MAX_COMPONENTS];
  173690. int next_row_out; /* counts rows emitted from color_buf */
  173691. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173692. /* Height of an input row group for each component. */
  173693. int rowgroup_height[MAX_COMPONENTS];
  173694. /* These arrays save pixel expansion factors so that int_expand need not
  173695. * recompute them each time. They are unused for other upsampling methods.
  173696. */
  173697. UINT8 h_expand[MAX_COMPONENTS];
  173698. UINT8 v_expand[MAX_COMPONENTS];
  173699. } my_upsampler2;
  173700. typedef my_upsampler2 * my_upsample_ptr2;
  173701. /*
  173702. * Initialize for an upsampling pass.
  173703. */
  173704. METHODDEF(void)
  173705. start_pass_upsample (j_decompress_ptr cinfo)
  173706. {
  173707. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173708. /* Mark the conversion buffer empty */
  173709. upsample->next_row_out = cinfo->max_v_samp_factor;
  173710. /* Initialize total-height counter for detecting bottom of image */
  173711. upsample->rows_to_go = cinfo->output_height;
  173712. }
  173713. /*
  173714. * Control routine to do upsampling (and color conversion).
  173715. *
  173716. * In this version we upsample each component independently.
  173717. * We upsample one row group into the conversion buffer, then apply
  173718. * color conversion a row at a time.
  173719. */
  173720. METHODDEF(void)
  173721. sep_upsample (j_decompress_ptr cinfo,
  173722. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173723. JDIMENSION,
  173724. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173725. JDIMENSION out_rows_avail)
  173726. {
  173727. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173728. int ci;
  173729. jpeg_component_info * compptr;
  173730. JDIMENSION num_rows;
  173731. /* Fill the conversion buffer, if it's empty */
  173732. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173733. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173734. ci++, compptr++) {
  173735. /* Invoke per-component upsample method. Notice we pass a POINTER
  173736. * to color_buf[ci], so that fullsize_upsample can change it.
  173737. */
  173738. (*upsample->methods[ci]) (cinfo, compptr,
  173739. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173740. upsample->color_buf + ci);
  173741. }
  173742. upsample->next_row_out = 0;
  173743. }
  173744. /* Color-convert and emit rows */
  173745. /* How many we have in the buffer: */
  173746. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173747. /* Not more than the distance to the end of the image. Need this test
  173748. * in case the image height is not a multiple of max_v_samp_factor:
  173749. */
  173750. if (num_rows > upsample->rows_to_go)
  173751. num_rows = upsample->rows_to_go;
  173752. /* And not more than what the client can accept: */
  173753. out_rows_avail -= *out_row_ctr;
  173754. if (num_rows > out_rows_avail)
  173755. num_rows = out_rows_avail;
  173756. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173757. (JDIMENSION) upsample->next_row_out,
  173758. output_buf + *out_row_ctr,
  173759. (int) num_rows);
  173760. /* Adjust counts */
  173761. *out_row_ctr += num_rows;
  173762. upsample->rows_to_go -= num_rows;
  173763. upsample->next_row_out += num_rows;
  173764. /* When the buffer is emptied, declare this input row group consumed */
  173765. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173766. (*in_row_group_ctr)++;
  173767. }
  173768. /*
  173769. * These are the routines invoked by sep_upsample to upsample pixel values
  173770. * of a single component. One row group is processed per call.
  173771. */
  173772. /*
  173773. * For full-size components, we just make color_buf[ci] point at the
  173774. * input buffer, and thus avoid copying any data. Note that this is
  173775. * safe only because sep_upsample doesn't declare the input row group
  173776. * "consumed" until we are done color converting and emitting it.
  173777. */
  173778. METHODDEF(void)
  173779. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173780. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173781. {
  173782. *output_data_ptr = input_data;
  173783. }
  173784. /*
  173785. * This is a no-op version used for "uninteresting" components.
  173786. * These components will not be referenced by color conversion.
  173787. */
  173788. METHODDEF(void)
  173789. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173790. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173791. {
  173792. *output_data_ptr = NULL; /* safety check */
  173793. }
  173794. /*
  173795. * This version handles any integral sampling ratios.
  173796. * This is not used for typical JPEG files, so it need not be fast.
  173797. * Nor, for that matter, is it particularly accurate: the algorithm is
  173798. * simple replication of the input pixel onto the corresponding output
  173799. * pixels. The hi-falutin sampling literature refers to this as a
  173800. * "box filter". A box filter tends to introduce visible artifacts,
  173801. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173802. * you would be well advised to improve this code.
  173803. */
  173804. METHODDEF(void)
  173805. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173806. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173807. {
  173808. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173809. JSAMPARRAY output_data = *output_data_ptr;
  173810. register JSAMPROW inptr, outptr;
  173811. register JSAMPLE invalue;
  173812. register int h;
  173813. JSAMPROW outend;
  173814. int h_expand, v_expand;
  173815. int inrow, outrow;
  173816. h_expand = upsample->h_expand[compptr->component_index];
  173817. v_expand = upsample->v_expand[compptr->component_index];
  173818. inrow = outrow = 0;
  173819. while (outrow < cinfo->max_v_samp_factor) {
  173820. /* Generate one output row with proper horizontal expansion */
  173821. inptr = input_data[inrow];
  173822. outptr = output_data[outrow];
  173823. outend = outptr + cinfo->output_width;
  173824. while (outptr < outend) {
  173825. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173826. for (h = h_expand; h > 0; h--) {
  173827. *outptr++ = invalue;
  173828. }
  173829. }
  173830. /* Generate any additional output rows by duplicating the first one */
  173831. if (v_expand > 1) {
  173832. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173833. v_expand-1, cinfo->output_width);
  173834. }
  173835. inrow++;
  173836. outrow += v_expand;
  173837. }
  173838. }
  173839. /*
  173840. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173841. * It's still a box filter.
  173842. */
  173843. METHODDEF(void)
  173844. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173845. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173846. {
  173847. JSAMPARRAY output_data = *output_data_ptr;
  173848. register JSAMPROW inptr, outptr;
  173849. register JSAMPLE invalue;
  173850. JSAMPROW outend;
  173851. int inrow;
  173852. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173853. inptr = input_data[inrow];
  173854. outptr = output_data[inrow];
  173855. outend = outptr + cinfo->output_width;
  173856. while (outptr < outend) {
  173857. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173858. *outptr++ = invalue;
  173859. *outptr++ = invalue;
  173860. }
  173861. }
  173862. }
  173863. /*
  173864. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173865. * It's still a box filter.
  173866. */
  173867. METHODDEF(void)
  173868. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173869. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173870. {
  173871. JSAMPARRAY output_data = *output_data_ptr;
  173872. register JSAMPROW inptr, outptr;
  173873. register JSAMPLE invalue;
  173874. JSAMPROW outend;
  173875. int inrow, outrow;
  173876. inrow = outrow = 0;
  173877. while (outrow < cinfo->max_v_samp_factor) {
  173878. inptr = input_data[inrow];
  173879. outptr = output_data[outrow];
  173880. outend = outptr + cinfo->output_width;
  173881. while (outptr < outend) {
  173882. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173883. *outptr++ = invalue;
  173884. *outptr++ = invalue;
  173885. }
  173886. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173887. 1, cinfo->output_width);
  173888. inrow++;
  173889. outrow += 2;
  173890. }
  173891. }
  173892. /*
  173893. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173894. *
  173895. * The upsampling algorithm is linear interpolation between pixel centers,
  173896. * also known as a "triangle filter". This is a good compromise between
  173897. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173898. * of the way between input pixel centers.
  173899. *
  173900. * A note about the "bias" calculations: when rounding fractional values to
  173901. * integer, we do not want to always round 0.5 up to the next integer.
  173902. * If we did that, we'd introduce a noticeable bias towards larger values.
  173903. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173904. * alternate pixel locations (a simple ordered dither pattern).
  173905. */
  173906. METHODDEF(void)
  173907. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173908. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173909. {
  173910. JSAMPARRAY output_data = *output_data_ptr;
  173911. register JSAMPROW inptr, outptr;
  173912. register int invalue;
  173913. register JDIMENSION colctr;
  173914. int inrow;
  173915. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173916. inptr = input_data[inrow];
  173917. outptr = output_data[inrow];
  173918. /* Special case for first column */
  173919. invalue = GETJSAMPLE(*inptr++);
  173920. *outptr++ = (JSAMPLE) invalue;
  173921. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173922. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173923. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173924. invalue = GETJSAMPLE(*inptr++) * 3;
  173925. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173926. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173927. }
  173928. /* Special case for last column */
  173929. invalue = GETJSAMPLE(*inptr);
  173930. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173931. *outptr++ = (JSAMPLE) invalue;
  173932. }
  173933. }
  173934. /*
  173935. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173936. * Again a triangle filter; see comments for h2v1 case, above.
  173937. *
  173938. * It is OK for us to reference the adjacent input rows because we demanded
  173939. * context from the main buffer controller (see initialization code).
  173940. */
  173941. METHODDEF(void)
  173942. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173943. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173944. {
  173945. JSAMPARRAY output_data = *output_data_ptr;
  173946. register JSAMPROW inptr0, inptr1, outptr;
  173947. #if BITS_IN_JSAMPLE == 8
  173948. register int thiscolsum, lastcolsum, nextcolsum;
  173949. #else
  173950. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173951. #endif
  173952. register JDIMENSION colctr;
  173953. int inrow, outrow, v;
  173954. inrow = outrow = 0;
  173955. while (outrow < cinfo->max_v_samp_factor) {
  173956. for (v = 0; v < 2; v++) {
  173957. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173958. inptr0 = input_data[inrow];
  173959. if (v == 0) /* next nearest is row above */
  173960. inptr1 = input_data[inrow-1];
  173961. else /* next nearest is row below */
  173962. inptr1 = input_data[inrow+1];
  173963. outptr = output_data[outrow++];
  173964. /* Special case for first column */
  173965. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173966. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173967. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173968. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173969. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173970. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173971. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173972. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173973. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173974. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173975. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173976. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173977. }
  173978. /* Special case for last column */
  173979. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173980. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173981. }
  173982. inrow++;
  173983. }
  173984. }
  173985. /*
  173986. * Module initialization routine for upsampling.
  173987. */
  173988. GLOBAL(void)
  173989. jinit_upsampler (j_decompress_ptr cinfo)
  173990. {
  173991. my_upsample_ptr2 upsample;
  173992. int ci;
  173993. jpeg_component_info * compptr;
  173994. boolean need_buffer, do_fancy;
  173995. int h_in_group, v_in_group, h_out_group, v_out_group;
  173996. upsample = (my_upsample_ptr2)
  173997. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173998. SIZEOF(my_upsampler2));
  173999. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174000. upsample->pub.start_pass = start_pass_upsample;
  174001. upsample->pub.upsample = sep_upsample;
  174002. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174003. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174004. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174005. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174006. * so don't ask for it.
  174007. */
  174008. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174009. /* Verify we can handle the sampling factors, select per-component methods,
  174010. * and create storage as needed.
  174011. */
  174012. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174013. ci++, compptr++) {
  174014. /* Compute size of an "input group" after IDCT scaling. This many samples
  174015. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174016. */
  174017. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174018. cinfo->min_DCT_scaled_size;
  174019. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174020. cinfo->min_DCT_scaled_size;
  174021. h_out_group = cinfo->max_h_samp_factor;
  174022. v_out_group = cinfo->max_v_samp_factor;
  174023. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174024. need_buffer = TRUE;
  174025. if (! compptr->component_needed) {
  174026. /* Don't bother to upsample an uninteresting component. */
  174027. upsample->methods[ci] = noop_upsample;
  174028. need_buffer = FALSE;
  174029. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174030. /* Fullsize components can be processed without any work. */
  174031. upsample->methods[ci] = fullsize_upsample;
  174032. need_buffer = FALSE;
  174033. } else if (h_in_group * 2 == h_out_group &&
  174034. v_in_group == v_out_group) {
  174035. /* Special cases for 2h1v upsampling */
  174036. if (do_fancy && compptr->downsampled_width > 2)
  174037. upsample->methods[ci] = h2v1_fancy_upsample;
  174038. else
  174039. upsample->methods[ci] = h2v1_upsample;
  174040. } else if (h_in_group * 2 == h_out_group &&
  174041. v_in_group * 2 == v_out_group) {
  174042. /* Special cases for 2h2v upsampling */
  174043. if (do_fancy && compptr->downsampled_width > 2) {
  174044. upsample->methods[ci] = h2v2_fancy_upsample;
  174045. upsample->pub.need_context_rows = TRUE;
  174046. } else
  174047. upsample->methods[ci] = h2v2_upsample;
  174048. } else if ((h_out_group % h_in_group) == 0 &&
  174049. (v_out_group % v_in_group) == 0) {
  174050. /* Generic integral-factors upsampling method */
  174051. upsample->methods[ci] = int_upsample;
  174052. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174053. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174054. } else
  174055. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174056. if (need_buffer) {
  174057. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174058. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174059. (JDIMENSION) jround_up((long) cinfo->output_width,
  174060. (long) cinfo->max_h_samp_factor),
  174061. (JDIMENSION) cinfo->max_v_samp_factor);
  174062. }
  174063. }
  174064. }
  174065. /*** End of inlined file: jdsample.c ***/
  174066. /*** Start of inlined file: jdtrans.c ***/
  174067. #define JPEG_INTERNALS
  174068. /* Forward declarations */
  174069. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174070. /*
  174071. * Read the coefficient arrays from a JPEG file.
  174072. * jpeg_read_header must be completed before calling this.
  174073. *
  174074. * The entire image is read into a set of virtual coefficient-block arrays,
  174075. * one per component. The return value is a pointer to the array of
  174076. * virtual-array descriptors. These can be manipulated directly via the
  174077. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174078. * To release the memory occupied by the virtual arrays, call
  174079. * jpeg_finish_decompress() when done with the data.
  174080. *
  174081. * An alternative usage is to simply obtain access to the coefficient arrays
  174082. * during a buffered-image-mode decompression operation. This is allowed
  174083. * after any jpeg_finish_output() call. The arrays can be accessed until
  174084. * jpeg_finish_decompress() is called. (Note that any call to the library
  174085. * may reposition the arrays, so don't rely on access_virt_barray() results
  174086. * to stay valid across library calls.)
  174087. *
  174088. * Returns NULL if suspended. This case need be checked only if
  174089. * a suspending data source is used.
  174090. */
  174091. GLOBAL(jvirt_barray_ptr *)
  174092. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174093. {
  174094. if (cinfo->global_state == DSTATE_READY) {
  174095. /* First call: initialize active modules */
  174096. transdecode_master_selection(cinfo);
  174097. cinfo->global_state = DSTATE_RDCOEFS;
  174098. }
  174099. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174100. /* Absorb whole file into the coef buffer */
  174101. for (;;) {
  174102. int retcode;
  174103. /* Call progress monitor hook if present */
  174104. if (cinfo->progress != NULL)
  174105. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174106. /* Absorb some more input */
  174107. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174108. if (retcode == JPEG_SUSPENDED)
  174109. return NULL;
  174110. if (retcode == JPEG_REACHED_EOI)
  174111. break;
  174112. /* Advance progress counter if appropriate */
  174113. if (cinfo->progress != NULL &&
  174114. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174115. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174116. /* startup underestimated number of scans; ratchet up one scan */
  174117. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174118. }
  174119. }
  174120. }
  174121. /* Set state so that jpeg_finish_decompress does the right thing */
  174122. cinfo->global_state = DSTATE_STOPPING;
  174123. }
  174124. /* At this point we should be in state DSTATE_STOPPING if being used
  174125. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174126. * to the coefficients during a full buffered-image-mode decompression.
  174127. */
  174128. if ((cinfo->global_state == DSTATE_STOPPING ||
  174129. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174130. return cinfo->coef->coef_arrays;
  174131. }
  174132. /* Oops, improper usage */
  174133. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174134. return NULL; /* keep compiler happy */
  174135. }
  174136. /*
  174137. * Master selection of decompression modules for transcoding.
  174138. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174139. */
  174140. LOCAL(void)
  174141. transdecode_master_selection (j_decompress_ptr cinfo)
  174142. {
  174143. /* This is effectively a buffered-image operation. */
  174144. cinfo->buffered_image = TRUE;
  174145. /* Entropy decoding: either Huffman or arithmetic coding. */
  174146. if (cinfo->arith_code) {
  174147. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174148. } else {
  174149. if (cinfo->progressive_mode) {
  174150. #ifdef D_PROGRESSIVE_SUPPORTED
  174151. jinit_phuff_decoder(cinfo);
  174152. #else
  174153. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174154. #endif
  174155. } else
  174156. jinit_huff_decoder(cinfo);
  174157. }
  174158. /* Always get a full-image coefficient buffer. */
  174159. jinit_d_coef_controller(cinfo, TRUE);
  174160. /* We can now tell the memory manager to allocate virtual arrays. */
  174161. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174162. /* Initialize input side of decompressor to consume first scan. */
  174163. (*cinfo->inputctl->start_input_pass) (cinfo);
  174164. /* Initialize progress monitoring. */
  174165. if (cinfo->progress != NULL) {
  174166. int nscans;
  174167. /* Estimate number of scans to set pass_limit. */
  174168. if (cinfo->progressive_mode) {
  174169. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174170. nscans = 2 + 3 * cinfo->num_components;
  174171. } else if (cinfo->inputctl->has_multiple_scans) {
  174172. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174173. nscans = cinfo->num_components;
  174174. } else {
  174175. nscans = 1;
  174176. }
  174177. cinfo->progress->pass_counter = 0L;
  174178. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174179. cinfo->progress->completed_passes = 0;
  174180. cinfo->progress->total_passes = 1;
  174181. }
  174182. }
  174183. /*** End of inlined file: jdtrans.c ***/
  174184. /*** Start of inlined file: jfdctflt.c ***/
  174185. #define JPEG_INTERNALS
  174186. #ifdef DCT_FLOAT_SUPPORTED
  174187. /*
  174188. * This module is specialized to the case DCTSIZE = 8.
  174189. */
  174190. #if DCTSIZE != 8
  174191. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174192. #endif
  174193. /*
  174194. * Perform the forward DCT on one block of samples.
  174195. */
  174196. GLOBAL(void)
  174197. jpeg_fdct_float (FAST_FLOAT * data)
  174198. {
  174199. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174200. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174201. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174202. FAST_FLOAT *dataptr;
  174203. int ctr;
  174204. /* Pass 1: process rows. */
  174205. dataptr = data;
  174206. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174207. tmp0 = dataptr[0] + dataptr[7];
  174208. tmp7 = dataptr[0] - dataptr[7];
  174209. tmp1 = dataptr[1] + dataptr[6];
  174210. tmp6 = dataptr[1] - dataptr[6];
  174211. tmp2 = dataptr[2] + dataptr[5];
  174212. tmp5 = dataptr[2] - dataptr[5];
  174213. tmp3 = dataptr[3] + dataptr[4];
  174214. tmp4 = dataptr[3] - dataptr[4];
  174215. /* Even part */
  174216. tmp10 = tmp0 + tmp3; /* phase 2 */
  174217. tmp13 = tmp0 - tmp3;
  174218. tmp11 = tmp1 + tmp2;
  174219. tmp12 = tmp1 - tmp2;
  174220. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174221. dataptr[4] = tmp10 - tmp11;
  174222. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174223. dataptr[2] = tmp13 + z1; /* phase 5 */
  174224. dataptr[6] = tmp13 - z1;
  174225. /* Odd part */
  174226. tmp10 = tmp4 + tmp5; /* phase 2 */
  174227. tmp11 = tmp5 + tmp6;
  174228. tmp12 = tmp6 + tmp7;
  174229. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174230. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174231. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174232. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174233. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174234. z11 = tmp7 + z3; /* phase 5 */
  174235. z13 = tmp7 - z3;
  174236. dataptr[5] = z13 + z2; /* phase 6 */
  174237. dataptr[3] = z13 - z2;
  174238. dataptr[1] = z11 + z4;
  174239. dataptr[7] = z11 - z4;
  174240. dataptr += DCTSIZE; /* advance pointer to next row */
  174241. }
  174242. /* Pass 2: process columns. */
  174243. dataptr = data;
  174244. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174245. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174246. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174247. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174248. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174249. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174250. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174251. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174252. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174253. /* Even part */
  174254. tmp10 = tmp0 + tmp3; /* phase 2 */
  174255. tmp13 = tmp0 - tmp3;
  174256. tmp11 = tmp1 + tmp2;
  174257. tmp12 = tmp1 - tmp2;
  174258. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174259. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174260. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174261. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174262. dataptr[DCTSIZE*6] = tmp13 - z1;
  174263. /* Odd part */
  174264. tmp10 = tmp4 + tmp5; /* phase 2 */
  174265. tmp11 = tmp5 + tmp6;
  174266. tmp12 = tmp6 + tmp7;
  174267. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174268. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174269. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174270. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174271. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174272. z11 = tmp7 + z3; /* phase 5 */
  174273. z13 = tmp7 - z3;
  174274. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174275. dataptr[DCTSIZE*3] = z13 - z2;
  174276. dataptr[DCTSIZE*1] = z11 + z4;
  174277. dataptr[DCTSIZE*7] = z11 - z4;
  174278. dataptr++; /* advance pointer to next column */
  174279. }
  174280. }
  174281. #endif /* DCT_FLOAT_SUPPORTED */
  174282. /*** End of inlined file: jfdctflt.c ***/
  174283. /*** Start of inlined file: jfdctint.c ***/
  174284. #define JPEG_INTERNALS
  174285. #ifdef DCT_ISLOW_SUPPORTED
  174286. /*
  174287. * This module is specialized to the case DCTSIZE = 8.
  174288. */
  174289. #if DCTSIZE != 8
  174290. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174291. #endif
  174292. /*
  174293. * The poop on this scaling stuff is as follows:
  174294. *
  174295. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174296. * larger than the true DCT outputs. The final outputs are therefore
  174297. * a factor of N larger than desired; since N=8 this can be cured by
  174298. * a simple right shift at the end of the algorithm. The advantage of
  174299. * this arrangement is that we save two multiplications per 1-D DCT,
  174300. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174301. * In the IJG code, this factor of 8 is removed by the quantization step
  174302. * (in jcdctmgr.c), NOT in this module.
  174303. *
  174304. * We have to do addition and subtraction of the integer inputs, which
  174305. * is no problem, and multiplication by fractional constants, which is
  174306. * a problem to do in integer arithmetic. We multiply all the constants
  174307. * by CONST_SCALE and convert them to integer constants (thus retaining
  174308. * CONST_BITS bits of precision in the constants). After doing a
  174309. * multiplication we have to divide the product by CONST_SCALE, with proper
  174310. * rounding, to produce the correct output. This division can be done
  174311. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174312. * as long as possible so that partial sums can be added together with
  174313. * full fractional precision.
  174314. *
  174315. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174316. * they are represented to better-than-integral precision. These outputs
  174317. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174318. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174319. * array is INT32 anyway.)
  174320. *
  174321. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174322. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174323. * shows that the values given below are the most effective.
  174324. */
  174325. #if BITS_IN_JSAMPLE == 8
  174326. #define CONST_BITS 13
  174327. #define PASS1_BITS 2
  174328. #else
  174329. #define CONST_BITS 13
  174330. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174331. #endif
  174332. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174333. * causing a lot of useless floating-point operations at run time.
  174334. * To get around this we use the following pre-calculated constants.
  174335. * If you change CONST_BITS you may want to add appropriate values.
  174336. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174337. */
  174338. #if CONST_BITS == 13
  174339. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174340. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174341. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174342. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174343. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174344. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174345. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174346. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174347. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174348. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174349. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174350. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174351. #else
  174352. #define FIX_0_298631336 FIX(0.298631336)
  174353. #define FIX_0_390180644 FIX(0.390180644)
  174354. #define FIX_0_541196100 FIX(0.541196100)
  174355. #define FIX_0_765366865 FIX(0.765366865)
  174356. #define FIX_0_899976223 FIX(0.899976223)
  174357. #define FIX_1_175875602 FIX(1.175875602)
  174358. #define FIX_1_501321110 FIX(1.501321110)
  174359. #define FIX_1_847759065 FIX(1.847759065)
  174360. #define FIX_1_961570560 FIX(1.961570560)
  174361. #define FIX_2_053119869 FIX(2.053119869)
  174362. #define FIX_2_562915447 FIX(2.562915447)
  174363. #define FIX_3_072711026 FIX(3.072711026)
  174364. #endif
  174365. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174366. * For 8-bit samples with the recommended scaling, all the variable
  174367. * and constant values involved are no more than 16 bits wide, so a
  174368. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174369. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174370. */
  174371. #if BITS_IN_JSAMPLE == 8
  174372. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174373. #else
  174374. #define MULTIPLY(var,const) ((var) * (const))
  174375. #endif
  174376. /*
  174377. * Perform the forward DCT on one block of samples.
  174378. */
  174379. GLOBAL(void)
  174380. jpeg_fdct_islow (DCTELEM * data)
  174381. {
  174382. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174383. INT32 tmp10, tmp11, tmp12, tmp13;
  174384. INT32 z1, z2, z3, z4, z5;
  174385. DCTELEM *dataptr;
  174386. int ctr;
  174387. SHIFT_TEMPS
  174388. /* Pass 1: process rows. */
  174389. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174390. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174391. dataptr = data;
  174392. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174393. tmp0 = dataptr[0] + dataptr[7];
  174394. tmp7 = dataptr[0] - dataptr[7];
  174395. tmp1 = dataptr[1] + dataptr[6];
  174396. tmp6 = dataptr[1] - dataptr[6];
  174397. tmp2 = dataptr[2] + dataptr[5];
  174398. tmp5 = dataptr[2] - dataptr[5];
  174399. tmp3 = dataptr[3] + dataptr[4];
  174400. tmp4 = dataptr[3] - dataptr[4];
  174401. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174402. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174403. */
  174404. tmp10 = tmp0 + tmp3;
  174405. tmp13 = tmp0 - tmp3;
  174406. tmp11 = tmp1 + tmp2;
  174407. tmp12 = tmp1 - tmp2;
  174408. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174409. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174410. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174411. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174412. CONST_BITS-PASS1_BITS);
  174413. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174414. CONST_BITS-PASS1_BITS);
  174415. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174416. * cK represents cos(K*pi/16).
  174417. * i0..i3 in the paper are tmp4..tmp7 here.
  174418. */
  174419. z1 = tmp4 + tmp7;
  174420. z2 = tmp5 + tmp6;
  174421. z3 = tmp4 + tmp6;
  174422. z4 = tmp5 + tmp7;
  174423. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174424. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174425. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174426. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174427. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174428. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174429. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174430. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174431. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174432. z3 += z5;
  174433. z4 += z5;
  174434. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174435. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174436. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174437. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174438. dataptr += DCTSIZE; /* advance pointer to next row */
  174439. }
  174440. /* Pass 2: process columns.
  174441. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174442. * by an overall factor of 8.
  174443. */
  174444. dataptr = data;
  174445. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174446. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174447. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174448. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174449. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174450. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174451. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174452. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174453. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174454. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174455. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174456. */
  174457. tmp10 = tmp0 + tmp3;
  174458. tmp13 = tmp0 - tmp3;
  174459. tmp11 = tmp1 + tmp2;
  174460. tmp12 = tmp1 - tmp2;
  174461. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174462. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174463. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174464. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174465. CONST_BITS+PASS1_BITS);
  174466. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174467. CONST_BITS+PASS1_BITS);
  174468. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174469. * cK represents cos(K*pi/16).
  174470. * i0..i3 in the paper are tmp4..tmp7 here.
  174471. */
  174472. z1 = tmp4 + tmp7;
  174473. z2 = tmp5 + tmp6;
  174474. z3 = tmp4 + tmp6;
  174475. z4 = tmp5 + tmp7;
  174476. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174477. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174478. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174479. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174480. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174481. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174482. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174483. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174484. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174485. z3 += z5;
  174486. z4 += z5;
  174487. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174488. CONST_BITS+PASS1_BITS);
  174489. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174490. CONST_BITS+PASS1_BITS);
  174491. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174492. CONST_BITS+PASS1_BITS);
  174493. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174494. CONST_BITS+PASS1_BITS);
  174495. dataptr++; /* advance pointer to next column */
  174496. }
  174497. }
  174498. #endif /* DCT_ISLOW_SUPPORTED */
  174499. /*** End of inlined file: jfdctint.c ***/
  174500. #undef CONST_BITS
  174501. #undef MULTIPLY
  174502. #undef FIX_0_541196100
  174503. /*** Start of inlined file: jfdctfst.c ***/
  174504. #define JPEG_INTERNALS
  174505. #ifdef DCT_IFAST_SUPPORTED
  174506. /*
  174507. * This module is specialized to the case DCTSIZE = 8.
  174508. */
  174509. #if DCTSIZE != 8
  174510. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174511. #endif
  174512. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174513. * see jfdctint.c for more details. However, we choose to descale
  174514. * (right shift) multiplication products as soon as they are formed,
  174515. * rather than carrying additional fractional bits into subsequent additions.
  174516. * This compromises accuracy slightly, but it lets us save a few shifts.
  174517. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174518. * everywhere except in the multiplications proper; this saves a good deal
  174519. * of work on 16-bit-int machines.
  174520. *
  174521. * Again to save a few shifts, the intermediate results between pass 1 and
  174522. * pass 2 are not upscaled, but are represented only to integral precision.
  174523. *
  174524. * A final compromise is to represent the multiplicative constants to only
  174525. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174526. * machines, and may also reduce the cost of multiplication (since there
  174527. * are fewer one-bits in the constants).
  174528. */
  174529. #define CONST_BITS 8
  174530. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174531. * causing a lot of useless floating-point operations at run time.
  174532. * To get around this we use the following pre-calculated constants.
  174533. * If you change CONST_BITS you may want to add appropriate values.
  174534. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174535. */
  174536. #if CONST_BITS == 8
  174537. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174538. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174539. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174540. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174541. #else
  174542. #define FIX_0_382683433 FIX(0.382683433)
  174543. #define FIX_0_541196100 FIX(0.541196100)
  174544. #define FIX_0_707106781 FIX(0.707106781)
  174545. #define FIX_1_306562965 FIX(1.306562965)
  174546. #endif
  174547. /* We can gain a little more speed, with a further compromise in accuracy,
  174548. * by omitting the addition in a descaling shift. This yields an incorrectly
  174549. * rounded result half the time...
  174550. */
  174551. #ifndef USE_ACCURATE_ROUNDING
  174552. #undef DESCALE
  174553. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174554. #endif
  174555. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174556. * descale to yield a DCTELEM result.
  174557. */
  174558. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174559. /*
  174560. * Perform the forward DCT on one block of samples.
  174561. */
  174562. GLOBAL(void)
  174563. jpeg_fdct_ifast (DCTELEM * data)
  174564. {
  174565. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174566. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174567. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174568. DCTELEM *dataptr;
  174569. int ctr;
  174570. SHIFT_TEMPS
  174571. /* Pass 1: process rows. */
  174572. dataptr = data;
  174573. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174574. tmp0 = dataptr[0] + dataptr[7];
  174575. tmp7 = dataptr[0] - dataptr[7];
  174576. tmp1 = dataptr[1] + dataptr[6];
  174577. tmp6 = dataptr[1] - dataptr[6];
  174578. tmp2 = dataptr[2] + dataptr[5];
  174579. tmp5 = dataptr[2] - dataptr[5];
  174580. tmp3 = dataptr[3] + dataptr[4];
  174581. tmp4 = dataptr[3] - dataptr[4];
  174582. /* Even part */
  174583. tmp10 = tmp0 + tmp3; /* phase 2 */
  174584. tmp13 = tmp0 - tmp3;
  174585. tmp11 = tmp1 + tmp2;
  174586. tmp12 = tmp1 - tmp2;
  174587. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174588. dataptr[4] = tmp10 - tmp11;
  174589. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174590. dataptr[2] = tmp13 + z1; /* phase 5 */
  174591. dataptr[6] = tmp13 - z1;
  174592. /* Odd part */
  174593. tmp10 = tmp4 + tmp5; /* phase 2 */
  174594. tmp11 = tmp5 + tmp6;
  174595. tmp12 = tmp6 + tmp7;
  174596. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174597. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174598. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174599. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174600. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174601. z11 = tmp7 + z3; /* phase 5 */
  174602. z13 = tmp7 - z3;
  174603. dataptr[5] = z13 + z2; /* phase 6 */
  174604. dataptr[3] = z13 - z2;
  174605. dataptr[1] = z11 + z4;
  174606. dataptr[7] = z11 - z4;
  174607. dataptr += DCTSIZE; /* advance pointer to next row */
  174608. }
  174609. /* Pass 2: process columns. */
  174610. dataptr = data;
  174611. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174612. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174613. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174614. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174615. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174616. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174617. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174618. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174619. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174620. /* Even part */
  174621. tmp10 = tmp0 + tmp3; /* phase 2 */
  174622. tmp13 = tmp0 - tmp3;
  174623. tmp11 = tmp1 + tmp2;
  174624. tmp12 = tmp1 - tmp2;
  174625. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174626. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174627. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174628. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174629. dataptr[DCTSIZE*6] = tmp13 - z1;
  174630. /* Odd part */
  174631. tmp10 = tmp4 + tmp5; /* phase 2 */
  174632. tmp11 = tmp5 + tmp6;
  174633. tmp12 = tmp6 + tmp7;
  174634. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174635. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174636. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174637. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174638. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174639. z11 = tmp7 + z3; /* phase 5 */
  174640. z13 = tmp7 - z3;
  174641. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174642. dataptr[DCTSIZE*3] = z13 - z2;
  174643. dataptr[DCTSIZE*1] = z11 + z4;
  174644. dataptr[DCTSIZE*7] = z11 - z4;
  174645. dataptr++; /* advance pointer to next column */
  174646. }
  174647. }
  174648. #endif /* DCT_IFAST_SUPPORTED */
  174649. /*** End of inlined file: jfdctfst.c ***/
  174650. #undef FIX_0_541196100
  174651. /*** Start of inlined file: jidctflt.c ***/
  174652. #define JPEG_INTERNALS
  174653. #ifdef DCT_FLOAT_SUPPORTED
  174654. /*
  174655. * This module is specialized to the case DCTSIZE = 8.
  174656. */
  174657. #if DCTSIZE != 8
  174658. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174659. #endif
  174660. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174661. * entry; produce a float result.
  174662. */
  174663. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174664. /*
  174665. * Perform dequantization and inverse DCT on one block of coefficients.
  174666. */
  174667. GLOBAL(void)
  174668. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174669. JCOEFPTR coef_block,
  174670. JSAMPARRAY output_buf, JDIMENSION output_col)
  174671. {
  174672. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174673. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174674. FAST_FLOAT z5, z10, z11, z12, z13;
  174675. JCOEFPTR inptr;
  174676. FLOAT_MULT_TYPE * quantptr;
  174677. FAST_FLOAT * wsptr;
  174678. JSAMPROW outptr;
  174679. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174680. int ctr;
  174681. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174682. SHIFT_TEMPS
  174683. /* Pass 1: process columns from input, store into work array. */
  174684. inptr = coef_block;
  174685. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174686. wsptr = workspace;
  174687. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174688. /* Due to quantization, we will usually find that many of the input
  174689. * coefficients are zero, especially the AC terms. We can exploit this
  174690. * by short-circuiting the IDCT calculation for any column in which all
  174691. * the AC terms are zero. In that case each output is equal to the
  174692. * DC coefficient (with scale factor as needed).
  174693. * With typical images and quantization tables, half or more of the
  174694. * column DCT calculations can be simplified this way.
  174695. */
  174696. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174697. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174698. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174699. inptr[DCTSIZE*7] == 0) {
  174700. /* AC terms all zero */
  174701. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174702. wsptr[DCTSIZE*0] = dcval;
  174703. wsptr[DCTSIZE*1] = dcval;
  174704. wsptr[DCTSIZE*2] = dcval;
  174705. wsptr[DCTSIZE*3] = dcval;
  174706. wsptr[DCTSIZE*4] = dcval;
  174707. wsptr[DCTSIZE*5] = dcval;
  174708. wsptr[DCTSIZE*6] = dcval;
  174709. wsptr[DCTSIZE*7] = dcval;
  174710. inptr++; /* advance pointers to next column */
  174711. quantptr++;
  174712. wsptr++;
  174713. continue;
  174714. }
  174715. /* Even part */
  174716. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174717. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174718. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174719. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174720. tmp10 = tmp0 + tmp2; /* phase 3 */
  174721. tmp11 = tmp0 - tmp2;
  174722. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174723. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174724. tmp0 = tmp10 + tmp13; /* phase 2 */
  174725. tmp3 = tmp10 - tmp13;
  174726. tmp1 = tmp11 + tmp12;
  174727. tmp2 = tmp11 - tmp12;
  174728. /* Odd part */
  174729. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174730. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174731. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174732. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174733. z13 = tmp6 + tmp5; /* phase 6 */
  174734. z10 = tmp6 - tmp5;
  174735. z11 = tmp4 + tmp7;
  174736. z12 = tmp4 - tmp7;
  174737. tmp7 = z11 + z13; /* phase 5 */
  174738. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174739. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174740. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174741. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174742. tmp6 = tmp12 - tmp7; /* phase 2 */
  174743. tmp5 = tmp11 - tmp6;
  174744. tmp4 = tmp10 + tmp5;
  174745. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174746. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174747. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174748. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174749. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174750. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174751. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174752. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174753. inptr++; /* advance pointers to next column */
  174754. quantptr++;
  174755. wsptr++;
  174756. }
  174757. /* Pass 2: process rows from work array, store into output array. */
  174758. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174759. wsptr = workspace;
  174760. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174761. outptr = output_buf[ctr] + output_col;
  174762. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174763. * However, the column calculation has created many nonzero AC terms, so
  174764. * the simplification applies less often (typically 5% to 10% of the time).
  174765. * And testing floats for zero is relatively expensive, so we don't bother.
  174766. */
  174767. /* Even part */
  174768. tmp10 = wsptr[0] + wsptr[4];
  174769. tmp11 = wsptr[0] - wsptr[4];
  174770. tmp13 = wsptr[2] + wsptr[6];
  174771. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174772. tmp0 = tmp10 + tmp13;
  174773. tmp3 = tmp10 - tmp13;
  174774. tmp1 = tmp11 + tmp12;
  174775. tmp2 = tmp11 - tmp12;
  174776. /* Odd part */
  174777. z13 = wsptr[5] + wsptr[3];
  174778. z10 = wsptr[5] - wsptr[3];
  174779. z11 = wsptr[1] + wsptr[7];
  174780. z12 = wsptr[1] - wsptr[7];
  174781. tmp7 = z11 + z13;
  174782. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174783. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174784. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174785. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174786. tmp6 = tmp12 - tmp7;
  174787. tmp5 = tmp11 - tmp6;
  174788. tmp4 = tmp10 + tmp5;
  174789. /* Final output stage: scale down by a factor of 8 and range-limit */
  174790. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174791. & RANGE_MASK];
  174792. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174793. & RANGE_MASK];
  174794. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174795. & RANGE_MASK];
  174796. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174797. & RANGE_MASK];
  174798. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174799. & RANGE_MASK];
  174800. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174801. & RANGE_MASK];
  174802. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174803. & RANGE_MASK];
  174804. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174805. & RANGE_MASK];
  174806. wsptr += DCTSIZE; /* advance pointer to next row */
  174807. }
  174808. }
  174809. #endif /* DCT_FLOAT_SUPPORTED */
  174810. /*** End of inlined file: jidctflt.c ***/
  174811. #undef CONST_BITS
  174812. #undef FIX_1_847759065
  174813. #undef MULTIPLY
  174814. #undef DEQUANTIZE
  174815. #undef DESCALE
  174816. /*** Start of inlined file: jidctfst.c ***/
  174817. #define JPEG_INTERNALS
  174818. #ifdef DCT_IFAST_SUPPORTED
  174819. /*
  174820. * This module is specialized to the case DCTSIZE = 8.
  174821. */
  174822. #if DCTSIZE != 8
  174823. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174824. #endif
  174825. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174826. * see jidctint.c for more details. However, we choose to descale
  174827. * (right shift) multiplication products as soon as they are formed,
  174828. * rather than carrying additional fractional bits into subsequent additions.
  174829. * This compromises accuracy slightly, but it lets us save a few shifts.
  174830. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174831. * everywhere except in the multiplications proper; this saves a good deal
  174832. * of work on 16-bit-int machines.
  174833. *
  174834. * The dequantized coefficients are not integers because the AA&N scaling
  174835. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174836. * so that the first and second IDCT rounds have the same input scaling.
  174837. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174838. * avoid a descaling shift; this compromises accuracy rather drastically
  174839. * for small quantization table entries, but it saves a lot of shifts.
  174840. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174841. * so we use a much larger scaling factor to preserve accuracy.
  174842. *
  174843. * A final compromise is to represent the multiplicative constants to only
  174844. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174845. * machines, and may also reduce the cost of multiplication (since there
  174846. * are fewer one-bits in the constants).
  174847. */
  174848. #if BITS_IN_JSAMPLE == 8
  174849. #define CONST_BITS 8
  174850. #define PASS1_BITS 2
  174851. #else
  174852. #define CONST_BITS 8
  174853. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174854. #endif
  174855. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174856. * causing a lot of useless floating-point operations at run time.
  174857. * To get around this we use the following pre-calculated constants.
  174858. * If you change CONST_BITS you may want to add appropriate values.
  174859. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174860. */
  174861. #if CONST_BITS == 8
  174862. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174863. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174864. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174865. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174866. #else
  174867. #define FIX_1_082392200 FIX(1.082392200)
  174868. #define FIX_1_414213562 FIX(1.414213562)
  174869. #define FIX_1_847759065 FIX(1.847759065)
  174870. #define FIX_2_613125930 FIX(2.613125930)
  174871. #endif
  174872. /* We can gain a little more speed, with a further compromise in accuracy,
  174873. * by omitting the addition in a descaling shift. This yields an incorrectly
  174874. * rounded result half the time...
  174875. */
  174876. #ifndef USE_ACCURATE_ROUNDING
  174877. #undef DESCALE
  174878. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174879. #endif
  174880. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174881. * descale to yield a DCTELEM result.
  174882. */
  174883. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174884. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174885. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174886. * multiplication will do. For 12-bit data, the multiplier table is
  174887. * declared INT32, so a 32-bit multiply will be used.
  174888. */
  174889. #if BITS_IN_JSAMPLE == 8
  174890. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174891. #else
  174892. #define DEQUANTIZE(coef,quantval) \
  174893. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174894. #endif
  174895. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174896. * We assume that int right shift is unsigned if INT32 right shift is.
  174897. */
  174898. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174899. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174900. #if BITS_IN_JSAMPLE == 8
  174901. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174902. #else
  174903. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174904. #endif
  174905. #define IRIGHT_SHIFT(x,shft) \
  174906. ((ishift_temp = (x)) < 0 ? \
  174907. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174908. (ishift_temp >> (shft)))
  174909. #else
  174910. #define ISHIFT_TEMPS
  174911. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174912. #endif
  174913. #ifdef USE_ACCURATE_ROUNDING
  174914. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174915. #else
  174916. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174917. #endif
  174918. /*
  174919. * Perform dequantization and inverse DCT on one block of coefficients.
  174920. */
  174921. GLOBAL(void)
  174922. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174923. JCOEFPTR coef_block,
  174924. JSAMPARRAY output_buf, JDIMENSION output_col)
  174925. {
  174926. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174927. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174928. DCTELEM z5, z10, z11, z12, z13;
  174929. JCOEFPTR inptr;
  174930. IFAST_MULT_TYPE * quantptr;
  174931. int * wsptr;
  174932. JSAMPROW outptr;
  174933. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174934. int ctr;
  174935. int workspace[DCTSIZE2]; /* buffers data between passes */
  174936. SHIFT_TEMPS /* for DESCALE */
  174937. ISHIFT_TEMPS /* for IDESCALE */
  174938. /* Pass 1: process columns from input, store into work array. */
  174939. inptr = coef_block;
  174940. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174941. wsptr = workspace;
  174942. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174943. /* Due to quantization, we will usually find that many of the input
  174944. * coefficients are zero, especially the AC terms. We can exploit this
  174945. * by short-circuiting the IDCT calculation for any column in which all
  174946. * the AC terms are zero. In that case each output is equal to the
  174947. * DC coefficient (with scale factor as needed).
  174948. * With typical images and quantization tables, half or more of the
  174949. * column DCT calculations can be simplified this way.
  174950. */
  174951. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174952. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174953. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174954. inptr[DCTSIZE*7] == 0) {
  174955. /* AC terms all zero */
  174956. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174957. wsptr[DCTSIZE*0] = dcval;
  174958. wsptr[DCTSIZE*1] = dcval;
  174959. wsptr[DCTSIZE*2] = dcval;
  174960. wsptr[DCTSIZE*3] = dcval;
  174961. wsptr[DCTSIZE*4] = dcval;
  174962. wsptr[DCTSIZE*5] = dcval;
  174963. wsptr[DCTSIZE*6] = dcval;
  174964. wsptr[DCTSIZE*7] = dcval;
  174965. inptr++; /* advance pointers to next column */
  174966. quantptr++;
  174967. wsptr++;
  174968. continue;
  174969. }
  174970. /* Even part */
  174971. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174972. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174973. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174974. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174975. tmp10 = tmp0 + tmp2; /* phase 3 */
  174976. tmp11 = tmp0 - tmp2;
  174977. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174978. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174979. tmp0 = tmp10 + tmp13; /* phase 2 */
  174980. tmp3 = tmp10 - tmp13;
  174981. tmp1 = tmp11 + tmp12;
  174982. tmp2 = tmp11 - tmp12;
  174983. /* Odd part */
  174984. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174985. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174986. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174987. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174988. z13 = tmp6 + tmp5; /* phase 6 */
  174989. z10 = tmp6 - tmp5;
  174990. z11 = tmp4 + tmp7;
  174991. z12 = tmp4 - tmp7;
  174992. tmp7 = z11 + z13; /* phase 5 */
  174993. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174994. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174995. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174996. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174997. tmp6 = tmp12 - tmp7; /* phase 2 */
  174998. tmp5 = tmp11 - tmp6;
  174999. tmp4 = tmp10 + tmp5;
  175000. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175001. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175002. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175003. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175004. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175005. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175006. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175007. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175008. inptr++; /* advance pointers to next column */
  175009. quantptr++;
  175010. wsptr++;
  175011. }
  175012. /* Pass 2: process rows from work array, store into output array. */
  175013. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175014. /* and also undo the PASS1_BITS scaling. */
  175015. wsptr = workspace;
  175016. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175017. outptr = output_buf[ctr] + output_col;
  175018. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175019. * However, the column calculation has created many nonzero AC terms, so
  175020. * the simplification applies less often (typically 5% to 10% of the time).
  175021. * On machines with very fast multiplication, it's possible that the
  175022. * test takes more time than it's worth. In that case this section
  175023. * may be commented out.
  175024. */
  175025. #ifndef NO_ZERO_ROW_TEST
  175026. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175027. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175028. /* AC terms all zero */
  175029. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175030. & RANGE_MASK];
  175031. outptr[0] = dcval;
  175032. outptr[1] = dcval;
  175033. outptr[2] = dcval;
  175034. outptr[3] = dcval;
  175035. outptr[4] = dcval;
  175036. outptr[5] = dcval;
  175037. outptr[6] = dcval;
  175038. outptr[7] = dcval;
  175039. wsptr += DCTSIZE; /* advance pointer to next row */
  175040. continue;
  175041. }
  175042. #endif
  175043. /* Even part */
  175044. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175045. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175046. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175047. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175048. - tmp13;
  175049. tmp0 = tmp10 + tmp13;
  175050. tmp3 = tmp10 - tmp13;
  175051. tmp1 = tmp11 + tmp12;
  175052. tmp2 = tmp11 - tmp12;
  175053. /* Odd part */
  175054. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175055. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175056. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175057. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175058. tmp7 = z11 + z13; /* phase 5 */
  175059. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175060. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175061. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175062. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175063. tmp6 = tmp12 - tmp7; /* phase 2 */
  175064. tmp5 = tmp11 - tmp6;
  175065. tmp4 = tmp10 + tmp5;
  175066. /* Final output stage: scale down by a factor of 8 and range-limit */
  175067. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175068. & RANGE_MASK];
  175069. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175070. & RANGE_MASK];
  175071. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175072. & RANGE_MASK];
  175073. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175074. & RANGE_MASK];
  175075. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175076. & RANGE_MASK];
  175077. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175078. & RANGE_MASK];
  175079. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175080. & RANGE_MASK];
  175081. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175082. & RANGE_MASK];
  175083. wsptr += DCTSIZE; /* advance pointer to next row */
  175084. }
  175085. }
  175086. #endif /* DCT_IFAST_SUPPORTED */
  175087. /*** End of inlined file: jidctfst.c ***/
  175088. #undef CONST_BITS
  175089. #undef FIX_1_847759065
  175090. #undef MULTIPLY
  175091. #undef DEQUANTIZE
  175092. /*** Start of inlined file: jidctint.c ***/
  175093. #define JPEG_INTERNALS
  175094. #ifdef DCT_ISLOW_SUPPORTED
  175095. /*
  175096. * This module is specialized to the case DCTSIZE = 8.
  175097. */
  175098. #if DCTSIZE != 8
  175099. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175100. #endif
  175101. /*
  175102. * The poop on this scaling stuff is as follows:
  175103. *
  175104. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175105. * larger than the true IDCT outputs. The final outputs are therefore
  175106. * a factor of N larger than desired; since N=8 this can be cured by
  175107. * a simple right shift at the end of the algorithm. The advantage of
  175108. * this arrangement is that we save two multiplications per 1-D IDCT,
  175109. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175110. *
  175111. * We have to do addition and subtraction of the integer inputs, which
  175112. * is no problem, and multiplication by fractional constants, which is
  175113. * a problem to do in integer arithmetic. We multiply all the constants
  175114. * by CONST_SCALE and convert them to integer constants (thus retaining
  175115. * CONST_BITS bits of precision in the constants). After doing a
  175116. * multiplication we have to divide the product by CONST_SCALE, with proper
  175117. * rounding, to produce the correct output. This division can be done
  175118. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175119. * as long as possible so that partial sums can be added together with
  175120. * full fractional precision.
  175121. *
  175122. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175123. * they are represented to better-than-integral precision. These outputs
  175124. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175125. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175126. * intermediate INT32 array would be needed.)
  175127. *
  175128. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175129. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175130. * shows that the values given below are the most effective.
  175131. */
  175132. #if BITS_IN_JSAMPLE == 8
  175133. #define CONST_BITS 13
  175134. #define PASS1_BITS 2
  175135. #else
  175136. #define CONST_BITS 13
  175137. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175138. #endif
  175139. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175140. * causing a lot of useless floating-point operations at run time.
  175141. * To get around this we use the following pre-calculated constants.
  175142. * If you change CONST_BITS you may want to add appropriate values.
  175143. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175144. */
  175145. #if CONST_BITS == 13
  175146. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175147. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175148. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175149. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175150. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175151. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175152. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175153. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175154. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175155. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175156. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175157. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175158. #else
  175159. #define FIX_0_298631336 FIX(0.298631336)
  175160. #define FIX_0_390180644 FIX(0.390180644)
  175161. #define FIX_0_541196100 FIX(0.541196100)
  175162. #define FIX_0_765366865 FIX(0.765366865)
  175163. #define FIX_0_899976223 FIX(0.899976223)
  175164. #define FIX_1_175875602 FIX(1.175875602)
  175165. #define FIX_1_501321110 FIX(1.501321110)
  175166. #define FIX_1_847759065 FIX(1.847759065)
  175167. #define FIX_1_961570560 FIX(1.961570560)
  175168. #define FIX_2_053119869 FIX(2.053119869)
  175169. #define FIX_2_562915447 FIX(2.562915447)
  175170. #define FIX_3_072711026 FIX(3.072711026)
  175171. #endif
  175172. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175173. * For 8-bit samples with the recommended scaling, all the variable
  175174. * and constant values involved are no more than 16 bits wide, so a
  175175. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175176. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175177. */
  175178. #if BITS_IN_JSAMPLE == 8
  175179. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175180. #else
  175181. #define MULTIPLY(var,const) ((var) * (const))
  175182. #endif
  175183. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175184. * entry; produce an int result. In this module, both inputs and result
  175185. * are 16 bits or less, so either int or short multiply will work.
  175186. */
  175187. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175188. /*
  175189. * Perform dequantization and inverse DCT on one block of coefficients.
  175190. */
  175191. GLOBAL(void)
  175192. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175193. JCOEFPTR coef_block,
  175194. JSAMPARRAY output_buf, JDIMENSION output_col)
  175195. {
  175196. INT32 tmp0, tmp1, tmp2, tmp3;
  175197. INT32 tmp10, tmp11, tmp12, tmp13;
  175198. INT32 z1, z2, z3, z4, z5;
  175199. JCOEFPTR inptr;
  175200. ISLOW_MULT_TYPE * quantptr;
  175201. int * wsptr;
  175202. JSAMPROW outptr;
  175203. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175204. int ctr;
  175205. int workspace[DCTSIZE2]; /* buffers data between passes */
  175206. SHIFT_TEMPS
  175207. /* Pass 1: process columns from input, store into work array. */
  175208. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175209. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175210. inptr = coef_block;
  175211. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175212. wsptr = workspace;
  175213. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175214. /* Due to quantization, we will usually find that many of the input
  175215. * coefficients are zero, especially the AC terms. We can exploit this
  175216. * by short-circuiting the IDCT calculation for any column in which all
  175217. * the AC terms are zero. In that case each output is equal to the
  175218. * DC coefficient (with scale factor as needed).
  175219. * With typical images and quantization tables, half or more of the
  175220. * column DCT calculations can be simplified this way.
  175221. */
  175222. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175223. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175224. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175225. inptr[DCTSIZE*7] == 0) {
  175226. /* AC terms all zero */
  175227. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175228. wsptr[DCTSIZE*0] = dcval;
  175229. wsptr[DCTSIZE*1] = dcval;
  175230. wsptr[DCTSIZE*2] = dcval;
  175231. wsptr[DCTSIZE*3] = dcval;
  175232. wsptr[DCTSIZE*4] = dcval;
  175233. wsptr[DCTSIZE*5] = dcval;
  175234. wsptr[DCTSIZE*6] = dcval;
  175235. wsptr[DCTSIZE*7] = dcval;
  175236. inptr++; /* advance pointers to next column */
  175237. quantptr++;
  175238. wsptr++;
  175239. continue;
  175240. }
  175241. /* Even part: reverse the even part of the forward DCT. */
  175242. /* The rotator is sqrt(2)*c(-6). */
  175243. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175244. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175245. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175246. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175247. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175248. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175249. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175250. tmp0 = (z2 + z3) << CONST_BITS;
  175251. tmp1 = (z2 - z3) << CONST_BITS;
  175252. tmp10 = tmp0 + tmp3;
  175253. tmp13 = tmp0 - tmp3;
  175254. tmp11 = tmp1 + tmp2;
  175255. tmp12 = tmp1 - tmp2;
  175256. /* Odd part per figure 8; the matrix is unitary and hence its
  175257. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175258. */
  175259. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175260. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175261. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175262. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175263. z1 = tmp0 + tmp3;
  175264. z2 = tmp1 + tmp2;
  175265. z3 = tmp0 + tmp2;
  175266. z4 = tmp1 + tmp3;
  175267. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175268. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175269. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175270. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175271. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175272. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175273. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175274. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175275. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175276. z3 += z5;
  175277. z4 += z5;
  175278. tmp0 += z1 + z3;
  175279. tmp1 += z2 + z4;
  175280. tmp2 += z2 + z3;
  175281. tmp3 += z1 + z4;
  175282. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175283. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175284. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175285. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175286. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175287. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175288. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175289. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175290. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175291. inptr++; /* advance pointers to next column */
  175292. quantptr++;
  175293. wsptr++;
  175294. }
  175295. /* Pass 2: process rows from work array, store into output array. */
  175296. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175297. /* and also undo the PASS1_BITS scaling. */
  175298. wsptr = workspace;
  175299. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175300. outptr = output_buf[ctr] + output_col;
  175301. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175302. * However, the column calculation has created many nonzero AC terms, so
  175303. * the simplification applies less often (typically 5% to 10% of the time).
  175304. * On machines with very fast multiplication, it's possible that the
  175305. * test takes more time than it's worth. In that case this section
  175306. * may be commented out.
  175307. */
  175308. #ifndef NO_ZERO_ROW_TEST
  175309. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175310. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175311. /* AC terms all zero */
  175312. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175313. & RANGE_MASK];
  175314. outptr[0] = dcval;
  175315. outptr[1] = dcval;
  175316. outptr[2] = dcval;
  175317. outptr[3] = dcval;
  175318. outptr[4] = dcval;
  175319. outptr[5] = dcval;
  175320. outptr[6] = dcval;
  175321. outptr[7] = dcval;
  175322. wsptr += DCTSIZE; /* advance pointer to next row */
  175323. continue;
  175324. }
  175325. #endif
  175326. /* Even part: reverse the even part of the forward DCT. */
  175327. /* The rotator is sqrt(2)*c(-6). */
  175328. z2 = (INT32) wsptr[2];
  175329. z3 = (INT32) wsptr[6];
  175330. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175331. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175332. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175333. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175334. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175335. tmp10 = tmp0 + tmp3;
  175336. tmp13 = tmp0 - tmp3;
  175337. tmp11 = tmp1 + tmp2;
  175338. tmp12 = tmp1 - tmp2;
  175339. /* Odd part per figure 8; the matrix is unitary and hence its
  175340. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175341. */
  175342. tmp0 = (INT32) wsptr[7];
  175343. tmp1 = (INT32) wsptr[5];
  175344. tmp2 = (INT32) wsptr[3];
  175345. tmp3 = (INT32) wsptr[1];
  175346. z1 = tmp0 + tmp3;
  175347. z2 = tmp1 + tmp2;
  175348. z3 = tmp0 + tmp2;
  175349. z4 = tmp1 + tmp3;
  175350. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175351. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175352. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175353. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175354. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175355. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175356. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175357. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175358. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175359. z3 += z5;
  175360. z4 += z5;
  175361. tmp0 += z1 + z3;
  175362. tmp1 += z2 + z4;
  175363. tmp2 += z2 + z3;
  175364. tmp3 += z1 + z4;
  175365. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175366. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175367. CONST_BITS+PASS1_BITS+3)
  175368. & RANGE_MASK];
  175369. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175370. CONST_BITS+PASS1_BITS+3)
  175371. & RANGE_MASK];
  175372. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175373. CONST_BITS+PASS1_BITS+3)
  175374. & RANGE_MASK];
  175375. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175376. CONST_BITS+PASS1_BITS+3)
  175377. & RANGE_MASK];
  175378. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175379. CONST_BITS+PASS1_BITS+3)
  175380. & RANGE_MASK];
  175381. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175382. CONST_BITS+PASS1_BITS+3)
  175383. & RANGE_MASK];
  175384. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175385. CONST_BITS+PASS1_BITS+3)
  175386. & RANGE_MASK];
  175387. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175388. CONST_BITS+PASS1_BITS+3)
  175389. & RANGE_MASK];
  175390. wsptr += DCTSIZE; /* advance pointer to next row */
  175391. }
  175392. }
  175393. #endif /* DCT_ISLOW_SUPPORTED */
  175394. /*** End of inlined file: jidctint.c ***/
  175395. /*** Start of inlined file: jidctred.c ***/
  175396. #define JPEG_INTERNALS
  175397. #ifdef IDCT_SCALING_SUPPORTED
  175398. /*
  175399. * This module is specialized to the case DCTSIZE = 8.
  175400. */
  175401. #if DCTSIZE != 8
  175402. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175403. #endif
  175404. /* Scaling is the same as in jidctint.c. */
  175405. #if BITS_IN_JSAMPLE == 8
  175406. #define CONST_BITS 13
  175407. #define PASS1_BITS 2
  175408. #else
  175409. #define CONST_BITS 13
  175410. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175411. #endif
  175412. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175413. * causing a lot of useless floating-point operations at run time.
  175414. * To get around this we use the following pre-calculated constants.
  175415. * If you change CONST_BITS you may want to add appropriate values.
  175416. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175417. */
  175418. #if CONST_BITS == 13
  175419. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175420. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175421. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175422. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175423. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175424. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175425. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175426. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175427. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175428. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175429. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175430. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175431. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175432. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175433. #else
  175434. #define FIX_0_211164243 FIX(0.211164243)
  175435. #define FIX_0_509795579 FIX(0.509795579)
  175436. #define FIX_0_601344887 FIX(0.601344887)
  175437. #define FIX_0_720959822 FIX(0.720959822)
  175438. #define FIX_0_765366865 FIX(0.765366865)
  175439. #define FIX_0_850430095 FIX(0.850430095)
  175440. #define FIX_0_899976223 FIX(0.899976223)
  175441. #define FIX_1_061594337 FIX(1.061594337)
  175442. #define FIX_1_272758580 FIX(1.272758580)
  175443. #define FIX_1_451774981 FIX(1.451774981)
  175444. #define FIX_1_847759065 FIX(1.847759065)
  175445. #define FIX_2_172734803 FIX(2.172734803)
  175446. #define FIX_2_562915447 FIX(2.562915447)
  175447. #define FIX_3_624509785 FIX(3.624509785)
  175448. #endif
  175449. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175450. * For 8-bit samples with the recommended scaling, all the variable
  175451. * and constant values involved are no more than 16 bits wide, so a
  175452. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175453. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175454. */
  175455. #if BITS_IN_JSAMPLE == 8
  175456. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175457. #else
  175458. #define MULTIPLY(var,const) ((var) * (const))
  175459. #endif
  175460. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175461. * entry; produce an int result. In this module, both inputs and result
  175462. * are 16 bits or less, so either int or short multiply will work.
  175463. */
  175464. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175465. /*
  175466. * Perform dequantization and inverse DCT on one block of coefficients,
  175467. * producing a reduced-size 4x4 output block.
  175468. */
  175469. GLOBAL(void)
  175470. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175471. JCOEFPTR coef_block,
  175472. JSAMPARRAY output_buf, JDIMENSION output_col)
  175473. {
  175474. INT32 tmp0, tmp2, tmp10, tmp12;
  175475. INT32 z1, z2, z3, z4;
  175476. JCOEFPTR inptr;
  175477. ISLOW_MULT_TYPE * quantptr;
  175478. int * wsptr;
  175479. JSAMPROW outptr;
  175480. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175481. int ctr;
  175482. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175483. SHIFT_TEMPS
  175484. /* Pass 1: process columns from input, store into work array. */
  175485. inptr = coef_block;
  175486. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175487. wsptr = workspace;
  175488. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175489. /* Don't bother to process column 4, because second pass won't use it */
  175490. if (ctr == DCTSIZE-4)
  175491. continue;
  175492. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175493. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175494. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175495. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175496. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175497. wsptr[DCTSIZE*0] = dcval;
  175498. wsptr[DCTSIZE*1] = dcval;
  175499. wsptr[DCTSIZE*2] = dcval;
  175500. wsptr[DCTSIZE*3] = dcval;
  175501. continue;
  175502. }
  175503. /* Even part */
  175504. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175505. tmp0 <<= (CONST_BITS+1);
  175506. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175507. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175508. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175509. tmp10 = tmp0 + tmp2;
  175510. tmp12 = tmp0 - tmp2;
  175511. /* Odd part */
  175512. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175513. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175514. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175515. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175516. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175517. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175518. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175519. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175520. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175521. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175522. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175523. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175524. /* Final output stage */
  175525. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175526. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175527. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175528. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175529. }
  175530. /* Pass 2: process 4 rows from work array, store into output array. */
  175531. wsptr = workspace;
  175532. for (ctr = 0; ctr < 4; ctr++) {
  175533. outptr = output_buf[ctr] + output_col;
  175534. /* It's not clear whether a zero row test is worthwhile here ... */
  175535. #ifndef NO_ZERO_ROW_TEST
  175536. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175537. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175538. /* AC terms all zero */
  175539. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175540. & RANGE_MASK];
  175541. outptr[0] = dcval;
  175542. outptr[1] = dcval;
  175543. outptr[2] = dcval;
  175544. outptr[3] = dcval;
  175545. wsptr += DCTSIZE; /* advance pointer to next row */
  175546. continue;
  175547. }
  175548. #endif
  175549. /* Even part */
  175550. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175551. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175552. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175553. tmp10 = tmp0 + tmp2;
  175554. tmp12 = tmp0 - tmp2;
  175555. /* Odd part */
  175556. z1 = (INT32) wsptr[7];
  175557. z2 = (INT32) wsptr[5];
  175558. z3 = (INT32) wsptr[3];
  175559. z4 = (INT32) wsptr[1];
  175560. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175561. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175562. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175563. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175564. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175565. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175566. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175567. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175568. /* Final output stage */
  175569. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175570. CONST_BITS+PASS1_BITS+3+1)
  175571. & RANGE_MASK];
  175572. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175573. CONST_BITS+PASS1_BITS+3+1)
  175574. & RANGE_MASK];
  175575. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175576. CONST_BITS+PASS1_BITS+3+1)
  175577. & RANGE_MASK];
  175578. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175579. CONST_BITS+PASS1_BITS+3+1)
  175580. & RANGE_MASK];
  175581. wsptr += DCTSIZE; /* advance pointer to next row */
  175582. }
  175583. }
  175584. /*
  175585. * Perform dequantization and inverse DCT on one block of coefficients,
  175586. * producing a reduced-size 2x2 output block.
  175587. */
  175588. GLOBAL(void)
  175589. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175590. JCOEFPTR coef_block,
  175591. JSAMPARRAY output_buf, JDIMENSION output_col)
  175592. {
  175593. INT32 tmp0, tmp10, z1;
  175594. JCOEFPTR inptr;
  175595. ISLOW_MULT_TYPE * quantptr;
  175596. int * wsptr;
  175597. JSAMPROW outptr;
  175598. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175599. int ctr;
  175600. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175601. SHIFT_TEMPS
  175602. /* Pass 1: process columns from input, store into work array. */
  175603. inptr = coef_block;
  175604. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175605. wsptr = workspace;
  175606. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175607. /* Don't bother to process columns 2,4,6 */
  175608. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175609. continue;
  175610. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175611. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175612. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175613. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175614. wsptr[DCTSIZE*0] = dcval;
  175615. wsptr[DCTSIZE*1] = dcval;
  175616. continue;
  175617. }
  175618. /* Even part */
  175619. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175620. tmp10 = z1 << (CONST_BITS+2);
  175621. /* Odd part */
  175622. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175623. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175624. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175625. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175626. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175627. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175628. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175629. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175630. /* Final output stage */
  175631. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175632. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175633. }
  175634. /* Pass 2: process 2 rows from work array, store into output array. */
  175635. wsptr = workspace;
  175636. for (ctr = 0; ctr < 2; ctr++) {
  175637. outptr = output_buf[ctr] + output_col;
  175638. /* It's not clear whether a zero row test is worthwhile here ... */
  175639. #ifndef NO_ZERO_ROW_TEST
  175640. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175641. /* AC terms all zero */
  175642. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175643. & RANGE_MASK];
  175644. outptr[0] = dcval;
  175645. outptr[1] = dcval;
  175646. wsptr += DCTSIZE; /* advance pointer to next row */
  175647. continue;
  175648. }
  175649. #endif
  175650. /* Even part */
  175651. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175652. /* Odd part */
  175653. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175654. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175655. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175656. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175657. /* Final output stage */
  175658. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175659. CONST_BITS+PASS1_BITS+3+2)
  175660. & RANGE_MASK];
  175661. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175662. CONST_BITS+PASS1_BITS+3+2)
  175663. & RANGE_MASK];
  175664. wsptr += DCTSIZE; /* advance pointer to next row */
  175665. }
  175666. }
  175667. /*
  175668. * Perform dequantization and inverse DCT on one block of coefficients,
  175669. * producing a reduced-size 1x1 output block.
  175670. */
  175671. GLOBAL(void)
  175672. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175673. JCOEFPTR coef_block,
  175674. JSAMPARRAY output_buf, JDIMENSION output_col)
  175675. {
  175676. int dcval;
  175677. ISLOW_MULT_TYPE * quantptr;
  175678. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175679. SHIFT_TEMPS
  175680. /* We hardly need an inverse DCT routine for this: just take the
  175681. * average pixel value, which is one-eighth of the DC coefficient.
  175682. */
  175683. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175684. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175685. dcval = (int) DESCALE((INT32) dcval, 3);
  175686. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175687. }
  175688. #endif /* IDCT_SCALING_SUPPORTED */
  175689. /*** End of inlined file: jidctred.c ***/
  175690. /*** Start of inlined file: jmemmgr.c ***/
  175691. #define JPEG_INTERNALS
  175692. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175693. /*** Start of inlined file: jmemsys.h ***/
  175694. #ifndef __jmemsys_h__
  175695. #define __jmemsys_h__
  175696. /* Short forms of external names for systems with brain-damaged linkers. */
  175697. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175698. #define jpeg_get_small jGetSmall
  175699. #define jpeg_free_small jFreeSmall
  175700. #define jpeg_get_large jGetLarge
  175701. #define jpeg_free_large jFreeLarge
  175702. #define jpeg_mem_available jMemAvail
  175703. #define jpeg_open_backing_store jOpenBackStore
  175704. #define jpeg_mem_init jMemInit
  175705. #define jpeg_mem_term jMemTerm
  175706. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175707. /*
  175708. * These two functions are used to allocate and release small chunks of
  175709. * memory. (Typically the total amount requested through jpeg_get_small is
  175710. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175711. * Behavior should be the same as for the standard library functions malloc
  175712. * and free; in particular, jpeg_get_small must return NULL on failure.
  175713. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175714. * size of the object being freed, just in case it's needed.
  175715. * On an 80x86 machine using small-data memory model, these manage near heap.
  175716. */
  175717. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175718. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175719. size_t sizeofobject));
  175720. /*
  175721. * These two functions are used to allocate and release large chunks of
  175722. * memory (up to the total free space designated by jpeg_mem_available).
  175723. * The interface is the same as above, except that on an 80x86 machine,
  175724. * far pointers are used. On most other machines these are identical to
  175725. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175726. * in case a different allocation strategy is desirable for large chunks.
  175727. */
  175728. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175729. size_t sizeofobject));
  175730. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175731. size_t sizeofobject));
  175732. /*
  175733. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175734. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175735. * matter, but that case should never come into play). This macro is needed
  175736. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175737. * On those machines, we expect that jconfig.h will provide a proper value.
  175738. * On machines with 32-bit flat address spaces, any large constant may be used.
  175739. *
  175740. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175741. * size_t and will be a multiple of sizeof(align_type).
  175742. */
  175743. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175744. #define MAX_ALLOC_CHUNK 1000000000L
  175745. #endif
  175746. /*
  175747. * This routine computes the total space still available for allocation by
  175748. * jpeg_get_large. If more space than this is needed, backing store will be
  175749. * used. NOTE: any memory already allocated must not be counted.
  175750. *
  175751. * There is a minimum space requirement, corresponding to the minimum
  175752. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175753. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175754. * all working storage in memory, is also passed in case it is useful.
  175755. * Finally, the total space already allocated is passed. If no better
  175756. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175757. * is often a suitable calculation.
  175758. *
  175759. * It is OK for jpeg_mem_available to underestimate the space available
  175760. * (that'll just lead to more backing-store access than is really necessary).
  175761. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175762. * a slop factor from the true available space. 5% should be enough.
  175763. *
  175764. * On machines with lots of virtual memory, any large constant may be returned.
  175765. * Conversely, zero may be returned to always use the minimum amount of memory.
  175766. */
  175767. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175768. long min_bytes_needed,
  175769. long max_bytes_needed,
  175770. long already_allocated));
  175771. /*
  175772. * This structure holds whatever state is needed to access a single
  175773. * backing-store object. The read/write/close method pointers are called
  175774. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175775. * are private to the system-dependent backing store routines.
  175776. */
  175777. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175778. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175779. typedef unsigned short XMSH; /* type of extended-memory handles */
  175780. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175781. typedef union {
  175782. short file_handle; /* DOS file handle if it's a temp file */
  175783. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175784. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175785. } handle_union;
  175786. #endif /* USE_MSDOS_MEMMGR */
  175787. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175788. #include <Files.h>
  175789. #endif /* USE_MAC_MEMMGR */
  175790. //typedef struct backing_store_struct * backing_store_ptr;
  175791. typedef struct backing_store_struct {
  175792. /* Methods for reading/writing/closing this backing-store object */
  175793. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175794. struct backing_store_struct *info,
  175795. void FAR * buffer_address,
  175796. long file_offset, long byte_count));
  175797. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175798. struct backing_store_struct *info,
  175799. void FAR * buffer_address,
  175800. long file_offset, long byte_count));
  175801. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175802. struct backing_store_struct *info));
  175803. /* Private fields for system-dependent backing-store management */
  175804. #ifdef USE_MSDOS_MEMMGR
  175805. /* For the MS-DOS manager (jmemdos.c), we need: */
  175806. handle_union handle; /* reference to backing-store storage object */
  175807. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175808. #else
  175809. #ifdef USE_MAC_MEMMGR
  175810. /* For the Mac manager (jmemmac.c), we need: */
  175811. short temp_file; /* file reference number to temp file */
  175812. FSSpec tempSpec; /* the FSSpec for the temp file */
  175813. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175814. #else
  175815. /* For a typical implementation with temp files, we need: */
  175816. FILE * temp_file; /* stdio reference to temp file */
  175817. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175818. #endif
  175819. #endif
  175820. } backing_store_info;
  175821. /*
  175822. * Initial opening of a backing-store object. This must fill in the
  175823. * read/write/close pointers in the object. The read/write routines
  175824. * may take an error exit if the specified maximum file size is exceeded.
  175825. * (If jpeg_mem_available always returns a large value, this routine can
  175826. * just take an error exit.)
  175827. */
  175828. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175829. struct backing_store_struct *info,
  175830. long total_bytes_needed));
  175831. /*
  175832. * These routines take care of any system-dependent initialization and
  175833. * cleanup required. jpeg_mem_init will be called before anything is
  175834. * allocated (and, therefore, nothing in cinfo is of use except the error
  175835. * manager pointer). It should return a suitable default value for
  175836. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175837. * application. (Note that max_memory_to_use is only important if
  175838. * jpeg_mem_available chooses to consult it ... no one else will.)
  175839. * jpeg_mem_term may assume that all requested memory has been freed and that
  175840. * all opened backing-store objects have been closed.
  175841. */
  175842. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175843. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175844. #endif
  175845. /*** End of inlined file: jmemsys.h ***/
  175846. /* import the system-dependent declarations */
  175847. #ifndef NO_GETENV
  175848. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175849. extern char * getenv JPP((const char * name));
  175850. #endif
  175851. #endif
  175852. /*
  175853. * Some important notes:
  175854. * The allocation routines provided here must never return NULL.
  175855. * They should exit to error_exit if unsuccessful.
  175856. *
  175857. * It's not a good idea to try to merge the sarray and barray routines,
  175858. * even though they are textually almost the same, because samples are
  175859. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175860. * in machines where byte pointers have a different representation from
  175861. * word pointers, the resulting machine code could not be the same.
  175862. */
  175863. /*
  175864. * Many machines require storage alignment: longs must start on 4-byte
  175865. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175866. * always returns pointers that are multiples of the worst-case alignment
  175867. * requirement, and we had better do so too.
  175868. * There isn't any really portable way to determine the worst-case alignment
  175869. * requirement. This module assumes that the alignment requirement is
  175870. * multiples of sizeof(ALIGN_TYPE).
  175871. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175872. * workstations (where doubles really do need 8-byte alignment) and will work
  175873. * fine on nearly everything. If your machine has lesser alignment needs,
  175874. * you can save a few bytes by making ALIGN_TYPE smaller.
  175875. * The only place I know of where this will NOT work is certain Macintosh
  175876. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175877. * Doing 10-byte alignment is counterproductive because longwords won't be
  175878. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175879. * such a compiler.
  175880. */
  175881. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175882. #define ALIGN_TYPE double
  175883. #endif
  175884. /*
  175885. * We allocate objects from "pools", where each pool is gotten with a single
  175886. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175887. * overhead within a pool, except for alignment padding. Each pool has a
  175888. * header with a link to the next pool of the same class.
  175889. * Small and large pool headers are identical except that the latter's
  175890. * link pointer must be FAR on 80x86 machines.
  175891. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175892. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175893. * of the alignment requirement of ALIGN_TYPE.
  175894. */
  175895. typedef union small_pool_struct * small_pool_ptr;
  175896. typedef union small_pool_struct {
  175897. struct {
  175898. small_pool_ptr next; /* next in list of pools */
  175899. size_t bytes_used; /* how many bytes already used within pool */
  175900. size_t bytes_left; /* bytes still available in this pool */
  175901. } hdr;
  175902. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175903. } small_pool_hdr;
  175904. typedef union large_pool_struct FAR * large_pool_ptr;
  175905. typedef union large_pool_struct {
  175906. struct {
  175907. large_pool_ptr next; /* next in list of pools */
  175908. size_t bytes_used; /* how many bytes already used within pool */
  175909. size_t bytes_left; /* bytes still available in this pool */
  175910. } hdr;
  175911. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175912. } large_pool_hdr;
  175913. /*
  175914. * Here is the full definition of a memory manager object.
  175915. */
  175916. typedef struct {
  175917. struct jpeg_memory_mgr pub; /* public fields */
  175918. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175919. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175920. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175921. /* Since we only have one lifetime class of virtual arrays, only one
  175922. * linked list is necessary (for each datatype). Note that the virtual
  175923. * array control blocks being linked together are actually stored somewhere
  175924. * in the small-pool list.
  175925. */
  175926. jvirt_sarray_ptr virt_sarray_list;
  175927. jvirt_barray_ptr virt_barray_list;
  175928. /* This counts total space obtained from jpeg_get_small/large */
  175929. long total_space_allocated;
  175930. /* alloc_sarray and alloc_barray set this value for use by virtual
  175931. * array routines.
  175932. */
  175933. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175934. } my_memory_mgr;
  175935. typedef my_memory_mgr * my_mem_ptr;
  175936. /*
  175937. * The control blocks for virtual arrays.
  175938. * Note that these blocks are allocated in the "small" pool area.
  175939. * System-dependent info for the associated backing store (if any) is hidden
  175940. * inside the backing_store_info struct.
  175941. */
  175942. struct jvirt_sarray_control {
  175943. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175944. JDIMENSION rows_in_array; /* total virtual array height */
  175945. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175946. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175947. JDIMENSION rows_in_mem; /* height of memory buffer */
  175948. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175949. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175950. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175951. boolean pre_zero; /* pre-zero mode requested? */
  175952. boolean dirty; /* do current buffer contents need written? */
  175953. boolean b_s_open; /* is backing-store data valid? */
  175954. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175955. backing_store_info b_s_info; /* System-dependent control info */
  175956. };
  175957. struct jvirt_barray_control {
  175958. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175959. JDIMENSION rows_in_array; /* total virtual array height */
  175960. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175961. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175962. JDIMENSION rows_in_mem; /* height of memory buffer */
  175963. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175964. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175965. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175966. boolean pre_zero; /* pre-zero mode requested? */
  175967. boolean dirty; /* do current buffer contents need written? */
  175968. boolean b_s_open; /* is backing-store data valid? */
  175969. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175970. backing_store_info b_s_info; /* System-dependent control info */
  175971. };
  175972. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175973. LOCAL(void)
  175974. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175975. {
  175976. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175977. small_pool_ptr shdr_ptr;
  175978. large_pool_ptr lhdr_ptr;
  175979. /* Since this is only a debugging stub, we can cheat a little by using
  175980. * fprintf directly rather than going through the trace message code.
  175981. * This is helpful because message parm array can't handle longs.
  175982. */
  175983. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175984. pool_id, mem->total_space_allocated);
  175985. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175986. lhdr_ptr = lhdr_ptr->hdr.next) {
  175987. fprintf(stderr, " Large chunk used %ld\n",
  175988. (long) lhdr_ptr->hdr.bytes_used);
  175989. }
  175990. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175991. shdr_ptr = shdr_ptr->hdr.next) {
  175992. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175993. (long) shdr_ptr->hdr.bytes_used,
  175994. (long) shdr_ptr->hdr.bytes_left);
  175995. }
  175996. }
  175997. #endif /* MEM_STATS */
  175998. LOCAL(void)
  175999. out_of_memory (j_common_ptr cinfo, int which)
  176000. /* Report an out-of-memory error and stop execution */
  176001. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176002. {
  176003. #ifdef MEM_STATS
  176004. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176005. #endif
  176006. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176007. }
  176008. /*
  176009. * Allocation of "small" objects.
  176010. *
  176011. * For these, we use pooled storage. When a new pool must be created,
  176012. * we try to get enough space for the current request plus a "slop" factor,
  176013. * where the slop will be the amount of leftover space in the new pool.
  176014. * The speed vs. space tradeoff is largely determined by the slop values.
  176015. * A different slop value is provided for each pool class (lifetime),
  176016. * and we also distinguish the first pool of a class from later ones.
  176017. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176018. * machines, but may be too small if longs are 64 bits or more.
  176019. */
  176020. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176021. {
  176022. 1600, /* first PERMANENT pool */
  176023. 16000 /* first IMAGE pool */
  176024. };
  176025. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176026. {
  176027. 0, /* additional PERMANENT pools */
  176028. 5000 /* additional IMAGE pools */
  176029. };
  176030. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176031. METHODDEF(void *)
  176032. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176033. /* Allocate a "small" object */
  176034. {
  176035. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176036. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176037. char * data_ptr;
  176038. size_t odd_bytes, min_request, slop;
  176039. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176040. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176041. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176042. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176043. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176044. if (odd_bytes > 0)
  176045. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176046. /* See if space is available in any existing pool */
  176047. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176048. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176049. prev_hdr_ptr = NULL;
  176050. hdr_ptr = mem->small_list[pool_id];
  176051. while (hdr_ptr != NULL) {
  176052. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176053. break; /* found pool with enough space */
  176054. prev_hdr_ptr = hdr_ptr;
  176055. hdr_ptr = hdr_ptr->hdr.next;
  176056. }
  176057. /* Time to make a new pool? */
  176058. if (hdr_ptr == NULL) {
  176059. /* min_request is what we need now, slop is what will be leftover */
  176060. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176061. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176062. slop = first_pool_slop[pool_id];
  176063. else
  176064. slop = extra_pool_slop[pool_id];
  176065. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176066. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176067. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176068. /* Try to get space, if fail reduce slop and try again */
  176069. for (;;) {
  176070. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176071. if (hdr_ptr != NULL)
  176072. break;
  176073. slop /= 2;
  176074. if (slop < MIN_SLOP) /* give up when it gets real small */
  176075. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176076. }
  176077. mem->total_space_allocated += min_request + slop;
  176078. /* Success, initialize the new pool header and add to end of list */
  176079. hdr_ptr->hdr.next = NULL;
  176080. hdr_ptr->hdr.bytes_used = 0;
  176081. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176082. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176083. mem->small_list[pool_id] = hdr_ptr;
  176084. else
  176085. prev_hdr_ptr->hdr.next = hdr_ptr;
  176086. }
  176087. /* OK, allocate the object from the current pool */
  176088. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176089. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176090. hdr_ptr->hdr.bytes_used += sizeofobject;
  176091. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176092. return (void *) data_ptr;
  176093. }
  176094. /*
  176095. * Allocation of "large" objects.
  176096. *
  176097. * The external semantics of these are the same as "small" objects,
  176098. * except that FAR pointers are used on 80x86. However the pool
  176099. * management heuristics are quite different. We assume that each
  176100. * request is large enough that it may as well be passed directly to
  176101. * jpeg_get_large; the pool management just links everything together
  176102. * so that we can free it all on demand.
  176103. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176104. * structures. The routines that create these structures (see below)
  176105. * deliberately bunch rows together to ensure a large request size.
  176106. */
  176107. METHODDEF(void FAR *)
  176108. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176109. /* Allocate a "large" object */
  176110. {
  176111. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176112. large_pool_ptr hdr_ptr;
  176113. size_t odd_bytes;
  176114. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176115. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176116. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176117. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176118. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176119. if (odd_bytes > 0)
  176120. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176121. /* Always make a new pool */
  176122. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176123. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176124. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176125. SIZEOF(large_pool_hdr));
  176126. if (hdr_ptr == NULL)
  176127. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176128. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176129. /* Success, initialize the new pool header and add to list */
  176130. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176131. /* We maintain space counts in each pool header for statistical purposes,
  176132. * even though they are not needed for allocation.
  176133. */
  176134. hdr_ptr->hdr.bytes_used = sizeofobject;
  176135. hdr_ptr->hdr.bytes_left = 0;
  176136. mem->large_list[pool_id] = hdr_ptr;
  176137. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176138. }
  176139. /*
  176140. * Creation of 2-D sample arrays.
  176141. * The pointers are in near heap, the samples themselves in FAR heap.
  176142. *
  176143. * To minimize allocation overhead and to allow I/O of large contiguous
  176144. * blocks, we allocate the sample rows in groups of as many rows as possible
  176145. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176146. * NB: the virtual array control routines, later in this file, know about
  176147. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176148. * object so that it can be saved away if this sarray is the workspace for
  176149. * a virtual array.
  176150. */
  176151. METHODDEF(JSAMPARRAY)
  176152. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176153. JDIMENSION samplesperrow, JDIMENSION numrows)
  176154. /* Allocate a 2-D sample array */
  176155. {
  176156. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176157. JSAMPARRAY result;
  176158. JSAMPROW workspace;
  176159. JDIMENSION rowsperchunk, currow, i;
  176160. long ltemp;
  176161. /* Calculate max # of rows allowed in one allocation chunk */
  176162. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176163. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176164. if (ltemp <= 0)
  176165. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176166. if (ltemp < (long) numrows)
  176167. rowsperchunk = (JDIMENSION) ltemp;
  176168. else
  176169. rowsperchunk = numrows;
  176170. mem->last_rowsperchunk = rowsperchunk;
  176171. /* Get space for row pointers (small object) */
  176172. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176173. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176174. /* Get the rows themselves (large objects) */
  176175. currow = 0;
  176176. while (currow < numrows) {
  176177. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176178. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176179. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176180. * SIZEOF(JSAMPLE)));
  176181. for (i = rowsperchunk; i > 0; i--) {
  176182. result[currow++] = workspace;
  176183. workspace += samplesperrow;
  176184. }
  176185. }
  176186. return result;
  176187. }
  176188. /*
  176189. * Creation of 2-D coefficient-block arrays.
  176190. * This is essentially the same as the code for sample arrays, above.
  176191. */
  176192. METHODDEF(JBLOCKARRAY)
  176193. alloc_barray (j_common_ptr cinfo, int pool_id,
  176194. JDIMENSION blocksperrow, JDIMENSION numrows)
  176195. /* Allocate a 2-D coefficient-block array */
  176196. {
  176197. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176198. JBLOCKARRAY result;
  176199. JBLOCKROW workspace;
  176200. JDIMENSION rowsperchunk, currow, i;
  176201. long ltemp;
  176202. /* Calculate max # of rows allowed in one allocation chunk */
  176203. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176204. ((long) blocksperrow * SIZEOF(JBLOCK));
  176205. if (ltemp <= 0)
  176206. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176207. if (ltemp < (long) numrows)
  176208. rowsperchunk = (JDIMENSION) ltemp;
  176209. else
  176210. rowsperchunk = numrows;
  176211. mem->last_rowsperchunk = rowsperchunk;
  176212. /* Get space for row pointers (small object) */
  176213. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176214. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176215. /* Get the rows themselves (large objects) */
  176216. currow = 0;
  176217. while (currow < numrows) {
  176218. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176219. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176220. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176221. * SIZEOF(JBLOCK)));
  176222. for (i = rowsperchunk; i > 0; i--) {
  176223. result[currow++] = workspace;
  176224. workspace += blocksperrow;
  176225. }
  176226. }
  176227. return result;
  176228. }
  176229. /*
  176230. * About virtual array management:
  176231. *
  176232. * The above "normal" array routines are only used to allocate strip buffers
  176233. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176234. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176235. * time, but the memory manager must save the whole array for repeated
  176236. * accesses. The intended implementation is that there is a strip buffer in
  176237. * memory (as high as is possible given the desired memory limit), plus a
  176238. * backing file that holds the rest of the array.
  176239. *
  176240. * The request_virt_array routines are told the total size of the image and
  176241. * the maximum number of rows that will be accessed at once. The in-memory
  176242. * buffer must be at least as large as the maxaccess value.
  176243. *
  176244. * The request routines create control blocks but not the in-memory buffers.
  176245. * That is postponed until realize_virt_arrays is called. At that time the
  176246. * total amount of space needed is known (approximately, anyway), so free
  176247. * memory can be divided up fairly.
  176248. *
  176249. * The access_virt_array routines are responsible for making a specific strip
  176250. * area accessible (after reading or writing the backing file, if necessary).
  176251. * Note that the access routines are told whether the caller intends to modify
  176252. * the accessed strip; during a read-only pass this saves having to rewrite
  176253. * data to disk. The access routines are also responsible for pre-zeroing
  176254. * any newly accessed rows, if pre-zeroing was requested.
  176255. *
  176256. * In current usage, the access requests are usually for nonoverlapping
  176257. * strips; that is, successive access start_row numbers differ by exactly
  176258. * num_rows = maxaccess. This means we can get good performance with simple
  176259. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176260. * of the access height; then there will never be accesses across bufferload
  176261. * boundaries. The code will still work with overlapping access requests,
  176262. * but it doesn't handle bufferload overlaps very efficiently.
  176263. */
  176264. METHODDEF(jvirt_sarray_ptr)
  176265. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176266. JDIMENSION samplesperrow, JDIMENSION numrows,
  176267. JDIMENSION maxaccess)
  176268. /* Request a virtual 2-D sample array */
  176269. {
  176270. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176271. jvirt_sarray_ptr result;
  176272. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176273. if (pool_id != JPOOL_IMAGE)
  176274. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176275. /* get control block */
  176276. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176277. SIZEOF(struct jvirt_sarray_control));
  176278. result->mem_buffer = NULL; /* marks array not yet realized */
  176279. result->rows_in_array = numrows;
  176280. result->samplesperrow = samplesperrow;
  176281. result->maxaccess = maxaccess;
  176282. result->pre_zero = pre_zero;
  176283. result->b_s_open = FALSE; /* no associated backing-store object */
  176284. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176285. mem->virt_sarray_list = result;
  176286. return result;
  176287. }
  176288. METHODDEF(jvirt_barray_ptr)
  176289. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176290. JDIMENSION blocksperrow, JDIMENSION numrows,
  176291. JDIMENSION maxaccess)
  176292. /* Request a virtual 2-D coefficient-block array */
  176293. {
  176294. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176295. jvirt_barray_ptr result;
  176296. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176297. if (pool_id != JPOOL_IMAGE)
  176298. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176299. /* get control block */
  176300. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176301. SIZEOF(struct jvirt_barray_control));
  176302. result->mem_buffer = NULL; /* marks array not yet realized */
  176303. result->rows_in_array = numrows;
  176304. result->blocksperrow = blocksperrow;
  176305. result->maxaccess = maxaccess;
  176306. result->pre_zero = pre_zero;
  176307. result->b_s_open = FALSE; /* no associated backing-store object */
  176308. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176309. mem->virt_barray_list = result;
  176310. return result;
  176311. }
  176312. METHODDEF(void)
  176313. realize_virt_arrays (j_common_ptr cinfo)
  176314. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176315. {
  176316. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176317. long space_per_minheight, maximum_space, avail_mem;
  176318. long minheights, max_minheights;
  176319. jvirt_sarray_ptr sptr;
  176320. jvirt_barray_ptr bptr;
  176321. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176322. * and the maximum space needed (full image height in each buffer).
  176323. * These may be of use to the system-dependent jpeg_mem_available routine.
  176324. */
  176325. space_per_minheight = 0;
  176326. maximum_space = 0;
  176327. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176328. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176329. space_per_minheight += (long) sptr->maxaccess *
  176330. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176331. maximum_space += (long) sptr->rows_in_array *
  176332. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176333. }
  176334. }
  176335. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176336. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176337. space_per_minheight += (long) bptr->maxaccess *
  176338. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176339. maximum_space += (long) bptr->rows_in_array *
  176340. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176341. }
  176342. }
  176343. if (space_per_minheight <= 0)
  176344. return; /* no unrealized arrays, no work */
  176345. /* Determine amount of memory to actually use; this is system-dependent. */
  176346. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176347. mem->total_space_allocated);
  176348. /* If the maximum space needed is available, make all the buffers full
  176349. * height; otherwise parcel it out with the same number of minheights
  176350. * in each buffer.
  176351. */
  176352. if (avail_mem >= maximum_space)
  176353. max_minheights = 1000000000L;
  176354. else {
  176355. max_minheights = avail_mem / space_per_minheight;
  176356. /* If there doesn't seem to be enough space, try to get the minimum
  176357. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176358. */
  176359. if (max_minheights <= 0)
  176360. max_minheights = 1;
  176361. }
  176362. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176363. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176364. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176365. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176366. if (minheights <= max_minheights) {
  176367. /* This buffer fits in memory */
  176368. sptr->rows_in_mem = sptr->rows_in_array;
  176369. } else {
  176370. /* It doesn't fit in memory, create backing store. */
  176371. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176372. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176373. (long) sptr->rows_in_array *
  176374. (long) sptr->samplesperrow *
  176375. (long) SIZEOF(JSAMPLE));
  176376. sptr->b_s_open = TRUE;
  176377. }
  176378. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176379. sptr->samplesperrow, sptr->rows_in_mem);
  176380. sptr->rowsperchunk = mem->last_rowsperchunk;
  176381. sptr->cur_start_row = 0;
  176382. sptr->first_undef_row = 0;
  176383. sptr->dirty = FALSE;
  176384. }
  176385. }
  176386. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176387. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176388. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176389. if (minheights <= max_minheights) {
  176390. /* This buffer fits in memory */
  176391. bptr->rows_in_mem = bptr->rows_in_array;
  176392. } else {
  176393. /* It doesn't fit in memory, create backing store. */
  176394. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176395. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176396. (long) bptr->rows_in_array *
  176397. (long) bptr->blocksperrow *
  176398. (long) SIZEOF(JBLOCK));
  176399. bptr->b_s_open = TRUE;
  176400. }
  176401. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176402. bptr->blocksperrow, bptr->rows_in_mem);
  176403. bptr->rowsperchunk = mem->last_rowsperchunk;
  176404. bptr->cur_start_row = 0;
  176405. bptr->first_undef_row = 0;
  176406. bptr->dirty = FALSE;
  176407. }
  176408. }
  176409. }
  176410. LOCAL(void)
  176411. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176412. /* Do backing store read or write of a virtual sample array */
  176413. {
  176414. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176415. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176416. file_offset = ptr->cur_start_row * bytesperrow;
  176417. /* Loop to read or write each allocation chunk in mem_buffer */
  176418. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176419. /* One chunk, but check for short chunk at end of buffer */
  176420. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176421. /* Transfer no more than is currently defined */
  176422. thisrow = (long) ptr->cur_start_row + i;
  176423. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176424. /* Transfer no more than fits in file */
  176425. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176426. if (rows <= 0) /* this chunk might be past end of file! */
  176427. break;
  176428. byte_count = rows * bytesperrow;
  176429. if (writing)
  176430. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176431. (void FAR *) ptr->mem_buffer[i],
  176432. file_offset, byte_count);
  176433. else
  176434. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176435. (void FAR *) ptr->mem_buffer[i],
  176436. file_offset, byte_count);
  176437. file_offset += byte_count;
  176438. }
  176439. }
  176440. LOCAL(void)
  176441. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176442. /* Do backing store read or write of a virtual coefficient-block array */
  176443. {
  176444. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176445. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176446. file_offset = ptr->cur_start_row * bytesperrow;
  176447. /* Loop to read or write each allocation chunk in mem_buffer */
  176448. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176449. /* One chunk, but check for short chunk at end of buffer */
  176450. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176451. /* Transfer no more than is currently defined */
  176452. thisrow = (long) ptr->cur_start_row + i;
  176453. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176454. /* Transfer no more than fits in file */
  176455. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176456. if (rows <= 0) /* this chunk might be past end of file! */
  176457. break;
  176458. byte_count = rows * bytesperrow;
  176459. if (writing)
  176460. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176461. (void FAR *) ptr->mem_buffer[i],
  176462. file_offset, byte_count);
  176463. else
  176464. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176465. (void FAR *) ptr->mem_buffer[i],
  176466. file_offset, byte_count);
  176467. file_offset += byte_count;
  176468. }
  176469. }
  176470. METHODDEF(JSAMPARRAY)
  176471. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176472. JDIMENSION start_row, JDIMENSION num_rows,
  176473. boolean writable)
  176474. /* Access the part of a virtual sample array starting at start_row */
  176475. /* and extending for num_rows rows. writable is true if */
  176476. /* caller intends to modify the accessed area. */
  176477. {
  176478. JDIMENSION end_row = start_row + num_rows;
  176479. JDIMENSION undef_row;
  176480. /* debugging check */
  176481. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176482. ptr->mem_buffer == NULL)
  176483. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176484. /* Make the desired part of the virtual array accessible */
  176485. if (start_row < ptr->cur_start_row ||
  176486. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176487. if (! ptr->b_s_open)
  176488. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176489. /* Flush old buffer contents if necessary */
  176490. if (ptr->dirty) {
  176491. do_sarray_io(cinfo, ptr, TRUE);
  176492. ptr->dirty = FALSE;
  176493. }
  176494. /* Decide what part of virtual array to access.
  176495. * Algorithm: if target address > current window, assume forward scan,
  176496. * load starting at target address. If target address < current window,
  176497. * assume backward scan, load so that target area is top of window.
  176498. * Note that when switching from forward write to forward read, will have
  176499. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176500. */
  176501. if (start_row > ptr->cur_start_row) {
  176502. ptr->cur_start_row = start_row;
  176503. } else {
  176504. /* use long arithmetic here to avoid overflow & unsigned problems */
  176505. long ltemp;
  176506. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176507. if (ltemp < 0)
  176508. ltemp = 0; /* don't fall off front end of file */
  176509. ptr->cur_start_row = (JDIMENSION) ltemp;
  176510. }
  176511. /* Read in the selected part of the array.
  176512. * During the initial write pass, we will do no actual read
  176513. * because the selected part is all undefined.
  176514. */
  176515. do_sarray_io(cinfo, ptr, FALSE);
  176516. }
  176517. /* Ensure the accessed part of the array is defined; prezero if needed.
  176518. * To improve locality of access, we only prezero the part of the array
  176519. * that the caller is about to access, not the entire in-memory array.
  176520. */
  176521. if (ptr->first_undef_row < end_row) {
  176522. if (ptr->first_undef_row < start_row) {
  176523. if (writable) /* writer skipped over a section of array */
  176524. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176525. undef_row = start_row; /* but reader is allowed to read ahead */
  176526. } else {
  176527. undef_row = ptr->first_undef_row;
  176528. }
  176529. if (writable)
  176530. ptr->first_undef_row = end_row;
  176531. if (ptr->pre_zero) {
  176532. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176533. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176534. end_row -= ptr->cur_start_row;
  176535. while (undef_row < end_row) {
  176536. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176537. undef_row++;
  176538. }
  176539. } else {
  176540. if (! writable) /* reader looking at undefined data */
  176541. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176542. }
  176543. }
  176544. /* Flag the buffer dirty if caller will write in it */
  176545. if (writable)
  176546. ptr->dirty = TRUE;
  176547. /* Return address of proper part of the buffer */
  176548. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176549. }
  176550. METHODDEF(JBLOCKARRAY)
  176551. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176552. JDIMENSION start_row, JDIMENSION num_rows,
  176553. boolean writable)
  176554. /* Access the part of a virtual block array starting at start_row */
  176555. /* and extending for num_rows rows. writable is true if */
  176556. /* caller intends to modify the accessed area. */
  176557. {
  176558. JDIMENSION end_row = start_row + num_rows;
  176559. JDIMENSION undef_row;
  176560. /* debugging check */
  176561. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176562. ptr->mem_buffer == NULL)
  176563. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176564. /* Make the desired part of the virtual array accessible */
  176565. if (start_row < ptr->cur_start_row ||
  176566. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176567. if (! ptr->b_s_open)
  176568. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176569. /* Flush old buffer contents if necessary */
  176570. if (ptr->dirty) {
  176571. do_barray_io(cinfo, ptr, TRUE);
  176572. ptr->dirty = FALSE;
  176573. }
  176574. /* Decide what part of virtual array to access.
  176575. * Algorithm: if target address > current window, assume forward scan,
  176576. * load starting at target address. If target address < current window,
  176577. * assume backward scan, load so that target area is top of window.
  176578. * Note that when switching from forward write to forward read, will have
  176579. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176580. */
  176581. if (start_row > ptr->cur_start_row) {
  176582. ptr->cur_start_row = start_row;
  176583. } else {
  176584. /* use long arithmetic here to avoid overflow & unsigned problems */
  176585. long ltemp;
  176586. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176587. if (ltemp < 0)
  176588. ltemp = 0; /* don't fall off front end of file */
  176589. ptr->cur_start_row = (JDIMENSION) ltemp;
  176590. }
  176591. /* Read in the selected part of the array.
  176592. * During the initial write pass, we will do no actual read
  176593. * because the selected part is all undefined.
  176594. */
  176595. do_barray_io(cinfo, ptr, FALSE);
  176596. }
  176597. /* Ensure the accessed part of the array is defined; prezero if needed.
  176598. * To improve locality of access, we only prezero the part of the array
  176599. * that the caller is about to access, not the entire in-memory array.
  176600. */
  176601. if (ptr->first_undef_row < end_row) {
  176602. if (ptr->first_undef_row < start_row) {
  176603. if (writable) /* writer skipped over a section of array */
  176604. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176605. undef_row = start_row; /* but reader is allowed to read ahead */
  176606. } else {
  176607. undef_row = ptr->first_undef_row;
  176608. }
  176609. if (writable)
  176610. ptr->first_undef_row = end_row;
  176611. if (ptr->pre_zero) {
  176612. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176613. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176614. end_row -= ptr->cur_start_row;
  176615. while (undef_row < end_row) {
  176616. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176617. undef_row++;
  176618. }
  176619. } else {
  176620. if (! writable) /* reader looking at undefined data */
  176621. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176622. }
  176623. }
  176624. /* Flag the buffer dirty if caller will write in it */
  176625. if (writable)
  176626. ptr->dirty = TRUE;
  176627. /* Return address of proper part of the buffer */
  176628. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176629. }
  176630. /*
  176631. * Release all objects belonging to a specified pool.
  176632. */
  176633. METHODDEF(void)
  176634. free_pool (j_common_ptr cinfo, int pool_id)
  176635. {
  176636. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176637. small_pool_ptr shdr_ptr;
  176638. large_pool_ptr lhdr_ptr;
  176639. size_t space_freed;
  176640. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176641. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176642. #ifdef MEM_STATS
  176643. if (cinfo->err->trace_level > 1)
  176644. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176645. #endif
  176646. /* If freeing IMAGE pool, close any virtual arrays first */
  176647. if (pool_id == JPOOL_IMAGE) {
  176648. jvirt_sarray_ptr sptr;
  176649. jvirt_barray_ptr bptr;
  176650. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176651. if (sptr->b_s_open) { /* there may be no backing store */
  176652. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176653. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176654. }
  176655. }
  176656. mem->virt_sarray_list = NULL;
  176657. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176658. if (bptr->b_s_open) { /* there may be no backing store */
  176659. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176660. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176661. }
  176662. }
  176663. mem->virt_barray_list = NULL;
  176664. }
  176665. /* Release large objects */
  176666. lhdr_ptr = mem->large_list[pool_id];
  176667. mem->large_list[pool_id] = NULL;
  176668. while (lhdr_ptr != NULL) {
  176669. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176670. space_freed = lhdr_ptr->hdr.bytes_used +
  176671. lhdr_ptr->hdr.bytes_left +
  176672. SIZEOF(large_pool_hdr);
  176673. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176674. mem->total_space_allocated -= space_freed;
  176675. lhdr_ptr = next_lhdr_ptr;
  176676. }
  176677. /* Release small objects */
  176678. shdr_ptr = mem->small_list[pool_id];
  176679. mem->small_list[pool_id] = NULL;
  176680. while (shdr_ptr != NULL) {
  176681. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176682. space_freed = shdr_ptr->hdr.bytes_used +
  176683. shdr_ptr->hdr.bytes_left +
  176684. SIZEOF(small_pool_hdr);
  176685. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176686. mem->total_space_allocated -= space_freed;
  176687. shdr_ptr = next_shdr_ptr;
  176688. }
  176689. }
  176690. /*
  176691. * Close up shop entirely.
  176692. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176693. */
  176694. METHODDEF(void)
  176695. self_destruct (j_common_ptr cinfo)
  176696. {
  176697. int pool;
  176698. /* Close all backing store, release all memory.
  176699. * Releasing pools in reverse order might help avoid fragmentation
  176700. * with some (brain-damaged) malloc libraries.
  176701. */
  176702. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176703. free_pool(cinfo, pool);
  176704. }
  176705. /* Release the memory manager control block too. */
  176706. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176707. cinfo->mem = NULL; /* ensures I will be called only once */
  176708. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176709. }
  176710. /*
  176711. * Memory manager initialization.
  176712. * When this is called, only the error manager pointer is valid in cinfo!
  176713. */
  176714. GLOBAL(void)
  176715. jinit_memory_mgr (j_common_ptr cinfo)
  176716. {
  176717. my_mem_ptr mem;
  176718. long max_to_use;
  176719. int pool;
  176720. size_t test_mac;
  176721. cinfo->mem = NULL; /* for safety if init fails */
  176722. /* Check for configuration errors.
  176723. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176724. * doesn't reflect any real hardware alignment requirement.
  176725. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176726. * in common if and only if X is a power of 2, ie has only one one-bit.
  176727. * Some compilers may give an "unreachable code" warning here; ignore it.
  176728. */
  176729. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176730. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176731. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176732. * a multiple of SIZEOF(ALIGN_TYPE).
  176733. * Again, an "unreachable code" warning may be ignored here.
  176734. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176735. */
  176736. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176737. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176738. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176739. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176740. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176741. /* Attempt to allocate memory manager's control block */
  176742. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176743. if (mem == NULL) {
  176744. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176745. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176746. }
  176747. /* OK, fill in the method pointers */
  176748. mem->pub.alloc_small = alloc_small;
  176749. mem->pub.alloc_large = alloc_large;
  176750. mem->pub.alloc_sarray = alloc_sarray;
  176751. mem->pub.alloc_barray = alloc_barray;
  176752. mem->pub.request_virt_sarray = request_virt_sarray;
  176753. mem->pub.request_virt_barray = request_virt_barray;
  176754. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176755. mem->pub.access_virt_sarray = access_virt_sarray;
  176756. mem->pub.access_virt_barray = access_virt_barray;
  176757. mem->pub.free_pool = free_pool;
  176758. mem->pub.self_destruct = self_destruct;
  176759. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176760. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176761. /* Initialize working state */
  176762. mem->pub.max_memory_to_use = max_to_use;
  176763. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176764. mem->small_list[pool] = NULL;
  176765. mem->large_list[pool] = NULL;
  176766. }
  176767. mem->virt_sarray_list = NULL;
  176768. mem->virt_barray_list = NULL;
  176769. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176770. /* Declare ourselves open for business */
  176771. cinfo->mem = & mem->pub;
  176772. /* Check for an environment variable JPEGMEM; if found, override the
  176773. * default max_memory setting from jpeg_mem_init. Note that the
  176774. * surrounding application may again override this value.
  176775. * If your system doesn't support getenv(), define NO_GETENV to disable
  176776. * this feature.
  176777. */
  176778. #ifndef NO_GETENV
  176779. { char * memenv;
  176780. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176781. char ch = 'x';
  176782. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176783. if (ch == 'm' || ch == 'M')
  176784. max_to_use *= 1000L;
  176785. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176786. }
  176787. }
  176788. }
  176789. #endif
  176790. }
  176791. /*** End of inlined file: jmemmgr.c ***/
  176792. /*** Start of inlined file: jmemnobs.c ***/
  176793. #define JPEG_INTERNALS
  176794. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176795. extern void * malloc JPP((size_t size));
  176796. extern void free JPP((void *ptr));
  176797. #endif
  176798. /*
  176799. * Memory allocation and freeing are controlled by the regular library
  176800. * routines malloc() and free().
  176801. */
  176802. GLOBAL(void *)
  176803. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176804. {
  176805. return (void *) malloc(sizeofobject);
  176806. }
  176807. GLOBAL(void)
  176808. jpeg_free_small (j_common_ptr , void * object, size_t)
  176809. {
  176810. free(object);
  176811. }
  176812. /*
  176813. * "Large" objects are treated the same as "small" ones.
  176814. * NB: although we include FAR keywords in the routine declarations,
  176815. * this file won't actually work in 80x86 small/medium model; at least,
  176816. * you probably won't be able to process useful-size images in only 64KB.
  176817. */
  176818. GLOBAL(void FAR *)
  176819. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176820. {
  176821. return (void FAR *) malloc(sizeofobject);
  176822. }
  176823. GLOBAL(void)
  176824. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176825. {
  176826. free(object);
  176827. }
  176828. /*
  176829. * This routine computes the total memory space available for allocation.
  176830. * Here we always say, "we got all you want bud!"
  176831. */
  176832. GLOBAL(long)
  176833. jpeg_mem_available (j_common_ptr, long,
  176834. long max_bytes_needed, long)
  176835. {
  176836. return max_bytes_needed;
  176837. }
  176838. /*
  176839. * Backing store (temporary file) management.
  176840. * Since jpeg_mem_available always promised the moon,
  176841. * this should never be called and we can just error out.
  176842. */
  176843. GLOBAL(void)
  176844. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176845. long )
  176846. {
  176847. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176848. }
  176849. /*
  176850. * These routines take care of any system-dependent initialization and
  176851. * cleanup required. Here, there isn't any.
  176852. */
  176853. GLOBAL(long)
  176854. jpeg_mem_init (j_common_ptr)
  176855. {
  176856. return 0; /* just set max_memory_to_use to 0 */
  176857. }
  176858. GLOBAL(void)
  176859. jpeg_mem_term (j_common_ptr)
  176860. {
  176861. /* no work */
  176862. }
  176863. /*** End of inlined file: jmemnobs.c ***/
  176864. /*** Start of inlined file: jquant1.c ***/
  176865. #define JPEG_INTERNALS
  176866. #ifdef QUANT_1PASS_SUPPORTED
  176867. /*
  176868. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176869. * high quality, colormapped output capability. A 2-pass quantizer usually
  176870. * gives better visual quality; however, for quantized grayscale output this
  176871. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176872. * quantizer, though you can turn it off if you really want to.
  176873. *
  176874. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176875. * image. We use a map consisting of all combinations of Ncolors[i] color
  176876. * values for the i'th component. The Ncolors[] values are chosen so that
  176877. * their product, the total number of colors, is no more than that requested.
  176878. * (In most cases, the product will be somewhat less.)
  176879. *
  176880. * Since the colormap is orthogonal, the representative value for each color
  176881. * component can be determined without considering the other components;
  176882. * then these indexes can be combined into a colormap index by a standard
  176883. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176884. * can be precalculated and stored in the lookup table colorindex[].
  176885. * colorindex[i][j] maps pixel value j in component i to the nearest
  176886. * representative value (grid plane) for that component; this index is
  176887. * multiplied by the array stride for component i, so that the
  176888. * index of the colormap entry closest to a given pixel value is just
  176889. * sum( colorindex[component-number][pixel-component-value] )
  176890. * Aside from being fast, this scheme allows for variable spacing between
  176891. * representative values with no additional lookup cost.
  176892. *
  176893. * If gamma correction has been applied in color conversion, it might be wise
  176894. * to adjust the color grid spacing so that the representative colors are
  176895. * equidistant in linear space. At this writing, gamma correction is not
  176896. * implemented by jdcolor, so nothing is done here.
  176897. */
  176898. /* Declarations for ordered dithering.
  176899. *
  176900. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176901. * dithering is described in many references, for instance Dale Schumacher's
  176902. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176903. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176904. * "dither" value to the input pixel and then round the result to the nearest
  176905. * output value. The dither value is equivalent to (0.5 - threshold) times
  176906. * the distance between output values. For ordered dithering, we assume that
  176907. * the output colors are equally spaced; if not, results will probably be
  176908. * worse, since the dither may be too much or too little at a given point.
  176909. *
  176910. * The normal calculation would be to form pixel value + dither, range-limit
  176911. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176912. * We can skip the separate range-limiting step by extending the colorindex
  176913. * table in both directions.
  176914. */
  176915. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176916. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176917. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176918. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176919. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176920. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176921. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176922. /* Bayer's order-4 dither array. Generated by the code given in
  176923. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176924. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176925. */
  176926. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176927. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176928. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176929. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176930. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176931. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176932. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176933. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176934. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176935. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176936. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176937. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176938. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176939. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176940. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176941. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176942. };
  176943. /* Declarations for Floyd-Steinberg dithering.
  176944. *
  176945. * Errors are accumulated into the array fserrors[], at a resolution of
  176946. * 1/16th of a pixel count. The error at a given pixel is propagated
  176947. * to its not-yet-processed neighbors using the standard F-S fractions,
  176948. * ... (here) 7/16
  176949. * 3/16 5/16 1/16
  176950. * We work left-to-right on even rows, right-to-left on odd rows.
  176951. *
  176952. * We can get away with a single array (holding one row's worth of errors)
  176953. * by using it to store the current row's errors at pixel columns not yet
  176954. * processed, but the next row's errors at columns already processed. We
  176955. * need only a few extra variables to hold the errors immediately around the
  176956. * current column. (If we are lucky, those variables are in registers, but
  176957. * even if not, they're probably cheaper to access than array elements are.)
  176958. *
  176959. * The fserrors[] array is indexed [component#][position].
  176960. * We provide (#columns + 2) entries per component; the extra entry at each
  176961. * end saves us from special-casing the first and last pixels.
  176962. *
  176963. * Note: on a wide image, we might not have enough room in a PC's near data
  176964. * segment to hold the error array; so it is allocated with alloc_large.
  176965. */
  176966. #if BITS_IN_JSAMPLE == 8
  176967. typedef INT16 FSERROR; /* 16 bits should be enough */
  176968. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176969. #else
  176970. typedef INT32 FSERROR; /* may need more than 16 bits */
  176971. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176972. #endif
  176973. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176974. /* Private subobject */
  176975. #define MAX_Q_COMPS 4 /* max components I can handle */
  176976. typedef struct {
  176977. struct jpeg_color_quantizer pub; /* public fields */
  176978. /* Initially allocated colormap is saved here */
  176979. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176980. int sv_actual; /* number of entries in use */
  176981. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176982. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176983. * premultiplied as described above. Since colormap indexes must fit into
  176984. * JSAMPLEs, the entries of this array will too.
  176985. */
  176986. boolean is_padded; /* is the colorindex padded for odither? */
  176987. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176988. /* Variables for ordered dithering */
  176989. int row_index; /* cur row's vertical index in dither matrix */
  176990. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176991. /* Variables for Floyd-Steinberg dithering */
  176992. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176993. boolean on_odd_row; /* flag to remember which row we are on */
  176994. } my_cquantizer;
  176995. typedef my_cquantizer * my_cquantize_ptr;
  176996. /*
  176997. * Policy-making subroutines for create_colormap and create_colorindex.
  176998. * These routines determine the colormap to be used. The rest of the module
  176999. * only assumes that the colormap is orthogonal.
  177000. *
  177001. * * select_ncolors decides how to divvy up the available colors
  177002. * among the components.
  177003. * * output_value defines the set of representative values for a component.
  177004. * * largest_input_value defines the mapping from input values to
  177005. * representative values for a component.
  177006. * Note that the latter two routines may impose different policies for
  177007. * different components, though this is not currently done.
  177008. */
  177009. LOCAL(int)
  177010. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177011. /* Determine allocation of desired colors to components, */
  177012. /* and fill in Ncolors[] array to indicate choice. */
  177013. /* Return value is total number of colors (product of Ncolors[] values). */
  177014. {
  177015. int nc = cinfo->out_color_components; /* number of color components */
  177016. int max_colors = cinfo->desired_number_of_colors;
  177017. int total_colors, iroot, i, j;
  177018. boolean changed;
  177019. long temp;
  177020. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177021. /* We can allocate at least the nc'th root of max_colors per component. */
  177022. /* Compute floor(nc'th root of max_colors). */
  177023. iroot = 1;
  177024. do {
  177025. iroot++;
  177026. temp = iroot; /* set temp = iroot ** nc */
  177027. for (i = 1; i < nc; i++)
  177028. temp *= iroot;
  177029. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177030. iroot--; /* now iroot = floor(root) */
  177031. /* Must have at least 2 color values per component */
  177032. if (iroot < 2)
  177033. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177034. /* Initialize to iroot color values for each component */
  177035. total_colors = 1;
  177036. for (i = 0; i < nc; i++) {
  177037. Ncolors[i] = iroot;
  177038. total_colors *= iroot;
  177039. }
  177040. /* We may be able to increment the count for one or more components without
  177041. * exceeding max_colors, though we know not all can be incremented.
  177042. * Sometimes, the first component can be incremented more than once!
  177043. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177044. * In RGB colorspace, try to increment G first, then R, then B.
  177045. */
  177046. do {
  177047. changed = FALSE;
  177048. for (i = 0; i < nc; i++) {
  177049. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177050. /* calculate new total_colors if Ncolors[j] is incremented */
  177051. temp = total_colors / Ncolors[j];
  177052. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177053. if (temp > (long) max_colors)
  177054. break; /* won't fit, done with this pass */
  177055. Ncolors[j]++; /* OK, apply the increment */
  177056. total_colors = (int) temp;
  177057. changed = TRUE;
  177058. }
  177059. } while (changed);
  177060. return total_colors;
  177061. }
  177062. LOCAL(int)
  177063. output_value (j_decompress_ptr, int, int j, int maxj)
  177064. /* Return j'th output value, where j will range from 0 to maxj */
  177065. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177066. {
  177067. /* We always provide values 0 and MAXJSAMPLE for each component;
  177068. * any additional values are equally spaced between these limits.
  177069. * (Forcing the upper and lower values to the limits ensures that
  177070. * dithering can't produce a color outside the selected gamut.)
  177071. */
  177072. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177073. }
  177074. LOCAL(int)
  177075. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177076. /* Return largest input value that should map to j'th output value */
  177077. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177078. {
  177079. /* Breakpoints are halfway between values returned by output_value */
  177080. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177081. }
  177082. /*
  177083. * Create the colormap.
  177084. */
  177085. LOCAL(void)
  177086. create_colormap (j_decompress_ptr cinfo)
  177087. {
  177088. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177089. JSAMPARRAY colormap; /* Created colormap */
  177090. int total_colors; /* Number of distinct output colors */
  177091. int i,j,k, nci, blksize, blkdist, ptr, val;
  177092. /* Select number of colors for each component */
  177093. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177094. /* Report selected color counts */
  177095. if (cinfo->out_color_components == 3)
  177096. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177097. total_colors, cquantize->Ncolors[0],
  177098. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177099. else
  177100. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177101. /* Allocate and fill in the colormap. */
  177102. /* The colors are ordered in the map in standard row-major order, */
  177103. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177104. colormap = (*cinfo->mem->alloc_sarray)
  177105. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177106. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177107. /* blksize is number of adjacent repeated entries for a component */
  177108. /* blkdist is distance between groups of identical entries for a component */
  177109. blkdist = total_colors;
  177110. for (i = 0; i < cinfo->out_color_components; i++) {
  177111. /* fill in colormap entries for i'th color component */
  177112. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177113. blksize = blkdist / nci;
  177114. for (j = 0; j < nci; j++) {
  177115. /* Compute j'th output value (out of nci) for component */
  177116. val = output_value(cinfo, i, j, nci-1);
  177117. /* Fill in all colormap entries that have this value of this component */
  177118. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177119. /* fill in blksize entries beginning at ptr */
  177120. for (k = 0; k < blksize; k++)
  177121. colormap[i][ptr+k] = (JSAMPLE) val;
  177122. }
  177123. }
  177124. blkdist = blksize; /* blksize of this color is blkdist of next */
  177125. }
  177126. /* Save the colormap in private storage,
  177127. * where it will survive color quantization mode changes.
  177128. */
  177129. cquantize->sv_colormap = colormap;
  177130. cquantize->sv_actual = total_colors;
  177131. }
  177132. /*
  177133. * Create the color index table.
  177134. */
  177135. LOCAL(void)
  177136. create_colorindex (j_decompress_ptr cinfo)
  177137. {
  177138. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177139. JSAMPROW indexptr;
  177140. int i,j,k, nci, blksize, val, pad;
  177141. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177142. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177143. * This is not necessary in the other dithering modes. However, we
  177144. * flag whether it was done in case user changes dithering mode.
  177145. */
  177146. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177147. pad = MAXJSAMPLE*2;
  177148. cquantize->is_padded = TRUE;
  177149. } else {
  177150. pad = 0;
  177151. cquantize->is_padded = FALSE;
  177152. }
  177153. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177154. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177155. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177156. (JDIMENSION) cinfo->out_color_components);
  177157. /* blksize is number of adjacent repeated entries for a component */
  177158. blksize = cquantize->sv_actual;
  177159. for (i = 0; i < cinfo->out_color_components; i++) {
  177160. /* fill in colorindex entries for i'th color component */
  177161. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177162. blksize = blksize / nci;
  177163. /* adjust colorindex pointers to provide padding at negative indexes. */
  177164. if (pad)
  177165. cquantize->colorindex[i] += MAXJSAMPLE;
  177166. /* in loop, val = index of current output value, */
  177167. /* and k = largest j that maps to current val */
  177168. indexptr = cquantize->colorindex[i];
  177169. val = 0;
  177170. k = largest_input_value(cinfo, i, 0, nci-1);
  177171. for (j = 0; j <= MAXJSAMPLE; j++) {
  177172. while (j > k) /* advance val if past boundary */
  177173. k = largest_input_value(cinfo, i, ++val, nci-1);
  177174. /* premultiply so that no multiplication needed in main processing */
  177175. indexptr[j] = (JSAMPLE) (val * blksize);
  177176. }
  177177. /* Pad at both ends if necessary */
  177178. if (pad)
  177179. for (j = 1; j <= MAXJSAMPLE; j++) {
  177180. indexptr[-j] = indexptr[0];
  177181. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177182. }
  177183. }
  177184. }
  177185. /*
  177186. * Create an ordered-dither array for a component having ncolors
  177187. * distinct output values.
  177188. */
  177189. LOCAL(ODITHER_MATRIX_PTR)
  177190. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177191. {
  177192. ODITHER_MATRIX_PTR odither;
  177193. int j,k;
  177194. INT32 num,den;
  177195. odither = (ODITHER_MATRIX_PTR)
  177196. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177197. SIZEOF(ODITHER_MATRIX));
  177198. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177199. * Hence the dither value for the matrix cell with fill order f
  177200. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177201. * On 16-bit-int machine, be careful to avoid overflow.
  177202. */
  177203. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177204. for (j = 0; j < ODITHER_SIZE; j++) {
  177205. for (k = 0; k < ODITHER_SIZE; k++) {
  177206. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177207. * MAXJSAMPLE;
  177208. /* Ensure round towards zero despite C's lack of consistency
  177209. * about rounding negative values in integer division...
  177210. */
  177211. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177212. }
  177213. }
  177214. return odither;
  177215. }
  177216. /*
  177217. * Create the ordered-dither tables.
  177218. * Components having the same number of representative colors may
  177219. * share a dither table.
  177220. */
  177221. LOCAL(void)
  177222. create_odither_tables (j_decompress_ptr cinfo)
  177223. {
  177224. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177225. ODITHER_MATRIX_PTR odither;
  177226. int i, j, nci;
  177227. for (i = 0; i < cinfo->out_color_components; i++) {
  177228. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177229. odither = NULL; /* search for matching prior component */
  177230. for (j = 0; j < i; j++) {
  177231. if (nci == cquantize->Ncolors[j]) {
  177232. odither = cquantize->odither[j];
  177233. break;
  177234. }
  177235. }
  177236. if (odither == NULL) /* need a new table? */
  177237. odither = make_odither_array(cinfo, nci);
  177238. cquantize->odither[i] = odither;
  177239. }
  177240. }
  177241. /*
  177242. * Map some rows of pixels to the output colormapped representation.
  177243. */
  177244. METHODDEF(void)
  177245. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177246. JSAMPARRAY output_buf, int num_rows)
  177247. /* General case, no dithering */
  177248. {
  177249. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177250. JSAMPARRAY colorindex = cquantize->colorindex;
  177251. register int pixcode, ci;
  177252. register JSAMPROW ptrin, ptrout;
  177253. int row;
  177254. JDIMENSION col;
  177255. JDIMENSION width = cinfo->output_width;
  177256. register int nc = cinfo->out_color_components;
  177257. for (row = 0; row < num_rows; row++) {
  177258. ptrin = input_buf[row];
  177259. ptrout = output_buf[row];
  177260. for (col = width; col > 0; col--) {
  177261. pixcode = 0;
  177262. for (ci = 0; ci < nc; ci++) {
  177263. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177264. }
  177265. *ptrout++ = (JSAMPLE) pixcode;
  177266. }
  177267. }
  177268. }
  177269. METHODDEF(void)
  177270. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177271. JSAMPARRAY output_buf, int num_rows)
  177272. /* Fast path for out_color_components==3, no dithering */
  177273. {
  177274. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177275. register int pixcode;
  177276. register JSAMPROW ptrin, ptrout;
  177277. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177278. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177279. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177280. int row;
  177281. JDIMENSION col;
  177282. JDIMENSION width = cinfo->output_width;
  177283. for (row = 0; row < num_rows; row++) {
  177284. ptrin = input_buf[row];
  177285. ptrout = output_buf[row];
  177286. for (col = width; col > 0; col--) {
  177287. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177288. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177289. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177290. *ptrout++ = (JSAMPLE) pixcode;
  177291. }
  177292. }
  177293. }
  177294. METHODDEF(void)
  177295. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177296. JSAMPARRAY output_buf, int num_rows)
  177297. /* General case, with ordered dithering */
  177298. {
  177299. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177300. register JSAMPROW input_ptr;
  177301. register JSAMPROW output_ptr;
  177302. JSAMPROW colorindex_ci;
  177303. int * dither; /* points to active row of dither matrix */
  177304. int row_index, col_index; /* current indexes into dither matrix */
  177305. int nc = cinfo->out_color_components;
  177306. int ci;
  177307. int row;
  177308. JDIMENSION col;
  177309. JDIMENSION width = cinfo->output_width;
  177310. for (row = 0; row < num_rows; row++) {
  177311. /* Initialize output values to 0 so can process components separately */
  177312. jzero_far((void FAR *) output_buf[row],
  177313. (size_t) (width * SIZEOF(JSAMPLE)));
  177314. row_index = cquantize->row_index;
  177315. for (ci = 0; ci < nc; ci++) {
  177316. input_ptr = input_buf[row] + ci;
  177317. output_ptr = output_buf[row];
  177318. colorindex_ci = cquantize->colorindex[ci];
  177319. dither = cquantize->odither[ci][row_index];
  177320. col_index = 0;
  177321. for (col = width; col > 0; col--) {
  177322. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177323. * select output value, accumulate into output code for this pixel.
  177324. * Range-limiting need not be done explicitly, as we have extended
  177325. * the colorindex table to produce the right answers for out-of-range
  177326. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177327. * required amount of padding.
  177328. */
  177329. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177330. input_ptr += nc;
  177331. output_ptr++;
  177332. col_index = (col_index + 1) & ODITHER_MASK;
  177333. }
  177334. }
  177335. /* Advance row index for next row */
  177336. row_index = (row_index + 1) & ODITHER_MASK;
  177337. cquantize->row_index = row_index;
  177338. }
  177339. }
  177340. METHODDEF(void)
  177341. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177342. JSAMPARRAY output_buf, int num_rows)
  177343. /* Fast path for out_color_components==3, with ordered dithering */
  177344. {
  177345. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177346. register int pixcode;
  177347. register JSAMPROW input_ptr;
  177348. register JSAMPROW output_ptr;
  177349. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177350. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177351. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177352. int * dither0; /* points to active row of dither matrix */
  177353. int * dither1;
  177354. int * dither2;
  177355. int row_index, col_index; /* current indexes into dither matrix */
  177356. int row;
  177357. JDIMENSION col;
  177358. JDIMENSION width = cinfo->output_width;
  177359. for (row = 0; row < num_rows; row++) {
  177360. row_index = cquantize->row_index;
  177361. input_ptr = input_buf[row];
  177362. output_ptr = output_buf[row];
  177363. dither0 = cquantize->odither[0][row_index];
  177364. dither1 = cquantize->odither[1][row_index];
  177365. dither2 = cquantize->odither[2][row_index];
  177366. col_index = 0;
  177367. for (col = width; col > 0; col--) {
  177368. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177369. dither0[col_index]]);
  177370. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177371. dither1[col_index]]);
  177372. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177373. dither2[col_index]]);
  177374. *output_ptr++ = (JSAMPLE) pixcode;
  177375. col_index = (col_index + 1) & ODITHER_MASK;
  177376. }
  177377. row_index = (row_index + 1) & ODITHER_MASK;
  177378. cquantize->row_index = row_index;
  177379. }
  177380. }
  177381. METHODDEF(void)
  177382. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177383. JSAMPARRAY output_buf, int num_rows)
  177384. /* General case, with Floyd-Steinberg dithering */
  177385. {
  177386. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177387. register LOCFSERROR cur; /* current error or pixel value */
  177388. LOCFSERROR belowerr; /* error for pixel below cur */
  177389. LOCFSERROR bpreverr; /* error for below/prev col */
  177390. LOCFSERROR bnexterr; /* error for below/next col */
  177391. LOCFSERROR delta;
  177392. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177393. register JSAMPROW input_ptr;
  177394. register JSAMPROW output_ptr;
  177395. JSAMPROW colorindex_ci;
  177396. JSAMPROW colormap_ci;
  177397. int pixcode;
  177398. int nc = cinfo->out_color_components;
  177399. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177400. int dirnc; /* dir * nc */
  177401. int ci;
  177402. int row;
  177403. JDIMENSION col;
  177404. JDIMENSION width = cinfo->output_width;
  177405. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177406. SHIFT_TEMPS
  177407. for (row = 0; row < num_rows; row++) {
  177408. /* Initialize output values to 0 so can process components separately */
  177409. jzero_far((void FAR *) output_buf[row],
  177410. (size_t) (width * SIZEOF(JSAMPLE)));
  177411. for (ci = 0; ci < nc; ci++) {
  177412. input_ptr = input_buf[row] + ci;
  177413. output_ptr = output_buf[row];
  177414. if (cquantize->on_odd_row) {
  177415. /* work right to left in this row */
  177416. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177417. output_ptr += width-1;
  177418. dir = -1;
  177419. dirnc = -nc;
  177420. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177421. } else {
  177422. /* work left to right in this row */
  177423. dir = 1;
  177424. dirnc = nc;
  177425. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177426. }
  177427. colorindex_ci = cquantize->colorindex[ci];
  177428. colormap_ci = cquantize->sv_colormap[ci];
  177429. /* Preset error values: no error propagated to first pixel from left */
  177430. cur = 0;
  177431. /* and no error propagated to row below yet */
  177432. belowerr = bpreverr = 0;
  177433. for (col = width; col > 0; col--) {
  177434. /* cur holds the error propagated from the previous pixel on the
  177435. * current line. Add the error propagated from the previous line
  177436. * to form the complete error correction term for this pixel, and
  177437. * round the error term (which is expressed * 16) to an integer.
  177438. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177439. * for either sign of the error value.
  177440. * Note: errorptr points to *previous* column's array entry.
  177441. */
  177442. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177443. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177444. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177445. * of the range_limit array.
  177446. */
  177447. cur += GETJSAMPLE(*input_ptr);
  177448. cur = GETJSAMPLE(range_limit[cur]);
  177449. /* Select output value, accumulate into output code for this pixel */
  177450. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177451. *output_ptr += (JSAMPLE) pixcode;
  177452. /* Compute actual representation error at this pixel */
  177453. /* Note: we can do this even though we don't have the final */
  177454. /* pixel code, because the colormap is orthogonal. */
  177455. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177456. /* Compute error fractions to be propagated to adjacent pixels.
  177457. * Add these into the running sums, and simultaneously shift the
  177458. * next-line error sums left by 1 column.
  177459. */
  177460. bnexterr = cur;
  177461. delta = cur * 2;
  177462. cur += delta; /* form error * 3 */
  177463. errorptr[0] = (FSERROR) (bpreverr + cur);
  177464. cur += delta; /* form error * 5 */
  177465. bpreverr = belowerr + cur;
  177466. belowerr = bnexterr;
  177467. cur += delta; /* form error * 7 */
  177468. /* At this point cur contains the 7/16 error value to be propagated
  177469. * to the next pixel on the current line, and all the errors for the
  177470. * next line have been shifted over. We are therefore ready to move on.
  177471. */
  177472. input_ptr += dirnc; /* advance input ptr to next column */
  177473. output_ptr += dir; /* advance output ptr to next column */
  177474. errorptr += dir; /* advance errorptr to current column */
  177475. }
  177476. /* Post-loop cleanup: we must unload the final error value into the
  177477. * final fserrors[] entry. Note we need not unload belowerr because
  177478. * it is for the dummy column before or after the actual array.
  177479. */
  177480. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177481. }
  177482. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177483. }
  177484. }
  177485. /*
  177486. * Allocate workspace for Floyd-Steinberg errors.
  177487. */
  177488. LOCAL(void)
  177489. alloc_fs_workspace (j_decompress_ptr cinfo)
  177490. {
  177491. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177492. size_t arraysize;
  177493. int i;
  177494. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177495. for (i = 0; i < cinfo->out_color_components; i++) {
  177496. cquantize->fserrors[i] = (FSERRPTR)
  177497. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177498. }
  177499. }
  177500. /*
  177501. * Initialize for one-pass color quantization.
  177502. */
  177503. METHODDEF(void)
  177504. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177505. {
  177506. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177507. size_t arraysize;
  177508. int i;
  177509. /* Install my colormap. */
  177510. cinfo->colormap = cquantize->sv_colormap;
  177511. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177512. /* Initialize for desired dithering mode. */
  177513. switch (cinfo->dither_mode) {
  177514. case JDITHER_NONE:
  177515. if (cinfo->out_color_components == 3)
  177516. cquantize->pub.color_quantize = color_quantize3;
  177517. else
  177518. cquantize->pub.color_quantize = color_quantize;
  177519. break;
  177520. case JDITHER_ORDERED:
  177521. if (cinfo->out_color_components == 3)
  177522. cquantize->pub.color_quantize = quantize3_ord_dither;
  177523. else
  177524. cquantize->pub.color_quantize = quantize_ord_dither;
  177525. cquantize->row_index = 0; /* initialize state for ordered dither */
  177526. /* If user changed to ordered dither from another mode,
  177527. * we must recreate the color index table with padding.
  177528. * This will cost extra space, but probably isn't very likely.
  177529. */
  177530. if (! cquantize->is_padded)
  177531. create_colorindex(cinfo);
  177532. /* Create ordered-dither tables if we didn't already. */
  177533. if (cquantize->odither[0] == NULL)
  177534. create_odither_tables(cinfo);
  177535. break;
  177536. case JDITHER_FS:
  177537. cquantize->pub.color_quantize = quantize_fs_dither;
  177538. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177539. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177540. if (cquantize->fserrors[0] == NULL)
  177541. alloc_fs_workspace(cinfo);
  177542. /* Initialize the propagated errors to zero. */
  177543. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177544. for (i = 0; i < cinfo->out_color_components; i++)
  177545. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177546. break;
  177547. default:
  177548. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177549. break;
  177550. }
  177551. }
  177552. /*
  177553. * Finish up at the end of the pass.
  177554. */
  177555. METHODDEF(void)
  177556. finish_pass_1_quant (j_decompress_ptr)
  177557. {
  177558. /* no work in 1-pass case */
  177559. }
  177560. /*
  177561. * Switch to a new external colormap between output passes.
  177562. * Shouldn't get to this module!
  177563. */
  177564. METHODDEF(void)
  177565. new_color_map_1_quant (j_decompress_ptr cinfo)
  177566. {
  177567. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177568. }
  177569. /*
  177570. * Module initialization routine for 1-pass color quantization.
  177571. */
  177572. GLOBAL(void)
  177573. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177574. {
  177575. my_cquantize_ptr cquantize;
  177576. cquantize = (my_cquantize_ptr)
  177577. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177578. SIZEOF(my_cquantizer));
  177579. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177580. cquantize->pub.start_pass = start_pass_1_quant;
  177581. cquantize->pub.finish_pass = finish_pass_1_quant;
  177582. cquantize->pub.new_color_map = new_color_map_1_quant;
  177583. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177584. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177585. /* Make sure my internal arrays won't overflow */
  177586. if (cinfo->out_color_components > MAX_Q_COMPS)
  177587. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177588. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177589. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177590. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177591. /* Create the colormap and color index table. */
  177592. create_colormap(cinfo);
  177593. create_colorindex(cinfo);
  177594. /* Allocate Floyd-Steinberg workspace now if requested.
  177595. * We do this now since it is FAR storage and may affect the memory
  177596. * manager's space calculations. If the user changes to FS dither
  177597. * mode in a later pass, we will allocate the space then, and will
  177598. * possibly overrun the max_memory_to_use setting.
  177599. */
  177600. if (cinfo->dither_mode == JDITHER_FS)
  177601. alloc_fs_workspace(cinfo);
  177602. }
  177603. #endif /* QUANT_1PASS_SUPPORTED */
  177604. /*** End of inlined file: jquant1.c ***/
  177605. /*** Start of inlined file: jquant2.c ***/
  177606. #define JPEG_INTERNALS
  177607. #ifdef QUANT_2PASS_SUPPORTED
  177608. /*
  177609. * This module implements the well-known Heckbert paradigm for color
  177610. * quantization. Most of the ideas used here can be traced back to
  177611. * Heckbert's seminal paper
  177612. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177613. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177614. *
  177615. * In the first pass over the image, we accumulate a histogram showing the
  177616. * usage count of each possible color. To keep the histogram to a reasonable
  177617. * size, we reduce the precision of the input; typical practice is to retain
  177618. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177619. * in the same histogram cell.
  177620. *
  177621. * Next, the color-selection step begins with a box representing the whole
  177622. * color space, and repeatedly splits the "largest" remaining box until we
  177623. * have as many boxes as desired colors. Then the mean color in each
  177624. * remaining box becomes one of the possible output colors.
  177625. *
  177626. * The second pass over the image maps each input pixel to the closest output
  177627. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177628. * This mapping is logically trivial, but making it go fast enough requires
  177629. * considerable care.
  177630. *
  177631. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177632. * the "largest" box and deciding where to cut it. The particular policies
  177633. * used here have proved out well in experimental comparisons, but better ones
  177634. * may yet be found.
  177635. *
  177636. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177637. * space, processing the raw upsampled data without a color conversion step.
  177638. * This allowed the color conversion math to be done only once per colormap
  177639. * entry, not once per pixel. However, that optimization precluded other
  177640. * useful optimizations (such as merging color conversion with upsampling)
  177641. * and it also interfered with desired capabilities such as quantizing to an
  177642. * externally-supplied colormap. We have therefore abandoned that approach.
  177643. * The present code works in the post-conversion color space, typically RGB.
  177644. *
  177645. * To improve the visual quality of the results, we actually work in scaled
  177646. * RGB space, giving G distances more weight than R, and R in turn more than
  177647. * B. To do everything in integer math, we must use integer scale factors.
  177648. * The 2/3/1 scale factors used here correspond loosely to the relative
  177649. * weights of the colors in the NTSC grayscale equation.
  177650. * If you want to use this code to quantize a non-RGB color space, you'll
  177651. * probably need to change these scale factors.
  177652. */
  177653. #define R_SCALE 2 /* scale R distances by this much */
  177654. #define G_SCALE 3 /* scale G distances by this much */
  177655. #define B_SCALE 1 /* and B by this much */
  177656. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177657. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177658. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177659. * you'll get compile errors until you extend this logic. In that case
  177660. * you'll probably want to tweak the histogram sizes too.
  177661. */
  177662. #if RGB_RED == 0
  177663. #define C0_SCALE R_SCALE
  177664. #endif
  177665. #if RGB_BLUE == 0
  177666. #define C0_SCALE B_SCALE
  177667. #endif
  177668. #if RGB_GREEN == 1
  177669. #define C1_SCALE G_SCALE
  177670. #endif
  177671. #if RGB_RED == 2
  177672. #define C2_SCALE R_SCALE
  177673. #endif
  177674. #if RGB_BLUE == 2
  177675. #define C2_SCALE B_SCALE
  177676. #endif
  177677. /*
  177678. * First we have the histogram data structure and routines for creating it.
  177679. *
  177680. * The number of bits of precision can be adjusted by changing these symbols.
  177681. * We recommend keeping 6 bits for G and 5 each for R and B.
  177682. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177683. * better results; if you are short of memory, 5 bits all around will save
  177684. * some space but degrade the results.
  177685. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177686. * (preferably unsigned long) for each cell. In practice this is overkill;
  177687. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177688. * and clamping those that do overflow to the maximum value will give close-
  177689. * enough results. This reduces the recommended histogram size from 256Kb
  177690. * to 128Kb, which is a useful savings on PC-class machines.
  177691. * (In the second pass the histogram space is re-used for pixel mapping data;
  177692. * in that capacity, each cell must be able to store zero to the number of
  177693. * desired colors. 16 bits/cell is plenty for that too.)
  177694. * Since the JPEG code is intended to run in small memory model on 80x86
  177695. * machines, we can't just allocate the histogram in one chunk. Instead
  177696. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177697. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177698. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177699. * on 80x86 machines, the pointer row is in near memory but the actual
  177700. * arrays are in far memory (same arrangement as we use for image arrays).
  177701. */
  177702. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177703. /* These will do the right thing for either R,G,B or B,G,R color order,
  177704. * but you may not like the results for other color orders.
  177705. */
  177706. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177707. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177708. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177709. /* Number of elements along histogram axes. */
  177710. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177711. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177712. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177713. /* These are the amounts to shift an input value to get a histogram index. */
  177714. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177715. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177716. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177717. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177718. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177719. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177720. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177721. typedef hist2d * hist3d; /* type for top-level pointer */
  177722. /* Declarations for Floyd-Steinberg dithering.
  177723. *
  177724. * Errors are accumulated into the array fserrors[], at a resolution of
  177725. * 1/16th of a pixel count. The error at a given pixel is propagated
  177726. * to its not-yet-processed neighbors using the standard F-S fractions,
  177727. * ... (here) 7/16
  177728. * 3/16 5/16 1/16
  177729. * We work left-to-right on even rows, right-to-left on odd rows.
  177730. *
  177731. * We can get away with a single array (holding one row's worth of errors)
  177732. * by using it to store the current row's errors at pixel columns not yet
  177733. * processed, but the next row's errors at columns already processed. We
  177734. * need only a few extra variables to hold the errors immediately around the
  177735. * current column. (If we are lucky, those variables are in registers, but
  177736. * even if not, they're probably cheaper to access than array elements are.)
  177737. *
  177738. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177739. * each end saves us from special-casing the first and last pixels.
  177740. * Each entry is three values long, one value for each color component.
  177741. *
  177742. * Note: on a wide image, we might not have enough room in a PC's near data
  177743. * segment to hold the error array; so it is allocated with alloc_large.
  177744. */
  177745. #if BITS_IN_JSAMPLE == 8
  177746. typedef INT16 FSERROR; /* 16 bits should be enough */
  177747. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177748. #else
  177749. typedef INT32 FSERROR; /* may need more than 16 bits */
  177750. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177751. #endif
  177752. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177753. /* Private subobject */
  177754. typedef struct {
  177755. struct jpeg_color_quantizer pub; /* public fields */
  177756. /* Space for the eventually created colormap is stashed here */
  177757. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177758. int desired; /* desired # of colors = size of colormap */
  177759. /* Variables for accumulating image statistics */
  177760. hist3d histogram; /* pointer to the histogram */
  177761. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177762. /* Variables for Floyd-Steinberg dithering */
  177763. FSERRPTR fserrors; /* accumulated errors */
  177764. boolean on_odd_row; /* flag to remember which row we are on */
  177765. int * error_limiter; /* table for clamping the applied error */
  177766. } my_cquantizer2;
  177767. typedef my_cquantizer2 * my_cquantize_ptr2;
  177768. /*
  177769. * Prescan some rows of pixels.
  177770. * In this module the prescan simply updates the histogram, which has been
  177771. * initialized to zeroes by start_pass.
  177772. * An output_buf parameter is required by the method signature, but no data
  177773. * is actually output (in fact the buffer controller is probably passing a
  177774. * NULL pointer).
  177775. */
  177776. METHODDEF(void)
  177777. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177778. JSAMPARRAY, int num_rows)
  177779. {
  177780. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177781. register JSAMPROW ptr;
  177782. register histptr histp;
  177783. register hist3d histogram = cquantize->histogram;
  177784. int row;
  177785. JDIMENSION col;
  177786. JDIMENSION width = cinfo->output_width;
  177787. for (row = 0; row < num_rows; row++) {
  177788. ptr = input_buf[row];
  177789. for (col = width; col > 0; col--) {
  177790. /* get pixel value and index into the histogram */
  177791. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177792. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177793. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177794. /* increment, check for overflow and undo increment if so. */
  177795. if (++(*histp) <= 0)
  177796. (*histp)--;
  177797. ptr += 3;
  177798. }
  177799. }
  177800. }
  177801. /*
  177802. * Next we have the really interesting routines: selection of a colormap
  177803. * given the completed histogram.
  177804. * These routines work with a list of "boxes", each representing a rectangular
  177805. * subset of the input color space (to histogram precision).
  177806. */
  177807. typedef struct {
  177808. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177809. int c0min, c0max;
  177810. int c1min, c1max;
  177811. int c2min, c2max;
  177812. /* The volume (actually 2-norm) of the box */
  177813. INT32 volume;
  177814. /* The number of nonzero histogram cells within this box */
  177815. long colorcount;
  177816. } box;
  177817. typedef box * boxptr;
  177818. LOCAL(boxptr)
  177819. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177820. /* Find the splittable box with the largest color population */
  177821. /* Returns NULL if no splittable boxes remain */
  177822. {
  177823. register boxptr boxp;
  177824. register int i;
  177825. register long maxc = 0;
  177826. boxptr which = NULL;
  177827. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177828. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177829. which = boxp;
  177830. maxc = boxp->colorcount;
  177831. }
  177832. }
  177833. return which;
  177834. }
  177835. LOCAL(boxptr)
  177836. find_biggest_volume (boxptr boxlist, int numboxes)
  177837. /* Find the splittable box with the largest (scaled) volume */
  177838. /* Returns NULL if no splittable boxes remain */
  177839. {
  177840. register boxptr boxp;
  177841. register int i;
  177842. register INT32 maxv = 0;
  177843. boxptr which = NULL;
  177844. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177845. if (boxp->volume > maxv) {
  177846. which = boxp;
  177847. maxv = boxp->volume;
  177848. }
  177849. }
  177850. return which;
  177851. }
  177852. LOCAL(void)
  177853. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177854. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177855. /* and recompute its volume and population */
  177856. {
  177857. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177858. hist3d histogram = cquantize->histogram;
  177859. histptr histp;
  177860. int c0,c1,c2;
  177861. int c0min,c0max,c1min,c1max,c2min,c2max;
  177862. INT32 dist0,dist1,dist2;
  177863. long ccount;
  177864. c0min = boxp->c0min; c0max = boxp->c0max;
  177865. c1min = boxp->c1min; c1max = boxp->c1max;
  177866. c2min = boxp->c2min; c2max = boxp->c2max;
  177867. if (c0max > c0min)
  177868. for (c0 = c0min; c0 <= c0max; c0++)
  177869. for (c1 = c1min; c1 <= c1max; c1++) {
  177870. histp = & histogram[c0][c1][c2min];
  177871. for (c2 = c2min; c2 <= c2max; c2++)
  177872. if (*histp++ != 0) {
  177873. boxp->c0min = c0min = c0;
  177874. goto have_c0min;
  177875. }
  177876. }
  177877. have_c0min:
  177878. if (c0max > c0min)
  177879. for (c0 = c0max; c0 >= c0min; c0--)
  177880. for (c1 = c1min; c1 <= c1max; c1++) {
  177881. histp = & histogram[c0][c1][c2min];
  177882. for (c2 = c2min; c2 <= c2max; c2++)
  177883. if (*histp++ != 0) {
  177884. boxp->c0max = c0max = c0;
  177885. goto have_c0max;
  177886. }
  177887. }
  177888. have_c0max:
  177889. if (c1max > c1min)
  177890. for (c1 = c1min; c1 <= c1max; c1++)
  177891. for (c0 = c0min; c0 <= c0max; c0++) {
  177892. histp = & histogram[c0][c1][c2min];
  177893. for (c2 = c2min; c2 <= c2max; c2++)
  177894. if (*histp++ != 0) {
  177895. boxp->c1min = c1min = c1;
  177896. goto have_c1min;
  177897. }
  177898. }
  177899. have_c1min:
  177900. if (c1max > c1min)
  177901. for (c1 = c1max; c1 >= c1min; c1--)
  177902. for (c0 = c0min; c0 <= c0max; c0++) {
  177903. histp = & histogram[c0][c1][c2min];
  177904. for (c2 = c2min; c2 <= c2max; c2++)
  177905. if (*histp++ != 0) {
  177906. boxp->c1max = c1max = c1;
  177907. goto have_c1max;
  177908. }
  177909. }
  177910. have_c1max:
  177911. if (c2max > c2min)
  177912. for (c2 = c2min; c2 <= c2max; c2++)
  177913. for (c0 = c0min; c0 <= c0max; c0++) {
  177914. histp = & histogram[c0][c1min][c2];
  177915. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177916. if (*histp != 0) {
  177917. boxp->c2min = c2min = c2;
  177918. goto have_c2min;
  177919. }
  177920. }
  177921. have_c2min:
  177922. if (c2max > c2min)
  177923. for (c2 = c2max; c2 >= c2min; c2--)
  177924. for (c0 = c0min; c0 <= c0max; c0++) {
  177925. histp = & histogram[c0][c1min][c2];
  177926. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177927. if (*histp != 0) {
  177928. boxp->c2max = c2max = c2;
  177929. goto have_c2max;
  177930. }
  177931. }
  177932. have_c2max:
  177933. /* Update box volume.
  177934. * We use 2-norm rather than real volume here; this biases the method
  177935. * against making long narrow boxes, and it has the side benefit that
  177936. * a box is splittable iff norm > 0.
  177937. * Since the differences are expressed in histogram-cell units,
  177938. * we have to shift back to JSAMPLE units to get consistent distances;
  177939. * after which, we scale according to the selected distance scale factors.
  177940. */
  177941. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177942. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177943. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177944. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177945. /* Now scan remaining volume of box and compute population */
  177946. ccount = 0;
  177947. for (c0 = c0min; c0 <= c0max; c0++)
  177948. for (c1 = c1min; c1 <= c1max; c1++) {
  177949. histp = & histogram[c0][c1][c2min];
  177950. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177951. if (*histp != 0) {
  177952. ccount++;
  177953. }
  177954. }
  177955. boxp->colorcount = ccount;
  177956. }
  177957. LOCAL(int)
  177958. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177959. int desired_colors)
  177960. /* Repeatedly select and split the largest box until we have enough boxes */
  177961. {
  177962. int n,lb;
  177963. int c0,c1,c2,cmax;
  177964. register boxptr b1,b2;
  177965. while (numboxes < desired_colors) {
  177966. /* Select box to split.
  177967. * Current algorithm: by population for first half, then by volume.
  177968. */
  177969. if (numboxes*2 <= desired_colors) {
  177970. b1 = find_biggest_color_pop(boxlist, numboxes);
  177971. } else {
  177972. b1 = find_biggest_volume(boxlist, numboxes);
  177973. }
  177974. if (b1 == NULL) /* no splittable boxes left! */
  177975. break;
  177976. b2 = &boxlist[numboxes]; /* where new box will go */
  177977. /* Copy the color bounds to the new box. */
  177978. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177979. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177980. /* Choose which axis to split the box on.
  177981. * Current algorithm: longest scaled axis.
  177982. * See notes in update_box about scaling distances.
  177983. */
  177984. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177985. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177986. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177987. /* We want to break any ties in favor of green, then red, blue last.
  177988. * This code does the right thing for R,G,B or B,G,R color orders only.
  177989. */
  177990. #if RGB_RED == 0
  177991. cmax = c1; n = 1;
  177992. if (c0 > cmax) { cmax = c0; n = 0; }
  177993. if (c2 > cmax) { n = 2; }
  177994. #else
  177995. cmax = c1; n = 1;
  177996. if (c2 > cmax) { cmax = c2; n = 2; }
  177997. if (c0 > cmax) { n = 0; }
  177998. #endif
  177999. /* Choose split point along selected axis, and update box bounds.
  178000. * Current algorithm: split at halfway point.
  178001. * (Since the box has been shrunk to minimum volume,
  178002. * any split will produce two nonempty subboxes.)
  178003. * Note that lb value is max for lower box, so must be < old max.
  178004. */
  178005. switch (n) {
  178006. case 0:
  178007. lb = (b1->c0max + b1->c0min) / 2;
  178008. b1->c0max = lb;
  178009. b2->c0min = lb+1;
  178010. break;
  178011. case 1:
  178012. lb = (b1->c1max + b1->c1min) / 2;
  178013. b1->c1max = lb;
  178014. b2->c1min = lb+1;
  178015. break;
  178016. case 2:
  178017. lb = (b1->c2max + b1->c2min) / 2;
  178018. b1->c2max = lb;
  178019. b2->c2min = lb+1;
  178020. break;
  178021. }
  178022. /* Update stats for boxes */
  178023. update_box(cinfo, b1);
  178024. update_box(cinfo, b2);
  178025. numboxes++;
  178026. }
  178027. return numboxes;
  178028. }
  178029. LOCAL(void)
  178030. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178031. /* Compute representative color for a box, put it in colormap[icolor] */
  178032. {
  178033. /* Current algorithm: mean weighted by pixels (not colors) */
  178034. /* Note it is important to get the rounding correct! */
  178035. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178036. hist3d histogram = cquantize->histogram;
  178037. histptr histp;
  178038. int c0,c1,c2;
  178039. int c0min,c0max,c1min,c1max,c2min,c2max;
  178040. long count;
  178041. long total = 0;
  178042. long c0total = 0;
  178043. long c1total = 0;
  178044. long c2total = 0;
  178045. c0min = boxp->c0min; c0max = boxp->c0max;
  178046. c1min = boxp->c1min; c1max = boxp->c1max;
  178047. c2min = boxp->c2min; c2max = boxp->c2max;
  178048. for (c0 = c0min; c0 <= c0max; c0++)
  178049. for (c1 = c1min; c1 <= c1max; c1++) {
  178050. histp = & histogram[c0][c1][c2min];
  178051. for (c2 = c2min; c2 <= c2max; c2++) {
  178052. if ((count = *histp++) != 0) {
  178053. total += count;
  178054. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178055. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178056. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178057. }
  178058. }
  178059. }
  178060. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178061. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178062. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178063. }
  178064. LOCAL(void)
  178065. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178066. /* Master routine for color selection */
  178067. {
  178068. boxptr boxlist;
  178069. int numboxes;
  178070. int i;
  178071. /* Allocate workspace for box list */
  178072. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178073. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178074. /* Initialize one box containing whole space */
  178075. numboxes = 1;
  178076. boxlist[0].c0min = 0;
  178077. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178078. boxlist[0].c1min = 0;
  178079. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178080. boxlist[0].c2min = 0;
  178081. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178082. /* Shrink it to actually-used volume and set its statistics */
  178083. update_box(cinfo, & boxlist[0]);
  178084. /* Perform median-cut to produce final box list */
  178085. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178086. /* Compute the representative color for each box, fill colormap */
  178087. for (i = 0; i < numboxes; i++)
  178088. compute_color(cinfo, & boxlist[i], i);
  178089. cinfo->actual_number_of_colors = numboxes;
  178090. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178091. }
  178092. /*
  178093. * These routines are concerned with the time-critical task of mapping input
  178094. * colors to the nearest color in the selected colormap.
  178095. *
  178096. * We re-use the histogram space as an "inverse color map", essentially a
  178097. * cache for the results of nearest-color searches. All colors within a
  178098. * histogram cell will be mapped to the same colormap entry, namely the one
  178099. * closest to the cell's center. This may not be quite the closest entry to
  178100. * the actual input color, but it's almost as good. A zero in the cache
  178101. * indicates we haven't found the nearest color for that cell yet; the array
  178102. * is cleared to zeroes before starting the mapping pass. When we find the
  178103. * nearest color for a cell, its colormap index plus one is recorded in the
  178104. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178105. * when they need to use an unfilled entry in the cache.
  178106. *
  178107. * Our method of efficiently finding nearest colors is based on the "locally
  178108. * sorted search" idea described by Heckbert and on the incremental distance
  178109. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178110. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178111. * the distances from a given colormap entry to each cell of the histogram can
  178112. * be computed quickly using an incremental method: the differences between
  178113. * distances to adjacent cells themselves differ by a constant. This allows a
  178114. * fairly fast implementation of the "brute force" approach of computing the
  178115. * distance from every colormap entry to every histogram cell. Unfortunately,
  178116. * it needs a work array to hold the best-distance-so-far for each histogram
  178117. * cell (because the inner loop has to be over cells, not colormap entries).
  178118. * The work array elements have to be INT32s, so the work array would need
  178119. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178120. *
  178121. * To get around these problems, we apply Thomas' method to compute the
  178122. * nearest colors for only the cells within a small subbox of the histogram.
  178123. * The work array need be only as big as the subbox, so the memory usage
  178124. * problem is solved. Furthermore, we need not fill subboxes that are never
  178125. * referenced in pass2; many images use only part of the color gamut, so a
  178126. * fair amount of work is saved. An additional advantage of this
  178127. * approach is that we can apply Heckbert's locality criterion to quickly
  178128. * eliminate colormap entries that are far away from the subbox; typically
  178129. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178130. * and we need not compute their distances to individual cells in the subbox.
  178131. * The speed of this approach is heavily influenced by the subbox size: too
  178132. * small means too much overhead, too big loses because Heckbert's criterion
  178133. * can't eliminate as many colormap entries. Empirically the best subbox
  178134. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178135. *
  178136. * Thomas' article also describes a refined method which is asymptotically
  178137. * faster than the brute-force method, but it is also far more complex and
  178138. * cannot efficiently be applied to small subboxes. It is therefore not
  178139. * useful for programs intended to be portable to DOS machines. On machines
  178140. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178141. * refined method might be faster than the present code --- but then again,
  178142. * it might not be any faster, and it's certainly more complicated.
  178143. */
  178144. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178145. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178146. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178147. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178148. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178149. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178150. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178151. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178152. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178153. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178154. /*
  178155. * The next three routines implement inverse colormap filling. They could
  178156. * all be folded into one big routine, but splitting them up this way saves
  178157. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178158. * and may allow some compilers to produce better code by registerizing more
  178159. * inner-loop variables.
  178160. */
  178161. LOCAL(int)
  178162. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178163. JSAMPLE colorlist[])
  178164. /* Locate the colormap entries close enough to an update box to be candidates
  178165. * for the nearest entry to some cell(s) in the update box. The update box
  178166. * is specified by the center coordinates of its first cell. The number of
  178167. * candidate colormap entries is returned, and their colormap indexes are
  178168. * placed in colorlist[].
  178169. * This routine uses Heckbert's "locally sorted search" criterion to select
  178170. * the colors that need further consideration.
  178171. */
  178172. {
  178173. int numcolors = cinfo->actual_number_of_colors;
  178174. int maxc0, maxc1, maxc2;
  178175. int centerc0, centerc1, centerc2;
  178176. int i, x, ncolors;
  178177. INT32 minmaxdist, min_dist, max_dist, tdist;
  178178. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178179. /* Compute true coordinates of update box's upper corner and center.
  178180. * Actually we compute the coordinates of the center of the upper-corner
  178181. * histogram cell, which are the upper bounds of the volume we care about.
  178182. * Note that since ">>" rounds down, the "center" values may be closer to
  178183. * min than to max; hence comparisons to them must be "<=", not "<".
  178184. */
  178185. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178186. centerc0 = (minc0 + maxc0) >> 1;
  178187. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178188. centerc1 = (minc1 + maxc1) >> 1;
  178189. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178190. centerc2 = (minc2 + maxc2) >> 1;
  178191. /* For each color in colormap, find:
  178192. * 1. its minimum squared-distance to any point in the update box
  178193. * (zero if color is within update box);
  178194. * 2. its maximum squared-distance to any point in the update box.
  178195. * Both of these can be found by considering only the corners of the box.
  178196. * We save the minimum distance for each color in mindist[];
  178197. * only the smallest maximum distance is of interest.
  178198. */
  178199. minmaxdist = 0x7FFFFFFFL;
  178200. for (i = 0; i < numcolors; i++) {
  178201. /* We compute the squared-c0-distance term, then add in the other two. */
  178202. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178203. if (x < minc0) {
  178204. tdist = (x - minc0) * C0_SCALE;
  178205. min_dist = tdist*tdist;
  178206. tdist = (x - maxc0) * C0_SCALE;
  178207. max_dist = tdist*tdist;
  178208. } else if (x > maxc0) {
  178209. tdist = (x - maxc0) * C0_SCALE;
  178210. min_dist = tdist*tdist;
  178211. tdist = (x - minc0) * C0_SCALE;
  178212. max_dist = tdist*tdist;
  178213. } else {
  178214. /* within cell range so no contribution to min_dist */
  178215. min_dist = 0;
  178216. if (x <= centerc0) {
  178217. tdist = (x - maxc0) * C0_SCALE;
  178218. max_dist = tdist*tdist;
  178219. } else {
  178220. tdist = (x - minc0) * C0_SCALE;
  178221. max_dist = tdist*tdist;
  178222. }
  178223. }
  178224. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178225. if (x < minc1) {
  178226. tdist = (x - minc1) * C1_SCALE;
  178227. min_dist += tdist*tdist;
  178228. tdist = (x - maxc1) * C1_SCALE;
  178229. max_dist += tdist*tdist;
  178230. } else if (x > maxc1) {
  178231. tdist = (x - maxc1) * C1_SCALE;
  178232. min_dist += tdist*tdist;
  178233. tdist = (x - minc1) * C1_SCALE;
  178234. max_dist += tdist*tdist;
  178235. } else {
  178236. /* within cell range so no contribution to min_dist */
  178237. if (x <= centerc1) {
  178238. tdist = (x - maxc1) * C1_SCALE;
  178239. max_dist += tdist*tdist;
  178240. } else {
  178241. tdist = (x - minc1) * C1_SCALE;
  178242. max_dist += tdist*tdist;
  178243. }
  178244. }
  178245. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178246. if (x < minc2) {
  178247. tdist = (x - minc2) * C2_SCALE;
  178248. min_dist += tdist*tdist;
  178249. tdist = (x - maxc2) * C2_SCALE;
  178250. max_dist += tdist*tdist;
  178251. } else if (x > maxc2) {
  178252. tdist = (x - maxc2) * C2_SCALE;
  178253. min_dist += tdist*tdist;
  178254. tdist = (x - minc2) * C2_SCALE;
  178255. max_dist += tdist*tdist;
  178256. } else {
  178257. /* within cell range so no contribution to min_dist */
  178258. if (x <= centerc2) {
  178259. tdist = (x - maxc2) * C2_SCALE;
  178260. max_dist += tdist*tdist;
  178261. } else {
  178262. tdist = (x - minc2) * C2_SCALE;
  178263. max_dist += tdist*tdist;
  178264. }
  178265. }
  178266. mindist[i] = min_dist; /* save away the results */
  178267. if (max_dist < minmaxdist)
  178268. minmaxdist = max_dist;
  178269. }
  178270. /* Now we know that no cell in the update box is more than minmaxdist
  178271. * away from some colormap entry. Therefore, only colors that are
  178272. * within minmaxdist of some part of the box need be considered.
  178273. */
  178274. ncolors = 0;
  178275. for (i = 0; i < numcolors; i++) {
  178276. if (mindist[i] <= minmaxdist)
  178277. colorlist[ncolors++] = (JSAMPLE) i;
  178278. }
  178279. return ncolors;
  178280. }
  178281. LOCAL(void)
  178282. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178283. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178284. /* Find the closest colormap entry for each cell in the update box,
  178285. * given the list of candidate colors prepared by find_nearby_colors.
  178286. * Return the indexes of the closest entries in the bestcolor[] array.
  178287. * This routine uses Thomas' incremental distance calculation method to
  178288. * find the distance from a colormap entry to successive cells in the box.
  178289. */
  178290. {
  178291. int ic0, ic1, ic2;
  178292. int i, icolor;
  178293. register INT32 * bptr; /* pointer into bestdist[] array */
  178294. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178295. INT32 dist0, dist1; /* initial distance values */
  178296. register INT32 dist2; /* current distance in inner loop */
  178297. INT32 xx0, xx1; /* distance increments */
  178298. register INT32 xx2;
  178299. INT32 inc0, inc1, inc2; /* initial values for increments */
  178300. /* This array holds the distance to the nearest-so-far color for each cell */
  178301. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178302. /* Initialize best-distance for each cell of the update box */
  178303. bptr = bestdist;
  178304. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178305. *bptr++ = 0x7FFFFFFFL;
  178306. /* For each color selected by find_nearby_colors,
  178307. * compute its distance to the center of each cell in the box.
  178308. * If that's less than best-so-far, update best distance and color number.
  178309. */
  178310. /* Nominal steps between cell centers ("x" in Thomas article) */
  178311. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178312. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178313. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178314. for (i = 0; i < numcolors; i++) {
  178315. icolor = GETJSAMPLE(colorlist[i]);
  178316. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178317. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178318. dist0 = inc0*inc0;
  178319. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178320. dist0 += inc1*inc1;
  178321. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178322. dist0 += inc2*inc2;
  178323. /* Form the initial difference increments */
  178324. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178325. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178326. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178327. /* Now loop over all cells in box, updating distance per Thomas method */
  178328. bptr = bestdist;
  178329. cptr = bestcolor;
  178330. xx0 = inc0;
  178331. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178332. dist1 = dist0;
  178333. xx1 = inc1;
  178334. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178335. dist2 = dist1;
  178336. xx2 = inc2;
  178337. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178338. if (dist2 < *bptr) {
  178339. *bptr = dist2;
  178340. *cptr = (JSAMPLE) icolor;
  178341. }
  178342. dist2 += xx2;
  178343. xx2 += 2 * STEP_C2 * STEP_C2;
  178344. bptr++;
  178345. cptr++;
  178346. }
  178347. dist1 += xx1;
  178348. xx1 += 2 * STEP_C1 * STEP_C1;
  178349. }
  178350. dist0 += xx0;
  178351. xx0 += 2 * STEP_C0 * STEP_C0;
  178352. }
  178353. }
  178354. }
  178355. LOCAL(void)
  178356. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178357. /* Fill the inverse-colormap entries in the update box that contains */
  178358. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178359. /* we can fill as many others as we wish.) */
  178360. {
  178361. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178362. hist3d histogram = cquantize->histogram;
  178363. int minc0, minc1, minc2; /* lower left corner of update box */
  178364. int ic0, ic1, ic2;
  178365. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178366. register histptr cachep; /* pointer into main cache array */
  178367. /* This array lists the candidate colormap indexes. */
  178368. JSAMPLE colorlist[MAXNUMCOLORS];
  178369. int numcolors; /* number of candidate colors */
  178370. /* This array holds the actually closest colormap index for each cell. */
  178371. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178372. /* Convert cell coordinates to update box ID */
  178373. c0 >>= BOX_C0_LOG;
  178374. c1 >>= BOX_C1_LOG;
  178375. c2 >>= BOX_C2_LOG;
  178376. /* Compute true coordinates of update box's origin corner.
  178377. * Actually we compute the coordinates of the center of the corner
  178378. * histogram cell, which are the lower bounds of the volume we care about.
  178379. */
  178380. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178381. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178382. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178383. /* Determine which colormap entries are close enough to be candidates
  178384. * for the nearest entry to some cell in the update box.
  178385. */
  178386. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178387. /* Determine the actually nearest colors. */
  178388. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178389. bestcolor);
  178390. /* Save the best color numbers (plus 1) in the main cache array */
  178391. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178392. c1 <<= BOX_C1_LOG;
  178393. c2 <<= BOX_C2_LOG;
  178394. cptr = bestcolor;
  178395. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178396. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178397. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178398. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178399. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178400. }
  178401. }
  178402. }
  178403. }
  178404. /*
  178405. * Map some rows of pixels to the output colormapped representation.
  178406. */
  178407. METHODDEF(void)
  178408. pass2_no_dither (j_decompress_ptr cinfo,
  178409. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178410. /* This version performs no dithering */
  178411. {
  178412. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178413. hist3d histogram = cquantize->histogram;
  178414. register JSAMPROW inptr, outptr;
  178415. register histptr cachep;
  178416. register int c0, c1, c2;
  178417. int row;
  178418. JDIMENSION col;
  178419. JDIMENSION width = cinfo->output_width;
  178420. for (row = 0; row < num_rows; row++) {
  178421. inptr = input_buf[row];
  178422. outptr = output_buf[row];
  178423. for (col = width; col > 0; col--) {
  178424. /* get pixel value and index into the cache */
  178425. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178426. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178427. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178428. cachep = & histogram[c0][c1][c2];
  178429. /* If we have not seen this color before, find nearest colormap entry */
  178430. /* and update the cache */
  178431. if (*cachep == 0)
  178432. fill_inverse_cmap(cinfo, c0,c1,c2);
  178433. /* Now emit the colormap index for this cell */
  178434. *outptr++ = (JSAMPLE) (*cachep - 1);
  178435. }
  178436. }
  178437. }
  178438. METHODDEF(void)
  178439. pass2_fs_dither (j_decompress_ptr cinfo,
  178440. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178441. /* This version performs Floyd-Steinberg dithering */
  178442. {
  178443. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178444. hist3d histogram = cquantize->histogram;
  178445. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178446. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178447. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178448. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178449. JSAMPROW inptr; /* => current input pixel */
  178450. JSAMPROW outptr; /* => current output pixel */
  178451. histptr cachep;
  178452. int dir; /* +1 or -1 depending on direction */
  178453. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178454. int row;
  178455. JDIMENSION col;
  178456. JDIMENSION width = cinfo->output_width;
  178457. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178458. int *error_limit = cquantize->error_limiter;
  178459. JSAMPROW colormap0 = cinfo->colormap[0];
  178460. JSAMPROW colormap1 = cinfo->colormap[1];
  178461. JSAMPROW colormap2 = cinfo->colormap[2];
  178462. SHIFT_TEMPS
  178463. for (row = 0; row < num_rows; row++) {
  178464. inptr = input_buf[row];
  178465. outptr = output_buf[row];
  178466. if (cquantize->on_odd_row) {
  178467. /* work right to left in this row */
  178468. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178469. outptr += width-1;
  178470. dir = -1;
  178471. dir3 = -3;
  178472. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178473. cquantize->on_odd_row = FALSE; /* flip for next time */
  178474. } else {
  178475. /* work left to right in this row */
  178476. dir = 1;
  178477. dir3 = 3;
  178478. errorptr = cquantize->fserrors; /* => entry before first real column */
  178479. cquantize->on_odd_row = TRUE; /* flip for next time */
  178480. }
  178481. /* Preset error values: no error propagated to first pixel from left */
  178482. cur0 = cur1 = cur2 = 0;
  178483. /* and no error propagated to row below yet */
  178484. belowerr0 = belowerr1 = belowerr2 = 0;
  178485. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178486. for (col = width; col > 0; col--) {
  178487. /* curN holds the error propagated from the previous pixel on the
  178488. * current line. Add the error propagated from the previous line
  178489. * to form the complete error correction term for this pixel, and
  178490. * round the error term (which is expressed * 16) to an integer.
  178491. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178492. * for either sign of the error value.
  178493. * Note: errorptr points to *previous* column's array entry.
  178494. */
  178495. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178496. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178497. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178498. /* Limit the error using transfer function set by init_error_limit.
  178499. * See comments with init_error_limit for rationale.
  178500. */
  178501. cur0 = error_limit[cur0];
  178502. cur1 = error_limit[cur1];
  178503. cur2 = error_limit[cur2];
  178504. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178505. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178506. * this sets the required size of the range_limit array.
  178507. */
  178508. cur0 += GETJSAMPLE(inptr[0]);
  178509. cur1 += GETJSAMPLE(inptr[1]);
  178510. cur2 += GETJSAMPLE(inptr[2]);
  178511. cur0 = GETJSAMPLE(range_limit[cur0]);
  178512. cur1 = GETJSAMPLE(range_limit[cur1]);
  178513. cur2 = GETJSAMPLE(range_limit[cur2]);
  178514. /* Index into the cache with adjusted pixel value */
  178515. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178516. /* If we have not seen this color before, find nearest colormap */
  178517. /* entry and update the cache */
  178518. if (*cachep == 0)
  178519. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178520. /* Now emit the colormap index for this cell */
  178521. { register int pixcode = *cachep - 1;
  178522. *outptr = (JSAMPLE) pixcode;
  178523. /* Compute representation error for this pixel */
  178524. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178525. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178526. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178527. }
  178528. /* Compute error fractions to be propagated to adjacent pixels.
  178529. * Add these into the running sums, and simultaneously shift the
  178530. * next-line error sums left by 1 column.
  178531. */
  178532. { register LOCFSERROR bnexterr, delta;
  178533. bnexterr = cur0; /* Process component 0 */
  178534. delta = cur0 * 2;
  178535. cur0 += delta; /* form error * 3 */
  178536. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178537. cur0 += delta; /* form error * 5 */
  178538. bpreverr0 = belowerr0 + cur0;
  178539. belowerr0 = bnexterr;
  178540. cur0 += delta; /* form error * 7 */
  178541. bnexterr = cur1; /* Process component 1 */
  178542. delta = cur1 * 2;
  178543. cur1 += delta; /* form error * 3 */
  178544. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178545. cur1 += delta; /* form error * 5 */
  178546. bpreverr1 = belowerr1 + cur1;
  178547. belowerr1 = bnexterr;
  178548. cur1 += delta; /* form error * 7 */
  178549. bnexterr = cur2; /* Process component 2 */
  178550. delta = cur2 * 2;
  178551. cur2 += delta; /* form error * 3 */
  178552. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178553. cur2 += delta; /* form error * 5 */
  178554. bpreverr2 = belowerr2 + cur2;
  178555. belowerr2 = bnexterr;
  178556. cur2 += delta; /* form error * 7 */
  178557. }
  178558. /* At this point curN contains the 7/16 error value to be propagated
  178559. * to the next pixel on the current line, and all the errors for the
  178560. * next line have been shifted over. We are therefore ready to move on.
  178561. */
  178562. inptr += dir3; /* Advance pixel pointers to next column */
  178563. outptr += dir;
  178564. errorptr += dir3; /* advance errorptr to current column */
  178565. }
  178566. /* Post-loop cleanup: we must unload the final error values into the
  178567. * final fserrors[] entry. Note we need not unload belowerrN because
  178568. * it is for the dummy column before or after the actual array.
  178569. */
  178570. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178571. errorptr[1] = (FSERROR) bpreverr1;
  178572. errorptr[2] = (FSERROR) bpreverr2;
  178573. }
  178574. }
  178575. /*
  178576. * Initialize the error-limiting transfer function (lookup table).
  178577. * The raw F-S error computation can potentially compute error values of up to
  178578. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178579. * much less, otherwise obviously wrong pixels will be created. (Typical
  178580. * effects include weird fringes at color-area boundaries, isolated bright
  178581. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178582. * is to ensure that the "corners" of the color cube are allocated as output
  178583. * colors; then repeated errors in the same direction cannot cause cascading
  178584. * error buildup. However, that only prevents the error from getting
  178585. * completely out of hand; Aaron Giles reports that error limiting improves
  178586. * the results even with corner colors allocated.
  178587. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178588. * well, but the smoother transfer function used below is even better. Thanks
  178589. * to Aaron Giles for this idea.
  178590. */
  178591. LOCAL(void)
  178592. init_error_limit (j_decompress_ptr cinfo)
  178593. /* Allocate and fill in the error_limiter table */
  178594. {
  178595. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178596. int * table;
  178597. int in, out;
  178598. table = (int *) (*cinfo->mem->alloc_small)
  178599. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178600. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178601. cquantize->error_limiter = table;
  178602. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178603. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178604. out = 0;
  178605. for (in = 0; in < STEPSIZE; in++, out++) {
  178606. table[in] = out; table[-in] = -out;
  178607. }
  178608. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178609. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178610. table[in] = out; table[-in] = -out;
  178611. }
  178612. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178613. for (; in <= MAXJSAMPLE; in++) {
  178614. table[in] = out; table[-in] = -out;
  178615. }
  178616. #undef STEPSIZE
  178617. }
  178618. /*
  178619. * Finish up at the end of each pass.
  178620. */
  178621. METHODDEF(void)
  178622. finish_pass1 (j_decompress_ptr cinfo)
  178623. {
  178624. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178625. /* Select the representative colors and fill in cinfo->colormap */
  178626. cinfo->colormap = cquantize->sv_colormap;
  178627. select_colors(cinfo, cquantize->desired);
  178628. /* Force next pass to zero the color index table */
  178629. cquantize->needs_zeroed = TRUE;
  178630. }
  178631. METHODDEF(void)
  178632. finish_pass2 (j_decompress_ptr)
  178633. {
  178634. /* no work */
  178635. }
  178636. /*
  178637. * Initialize for each processing pass.
  178638. */
  178639. METHODDEF(void)
  178640. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178641. {
  178642. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178643. hist3d histogram = cquantize->histogram;
  178644. int i;
  178645. /* Only F-S dithering or no dithering is supported. */
  178646. /* If user asks for ordered dither, give him F-S. */
  178647. if (cinfo->dither_mode != JDITHER_NONE)
  178648. cinfo->dither_mode = JDITHER_FS;
  178649. if (is_pre_scan) {
  178650. /* Set up method pointers */
  178651. cquantize->pub.color_quantize = prescan_quantize;
  178652. cquantize->pub.finish_pass = finish_pass1;
  178653. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178654. } else {
  178655. /* Set up method pointers */
  178656. if (cinfo->dither_mode == JDITHER_FS)
  178657. cquantize->pub.color_quantize = pass2_fs_dither;
  178658. else
  178659. cquantize->pub.color_quantize = pass2_no_dither;
  178660. cquantize->pub.finish_pass = finish_pass2;
  178661. /* Make sure color count is acceptable */
  178662. i = cinfo->actual_number_of_colors;
  178663. if (i < 1)
  178664. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178665. if (i > MAXNUMCOLORS)
  178666. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178667. if (cinfo->dither_mode == JDITHER_FS) {
  178668. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178669. (3 * SIZEOF(FSERROR)));
  178670. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178671. if (cquantize->fserrors == NULL)
  178672. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178673. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178674. /* Initialize the propagated errors to zero. */
  178675. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178676. /* Make the error-limit table if we didn't already. */
  178677. if (cquantize->error_limiter == NULL)
  178678. init_error_limit(cinfo);
  178679. cquantize->on_odd_row = FALSE;
  178680. }
  178681. }
  178682. /* Zero the histogram or inverse color map, if necessary */
  178683. if (cquantize->needs_zeroed) {
  178684. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178685. jzero_far((void FAR *) histogram[i],
  178686. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178687. }
  178688. cquantize->needs_zeroed = FALSE;
  178689. }
  178690. }
  178691. /*
  178692. * Switch to a new external colormap between output passes.
  178693. */
  178694. METHODDEF(void)
  178695. new_color_map_2_quant (j_decompress_ptr cinfo)
  178696. {
  178697. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178698. /* Reset the inverse color map */
  178699. cquantize->needs_zeroed = TRUE;
  178700. }
  178701. /*
  178702. * Module initialization routine for 2-pass color quantization.
  178703. */
  178704. GLOBAL(void)
  178705. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178706. {
  178707. my_cquantize_ptr2 cquantize;
  178708. int i;
  178709. cquantize = (my_cquantize_ptr2)
  178710. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178711. SIZEOF(my_cquantizer2));
  178712. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178713. cquantize->pub.start_pass = start_pass_2_quant;
  178714. cquantize->pub.new_color_map = new_color_map_2_quant;
  178715. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178716. cquantize->error_limiter = NULL;
  178717. /* Make sure jdmaster didn't give me a case I can't handle */
  178718. if (cinfo->out_color_components != 3)
  178719. ERREXIT(cinfo, JERR_NOTIMPL);
  178720. /* Allocate the histogram/inverse colormap storage */
  178721. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178722. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178723. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178724. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178725. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178726. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178727. }
  178728. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178729. /* Allocate storage for the completed colormap, if required.
  178730. * We do this now since it is FAR storage and may affect
  178731. * the memory manager's space calculations.
  178732. */
  178733. if (cinfo->enable_2pass_quant) {
  178734. /* Make sure color count is acceptable */
  178735. int desired = cinfo->desired_number_of_colors;
  178736. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178737. if (desired < 8)
  178738. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178739. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178740. if (desired > MAXNUMCOLORS)
  178741. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178742. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178743. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178744. cquantize->desired = desired;
  178745. } else
  178746. cquantize->sv_colormap = NULL;
  178747. /* Only F-S dithering or no dithering is supported. */
  178748. /* If user asks for ordered dither, give him F-S. */
  178749. if (cinfo->dither_mode != JDITHER_NONE)
  178750. cinfo->dither_mode = JDITHER_FS;
  178751. /* Allocate Floyd-Steinberg workspace if necessary.
  178752. * This isn't really needed until pass 2, but again it is FAR storage.
  178753. * Although we will cope with a later change in dither_mode,
  178754. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178755. */
  178756. if (cinfo->dither_mode == JDITHER_FS) {
  178757. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178758. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178759. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178760. /* Might as well create the error-limiting table too. */
  178761. init_error_limit(cinfo);
  178762. }
  178763. }
  178764. #endif /* QUANT_2PASS_SUPPORTED */
  178765. /*** End of inlined file: jquant2.c ***/
  178766. /*** Start of inlined file: jutils.c ***/
  178767. #define JPEG_INTERNALS
  178768. /*
  178769. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178770. * of a DCT block read in natural order (left to right, top to bottom).
  178771. */
  178772. #if 0 /* This table is not actually needed in v6a */
  178773. const int jpeg_zigzag_order[DCTSIZE2] = {
  178774. 0, 1, 5, 6, 14, 15, 27, 28,
  178775. 2, 4, 7, 13, 16, 26, 29, 42,
  178776. 3, 8, 12, 17, 25, 30, 41, 43,
  178777. 9, 11, 18, 24, 31, 40, 44, 53,
  178778. 10, 19, 23, 32, 39, 45, 52, 54,
  178779. 20, 22, 33, 38, 46, 51, 55, 60,
  178780. 21, 34, 37, 47, 50, 56, 59, 61,
  178781. 35, 36, 48, 49, 57, 58, 62, 63
  178782. };
  178783. #endif
  178784. /*
  178785. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178786. * of zigzag order.
  178787. *
  178788. * When reading corrupted data, the Huffman decoders could attempt
  178789. * to reference an entry beyond the end of this array (if the decoded
  178790. * zero run length reaches past the end of the block). To prevent
  178791. * wild stores without adding an inner-loop test, we put some extra
  178792. * "63"s after the real entries. This will cause the extra coefficient
  178793. * to be stored in location 63 of the block, not somewhere random.
  178794. * The worst case would be a run-length of 15, which means we need 16
  178795. * fake entries.
  178796. */
  178797. const int jpeg_natural_order[DCTSIZE2+16] = {
  178798. 0, 1, 8, 16, 9, 2, 3, 10,
  178799. 17, 24, 32, 25, 18, 11, 4, 5,
  178800. 12, 19, 26, 33, 40, 48, 41, 34,
  178801. 27, 20, 13, 6, 7, 14, 21, 28,
  178802. 35, 42, 49, 56, 57, 50, 43, 36,
  178803. 29, 22, 15, 23, 30, 37, 44, 51,
  178804. 58, 59, 52, 45, 38, 31, 39, 46,
  178805. 53, 60, 61, 54, 47, 55, 62, 63,
  178806. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178807. 63, 63, 63, 63, 63, 63, 63, 63
  178808. };
  178809. /*
  178810. * Arithmetic utilities
  178811. */
  178812. GLOBAL(long)
  178813. jdiv_round_up (long a, long b)
  178814. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178815. /* Assumes a >= 0, b > 0 */
  178816. {
  178817. return (a + b - 1L) / b;
  178818. }
  178819. GLOBAL(long)
  178820. jround_up (long a, long b)
  178821. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178822. /* Assumes a >= 0, b > 0 */
  178823. {
  178824. a += b - 1L;
  178825. return a - (a % b);
  178826. }
  178827. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178828. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178829. * are FAR and we're assuming a small-pointer memory model. However, some
  178830. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178831. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178832. * Otherwise, the routines below do it the hard way. (The performance cost
  178833. * is not all that great, because these routines aren't very heavily used.)
  178834. */
  178835. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178836. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178837. #define FMEMZERO(target,size) MEMZERO(target,size)
  178838. #else /* 80x86 case, define if we can */
  178839. #ifdef USE_FMEM
  178840. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178841. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178842. #endif
  178843. #endif
  178844. GLOBAL(void)
  178845. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178846. JSAMPARRAY output_array, int dest_row,
  178847. int num_rows, JDIMENSION num_cols)
  178848. /* Copy some rows of samples from one place to another.
  178849. * num_rows rows are copied from input_array[source_row++]
  178850. * to output_array[dest_row++]; these areas may overlap for duplication.
  178851. * The source and destination arrays must be at least as wide as num_cols.
  178852. */
  178853. {
  178854. register JSAMPROW inptr, outptr;
  178855. #ifdef FMEMCOPY
  178856. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178857. #else
  178858. register JDIMENSION count;
  178859. #endif
  178860. register int row;
  178861. input_array += source_row;
  178862. output_array += dest_row;
  178863. for (row = num_rows; row > 0; row--) {
  178864. inptr = *input_array++;
  178865. outptr = *output_array++;
  178866. #ifdef FMEMCOPY
  178867. FMEMCOPY(outptr, inptr, count);
  178868. #else
  178869. for (count = num_cols; count > 0; count--)
  178870. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178871. #endif
  178872. }
  178873. }
  178874. GLOBAL(void)
  178875. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178876. JDIMENSION num_blocks)
  178877. /* Copy a row of coefficient blocks from one place to another. */
  178878. {
  178879. #ifdef FMEMCOPY
  178880. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178881. #else
  178882. register JCOEFPTR inptr, outptr;
  178883. register long count;
  178884. inptr = (JCOEFPTR) input_row;
  178885. outptr = (JCOEFPTR) output_row;
  178886. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178887. *outptr++ = *inptr++;
  178888. }
  178889. #endif
  178890. }
  178891. GLOBAL(void)
  178892. jzero_far (void FAR * target, size_t bytestozero)
  178893. /* Zero out a chunk of FAR memory. */
  178894. /* This might be sample-array data, block-array data, or alloc_large data. */
  178895. {
  178896. #ifdef FMEMZERO
  178897. FMEMZERO(target, bytestozero);
  178898. #else
  178899. register char FAR * ptr = (char FAR *) target;
  178900. register size_t count;
  178901. for (count = bytestozero; count > 0; count--) {
  178902. *ptr++ = 0;
  178903. }
  178904. #endif
  178905. }
  178906. /*** End of inlined file: jutils.c ***/
  178907. /*** Start of inlined file: transupp.c ***/
  178908. /* Although this file really shouldn't have access to the library internals,
  178909. * it's helpful to let it call jround_up() and jcopy_block_row().
  178910. */
  178911. #define JPEG_INTERNALS
  178912. /*** Start of inlined file: transupp.h ***/
  178913. /* If you happen not to want the image transform support, disable it here */
  178914. #ifndef TRANSFORMS_SUPPORTED
  178915. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178916. #endif
  178917. /* Short forms of external names for systems with brain-damaged linkers. */
  178918. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178919. #define jtransform_request_workspace jTrRequest
  178920. #define jtransform_adjust_parameters jTrAdjust
  178921. #define jtransform_execute_transformation jTrExec
  178922. #define jcopy_markers_setup jCMrkSetup
  178923. #define jcopy_markers_execute jCMrkExec
  178924. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178925. /*
  178926. * Codes for supported types of image transformations.
  178927. */
  178928. typedef enum {
  178929. JXFORM_NONE, /* no transformation */
  178930. JXFORM_FLIP_H, /* horizontal flip */
  178931. JXFORM_FLIP_V, /* vertical flip */
  178932. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178933. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178934. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178935. JXFORM_ROT_180, /* 180-degree rotation */
  178936. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178937. } JXFORM_CODE;
  178938. /*
  178939. * Although rotating and flipping data expressed as DCT coefficients is not
  178940. * hard, there is an asymmetry in the JPEG format specification for images
  178941. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178942. * image edges are padded out to the next iMCU boundary with junk data; but
  178943. * no padding is possible at the top and left edges. If we were to flip
  178944. * the whole image including the pad data, then pad garbage would become
  178945. * visible at the top and/or left, and real pixels would disappear into the
  178946. * pad margins --- perhaps permanently, since encoders & decoders may not
  178947. * bother to preserve DCT blocks that appear to be completely outside the
  178948. * nominal image area. So, we have to exclude any partial iMCUs from the
  178949. * basic transformation.
  178950. *
  178951. * Transpose is the only transformation that can handle partial iMCUs at the
  178952. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178953. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178954. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178955. * The other transforms are defined as combinations of these basic transforms
  178956. * and process edge blocks in a way that preserves the equivalence.
  178957. *
  178958. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178959. * this is not strictly lossless, but it usually gives the best-looking
  178960. * result for odd-size images. Note that when this option is active,
  178961. * the expected mathematical equivalences between the transforms may not hold.
  178962. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178963. * followed by -rot 180 -trim trims both edges.)
  178964. *
  178965. * We also offer a "force to grayscale" option, which simply discards the
  178966. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178967. * the luminance channel is preserved exactly. It's not the same kind of
  178968. * thing as the rotate/flip transformations, but it's convenient to handle it
  178969. * as part of this package, mainly because the transformation routines have to
  178970. * be aware of the option to know how many components to work on.
  178971. */
  178972. typedef struct {
  178973. /* Options: set by caller */
  178974. JXFORM_CODE transform; /* image transform operator */
  178975. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178976. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178977. /* Internal workspace: caller should not touch these */
  178978. int num_components; /* # of components in workspace */
  178979. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178980. } jpeg_transform_info;
  178981. #if TRANSFORMS_SUPPORTED
  178982. /* Request any required workspace */
  178983. EXTERN(void) jtransform_request_workspace
  178984. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178985. /* Adjust output image parameters */
  178986. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178987. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178988. jvirt_barray_ptr *src_coef_arrays,
  178989. jpeg_transform_info *info));
  178990. /* Execute the actual transformation, if any */
  178991. EXTERN(void) jtransform_execute_transformation
  178992. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178993. jvirt_barray_ptr *src_coef_arrays,
  178994. jpeg_transform_info *info));
  178995. #endif /* TRANSFORMS_SUPPORTED */
  178996. /*
  178997. * Support for copying optional markers from source to destination file.
  178998. */
  178999. typedef enum {
  179000. JCOPYOPT_NONE, /* copy no optional markers */
  179001. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179002. JCOPYOPT_ALL /* copy all optional markers */
  179003. } JCOPY_OPTION;
  179004. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179005. /* Setup decompression object to save desired markers in memory */
  179006. EXTERN(void) jcopy_markers_setup
  179007. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179008. /* Copy markers saved in the given source object to the destination object */
  179009. EXTERN(void) jcopy_markers_execute
  179010. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179011. JCOPY_OPTION option));
  179012. /*** End of inlined file: transupp.h ***/
  179013. /* My own external interface */
  179014. #if TRANSFORMS_SUPPORTED
  179015. /*
  179016. * Lossless image transformation routines. These routines work on DCT
  179017. * coefficient arrays and thus do not require any lossy decompression
  179018. * or recompression of the image.
  179019. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179020. *
  179021. * Horizontal flipping is done in-place, using a single top-to-bottom
  179022. * pass through the virtual source array. It will thus be much the
  179023. * fastest option for images larger than main memory.
  179024. *
  179025. * The other routines require a set of destination virtual arrays, so they
  179026. * need twice as much memory as jpegtran normally does. The destination
  179027. * arrays are always written in normal scan order (top to bottom) because
  179028. * the virtual array manager expects this. The source arrays will be scanned
  179029. * in the corresponding order, which means multiple passes through the source
  179030. * arrays for most of the transforms. That could result in much thrashing
  179031. * if the image is larger than main memory.
  179032. *
  179033. * Some notes about the operating environment of the individual transform
  179034. * routines:
  179035. * 1. Both the source and destination virtual arrays are allocated from the
  179036. * source JPEG object, and therefore should be manipulated by calling the
  179037. * source's memory manager.
  179038. * 2. The destination's component count should be used. It may be smaller
  179039. * than the source's when forcing to grayscale.
  179040. * 3. Likewise the destination's sampling factors should be used. When
  179041. * forcing to grayscale the destination's sampling factors will be all 1,
  179042. * and we may as well take that as the effective iMCU size.
  179043. * 4. When "trim" is in effect, the destination's dimensions will be the
  179044. * trimmed values but the source's will be untrimmed.
  179045. * 5. All the routines assume that the source and destination buffers are
  179046. * padded out to a full iMCU boundary. This is true, although for the
  179047. * source buffer it is an undocumented property of jdcoefct.c.
  179048. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179049. * dimensions and ignore the source's.
  179050. */
  179051. LOCAL(void)
  179052. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179053. jvirt_barray_ptr *src_coef_arrays)
  179054. /* Horizontal flip; done in-place, so no separate dest array is required */
  179055. {
  179056. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179057. int ci, k, offset_y;
  179058. JBLOCKARRAY buffer;
  179059. JCOEFPTR ptr1, ptr2;
  179060. JCOEF temp1, temp2;
  179061. jpeg_component_info *compptr;
  179062. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179063. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179064. * mirroring by changing the signs of odd-numbered columns.
  179065. * Partial iMCUs at the right edge are left untouched.
  179066. */
  179067. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179068. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179069. compptr = dstinfo->comp_info + ci;
  179070. comp_width = MCU_cols * compptr->h_samp_factor;
  179071. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179072. blk_y += compptr->v_samp_factor) {
  179073. buffer = (*srcinfo->mem->access_virt_barray)
  179074. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179075. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179076. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179077. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179078. ptr1 = buffer[offset_y][blk_x];
  179079. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179080. /* this unrolled loop doesn't need to know which row it's on... */
  179081. for (k = 0; k < DCTSIZE2; k += 2) {
  179082. temp1 = *ptr1; /* swap even column */
  179083. temp2 = *ptr2;
  179084. *ptr1++ = temp2;
  179085. *ptr2++ = temp1;
  179086. temp1 = *ptr1; /* swap odd column with sign change */
  179087. temp2 = *ptr2;
  179088. *ptr1++ = -temp2;
  179089. *ptr2++ = -temp1;
  179090. }
  179091. }
  179092. }
  179093. }
  179094. }
  179095. }
  179096. LOCAL(void)
  179097. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179098. jvirt_barray_ptr *src_coef_arrays,
  179099. jvirt_barray_ptr *dst_coef_arrays)
  179100. /* Vertical flip */
  179101. {
  179102. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179103. int ci, i, j, offset_y;
  179104. JBLOCKARRAY src_buffer, dst_buffer;
  179105. JBLOCKROW src_row_ptr, dst_row_ptr;
  179106. JCOEFPTR src_ptr, dst_ptr;
  179107. jpeg_component_info *compptr;
  179108. /* We output into a separate array because we can't touch different
  179109. * rows of the source virtual array simultaneously. Otherwise, this
  179110. * is a pretty straightforward analog of horizontal flip.
  179111. * Within a DCT block, vertical mirroring is done by changing the signs
  179112. * of odd-numbered rows.
  179113. * Partial iMCUs at the bottom edge are copied verbatim.
  179114. */
  179115. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179116. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179117. compptr = dstinfo->comp_info + ci;
  179118. comp_height = MCU_rows * compptr->v_samp_factor;
  179119. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179120. dst_blk_y += compptr->v_samp_factor) {
  179121. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179122. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179123. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179124. if (dst_blk_y < comp_height) {
  179125. /* Row is within the mirrorable area. */
  179126. src_buffer = (*srcinfo->mem->access_virt_barray)
  179127. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179128. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179129. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179130. } else {
  179131. /* Bottom-edge blocks will be copied verbatim. */
  179132. src_buffer = (*srcinfo->mem->access_virt_barray)
  179133. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179134. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179135. }
  179136. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179137. if (dst_blk_y < comp_height) {
  179138. /* Row is within the mirrorable area. */
  179139. dst_row_ptr = dst_buffer[offset_y];
  179140. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179141. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179142. dst_blk_x++) {
  179143. dst_ptr = dst_row_ptr[dst_blk_x];
  179144. src_ptr = src_row_ptr[dst_blk_x];
  179145. for (i = 0; i < DCTSIZE; i += 2) {
  179146. /* copy even row */
  179147. for (j = 0; j < DCTSIZE; j++)
  179148. *dst_ptr++ = *src_ptr++;
  179149. /* copy odd row with sign change */
  179150. for (j = 0; j < DCTSIZE; j++)
  179151. *dst_ptr++ = - *src_ptr++;
  179152. }
  179153. }
  179154. } else {
  179155. /* Just copy row verbatim. */
  179156. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179157. compptr->width_in_blocks);
  179158. }
  179159. }
  179160. }
  179161. }
  179162. }
  179163. LOCAL(void)
  179164. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179165. jvirt_barray_ptr *src_coef_arrays,
  179166. jvirt_barray_ptr *dst_coef_arrays)
  179167. /* Transpose source into destination */
  179168. {
  179169. JDIMENSION dst_blk_x, dst_blk_y;
  179170. int ci, i, j, offset_x, offset_y;
  179171. JBLOCKARRAY src_buffer, dst_buffer;
  179172. JCOEFPTR src_ptr, dst_ptr;
  179173. jpeg_component_info *compptr;
  179174. /* Transposing pixels within a block just requires transposing the
  179175. * DCT coefficients.
  179176. * Partial iMCUs at the edges require no special treatment; we simply
  179177. * process all the available DCT blocks for every component.
  179178. */
  179179. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179180. compptr = dstinfo->comp_info + ci;
  179181. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179182. dst_blk_y += compptr->v_samp_factor) {
  179183. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179184. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179185. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179186. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179187. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179188. dst_blk_x += compptr->h_samp_factor) {
  179189. src_buffer = (*srcinfo->mem->access_virt_barray)
  179190. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179191. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179192. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179193. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179194. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179195. for (i = 0; i < DCTSIZE; i++)
  179196. for (j = 0; j < DCTSIZE; j++)
  179197. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179198. }
  179199. }
  179200. }
  179201. }
  179202. }
  179203. }
  179204. LOCAL(void)
  179205. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179206. jvirt_barray_ptr *src_coef_arrays,
  179207. jvirt_barray_ptr *dst_coef_arrays)
  179208. /* 90 degree rotation is equivalent to
  179209. * 1. Transposing the image;
  179210. * 2. Horizontal mirroring.
  179211. * These two steps are merged into a single processing routine.
  179212. */
  179213. {
  179214. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179215. int ci, i, j, offset_x, offset_y;
  179216. JBLOCKARRAY src_buffer, dst_buffer;
  179217. JCOEFPTR src_ptr, dst_ptr;
  179218. jpeg_component_info *compptr;
  179219. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179220. * at the (output) right edge properly. They just get transposed and
  179221. * not mirrored.
  179222. */
  179223. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179224. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179225. compptr = dstinfo->comp_info + ci;
  179226. comp_width = MCU_cols * compptr->h_samp_factor;
  179227. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179228. dst_blk_y += compptr->v_samp_factor) {
  179229. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179230. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179231. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179232. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179233. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179234. dst_blk_x += compptr->h_samp_factor) {
  179235. src_buffer = (*srcinfo->mem->access_virt_barray)
  179236. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179237. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179238. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179239. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179240. if (dst_blk_x < comp_width) {
  179241. /* Block is within the mirrorable area. */
  179242. dst_ptr = dst_buffer[offset_y]
  179243. [comp_width - dst_blk_x - offset_x - 1];
  179244. for (i = 0; i < DCTSIZE; i++) {
  179245. for (j = 0; j < DCTSIZE; j++)
  179246. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179247. i++;
  179248. for (j = 0; j < DCTSIZE; j++)
  179249. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179250. }
  179251. } else {
  179252. /* Edge blocks are transposed but not mirrored. */
  179253. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179254. for (i = 0; i < DCTSIZE; i++)
  179255. for (j = 0; j < DCTSIZE; j++)
  179256. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179257. }
  179258. }
  179259. }
  179260. }
  179261. }
  179262. }
  179263. }
  179264. LOCAL(void)
  179265. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179266. jvirt_barray_ptr *src_coef_arrays,
  179267. jvirt_barray_ptr *dst_coef_arrays)
  179268. /* 270 degree rotation is equivalent to
  179269. * 1. Horizontal mirroring;
  179270. * 2. Transposing the image.
  179271. * These two steps are merged into a single processing routine.
  179272. */
  179273. {
  179274. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179275. int ci, i, j, offset_x, offset_y;
  179276. JBLOCKARRAY src_buffer, dst_buffer;
  179277. JCOEFPTR src_ptr, dst_ptr;
  179278. jpeg_component_info *compptr;
  179279. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179280. * at the (output) bottom edge properly. They just get transposed and
  179281. * not mirrored.
  179282. */
  179283. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179284. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179285. compptr = dstinfo->comp_info + ci;
  179286. comp_height = MCU_rows * compptr->v_samp_factor;
  179287. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179288. dst_blk_y += compptr->v_samp_factor) {
  179289. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179290. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179291. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179292. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179293. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179294. dst_blk_x += compptr->h_samp_factor) {
  179295. src_buffer = (*srcinfo->mem->access_virt_barray)
  179296. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179297. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179298. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179299. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179300. if (dst_blk_y < comp_height) {
  179301. /* Block is within the mirrorable area. */
  179302. src_ptr = src_buffer[offset_x]
  179303. [comp_height - dst_blk_y - offset_y - 1];
  179304. for (i = 0; i < DCTSIZE; i++) {
  179305. for (j = 0; j < DCTSIZE; j++) {
  179306. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179307. j++;
  179308. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179309. }
  179310. }
  179311. } else {
  179312. /* Edge blocks are transposed but not mirrored. */
  179313. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179314. for (i = 0; i < DCTSIZE; i++)
  179315. for (j = 0; j < DCTSIZE; j++)
  179316. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179317. }
  179318. }
  179319. }
  179320. }
  179321. }
  179322. }
  179323. }
  179324. LOCAL(void)
  179325. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179326. jvirt_barray_ptr *src_coef_arrays,
  179327. jvirt_barray_ptr *dst_coef_arrays)
  179328. /* 180 degree rotation is equivalent to
  179329. * 1. Vertical mirroring;
  179330. * 2. Horizontal mirroring.
  179331. * These two steps are merged into a single processing routine.
  179332. */
  179333. {
  179334. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179335. int ci, i, j, offset_y;
  179336. JBLOCKARRAY src_buffer, dst_buffer;
  179337. JBLOCKROW src_row_ptr, dst_row_ptr;
  179338. JCOEFPTR src_ptr, dst_ptr;
  179339. jpeg_component_info *compptr;
  179340. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179341. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179342. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179343. compptr = dstinfo->comp_info + ci;
  179344. comp_width = MCU_cols * compptr->h_samp_factor;
  179345. comp_height = MCU_rows * compptr->v_samp_factor;
  179346. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179347. dst_blk_y += compptr->v_samp_factor) {
  179348. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179349. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179350. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179351. if (dst_blk_y < comp_height) {
  179352. /* Row is within the vertically mirrorable area. */
  179353. src_buffer = (*srcinfo->mem->access_virt_barray)
  179354. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179355. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179356. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179357. } else {
  179358. /* Bottom-edge rows are only mirrored horizontally. */
  179359. src_buffer = (*srcinfo->mem->access_virt_barray)
  179360. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179361. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179362. }
  179363. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179364. if (dst_blk_y < comp_height) {
  179365. /* Row is within the mirrorable area. */
  179366. dst_row_ptr = dst_buffer[offset_y];
  179367. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179368. /* Process the blocks that can be mirrored both ways. */
  179369. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179370. dst_ptr = dst_row_ptr[dst_blk_x];
  179371. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179372. for (i = 0; i < DCTSIZE; i += 2) {
  179373. /* For even row, negate every odd column. */
  179374. for (j = 0; j < DCTSIZE; j += 2) {
  179375. *dst_ptr++ = *src_ptr++;
  179376. *dst_ptr++ = - *src_ptr++;
  179377. }
  179378. /* For odd row, negate every even column. */
  179379. for (j = 0; j < DCTSIZE; j += 2) {
  179380. *dst_ptr++ = - *src_ptr++;
  179381. *dst_ptr++ = *src_ptr++;
  179382. }
  179383. }
  179384. }
  179385. /* Any remaining right-edge blocks are only mirrored vertically. */
  179386. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179387. dst_ptr = dst_row_ptr[dst_blk_x];
  179388. src_ptr = src_row_ptr[dst_blk_x];
  179389. for (i = 0; i < DCTSIZE; i += 2) {
  179390. for (j = 0; j < DCTSIZE; j++)
  179391. *dst_ptr++ = *src_ptr++;
  179392. for (j = 0; j < DCTSIZE; j++)
  179393. *dst_ptr++ = - *src_ptr++;
  179394. }
  179395. }
  179396. } else {
  179397. /* Remaining rows are just mirrored horizontally. */
  179398. dst_row_ptr = dst_buffer[offset_y];
  179399. src_row_ptr = src_buffer[offset_y];
  179400. /* Process the blocks that can be mirrored. */
  179401. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179402. dst_ptr = dst_row_ptr[dst_blk_x];
  179403. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179404. for (i = 0; i < DCTSIZE2; i += 2) {
  179405. *dst_ptr++ = *src_ptr++;
  179406. *dst_ptr++ = - *src_ptr++;
  179407. }
  179408. }
  179409. /* Any remaining right-edge blocks are only copied. */
  179410. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179411. dst_ptr = dst_row_ptr[dst_blk_x];
  179412. src_ptr = src_row_ptr[dst_blk_x];
  179413. for (i = 0; i < DCTSIZE2; i++)
  179414. *dst_ptr++ = *src_ptr++;
  179415. }
  179416. }
  179417. }
  179418. }
  179419. }
  179420. }
  179421. LOCAL(void)
  179422. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179423. jvirt_barray_ptr *src_coef_arrays,
  179424. jvirt_barray_ptr *dst_coef_arrays)
  179425. /* Transverse transpose is equivalent to
  179426. * 1. 180 degree rotation;
  179427. * 2. Transposition;
  179428. * or
  179429. * 1. Horizontal mirroring;
  179430. * 2. Transposition;
  179431. * 3. Horizontal mirroring.
  179432. * These steps are merged into a single processing routine.
  179433. */
  179434. {
  179435. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179436. int ci, i, j, offset_x, offset_y;
  179437. JBLOCKARRAY src_buffer, dst_buffer;
  179438. JCOEFPTR src_ptr, dst_ptr;
  179439. jpeg_component_info *compptr;
  179440. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179441. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179442. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179443. compptr = dstinfo->comp_info + ci;
  179444. comp_width = MCU_cols * compptr->h_samp_factor;
  179445. comp_height = MCU_rows * compptr->v_samp_factor;
  179446. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179447. dst_blk_y += compptr->v_samp_factor) {
  179448. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179449. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179450. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179451. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179452. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179453. dst_blk_x += compptr->h_samp_factor) {
  179454. src_buffer = (*srcinfo->mem->access_virt_barray)
  179455. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179456. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179457. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179458. if (dst_blk_y < comp_height) {
  179459. src_ptr = src_buffer[offset_x]
  179460. [comp_height - dst_blk_y - offset_y - 1];
  179461. if (dst_blk_x < comp_width) {
  179462. /* Block is within the mirrorable area. */
  179463. dst_ptr = dst_buffer[offset_y]
  179464. [comp_width - dst_blk_x - offset_x - 1];
  179465. for (i = 0; i < DCTSIZE; i++) {
  179466. for (j = 0; j < DCTSIZE; j++) {
  179467. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179468. j++;
  179469. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179470. }
  179471. i++;
  179472. for (j = 0; j < DCTSIZE; j++) {
  179473. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179474. j++;
  179475. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179476. }
  179477. }
  179478. } else {
  179479. /* Right-edge blocks are mirrored in y only */
  179480. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179481. for (i = 0; i < DCTSIZE; i++) {
  179482. for (j = 0; j < DCTSIZE; j++) {
  179483. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179484. j++;
  179485. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179486. }
  179487. }
  179488. }
  179489. } else {
  179490. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179491. if (dst_blk_x < comp_width) {
  179492. /* Bottom-edge blocks are mirrored in x only */
  179493. dst_ptr = dst_buffer[offset_y]
  179494. [comp_width - dst_blk_x - offset_x - 1];
  179495. for (i = 0; i < DCTSIZE; i++) {
  179496. for (j = 0; j < DCTSIZE; j++)
  179497. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179498. i++;
  179499. for (j = 0; j < DCTSIZE; j++)
  179500. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179501. }
  179502. } else {
  179503. /* At lower right corner, just transpose, no mirroring */
  179504. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179505. for (i = 0; i < DCTSIZE; i++)
  179506. for (j = 0; j < DCTSIZE; j++)
  179507. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179508. }
  179509. }
  179510. }
  179511. }
  179512. }
  179513. }
  179514. }
  179515. }
  179516. /* Request any required workspace.
  179517. *
  179518. * We allocate the workspace virtual arrays from the source decompression
  179519. * object, so that all the arrays (both the original data and the workspace)
  179520. * will be taken into account while making memory management decisions.
  179521. * Hence, this routine must be called after jpeg_read_header (which reads
  179522. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179523. * the source's virtual arrays).
  179524. */
  179525. GLOBAL(void)
  179526. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179527. jpeg_transform_info *info)
  179528. {
  179529. jvirt_barray_ptr *coef_arrays = NULL;
  179530. jpeg_component_info *compptr;
  179531. int ci;
  179532. if (info->force_grayscale &&
  179533. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179534. srcinfo->num_components == 3) {
  179535. /* We'll only process the first component */
  179536. info->num_components = 1;
  179537. } else {
  179538. /* Process all the components */
  179539. info->num_components = srcinfo->num_components;
  179540. }
  179541. switch (info->transform) {
  179542. case JXFORM_NONE:
  179543. case JXFORM_FLIP_H:
  179544. /* Don't need a workspace array */
  179545. break;
  179546. case JXFORM_FLIP_V:
  179547. case JXFORM_ROT_180:
  179548. /* Need workspace arrays having same dimensions as source image.
  179549. * Note that we allocate arrays padded out to the next iMCU boundary,
  179550. * so that transform routines need not worry about missing edge blocks.
  179551. */
  179552. coef_arrays = (jvirt_barray_ptr *)
  179553. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179554. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179555. for (ci = 0; ci < info->num_components; ci++) {
  179556. compptr = srcinfo->comp_info + ci;
  179557. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179558. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179559. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179560. (long) compptr->h_samp_factor),
  179561. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179562. (long) compptr->v_samp_factor),
  179563. (JDIMENSION) compptr->v_samp_factor);
  179564. }
  179565. break;
  179566. case JXFORM_TRANSPOSE:
  179567. case JXFORM_TRANSVERSE:
  179568. case JXFORM_ROT_90:
  179569. case JXFORM_ROT_270:
  179570. /* Need workspace arrays having transposed dimensions.
  179571. * Note that we allocate arrays padded out to the next iMCU boundary,
  179572. * so that transform routines need not worry about missing edge blocks.
  179573. */
  179574. coef_arrays = (jvirt_barray_ptr *)
  179575. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179576. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179577. for (ci = 0; ci < info->num_components; ci++) {
  179578. compptr = srcinfo->comp_info + ci;
  179579. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179580. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179581. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179582. (long) compptr->v_samp_factor),
  179583. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179584. (long) compptr->h_samp_factor),
  179585. (JDIMENSION) compptr->h_samp_factor);
  179586. }
  179587. break;
  179588. }
  179589. info->workspace_coef_arrays = coef_arrays;
  179590. }
  179591. /* Transpose destination image parameters */
  179592. LOCAL(void)
  179593. transpose_critical_parameters (j_compress_ptr dstinfo)
  179594. {
  179595. int tblno, i, j, ci, itemp;
  179596. jpeg_component_info *compptr;
  179597. JQUANT_TBL *qtblptr;
  179598. JDIMENSION dtemp;
  179599. UINT16 qtemp;
  179600. /* Transpose basic image dimensions */
  179601. dtemp = dstinfo->image_width;
  179602. dstinfo->image_width = dstinfo->image_height;
  179603. dstinfo->image_height = dtemp;
  179604. /* Transpose sampling factors */
  179605. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179606. compptr = dstinfo->comp_info + ci;
  179607. itemp = compptr->h_samp_factor;
  179608. compptr->h_samp_factor = compptr->v_samp_factor;
  179609. compptr->v_samp_factor = itemp;
  179610. }
  179611. /* Transpose quantization tables */
  179612. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179613. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179614. if (qtblptr != NULL) {
  179615. for (i = 0; i < DCTSIZE; i++) {
  179616. for (j = 0; j < i; j++) {
  179617. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179618. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179619. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179620. }
  179621. }
  179622. }
  179623. }
  179624. }
  179625. /* Trim off any partial iMCUs on the indicated destination edge */
  179626. LOCAL(void)
  179627. trim_right_edge (j_compress_ptr dstinfo)
  179628. {
  179629. int ci, max_h_samp_factor;
  179630. JDIMENSION MCU_cols;
  179631. /* We have to compute max_h_samp_factor ourselves,
  179632. * because it hasn't been set yet in the destination
  179633. * (and we don't want to use the source's value).
  179634. */
  179635. max_h_samp_factor = 1;
  179636. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179637. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179638. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179639. }
  179640. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179641. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179642. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179643. }
  179644. LOCAL(void)
  179645. trim_bottom_edge (j_compress_ptr dstinfo)
  179646. {
  179647. int ci, max_v_samp_factor;
  179648. JDIMENSION MCU_rows;
  179649. /* We have to compute max_v_samp_factor ourselves,
  179650. * because it hasn't been set yet in the destination
  179651. * (and we don't want to use the source's value).
  179652. */
  179653. max_v_samp_factor = 1;
  179654. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179655. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179656. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179657. }
  179658. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179659. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179660. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179661. }
  179662. /* Adjust output image parameters as needed.
  179663. *
  179664. * This must be called after jpeg_copy_critical_parameters()
  179665. * and before jpeg_write_coefficients().
  179666. *
  179667. * The return value is the set of virtual coefficient arrays to be written
  179668. * (either the ones allocated by jtransform_request_workspace, or the
  179669. * original source data arrays). The caller will need to pass this value
  179670. * to jpeg_write_coefficients().
  179671. */
  179672. GLOBAL(jvirt_barray_ptr *)
  179673. jtransform_adjust_parameters (j_decompress_ptr,
  179674. j_compress_ptr dstinfo,
  179675. jvirt_barray_ptr *src_coef_arrays,
  179676. jpeg_transform_info *info)
  179677. {
  179678. /* If force-to-grayscale is requested, adjust destination parameters */
  179679. if (info->force_grayscale) {
  179680. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179681. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179682. * will get set to 1, which typically won't match the source.
  179683. * In fact we do this even if the source is already grayscale; that
  179684. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179685. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179686. */
  179687. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179688. dstinfo->num_components == 3) ||
  179689. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179690. dstinfo->num_components == 1)) {
  179691. /* We have to preserve the source's quantization table number. */
  179692. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179693. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179694. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179695. } else {
  179696. /* Sorry, can't do it */
  179697. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179698. }
  179699. }
  179700. /* Correct the destination's image dimensions etc if necessary */
  179701. switch (info->transform) {
  179702. case JXFORM_NONE:
  179703. /* Nothing to do */
  179704. break;
  179705. case JXFORM_FLIP_H:
  179706. if (info->trim)
  179707. trim_right_edge(dstinfo);
  179708. break;
  179709. case JXFORM_FLIP_V:
  179710. if (info->trim)
  179711. trim_bottom_edge(dstinfo);
  179712. break;
  179713. case JXFORM_TRANSPOSE:
  179714. transpose_critical_parameters(dstinfo);
  179715. /* transpose does NOT have to trim anything */
  179716. break;
  179717. case JXFORM_TRANSVERSE:
  179718. transpose_critical_parameters(dstinfo);
  179719. if (info->trim) {
  179720. trim_right_edge(dstinfo);
  179721. trim_bottom_edge(dstinfo);
  179722. }
  179723. break;
  179724. case JXFORM_ROT_90:
  179725. transpose_critical_parameters(dstinfo);
  179726. if (info->trim)
  179727. trim_right_edge(dstinfo);
  179728. break;
  179729. case JXFORM_ROT_180:
  179730. if (info->trim) {
  179731. trim_right_edge(dstinfo);
  179732. trim_bottom_edge(dstinfo);
  179733. }
  179734. break;
  179735. case JXFORM_ROT_270:
  179736. transpose_critical_parameters(dstinfo);
  179737. if (info->trim)
  179738. trim_bottom_edge(dstinfo);
  179739. break;
  179740. }
  179741. /* Return the appropriate output data set */
  179742. if (info->workspace_coef_arrays != NULL)
  179743. return info->workspace_coef_arrays;
  179744. return src_coef_arrays;
  179745. }
  179746. /* Execute the actual transformation, if any.
  179747. *
  179748. * This must be called *after* jpeg_write_coefficients, because it depends
  179749. * on jpeg_write_coefficients to have computed subsidiary values such as
  179750. * the per-component width and height fields in the destination object.
  179751. *
  179752. * Note that some transformations will modify the source data arrays!
  179753. */
  179754. GLOBAL(void)
  179755. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179756. j_compress_ptr dstinfo,
  179757. jvirt_barray_ptr *src_coef_arrays,
  179758. jpeg_transform_info *info)
  179759. {
  179760. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179761. switch (info->transform) {
  179762. case JXFORM_NONE:
  179763. break;
  179764. case JXFORM_FLIP_H:
  179765. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179766. break;
  179767. case JXFORM_FLIP_V:
  179768. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179769. break;
  179770. case JXFORM_TRANSPOSE:
  179771. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179772. break;
  179773. case JXFORM_TRANSVERSE:
  179774. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179775. break;
  179776. case JXFORM_ROT_90:
  179777. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179778. break;
  179779. case JXFORM_ROT_180:
  179780. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179781. break;
  179782. case JXFORM_ROT_270:
  179783. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179784. break;
  179785. }
  179786. }
  179787. #endif /* TRANSFORMS_SUPPORTED */
  179788. /* Setup decompression object to save desired markers in memory.
  179789. * This must be called before jpeg_read_header() to have the desired effect.
  179790. */
  179791. GLOBAL(void)
  179792. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179793. {
  179794. #ifdef SAVE_MARKERS_SUPPORTED
  179795. int m;
  179796. /* Save comments except under NONE option */
  179797. if (option != JCOPYOPT_NONE) {
  179798. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179799. }
  179800. /* Save all types of APPn markers iff ALL option */
  179801. if (option == JCOPYOPT_ALL) {
  179802. for (m = 0; m < 16; m++)
  179803. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179804. }
  179805. #endif /* SAVE_MARKERS_SUPPORTED */
  179806. }
  179807. /* Copy markers saved in the given source object to the destination object.
  179808. * This should be called just after jpeg_start_compress() or
  179809. * jpeg_write_coefficients().
  179810. * Note that those routines will have written the SOI, and also the
  179811. * JFIF APP0 or Adobe APP14 markers if selected.
  179812. */
  179813. GLOBAL(void)
  179814. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179815. JCOPY_OPTION)
  179816. {
  179817. jpeg_saved_marker_ptr marker;
  179818. /* In the current implementation, we don't actually need to examine the
  179819. * option flag here; we just copy everything that got saved.
  179820. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179821. * if the encoder library already wrote one.
  179822. */
  179823. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179824. if (dstinfo->write_JFIF_header &&
  179825. marker->marker == JPEG_APP0 &&
  179826. marker->data_length >= 5 &&
  179827. GETJOCTET(marker->data[0]) == 0x4A &&
  179828. GETJOCTET(marker->data[1]) == 0x46 &&
  179829. GETJOCTET(marker->data[2]) == 0x49 &&
  179830. GETJOCTET(marker->data[3]) == 0x46 &&
  179831. GETJOCTET(marker->data[4]) == 0)
  179832. continue; /* reject duplicate JFIF */
  179833. if (dstinfo->write_Adobe_marker &&
  179834. marker->marker == JPEG_APP0+14 &&
  179835. marker->data_length >= 5 &&
  179836. GETJOCTET(marker->data[0]) == 0x41 &&
  179837. GETJOCTET(marker->data[1]) == 0x64 &&
  179838. GETJOCTET(marker->data[2]) == 0x6F &&
  179839. GETJOCTET(marker->data[3]) == 0x62 &&
  179840. GETJOCTET(marker->data[4]) == 0x65)
  179841. continue; /* reject duplicate Adobe */
  179842. #ifdef NEED_FAR_POINTERS
  179843. /* We could use jpeg_write_marker if the data weren't FAR... */
  179844. {
  179845. unsigned int i;
  179846. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179847. for (i = 0; i < marker->data_length; i++)
  179848. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179849. }
  179850. #else
  179851. jpeg_write_marker(dstinfo, marker->marker,
  179852. marker->data, marker->data_length);
  179853. #endif
  179854. }
  179855. }
  179856. /*** End of inlined file: transupp.c ***/
  179857. #else
  179858. #define JPEG_INTERNALS
  179859. #undef FAR
  179860. #include <jpeglib.h>
  179861. #endif
  179862. }
  179863. #undef max
  179864. #undef min
  179865. #if JUCE_MSVC
  179866. #pragma warning (pop)
  179867. #endif
  179868. BEGIN_JUCE_NAMESPACE
  179869. namespace JPEGHelpers
  179870. {
  179871. using namespace jpeglibNamespace;
  179872. #if ! JUCE_MSVC
  179873. using jpeglibNamespace::boolean;
  179874. #endif
  179875. struct JPEGDecodingFailure {};
  179876. void fatalErrorHandler (j_common_ptr)
  179877. {
  179878. throw JPEGDecodingFailure();
  179879. }
  179880. void silentErrorCallback1 (j_common_ptr) {}
  179881. void silentErrorCallback2 (j_common_ptr, int) {}
  179882. void silentErrorCallback3 (j_common_ptr, char*) {}
  179883. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179884. {
  179885. zerostruct (err);
  179886. err.error_exit = fatalErrorHandler;
  179887. err.emit_message = silentErrorCallback2;
  179888. err.output_message = silentErrorCallback1;
  179889. err.format_message = silentErrorCallback3;
  179890. err.reset_error_mgr = silentErrorCallback1;
  179891. }
  179892. void dummyCallback1 (j_decompress_ptr)
  179893. {
  179894. }
  179895. void jpegSkip (j_decompress_ptr decompStruct, long num)
  179896. {
  179897. decompStruct->src->next_input_byte += num;
  179898. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179899. decompStruct->src->bytes_in_buffer -= num;
  179900. }
  179901. boolean jpegFill (j_decompress_ptr)
  179902. {
  179903. return 0;
  179904. }
  179905. const int jpegBufferSize = 512;
  179906. struct JuceJpegDest : public jpeg_destination_mgr
  179907. {
  179908. OutputStream* output;
  179909. char* buffer;
  179910. };
  179911. void jpegWriteInit (j_compress_ptr)
  179912. {
  179913. }
  179914. void jpegWriteTerminate (j_compress_ptr cinfo)
  179915. {
  179916. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179917. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179918. dest->output->write (dest->buffer, (int) numToWrite);
  179919. }
  179920. boolean jpegWriteFlush (j_compress_ptr cinfo)
  179921. {
  179922. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179923. const int numToWrite = jpegBufferSize;
  179924. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179925. dest->free_in_buffer = jpegBufferSize;
  179926. return dest->output->write (dest->buffer, numToWrite);
  179927. }
  179928. }
  179929. JPEGImageFormat::JPEGImageFormat()
  179930. : quality (-1.0f)
  179931. {
  179932. }
  179933. JPEGImageFormat::~JPEGImageFormat() {}
  179934. void JPEGImageFormat::setQuality (const float newQuality)
  179935. {
  179936. quality = newQuality;
  179937. }
  179938. const String JPEGImageFormat::getFormatName()
  179939. {
  179940. return "JPEG";
  179941. }
  179942. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179943. {
  179944. const int bytesNeeded = 10;
  179945. uint8 header [bytesNeeded];
  179946. if (in.read (header, bytesNeeded) == bytesNeeded)
  179947. {
  179948. return header[0] == 0xff
  179949. && header[1] == 0xd8
  179950. && header[2] == 0xff
  179951. && (header[3] == 0xe0 || header[3] == 0xe1);
  179952. }
  179953. return false;
  179954. }
  179955. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179956. const Image juce_loadWithCoreImage (InputStream& input);
  179957. #endif
  179958. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179959. {
  179960. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179961. return juce_loadWithCoreImage (in);
  179962. #else
  179963. using namespace jpeglibNamespace;
  179964. using namespace JPEGHelpers;
  179965. MemoryOutputStream mb;
  179966. mb.writeFromInputStream (in, -1);
  179967. Image image;
  179968. if (mb.getDataSize() > 16)
  179969. {
  179970. struct jpeg_decompress_struct jpegDecompStruct;
  179971. struct jpeg_error_mgr jerr;
  179972. setupSilentErrorHandler (jerr);
  179973. jpegDecompStruct.err = &jerr;
  179974. jpeg_create_decompress (&jpegDecompStruct);
  179975. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179976. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179977. jpegDecompStruct.src->init_source = dummyCallback1;
  179978. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179979. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179980. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179981. jpegDecompStruct.src->term_source = dummyCallback1;
  179982. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179983. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179984. try
  179985. {
  179986. jpeg_read_header (&jpegDecompStruct, TRUE);
  179987. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179988. const int width = jpegDecompStruct.output_width;
  179989. const int height = jpegDecompStruct.output_height;
  179990. jpegDecompStruct.out_color_space = JCS_RGB;
  179991. JSAMPARRAY buffer
  179992. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179993. JPOOL_IMAGE,
  179994. width * 3, 1);
  179995. if (jpeg_start_decompress (&jpegDecompStruct))
  179996. {
  179997. image = Image (Image::RGB, width, height, false);
  179998. image.getProperties()->set ("originalImageHadAlpha", false);
  179999. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180000. const Image::BitmapData destData (image, true);
  180001. for (int y = 0; y < height; ++y)
  180002. {
  180003. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180004. const uint8* src = *buffer;
  180005. uint8* dest = destData.getLinePointer (y);
  180006. if (hasAlphaChan)
  180007. {
  180008. for (int i = width; --i >= 0;)
  180009. {
  180010. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180011. ((PixelARGB*) dest)->premultiply();
  180012. dest += destData.pixelStride;
  180013. src += 3;
  180014. }
  180015. }
  180016. else
  180017. {
  180018. for (int i = width; --i >= 0;)
  180019. {
  180020. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180021. dest += destData.pixelStride;
  180022. src += 3;
  180023. }
  180024. }
  180025. }
  180026. jpeg_finish_decompress (&jpegDecompStruct);
  180027. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180028. }
  180029. jpeg_destroy_decompress (&jpegDecompStruct);
  180030. }
  180031. catch (...)
  180032. {}
  180033. }
  180034. return image;
  180035. #endif
  180036. }
  180037. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180038. {
  180039. using namespace jpeglibNamespace;
  180040. using namespace JPEGHelpers;
  180041. if (image.hasAlphaChannel())
  180042. {
  180043. // this method could fill the background in white and still save the image..
  180044. jassertfalse;
  180045. return true;
  180046. }
  180047. struct jpeg_compress_struct jpegCompStruct;
  180048. struct jpeg_error_mgr jerr;
  180049. setupSilentErrorHandler (jerr);
  180050. jpegCompStruct.err = &jerr;
  180051. jpeg_create_compress (&jpegCompStruct);
  180052. JuceJpegDest dest;
  180053. jpegCompStruct.dest = &dest;
  180054. dest.output = &out;
  180055. HeapBlock <char> tempBuffer (jpegBufferSize);
  180056. dest.buffer = tempBuffer;
  180057. dest.next_output_byte = (JOCTET*) dest.buffer;
  180058. dest.free_in_buffer = jpegBufferSize;
  180059. dest.init_destination = jpegWriteInit;
  180060. dest.empty_output_buffer = jpegWriteFlush;
  180061. dest.term_destination = jpegWriteTerminate;
  180062. jpegCompStruct.image_width = image.getWidth();
  180063. jpegCompStruct.image_height = image.getHeight();
  180064. jpegCompStruct.input_components = 3;
  180065. jpegCompStruct.in_color_space = JCS_RGB;
  180066. jpegCompStruct.write_JFIF_header = 1;
  180067. jpegCompStruct.X_density = 72;
  180068. jpegCompStruct.Y_density = 72;
  180069. jpeg_set_defaults (&jpegCompStruct);
  180070. jpegCompStruct.dct_method = JDCT_FLOAT;
  180071. jpegCompStruct.optimize_coding = 1;
  180072. //jpegCompStruct.smoothing_factor = 10;
  180073. if (quality < 0.0f)
  180074. quality = 0.85f;
  180075. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180076. jpeg_start_compress (&jpegCompStruct, TRUE);
  180077. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180078. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180079. JPOOL_IMAGE, strideBytes, 1);
  180080. const Image::BitmapData srcData (image, false);
  180081. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180082. {
  180083. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180084. uint8* dst = *buffer;
  180085. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180086. {
  180087. *dst++ = ((const PixelRGB*) src)->getRed();
  180088. *dst++ = ((const PixelRGB*) src)->getGreen();
  180089. *dst++ = ((const PixelRGB*) src)->getBlue();
  180090. src += srcData.pixelStride;
  180091. }
  180092. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180093. }
  180094. jpeg_finish_compress (&jpegCompStruct);
  180095. jpeg_destroy_compress (&jpegCompStruct);
  180096. out.flush();
  180097. return true;
  180098. }
  180099. END_JUCE_NAMESPACE
  180100. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180101. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180102. #if JUCE_MSVC
  180103. #pragma warning (push)
  180104. #pragma warning (disable: 4390 4611)
  180105. #endif
  180106. namespace zlibNamespace
  180107. {
  180108. #if JUCE_INCLUDE_ZLIB_CODE
  180109. #undef OS_CODE
  180110. #undef fdopen
  180111. #undef OS_CODE
  180112. #else
  180113. #include <zlib.h>
  180114. #endif
  180115. }
  180116. namespace pnglibNamespace
  180117. {
  180118. using namespace zlibNamespace;
  180119. #if JUCE_INCLUDE_PNGLIB_CODE
  180120. #if _MSC_VER != 1310
  180121. using ::calloc; // (causes conflict in VS.NET 2003)
  180122. using ::malloc;
  180123. using ::free;
  180124. #endif
  180125. using ::abs;
  180126. #define PNG_INTERNAL
  180127. #define NO_DUMMY_DECL
  180128. #define PNG_SETJMP_NOT_SUPPORTED
  180129. /*** Start of inlined file: png.h ***/
  180130. /* png.h - header file for PNG reference library
  180131. *
  180132. * libpng version 1.2.21 - October 4, 2007
  180133. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180134. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180135. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180136. *
  180137. * Authors and maintainers:
  180138. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180139. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180140. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180141. * See also "Contributing Authors", below.
  180142. *
  180143. * Note about libpng version numbers:
  180144. *
  180145. * Due to various miscommunications, unforeseen code incompatibilities
  180146. * and occasional factors outside the authors' control, version numbering
  180147. * on the library has not always been consistent and straightforward.
  180148. * The following table summarizes matters since version 0.89c, which was
  180149. * the first widely used release:
  180150. *
  180151. * source png.h png.h shared-lib
  180152. * version string int version
  180153. * ------- ------ ----- ----------
  180154. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180155. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180156. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180157. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180158. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180159. * 0.97c 0.97 97 2.0.97
  180160. * 0.98 0.98 98 2.0.98
  180161. * 0.99 0.99 98 2.0.99
  180162. * 0.99a-m 0.99 99 2.0.99
  180163. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180164. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180165. * 1.0.1 png.h string is 10001 2.1.0
  180166. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180167. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180168. * 1.0.2a-b 10003 version, except as noted.
  180169. * 1.0.3 10003
  180170. * 1.0.3a-d 10004
  180171. * 1.0.4 10004
  180172. * 1.0.4a-f 10005
  180173. * 1.0.5 (+ 2 patches) 10005
  180174. * 1.0.5a-d 10006
  180175. * 1.0.5e-r 10100 (not source compatible)
  180176. * 1.0.5s-v 10006 (not binary compatible)
  180177. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180178. * 1.0.6d-f 10007 (still binary incompatible)
  180179. * 1.0.6g 10007
  180180. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180181. * 1.0.6i 10007 10.6i
  180182. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180183. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180184. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180185. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180186. * 1.0.7 1 10007 (still compatible)
  180187. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180188. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180189. * 1.0.8 1 10008 2.1.0.8
  180190. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180191. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180192. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180193. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180194. * 1.0.9 1 10009 2.1.0.9
  180195. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180196. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180197. * 1.0.10 1 10010 2.1.0.10
  180198. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180199. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180200. * 1.0.11 1 10011 2.1.0.11
  180201. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180202. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180203. * 1.0.12 2 10012 2.1.0.12
  180204. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180205. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180206. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180207. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180208. * 1.2.0 3 10200 3.1.2.0
  180209. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180210. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180211. * 1.2.1 3 10201 3.1.2.1
  180212. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180213. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180214. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180215. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180216. * 1.0.13 10 10013 10.so.0.1.0.13
  180217. * 1.2.2 12 10202 12.so.0.1.2.2
  180218. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180219. * 1.2.3 12 10203 12.so.0.1.2.3
  180220. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180221. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180222. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180223. * 1.0.14 10 10014 10.so.0.1.0.14
  180224. * 1.2.4 13 10204 12.so.0.1.2.4
  180225. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180226. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180227. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180228. * 1.0.15 10 10015 10.so.0.1.0.15
  180229. * 1.2.5 13 10205 12.so.0.1.2.5
  180230. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180231. * 1.0.16 10 10016 10.so.0.1.0.16
  180232. * 1.2.6 13 10206 12.so.0.1.2.6
  180233. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180234. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180235. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180236. * 1.0.17 10 10017 10.so.0.1.0.17
  180237. * 1.2.7 13 10207 12.so.0.1.2.7
  180238. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180239. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180240. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180241. * 1.0.18 10 10018 10.so.0.1.0.18
  180242. * 1.2.8 13 10208 12.so.0.1.2.8
  180243. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180244. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180245. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180246. * 1.2.9 13 10209 12.so.0.9[.0]
  180247. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180248. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180249. * 1.2.10 13 10210 12.so.0.10[.0]
  180250. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180251. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180252. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180253. * 1.0.19 10 10019 10.so.0.19[.0]
  180254. * 1.2.11 13 10211 12.so.0.11[.0]
  180255. * 1.0.20 10 10020 10.so.0.20[.0]
  180256. * 1.2.12 13 10212 12.so.0.12[.0]
  180257. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180258. * 1.0.21 10 10021 10.so.0.21[.0]
  180259. * 1.2.13 13 10213 12.so.0.13[.0]
  180260. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180261. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180262. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180263. * 1.0.22 10 10022 10.so.0.22[.0]
  180264. * 1.2.14 13 10214 12.so.0.14[.0]
  180265. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180266. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180267. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180268. * 1.0.23 10 10023 10.so.0.23[.0]
  180269. * 1.2.15 13 10215 12.so.0.15[.0]
  180270. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180271. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180272. * 1.0.24 10 10024 10.so.0.24[.0]
  180273. * 1.2.16 13 10216 12.so.0.16[.0]
  180274. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180275. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180276. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180277. * 1.0.25 10 10025 10.so.0.25[.0]
  180278. * 1.2.17 13 10217 12.so.0.17[.0]
  180279. * 1.0.26 10 10026 10.so.0.26[.0]
  180280. * 1.2.18 13 10218 12.so.0.18[.0]
  180281. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180282. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180283. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180284. * 1.0.27 10 10027 10.so.0.27[.0]
  180285. * 1.2.19 13 10219 12.so.0.19[.0]
  180286. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180287. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180288. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180289. * 1.0.28 10 10028 10.so.0.28[.0]
  180290. * 1.2.20 13 10220 12.so.0.20[.0]
  180291. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180292. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180293. * 1.0.29 10 10029 10.so.0.29[.0]
  180294. * 1.2.21 13 10221 12.so.0.21[.0]
  180295. *
  180296. * Henceforth the source version will match the shared-library major
  180297. * and minor numbers; the shared-library major version number will be
  180298. * used for changes in backward compatibility, as it is intended. The
  180299. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180300. * for applications, is an unsigned integer of the form xyyzz corresponding
  180301. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180302. * were given the previous public release number plus a letter, until
  180303. * version 1.0.6j; from then on they were given the upcoming public
  180304. * release number plus "betaNN" or "rcN".
  180305. *
  180306. * Binary incompatibility exists only when applications make direct access
  180307. * to the info_ptr or png_ptr members through png.h, and the compiled
  180308. * application is loaded with a different version of the library.
  180309. *
  180310. * DLLNUM will change each time there are forward or backward changes
  180311. * in binary compatibility (e.g., when a new feature is added).
  180312. *
  180313. * See libpng.txt or libpng.3 for more information. The PNG specification
  180314. * is available as a W3C Recommendation and as an ISO Specification,
  180315. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180316. */
  180317. /*
  180318. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180319. *
  180320. * If you modify libpng you may insert additional notices immediately following
  180321. * this sentence.
  180322. *
  180323. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180324. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180325. * distributed according to the same disclaimer and license as libpng-1.2.5
  180326. * with the following individual added to the list of Contributing Authors:
  180327. *
  180328. * Cosmin Truta
  180329. *
  180330. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180331. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180332. * distributed according to the same disclaimer and license as libpng-1.0.6
  180333. * with the following individuals added to the list of Contributing Authors:
  180334. *
  180335. * Simon-Pierre Cadieux
  180336. * Eric S. Raymond
  180337. * Gilles Vollant
  180338. *
  180339. * and with the following additions to the disclaimer:
  180340. *
  180341. * There is no warranty against interference with your enjoyment of the
  180342. * library or against infringement. There is no warranty that our
  180343. * efforts or the library will fulfill any of your particular purposes
  180344. * or needs. This library is provided with all faults, and the entire
  180345. * risk of satisfactory quality, performance, accuracy, and effort is with
  180346. * the user.
  180347. *
  180348. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180349. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180350. * distributed according to the same disclaimer and license as libpng-0.96,
  180351. * with the following individuals added to the list of Contributing Authors:
  180352. *
  180353. * Tom Lane
  180354. * Glenn Randers-Pehrson
  180355. * Willem van Schaik
  180356. *
  180357. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180358. * Copyright (c) 1996, 1997 Andreas Dilger
  180359. * Distributed according to the same disclaimer and license as libpng-0.88,
  180360. * with the following individuals added to the list of Contributing Authors:
  180361. *
  180362. * John Bowler
  180363. * Kevin Bracey
  180364. * Sam Bushell
  180365. * Magnus Holmgren
  180366. * Greg Roelofs
  180367. * Tom Tanner
  180368. *
  180369. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180370. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180371. *
  180372. * For the purposes of this copyright and license, "Contributing Authors"
  180373. * is defined as the following set of individuals:
  180374. *
  180375. * Andreas Dilger
  180376. * Dave Martindale
  180377. * Guy Eric Schalnat
  180378. * Paul Schmidt
  180379. * Tim Wegner
  180380. *
  180381. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180382. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180383. * including, without limitation, the warranties of merchantability and of
  180384. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180385. * assume no liability for direct, indirect, incidental, special, exemplary,
  180386. * or consequential damages, which may result from the use of the PNG
  180387. * Reference Library, even if advised of the possibility of such damage.
  180388. *
  180389. * Permission is hereby granted to use, copy, modify, and distribute this
  180390. * source code, or portions hereof, for any purpose, without fee, subject
  180391. * to the following restrictions:
  180392. *
  180393. * 1. The origin of this source code must not be misrepresented.
  180394. *
  180395. * 2. Altered versions must be plainly marked as such and
  180396. * must not be misrepresented as being the original source.
  180397. *
  180398. * 3. This Copyright notice may not be removed or altered from
  180399. * any source or altered source distribution.
  180400. *
  180401. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180402. * fee, and encourage the use of this source code as a component to
  180403. * supporting the PNG file format in commercial products. If you use this
  180404. * source code in a product, acknowledgment is not required but would be
  180405. * appreciated.
  180406. */
  180407. /*
  180408. * A "png_get_copyright" function is available, for convenient use in "about"
  180409. * boxes and the like:
  180410. *
  180411. * printf("%s",png_get_copyright(NULL));
  180412. *
  180413. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180414. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180415. */
  180416. /*
  180417. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180418. * certification mark of the Open Source Initiative.
  180419. */
  180420. /*
  180421. * The contributing authors would like to thank all those who helped
  180422. * with testing, bug fixes, and patience. This wouldn't have been
  180423. * possible without all of you.
  180424. *
  180425. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180426. */
  180427. /*
  180428. * Y2K compliance in libpng:
  180429. * =========================
  180430. *
  180431. * October 4, 2007
  180432. *
  180433. * Since the PNG Development group is an ad-hoc body, we can't make
  180434. * an official declaration.
  180435. *
  180436. * This is your unofficial assurance that libpng from version 0.71 and
  180437. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180438. * versions were also Y2K compliant.
  180439. *
  180440. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180441. * that will hold years up to 65535. The other two hold the date in text
  180442. * format, and will hold years up to 9999.
  180443. *
  180444. * The integer is
  180445. * "png_uint_16 year" in png_time_struct.
  180446. *
  180447. * The strings are
  180448. * "png_charp time_buffer" in png_struct and
  180449. * "near_time_buffer", which is a local character string in png.c.
  180450. *
  180451. * There are seven time-related functions:
  180452. * png.c: png_convert_to_rfc_1123() in png.c
  180453. * (formerly png_convert_to_rfc_1152() in error)
  180454. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180455. * png_convert_from_time_t() in pngwrite.c
  180456. * png_get_tIME() in pngget.c
  180457. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180458. * png_set_tIME() in pngset.c
  180459. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180460. *
  180461. * All handle dates properly in a Y2K environment. The
  180462. * png_convert_from_time_t() function calls gmtime() to convert from system
  180463. * clock time, which returns (year - 1900), which we properly convert to
  180464. * the full 4-digit year. There is a possibility that applications using
  180465. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180466. * function, or that they are incorrectly passing only a 2-digit year
  180467. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180468. * but this is not under our control. The libpng documentation has always
  180469. * stated that it works with 4-digit years, and the APIs have been
  180470. * documented as such.
  180471. *
  180472. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180473. * integer to hold the year, and can hold years as large as 65535.
  180474. *
  180475. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180476. * no date-related code.
  180477. *
  180478. * Glenn Randers-Pehrson
  180479. * libpng maintainer
  180480. * PNG Development Group
  180481. */
  180482. #ifndef PNG_H
  180483. #define PNG_H
  180484. /* This is not the place to learn how to use libpng. The file libpng.txt
  180485. * describes how to use libpng, and the file example.c summarizes it
  180486. * with some code on which to build. This file is useful for looking
  180487. * at the actual function definitions and structure components.
  180488. */
  180489. /* Version information for png.h - this should match the version in png.c */
  180490. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180491. #define PNG_HEADER_VERSION_STRING \
  180492. " libpng version 1.2.21 - October 4, 2007\n"
  180493. #define PNG_LIBPNG_VER_SONUM 0
  180494. #define PNG_LIBPNG_VER_DLLNUM 13
  180495. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180496. #define PNG_LIBPNG_VER_MAJOR 1
  180497. #define PNG_LIBPNG_VER_MINOR 2
  180498. #define PNG_LIBPNG_VER_RELEASE 21
  180499. /* This should match the numeric part of the final component of
  180500. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180501. #define PNG_LIBPNG_VER_BUILD 0
  180502. /* Release Status */
  180503. #define PNG_LIBPNG_BUILD_ALPHA 1
  180504. #define PNG_LIBPNG_BUILD_BETA 2
  180505. #define PNG_LIBPNG_BUILD_RC 3
  180506. #define PNG_LIBPNG_BUILD_STABLE 4
  180507. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180508. /* Release-Specific Flags */
  180509. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180510. PNG_LIBPNG_BUILD_STABLE only */
  180511. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180512. PNG_LIBPNG_BUILD_SPECIAL */
  180513. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180514. PNG_LIBPNG_BUILD_PRIVATE */
  180515. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180516. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180517. * We must not include leading zeros.
  180518. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180519. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180520. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180521. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180522. #ifndef PNG_VERSION_INFO_ONLY
  180523. /* include the compression library's header */
  180524. #endif
  180525. /* include all user configurable info, including optional assembler routines */
  180526. /*** Start of inlined file: pngconf.h ***/
  180527. /* pngconf.h - machine configurable file for libpng
  180528. *
  180529. * libpng version 1.2.21 - October 4, 2007
  180530. * For conditions of distribution and use, see copyright notice in png.h
  180531. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180532. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180533. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180534. */
  180535. /* Any machine specific code is near the front of this file, so if you
  180536. * are configuring libpng for a machine, you may want to read the section
  180537. * starting here down to where it starts to typedef png_color, png_text,
  180538. * and png_info.
  180539. */
  180540. #ifndef PNGCONF_H
  180541. #define PNGCONF_H
  180542. #define PNG_1_2_X
  180543. // These are some Juce config settings that should remove any unnecessary code bloat..
  180544. #define PNG_NO_STDIO 1
  180545. #define PNG_DEBUG 0
  180546. #define PNG_NO_WARNINGS 1
  180547. #define PNG_NO_ERROR_TEXT 1
  180548. #define PNG_NO_ERROR_NUMBERS 1
  180549. #define PNG_NO_USER_MEM 1
  180550. #define PNG_NO_READ_iCCP 1
  180551. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180552. #define PNG_NO_READ_USER_CHUNKS 1
  180553. #define PNG_NO_READ_iTXt 1
  180554. #define PNG_NO_READ_sCAL 1
  180555. #define PNG_NO_READ_sPLT 1
  180556. #define png_error(a, b) png_err(a)
  180557. #define png_warning(a, b)
  180558. #define png_chunk_error(a, b) png_err(a)
  180559. #define png_chunk_warning(a, b)
  180560. /*
  180561. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180562. * includes the resource compiler for Windows DLL configurations.
  180563. */
  180564. #ifdef PNG_USER_CONFIG
  180565. # ifndef PNG_USER_PRIVATEBUILD
  180566. # define PNG_USER_PRIVATEBUILD
  180567. # endif
  180568. #include "pngusr.h"
  180569. #endif
  180570. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180571. #ifdef PNG_CONFIGURE_LIBPNG
  180572. #ifdef HAVE_CONFIG_H
  180573. #include "config.h"
  180574. #endif
  180575. #endif
  180576. /*
  180577. * Added at libpng-1.2.8
  180578. *
  180579. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180580. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180581. * the DLL was built>
  180582. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180583. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180584. * distinguish your DLL from those of the official release. These
  180585. * correspond to the trailing letters that come after the version
  180586. * number and must match your private DLL name>
  180587. * e.g. // private DLL "libpng13gx.dll"
  180588. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180589. *
  180590. * The following macros are also at your disposal if you want to complete the
  180591. * DLL VERSIONINFO structure.
  180592. * - PNG_USER_VERSIONINFO_COMMENTS
  180593. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180594. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180595. */
  180596. #ifdef __STDC__
  180597. #ifdef SPECIALBUILD
  180598. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180599. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180600. #endif
  180601. #ifdef PRIVATEBUILD
  180602. # pragma message("PRIVATEBUILD is deprecated.\
  180603. Use PNG_USER_PRIVATEBUILD instead.")
  180604. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180605. #endif
  180606. #endif /* __STDC__ */
  180607. #ifndef PNG_VERSION_INFO_ONLY
  180608. /* End of material added to libpng-1.2.8 */
  180609. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180610. Restored at libpng-1.2.21 */
  180611. # define PNG_WARN_UNINITIALIZED_ROW 1
  180612. /* End of material added at libpng-1.2.19/1.2.21 */
  180613. /* This is the size of the compression buffer, and thus the size of
  180614. * an IDAT chunk. Make this whatever size you feel is best for your
  180615. * machine. One of these will be allocated per png_struct. When this
  180616. * is full, it writes the data to the disk, and does some other
  180617. * calculations. Making this an extremely small size will slow
  180618. * the library down, but you may want to experiment to determine
  180619. * where it becomes significant, if you are concerned with memory
  180620. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180621. * this describes the size of the buffer available to read the data in.
  180622. * Unless this gets smaller than the size of a row (compressed),
  180623. * it should not make much difference how big this is.
  180624. */
  180625. #ifndef PNG_ZBUF_SIZE
  180626. # define PNG_ZBUF_SIZE 8192
  180627. #endif
  180628. /* Enable if you want a write-only libpng */
  180629. #ifndef PNG_NO_READ_SUPPORTED
  180630. # define PNG_READ_SUPPORTED
  180631. #endif
  180632. /* Enable if you want a read-only libpng */
  180633. #ifndef PNG_NO_WRITE_SUPPORTED
  180634. # define PNG_WRITE_SUPPORTED
  180635. #endif
  180636. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180637. support PNGs that are embedded in MNG datastreams */
  180638. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180639. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180640. # define PNG_MNG_FEATURES_SUPPORTED
  180641. # endif
  180642. #endif
  180643. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180644. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180645. # define PNG_FLOATING_POINT_SUPPORTED
  180646. # endif
  180647. #endif
  180648. /* If you are running on a machine where you cannot allocate more
  180649. * than 64K of memory at once, uncomment this. While libpng will not
  180650. * normally need that much memory in a chunk (unless you load up a very
  180651. * large file), zlib needs to know how big of a chunk it can use, and
  180652. * libpng thus makes sure to check any memory allocation to verify it
  180653. * will fit into memory.
  180654. #define PNG_MAX_MALLOC_64K
  180655. */
  180656. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180657. # define PNG_MAX_MALLOC_64K
  180658. #endif
  180659. /* Special munging to support doing things the 'cygwin' way:
  180660. * 'Normal' png-on-win32 defines/defaults:
  180661. * PNG_BUILD_DLL -- building dll
  180662. * PNG_USE_DLL -- building an application, linking to dll
  180663. * (no define) -- building static library, or building an
  180664. * application and linking to the static lib
  180665. * 'Cygwin' defines/defaults:
  180666. * PNG_BUILD_DLL -- (ignored) building the dll
  180667. * (no define) -- (ignored) building an application, linking to the dll
  180668. * PNG_STATIC -- (ignored) building the static lib, or building an
  180669. * application that links to the static lib.
  180670. * ALL_STATIC -- (ignored) building various static libs, or building an
  180671. * application that links to the static libs.
  180672. * Thus,
  180673. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180674. * this bit of #ifdefs will define the 'correct' config variables based on
  180675. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180676. * unnecessary.
  180677. *
  180678. * Also, the precedence order is:
  180679. * ALL_STATIC (since we can't #undef something outside our namespace)
  180680. * PNG_BUILD_DLL
  180681. * PNG_STATIC
  180682. * (nothing) == PNG_USE_DLL
  180683. *
  180684. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180685. * of auto-import in binutils, we no longer need to worry about
  180686. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180687. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180688. * to __declspec() stuff. However, we DO need to worry about
  180689. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180690. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180691. */
  180692. #if defined(__CYGWIN__)
  180693. # if defined(ALL_STATIC)
  180694. # if defined(PNG_BUILD_DLL)
  180695. # undef PNG_BUILD_DLL
  180696. # endif
  180697. # if defined(PNG_USE_DLL)
  180698. # undef PNG_USE_DLL
  180699. # endif
  180700. # if defined(PNG_DLL)
  180701. # undef PNG_DLL
  180702. # endif
  180703. # if !defined(PNG_STATIC)
  180704. # define PNG_STATIC
  180705. # endif
  180706. # else
  180707. # if defined (PNG_BUILD_DLL)
  180708. # if defined(PNG_STATIC)
  180709. # undef PNG_STATIC
  180710. # endif
  180711. # if defined(PNG_USE_DLL)
  180712. # undef PNG_USE_DLL
  180713. # endif
  180714. # if !defined(PNG_DLL)
  180715. # define PNG_DLL
  180716. # endif
  180717. # else
  180718. # if defined(PNG_STATIC)
  180719. # if defined(PNG_USE_DLL)
  180720. # undef PNG_USE_DLL
  180721. # endif
  180722. # if defined(PNG_DLL)
  180723. # undef PNG_DLL
  180724. # endif
  180725. # else
  180726. # if !defined(PNG_USE_DLL)
  180727. # define PNG_USE_DLL
  180728. # endif
  180729. # if !defined(PNG_DLL)
  180730. # define PNG_DLL
  180731. # endif
  180732. # endif
  180733. # endif
  180734. # endif
  180735. #endif
  180736. /* This protects us against compilers that run on a windowing system
  180737. * and thus don't have or would rather us not use the stdio types:
  180738. * stdin, stdout, and stderr. The only one currently used is stderr
  180739. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180740. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180741. * will also prevent these, plus will prevent the entire set of stdio
  180742. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180743. * unless (PNG_DEBUG > 0) has been #defined.
  180744. *
  180745. * #define PNG_NO_CONSOLE_IO
  180746. * #define PNG_NO_STDIO
  180747. */
  180748. #if defined(_WIN32_WCE)
  180749. # include <windows.h>
  180750. /* Console I/O functions are not supported on WindowsCE */
  180751. # define PNG_NO_CONSOLE_IO
  180752. # ifdef PNG_DEBUG
  180753. # undef PNG_DEBUG
  180754. # endif
  180755. #endif
  180756. #ifdef PNG_BUILD_DLL
  180757. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180758. # ifndef PNG_NO_CONSOLE_IO
  180759. # define PNG_NO_CONSOLE_IO
  180760. # endif
  180761. # endif
  180762. #endif
  180763. # ifdef PNG_NO_STDIO
  180764. # ifndef PNG_NO_CONSOLE_IO
  180765. # define PNG_NO_CONSOLE_IO
  180766. # endif
  180767. # ifdef PNG_DEBUG
  180768. # if (PNG_DEBUG > 0)
  180769. # include <stdio.h>
  180770. # endif
  180771. # endif
  180772. # else
  180773. # if !defined(_WIN32_WCE)
  180774. /* "stdio.h" functions are not supported on WindowsCE */
  180775. # include <stdio.h>
  180776. # endif
  180777. # endif
  180778. /* This macro protects us against machines that don't have function
  180779. * prototypes (ie K&R style headers). If your compiler does not handle
  180780. * function prototypes, define this macro and use the included ansi2knr.
  180781. * I've always been able to use _NO_PROTO as the indicator, but you may
  180782. * need to drag the empty declaration out in front of here, or change the
  180783. * ifdef to suit your own needs.
  180784. */
  180785. #ifndef PNGARG
  180786. #ifdef OF /* zlib prototype munger */
  180787. # define PNGARG(arglist) OF(arglist)
  180788. #else
  180789. #ifdef _NO_PROTO
  180790. # define PNGARG(arglist) ()
  180791. # ifndef PNG_TYPECAST_NULL
  180792. # define PNG_TYPECAST_NULL
  180793. # endif
  180794. #else
  180795. # define PNGARG(arglist) arglist
  180796. #endif /* _NO_PROTO */
  180797. #endif /* OF */
  180798. #endif /* PNGARG */
  180799. /* Try to determine if we are compiling on a Mac. Note that testing for
  180800. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180801. * on non-Mac platforms.
  180802. */
  180803. #ifndef MACOS
  180804. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180805. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180806. # define MACOS
  180807. # endif
  180808. #endif
  180809. /* enough people need this for various reasons to include it here */
  180810. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180811. # include <sys/types.h>
  180812. #endif
  180813. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180814. # define PNG_SETJMP_SUPPORTED
  180815. #endif
  180816. #ifdef PNG_SETJMP_SUPPORTED
  180817. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180818. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180819. */
  180820. # ifdef __linux__
  180821. # ifdef _BSD_SOURCE
  180822. # define PNG_SAVE_BSD_SOURCE
  180823. # undef _BSD_SOURCE
  180824. # endif
  180825. # ifdef _SETJMP_H
  180826. /* If you encounter a compiler error here, see the explanation
  180827. * near the end of INSTALL.
  180828. */
  180829. __png.h__ already includes setjmp.h;
  180830. __dont__ include it again.;
  180831. # endif
  180832. # endif /* __linux__ */
  180833. /* include setjmp.h for error handling */
  180834. # include <setjmp.h>
  180835. # ifdef __linux__
  180836. # ifdef PNG_SAVE_BSD_SOURCE
  180837. # define _BSD_SOURCE
  180838. # undef PNG_SAVE_BSD_SOURCE
  180839. # endif
  180840. # endif /* __linux__ */
  180841. #endif /* PNG_SETJMP_SUPPORTED */
  180842. #ifdef BSD
  180843. #if ! JUCE_MAC
  180844. # include <strings.h>
  180845. #endif
  180846. #else
  180847. # include <string.h>
  180848. #endif
  180849. /* Other defines for things like memory and the like can go here. */
  180850. #ifdef PNG_INTERNAL
  180851. #include <stdlib.h>
  180852. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180853. * aren't usually used outside the library (as far as I know), so it is
  180854. * debatable if they should be exported at all. In the future, when it is
  180855. * possible to have run-time registry of chunk-handling functions, some of
  180856. * these will be made available again.
  180857. #define PNG_EXTERN extern
  180858. */
  180859. #define PNG_EXTERN
  180860. /* Other defines specific to compilers can go here. Try to keep
  180861. * them inside an appropriate ifdef/endif pair for portability.
  180862. */
  180863. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180864. # if defined(MACOS)
  180865. /* We need to check that <math.h> hasn't already been included earlier
  180866. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180867. * <fp.h> if possible.
  180868. */
  180869. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180870. # include <fp.h>
  180871. # endif
  180872. # else
  180873. # include <math.h>
  180874. # endif
  180875. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180876. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180877. * MATH=68881
  180878. */
  180879. # include <m68881.h>
  180880. # endif
  180881. #endif
  180882. /* Codewarrior on NT has linking problems without this. */
  180883. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180884. # define PNG_ALWAYS_EXTERN
  180885. #endif
  180886. /* This provides the non-ANSI (far) memory allocation routines. */
  180887. #if defined(__TURBOC__) && defined(__MSDOS__)
  180888. # include <mem.h>
  180889. # include <alloc.h>
  180890. #endif
  180891. /* I have no idea why is this necessary... */
  180892. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180893. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180894. # include <malloc.h>
  180895. #endif
  180896. /* This controls how fine the dithering gets. As this allocates
  180897. * a largish chunk of memory (32K), those who are not as concerned
  180898. * with dithering quality can decrease some or all of these.
  180899. */
  180900. #ifndef PNG_DITHER_RED_BITS
  180901. # define PNG_DITHER_RED_BITS 5
  180902. #endif
  180903. #ifndef PNG_DITHER_GREEN_BITS
  180904. # define PNG_DITHER_GREEN_BITS 5
  180905. #endif
  180906. #ifndef PNG_DITHER_BLUE_BITS
  180907. # define PNG_DITHER_BLUE_BITS 5
  180908. #endif
  180909. /* This controls how fine the gamma correction becomes when you
  180910. * are only interested in 8 bits anyway. Increasing this value
  180911. * results in more memory being used, and more pow() functions
  180912. * being called to fill in the gamma tables. Don't set this value
  180913. * less then 8, and even that may not work (I haven't tested it).
  180914. */
  180915. #ifndef PNG_MAX_GAMMA_8
  180916. # define PNG_MAX_GAMMA_8 11
  180917. #endif
  180918. /* This controls how much a difference in gamma we can tolerate before
  180919. * we actually start doing gamma conversion.
  180920. */
  180921. #ifndef PNG_GAMMA_THRESHOLD
  180922. # define PNG_GAMMA_THRESHOLD 0.05
  180923. #endif
  180924. #endif /* PNG_INTERNAL */
  180925. /* The following uses const char * instead of char * for error
  180926. * and warning message functions, so some compilers won't complain.
  180927. * If you do not want to use const, define PNG_NO_CONST here.
  180928. */
  180929. #ifndef PNG_NO_CONST
  180930. # define PNG_CONST const
  180931. #else
  180932. # define PNG_CONST
  180933. #endif
  180934. /* The following defines give you the ability to remove code from the
  180935. * library that you will not be using. I wish I could figure out how to
  180936. * automate this, but I can't do that without making it seriously hard
  180937. * on the users. So if you are not using an ability, change the #define
  180938. * to and #undef, and that part of the library will not be compiled. If
  180939. * your linker can't find a function, you may want to make sure the
  180940. * ability is defined here. Some of these depend upon some others being
  180941. * defined. I haven't figured out all the interactions here, so you may
  180942. * have to experiment awhile to get everything to compile. If you are
  180943. * creating or using a shared library, you probably shouldn't touch this,
  180944. * as it will affect the size of the structures, and this will cause bad
  180945. * things to happen if the library and/or application ever change.
  180946. */
  180947. /* Any features you will not be using can be undef'ed here */
  180948. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180949. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180950. * on the compile line, then pick and choose which ones to define without
  180951. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180952. * if you only want to have a png-compliant reader/writer but don't need
  180953. * any of the extra transformations. This saves about 80 kbytes in a
  180954. * typical installation of the library. (PNG_NO_* form added in version
  180955. * 1.0.1c, for consistency)
  180956. */
  180957. /* The size of the png_text structure changed in libpng-1.0.6 when
  180958. * iTXt support was added. iTXt support was turned off by default through
  180959. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180960. * instead of calling png_set_text() and letting libpng malloc it. It
  180961. * was turned on by default in libpng-1.3.0.
  180962. */
  180963. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180964. # ifndef PNG_NO_iTXt_SUPPORTED
  180965. # define PNG_NO_iTXt_SUPPORTED
  180966. # endif
  180967. # ifndef PNG_NO_READ_iTXt
  180968. # define PNG_NO_READ_iTXt
  180969. # endif
  180970. # ifndef PNG_NO_WRITE_iTXt
  180971. # define PNG_NO_WRITE_iTXt
  180972. # endif
  180973. #endif
  180974. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180975. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180976. # define PNG_READ_iTXt
  180977. # endif
  180978. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180979. # define PNG_WRITE_iTXt
  180980. # endif
  180981. #endif
  180982. /* The following support, added after version 1.0.0, can be turned off here en
  180983. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180984. * with old applications that require the length of png_struct and png_info
  180985. * to remain unchanged.
  180986. */
  180987. #ifdef PNG_LEGACY_SUPPORTED
  180988. # define PNG_NO_FREE_ME
  180989. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180990. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180991. # define PNG_NO_READ_USER_CHUNKS
  180992. # define PNG_NO_READ_iCCP
  180993. # define PNG_NO_WRITE_iCCP
  180994. # define PNG_NO_READ_iTXt
  180995. # define PNG_NO_WRITE_iTXt
  180996. # define PNG_NO_READ_sCAL
  180997. # define PNG_NO_WRITE_sCAL
  180998. # define PNG_NO_READ_sPLT
  180999. # define PNG_NO_WRITE_sPLT
  181000. # define PNG_NO_INFO_IMAGE
  181001. # define PNG_NO_READ_RGB_TO_GRAY
  181002. # define PNG_NO_READ_USER_TRANSFORM
  181003. # define PNG_NO_WRITE_USER_TRANSFORM
  181004. # define PNG_NO_USER_MEM
  181005. # define PNG_NO_READ_EMPTY_PLTE
  181006. # define PNG_NO_MNG_FEATURES
  181007. # define PNG_NO_FIXED_POINT_SUPPORTED
  181008. #endif
  181009. /* Ignore attempt to turn off both floating and fixed point support */
  181010. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181011. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181012. # define PNG_FIXED_POINT_SUPPORTED
  181013. #endif
  181014. #ifndef PNG_NO_FREE_ME
  181015. # define PNG_FREE_ME_SUPPORTED
  181016. #endif
  181017. #if defined(PNG_READ_SUPPORTED)
  181018. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181019. !defined(PNG_NO_READ_TRANSFORMS)
  181020. # define PNG_READ_TRANSFORMS_SUPPORTED
  181021. #endif
  181022. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181023. # ifndef PNG_NO_READ_EXPAND
  181024. # define PNG_READ_EXPAND_SUPPORTED
  181025. # endif
  181026. # ifndef PNG_NO_READ_SHIFT
  181027. # define PNG_READ_SHIFT_SUPPORTED
  181028. # endif
  181029. # ifndef PNG_NO_READ_PACK
  181030. # define PNG_READ_PACK_SUPPORTED
  181031. # endif
  181032. # ifndef PNG_NO_READ_BGR
  181033. # define PNG_READ_BGR_SUPPORTED
  181034. # endif
  181035. # ifndef PNG_NO_READ_SWAP
  181036. # define PNG_READ_SWAP_SUPPORTED
  181037. # endif
  181038. # ifndef PNG_NO_READ_PACKSWAP
  181039. # define PNG_READ_PACKSWAP_SUPPORTED
  181040. # endif
  181041. # ifndef PNG_NO_READ_INVERT
  181042. # define PNG_READ_INVERT_SUPPORTED
  181043. # endif
  181044. # ifndef PNG_NO_READ_DITHER
  181045. # define PNG_READ_DITHER_SUPPORTED
  181046. # endif
  181047. # ifndef PNG_NO_READ_BACKGROUND
  181048. # define PNG_READ_BACKGROUND_SUPPORTED
  181049. # endif
  181050. # ifndef PNG_NO_READ_16_TO_8
  181051. # define PNG_READ_16_TO_8_SUPPORTED
  181052. # endif
  181053. # ifndef PNG_NO_READ_FILLER
  181054. # define PNG_READ_FILLER_SUPPORTED
  181055. # endif
  181056. # ifndef PNG_NO_READ_GAMMA
  181057. # define PNG_READ_GAMMA_SUPPORTED
  181058. # endif
  181059. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181060. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181061. # endif
  181062. # ifndef PNG_NO_READ_SWAP_ALPHA
  181063. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181064. # endif
  181065. # ifndef PNG_NO_READ_INVERT_ALPHA
  181066. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181067. # endif
  181068. # ifndef PNG_NO_READ_STRIP_ALPHA
  181069. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181070. # endif
  181071. # ifndef PNG_NO_READ_USER_TRANSFORM
  181072. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181073. # endif
  181074. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181075. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181076. # endif
  181077. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181078. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181079. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181080. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181081. #endif /* about interlacing capability! You'll */
  181082. /* still have interlacing unless you change the following line: */
  181083. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181084. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181085. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181086. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181087. # endif
  181088. #endif
  181089. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181090. /* Deprecated, will be removed from version 2.0.0.
  181091. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181092. #ifndef PNG_NO_READ_EMPTY_PLTE
  181093. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181094. #endif
  181095. #endif
  181096. #endif /* PNG_READ_SUPPORTED */
  181097. #if defined(PNG_WRITE_SUPPORTED)
  181098. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181099. !defined(PNG_NO_WRITE_TRANSFORMS)
  181100. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181101. #endif
  181102. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181103. # ifndef PNG_NO_WRITE_SHIFT
  181104. # define PNG_WRITE_SHIFT_SUPPORTED
  181105. # endif
  181106. # ifndef PNG_NO_WRITE_PACK
  181107. # define PNG_WRITE_PACK_SUPPORTED
  181108. # endif
  181109. # ifndef PNG_NO_WRITE_BGR
  181110. # define PNG_WRITE_BGR_SUPPORTED
  181111. # endif
  181112. # ifndef PNG_NO_WRITE_SWAP
  181113. # define PNG_WRITE_SWAP_SUPPORTED
  181114. # endif
  181115. # ifndef PNG_NO_WRITE_PACKSWAP
  181116. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181117. # endif
  181118. # ifndef PNG_NO_WRITE_INVERT
  181119. # define PNG_WRITE_INVERT_SUPPORTED
  181120. # endif
  181121. # ifndef PNG_NO_WRITE_FILLER
  181122. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181123. # endif
  181124. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181125. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181126. # endif
  181127. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181128. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181129. # endif
  181130. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181131. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181132. # endif
  181133. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181134. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181135. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181136. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181137. encoders, but can cause trouble
  181138. if left undefined */
  181139. #endif
  181140. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181141. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181142. defined(PNG_FLOATING_POINT_SUPPORTED)
  181143. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181144. #endif
  181145. #ifndef PNG_NO_WRITE_FLUSH
  181146. # define PNG_WRITE_FLUSH_SUPPORTED
  181147. #endif
  181148. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181149. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181150. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181151. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181152. #endif
  181153. #endif
  181154. #endif /* PNG_WRITE_SUPPORTED */
  181155. #ifndef PNG_1_0_X
  181156. # ifndef PNG_NO_ERROR_NUMBERS
  181157. # define PNG_ERROR_NUMBERS_SUPPORTED
  181158. # endif
  181159. #endif /* PNG_1_0_X */
  181160. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181161. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181162. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181163. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181164. # endif
  181165. #endif
  181166. #ifndef PNG_NO_STDIO
  181167. # define PNG_TIME_RFC1123_SUPPORTED
  181168. #endif
  181169. /* This adds extra functions in pngget.c for accessing data from the
  181170. * info pointer (added in version 0.99)
  181171. * png_get_image_width()
  181172. * png_get_image_height()
  181173. * png_get_bit_depth()
  181174. * png_get_color_type()
  181175. * png_get_compression_type()
  181176. * png_get_filter_type()
  181177. * png_get_interlace_type()
  181178. * png_get_pixel_aspect_ratio()
  181179. * png_get_pixels_per_meter()
  181180. * png_get_x_offset_pixels()
  181181. * png_get_y_offset_pixels()
  181182. * png_get_x_offset_microns()
  181183. * png_get_y_offset_microns()
  181184. */
  181185. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181186. # define PNG_EASY_ACCESS_SUPPORTED
  181187. #endif
  181188. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181189. * and removed from version 1.2.20. The following will be removed
  181190. * from libpng-1.4.0
  181191. */
  181192. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181193. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181194. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181195. # endif
  181196. #endif
  181197. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181198. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181199. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181200. # endif
  181201. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181202. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181203. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181204. # define PNG_NO_MMX_CODE
  181205. # endif
  181206. # endif
  181207. # if defined(__APPLE__)
  181208. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181209. # define PNG_NO_MMX_CODE
  181210. # endif
  181211. # endif
  181212. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181213. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181214. # define PNG_NO_MMX_CODE
  181215. # endif
  181216. # endif
  181217. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181218. # define PNG_MMX_CODE_SUPPORTED
  181219. # endif
  181220. #endif
  181221. /* end of obsolete code to be removed from libpng-1.4.0 */
  181222. #if !defined(PNG_1_0_X)
  181223. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181224. # define PNG_USER_MEM_SUPPORTED
  181225. #endif
  181226. #endif /* PNG_1_0_X */
  181227. /* Added at libpng-1.2.6 */
  181228. #if !defined(PNG_1_0_X)
  181229. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181230. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181231. # define PNG_SET_USER_LIMITS_SUPPORTED
  181232. #endif
  181233. #endif
  181234. #endif /* PNG_1_0_X */
  181235. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181236. * how large, set these limits to 0x7fffffffL
  181237. */
  181238. #ifndef PNG_USER_WIDTH_MAX
  181239. # define PNG_USER_WIDTH_MAX 1000000L
  181240. #endif
  181241. #ifndef PNG_USER_HEIGHT_MAX
  181242. # define PNG_USER_HEIGHT_MAX 1000000L
  181243. #endif
  181244. /* These are currently experimental features, define them if you want */
  181245. /* very little testing */
  181246. /*
  181247. #ifdef PNG_READ_SUPPORTED
  181248. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181249. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181250. # endif
  181251. #endif
  181252. */
  181253. /* This is only for PowerPC big-endian and 680x0 systems */
  181254. /* some testing */
  181255. /*
  181256. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181257. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181258. #endif
  181259. */
  181260. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181261. /*
  181262. #define PNG_NO_POINTER_INDEXING
  181263. */
  181264. /* These functions are turned off by default, as they will be phased out. */
  181265. /*
  181266. #define PNG_USELESS_TESTS_SUPPORTED
  181267. #define PNG_CORRECT_PALETTE_SUPPORTED
  181268. */
  181269. /* Any chunks you are not interested in, you can undef here. The
  181270. * ones that allocate memory may be expecially important (hIST,
  181271. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181272. * a bit smaller.
  181273. */
  181274. #if defined(PNG_READ_SUPPORTED) && \
  181275. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181276. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181277. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181278. #endif
  181279. #if defined(PNG_WRITE_SUPPORTED) && \
  181280. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181281. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181282. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181283. #endif
  181284. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181285. #ifdef PNG_NO_READ_TEXT
  181286. # define PNG_NO_READ_iTXt
  181287. # define PNG_NO_READ_tEXt
  181288. # define PNG_NO_READ_zTXt
  181289. #endif
  181290. #ifndef PNG_NO_READ_bKGD
  181291. # define PNG_READ_bKGD_SUPPORTED
  181292. # define PNG_bKGD_SUPPORTED
  181293. #endif
  181294. #ifndef PNG_NO_READ_cHRM
  181295. # define PNG_READ_cHRM_SUPPORTED
  181296. # define PNG_cHRM_SUPPORTED
  181297. #endif
  181298. #ifndef PNG_NO_READ_gAMA
  181299. # define PNG_READ_gAMA_SUPPORTED
  181300. # define PNG_gAMA_SUPPORTED
  181301. #endif
  181302. #ifndef PNG_NO_READ_hIST
  181303. # define PNG_READ_hIST_SUPPORTED
  181304. # define PNG_hIST_SUPPORTED
  181305. #endif
  181306. #ifndef PNG_NO_READ_iCCP
  181307. # define PNG_READ_iCCP_SUPPORTED
  181308. # define PNG_iCCP_SUPPORTED
  181309. #endif
  181310. #ifndef PNG_NO_READ_iTXt
  181311. # ifndef PNG_READ_iTXt_SUPPORTED
  181312. # define PNG_READ_iTXt_SUPPORTED
  181313. # endif
  181314. # ifndef PNG_iTXt_SUPPORTED
  181315. # define PNG_iTXt_SUPPORTED
  181316. # endif
  181317. #endif
  181318. #ifndef PNG_NO_READ_oFFs
  181319. # define PNG_READ_oFFs_SUPPORTED
  181320. # define PNG_oFFs_SUPPORTED
  181321. #endif
  181322. #ifndef PNG_NO_READ_pCAL
  181323. # define PNG_READ_pCAL_SUPPORTED
  181324. # define PNG_pCAL_SUPPORTED
  181325. #endif
  181326. #ifndef PNG_NO_READ_sCAL
  181327. # define PNG_READ_sCAL_SUPPORTED
  181328. # define PNG_sCAL_SUPPORTED
  181329. #endif
  181330. #ifndef PNG_NO_READ_pHYs
  181331. # define PNG_READ_pHYs_SUPPORTED
  181332. # define PNG_pHYs_SUPPORTED
  181333. #endif
  181334. #ifndef PNG_NO_READ_sBIT
  181335. # define PNG_READ_sBIT_SUPPORTED
  181336. # define PNG_sBIT_SUPPORTED
  181337. #endif
  181338. #ifndef PNG_NO_READ_sPLT
  181339. # define PNG_READ_sPLT_SUPPORTED
  181340. # define PNG_sPLT_SUPPORTED
  181341. #endif
  181342. #ifndef PNG_NO_READ_sRGB
  181343. # define PNG_READ_sRGB_SUPPORTED
  181344. # define PNG_sRGB_SUPPORTED
  181345. #endif
  181346. #ifndef PNG_NO_READ_tEXt
  181347. # define PNG_READ_tEXt_SUPPORTED
  181348. # define PNG_tEXt_SUPPORTED
  181349. #endif
  181350. #ifndef PNG_NO_READ_tIME
  181351. # define PNG_READ_tIME_SUPPORTED
  181352. # define PNG_tIME_SUPPORTED
  181353. #endif
  181354. #ifndef PNG_NO_READ_tRNS
  181355. # define PNG_READ_tRNS_SUPPORTED
  181356. # define PNG_tRNS_SUPPORTED
  181357. #endif
  181358. #ifndef PNG_NO_READ_zTXt
  181359. # define PNG_READ_zTXt_SUPPORTED
  181360. # define PNG_zTXt_SUPPORTED
  181361. #endif
  181362. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181363. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181364. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181365. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181366. # endif
  181367. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181368. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181369. # endif
  181370. #endif
  181371. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181372. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181373. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181374. # define PNG_USER_CHUNKS_SUPPORTED
  181375. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181376. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181377. # endif
  181378. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181379. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181380. # endif
  181381. #endif
  181382. #ifndef PNG_NO_READ_OPT_PLTE
  181383. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181384. #endif /* optional PLTE chunk in RGB and RGBA images */
  181385. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181386. defined(PNG_READ_zTXt_SUPPORTED)
  181387. # define PNG_READ_TEXT_SUPPORTED
  181388. # define PNG_TEXT_SUPPORTED
  181389. #endif
  181390. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181391. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181392. #ifdef PNG_NO_WRITE_TEXT
  181393. # define PNG_NO_WRITE_iTXt
  181394. # define PNG_NO_WRITE_tEXt
  181395. # define PNG_NO_WRITE_zTXt
  181396. #endif
  181397. #ifndef PNG_NO_WRITE_bKGD
  181398. # define PNG_WRITE_bKGD_SUPPORTED
  181399. # ifndef PNG_bKGD_SUPPORTED
  181400. # define PNG_bKGD_SUPPORTED
  181401. # endif
  181402. #endif
  181403. #ifndef PNG_NO_WRITE_cHRM
  181404. # define PNG_WRITE_cHRM_SUPPORTED
  181405. # ifndef PNG_cHRM_SUPPORTED
  181406. # define PNG_cHRM_SUPPORTED
  181407. # endif
  181408. #endif
  181409. #ifndef PNG_NO_WRITE_gAMA
  181410. # define PNG_WRITE_gAMA_SUPPORTED
  181411. # ifndef PNG_gAMA_SUPPORTED
  181412. # define PNG_gAMA_SUPPORTED
  181413. # endif
  181414. #endif
  181415. #ifndef PNG_NO_WRITE_hIST
  181416. # define PNG_WRITE_hIST_SUPPORTED
  181417. # ifndef PNG_hIST_SUPPORTED
  181418. # define PNG_hIST_SUPPORTED
  181419. # endif
  181420. #endif
  181421. #ifndef PNG_NO_WRITE_iCCP
  181422. # define PNG_WRITE_iCCP_SUPPORTED
  181423. # ifndef PNG_iCCP_SUPPORTED
  181424. # define PNG_iCCP_SUPPORTED
  181425. # endif
  181426. #endif
  181427. #ifndef PNG_NO_WRITE_iTXt
  181428. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181429. # define PNG_WRITE_iTXt_SUPPORTED
  181430. # endif
  181431. # ifndef PNG_iTXt_SUPPORTED
  181432. # define PNG_iTXt_SUPPORTED
  181433. # endif
  181434. #endif
  181435. #ifndef PNG_NO_WRITE_oFFs
  181436. # define PNG_WRITE_oFFs_SUPPORTED
  181437. # ifndef PNG_oFFs_SUPPORTED
  181438. # define PNG_oFFs_SUPPORTED
  181439. # endif
  181440. #endif
  181441. #ifndef PNG_NO_WRITE_pCAL
  181442. # define PNG_WRITE_pCAL_SUPPORTED
  181443. # ifndef PNG_pCAL_SUPPORTED
  181444. # define PNG_pCAL_SUPPORTED
  181445. # endif
  181446. #endif
  181447. #ifndef PNG_NO_WRITE_sCAL
  181448. # define PNG_WRITE_sCAL_SUPPORTED
  181449. # ifndef PNG_sCAL_SUPPORTED
  181450. # define PNG_sCAL_SUPPORTED
  181451. # endif
  181452. #endif
  181453. #ifndef PNG_NO_WRITE_pHYs
  181454. # define PNG_WRITE_pHYs_SUPPORTED
  181455. # ifndef PNG_pHYs_SUPPORTED
  181456. # define PNG_pHYs_SUPPORTED
  181457. # endif
  181458. #endif
  181459. #ifndef PNG_NO_WRITE_sBIT
  181460. # define PNG_WRITE_sBIT_SUPPORTED
  181461. # ifndef PNG_sBIT_SUPPORTED
  181462. # define PNG_sBIT_SUPPORTED
  181463. # endif
  181464. #endif
  181465. #ifndef PNG_NO_WRITE_sPLT
  181466. # define PNG_WRITE_sPLT_SUPPORTED
  181467. # ifndef PNG_sPLT_SUPPORTED
  181468. # define PNG_sPLT_SUPPORTED
  181469. # endif
  181470. #endif
  181471. #ifndef PNG_NO_WRITE_sRGB
  181472. # define PNG_WRITE_sRGB_SUPPORTED
  181473. # ifndef PNG_sRGB_SUPPORTED
  181474. # define PNG_sRGB_SUPPORTED
  181475. # endif
  181476. #endif
  181477. #ifndef PNG_NO_WRITE_tEXt
  181478. # define PNG_WRITE_tEXt_SUPPORTED
  181479. # ifndef PNG_tEXt_SUPPORTED
  181480. # define PNG_tEXt_SUPPORTED
  181481. # endif
  181482. #endif
  181483. #ifndef PNG_NO_WRITE_tIME
  181484. # define PNG_WRITE_tIME_SUPPORTED
  181485. # ifndef PNG_tIME_SUPPORTED
  181486. # define PNG_tIME_SUPPORTED
  181487. # endif
  181488. #endif
  181489. #ifndef PNG_NO_WRITE_tRNS
  181490. # define PNG_WRITE_tRNS_SUPPORTED
  181491. # ifndef PNG_tRNS_SUPPORTED
  181492. # define PNG_tRNS_SUPPORTED
  181493. # endif
  181494. #endif
  181495. #ifndef PNG_NO_WRITE_zTXt
  181496. # define PNG_WRITE_zTXt_SUPPORTED
  181497. # ifndef PNG_zTXt_SUPPORTED
  181498. # define PNG_zTXt_SUPPORTED
  181499. # endif
  181500. #endif
  181501. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181502. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181503. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181504. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181505. # endif
  181506. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181507. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181508. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181509. # endif
  181510. # endif
  181511. #endif
  181512. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181513. defined(PNG_WRITE_zTXt_SUPPORTED)
  181514. # define PNG_WRITE_TEXT_SUPPORTED
  181515. # ifndef PNG_TEXT_SUPPORTED
  181516. # define PNG_TEXT_SUPPORTED
  181517. # endif
  181518. #endif
  181519. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181520. /* Turn this off to disable png_read_png() and
  181521. * png_write_png() and leave the row_pointers member
  181522. * out of the info structure.
  181523. */
  181524. #ifndef PNG_NO_INFO_IMAGE
  181525. # define PNG_INFO_IMAGE_SUPPORTED
  181526. #endif
  181527. /* need the time information for reading tIME chunks */
  181528. #if defined(PNG_tIME_SUPPORTED)
  181529. # if !defined(_WIN32_WCE)
  181530. /* "time.h" functions are not supported on WindowsCE */
  181531. # include <time.h>
  181532. # endif
  181533. #endif
  181534. /* Some typedefs to get us started. These should be safe on most of the
  181535. * common platforms. The typedefs should be at least as large as the
  181536. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181537. * don't have to be exactly that size. Some compilers dislike passing
  181538. * unsigned shorts as function parameters, so you may be better off using
  181539. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181540. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181541. */
  181542. typedef unsigned long png_uint_32;
  181543. typedef long png_int_32;
  181544. typedef unsigned short png_uint_16;
  181545. typedef short png_int_16;
  181546. typedef unsigned char png_byte;
  181547. /* This is usually size_t. It is typedef'ed just in case you need it to
  181548. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181549. #ifdef PNG_SIZE_T
  181550. typedef PNG_SIZE_T png_size_t;
  181551. # define png_sizeof(x) png_convert_size(sizeof (x))
  181552. #else
  181553. typedef size_t png_size_t;
  181554. # define png_sizeof(x) sizeof (x)
  181555. #endif
  181556. /* The following is needed for medium model support. It cannot be in the
  181557. * PNG_INTERNAL section. Needs modification for other compilers besides
  181558. * MSC. Model independent support declares all arrays and pointers to be
  181559. * large using the far keyword. The zlib version used must also support
  181560. * model independent data. As of version zlib 1.0.4, the necessary changes
  181561. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181562. * changes that are needed. (Tim Wegner)
  181563. */
  181564. /* Separate compiler dependencies (problem here is that zlib.h always
  181565. defines FAR. (SJT) */
  181566. #ifdef __BORLANDC__
  181567. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181568. # define LDATA 1
  181569. # else
  181570. # define LDATA 0
  181571. # endif
  181572. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181573. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181574. # define PNG_MAX_MALLOC_64K
  181575. # if (LDATA != 1)
  181576. # ifndef FAR
  181577. # define FAR __far
  181578. # endif
  181579. # define USE_FAR_KEYWORD
  181580. # endif /* LDATA != 1 */
  181581. /* Possibly useful for moving data out of default segment.
  181582. * Uncomment it if you want. Could also define FARDATA as
  181583. * const if your compiler supports it. (SJT)
  181584. # define FARDATA FAR
  181585. */
  181586. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181587. #endif /* __BORLANDC__ */
  181588. /* Suggest testing for specific compiler first before testing for
  181589. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181590. * making reliance oncertain keywords suspect. (SJT)
  181591. */
  181592. /* MSC Medium model */
  181593. #if defined(FAR)
  181594. # if defined(M_I86MM)
  181595. # define USE_FAR_KEYWORD
  181596. # define FARDATA FAR
  181597. # include <dos.h>
  181598. # endif
  181599. #endif
  181600. /* SJT: default case */
  181601. #ifndef FAR
  181602. # define FAR
  181603. #endif
  181604. /* At this point FAR is always defined */
  181605. #ifndef FARDATA
  181606. # define FARDATA
  181607. #endif
  181608. /* Typedef for floating-point numbers that are converted
  181609. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181610. typedef png_int_32 png_fixed_point;
  181611. /* Add typedefs for pointers */
  181612. typedef void FAR * png_voidp;
  181613. typedef png_byte FAR * png_bytep;
  181614. typedef png_uint_32 FAR * png_uint_32p;
  181615. typedef png_int_32 FAR * png_int_32p;
  181616. typedef png_uint_16 FAR * png_uint_16p;
  181617. typedef png_int_16 FAR * png_int_16p;
  181618. typedef PNG_CONST char FAR * png_const_charp;
  181619. typedef char FAR * png_charp;
  181620. typedef png_fixed_point FAR * png_fixed_point_p;
  181621. #ifndef PNG_NO_STDIO
  181622. #if defined(_WIN32_WCE)
  181623. typedef HANDLE png_FILE_p;
  181624. #else
  181625. typedef FILE * png_FILE_p;
  181626. #endif
  181627. #endif
  181628. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181629. typedef double FAR * png_doublep;
  181630. #endif
  181631. /* Pointers to pointers; i.e. arrays */
  181632. typedef png_byte FAR * FAR * png_bytepp;
  181633. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181634. typedef png_int_32 FAR * FAR * png_int_32pp;
  181635. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181636. typedef png_int_16 FAR * FAR * png_int_16pp;
  181637. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181638. typedef char FAR * FAR * png_charpp;
  181639. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181640. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181641. typedef double FAR * FAR * png_doublepp;
  181642. #endif
  181643. /* Pointers to pointers to pointers; i.e., pointer to array */
  181644. typedef char FAR * FAR * FAR * png_charppp;
  181645. #if 0
  181646. /* SPC - Is this stuff deprecated? */
  181647. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181648. /* libpng typedefs for types in zlib. If zlib changes
  181649. * or another compression library is used, then change these.
  181650. * Eliminates need to change all the source files.
  181651. */
  181652. typedef charf * png_zcharp;
  181653. typedef charf * FAR * png_zcharpp;
  181654. typedef z_stream FAR * png_zstreamp;
  181655. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181656. /*
  181657. * Define PNG_BUILD_DLL if the module being built is a Windows
  181658. * LIBPNG DLL.
  181659. *
  181660. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181661. * It is equivalent to Microsoft predefined macro _DLL that is
  181662. * automatically defined when you compile using the share
  181663. * version of the CRT (C Run-Time library)
  181664. *
  181665. * The cygwin mods make this behavior a little different:
  181666. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181667. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181668. * -or- if you are building an application that you want to link to the
  181669. * static library.
  181670. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181671. * the other flags is defined.
  181672. */
  181673. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181674. # define PNG_DLL
  181675. #endif
  181676. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181677. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181678. * command-line override
  181679. */
  181680. #if defined(__CYGWIN__)
  181681. # if !defined(PNG_STATIC)
  181682. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181683. # undef PNG_USE_GLOBAL_ARRAYS
  181684. # endif
  181685. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181686. # define PNG_USE_LOCAL_ARRAYS
  181687. # endif
  181688. # else
  181689. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181690. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181691. # undef PNG_USE_GLOBAL_ARRAYS
  181692. # endif
  181693. # endif
  181694. # endif
  181695. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181696. # define PNG_USE_LOCAL_ARRAYS
  181697. # endif
  181698. #endif
  181699. /* Do not use global arrays (helps with building DLL's)
  181700. * They are no longer used in libpng itself, since version 1.0.5c,
  181701. * but might be required for some pre-1.0.5c applications.
  181702. */
  181703. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181704. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181705. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181706. # define PNG_USE_LOCAL_ARRAYS
  181707. # else
  181708. # define PNG_USE_GLOBAL_ARRAYS
  181709. # endif
  181710. #endif
  181711. #if defined(__CYGWIN__)
  181712. # undef PNGAPI
  181713. # define PNGAPI __cdecl
  181714. # undef PNG_IMPEXP
  181715. # define PNG_IMPEXP
  181716. #endif
  181717. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181718. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181719. * Don't ignore those warnings; you must also reset the default calling
  181720. * convention in your compiler to match your PNGAPI, and you must build
  181721. * zlib and your applications the same way you build libpng.
  181722. */
  181723. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181724. # ifndef PNG_NO_MODULEDEF
  181725. # define PNG_NO_MODULEDEF
  181726. # endif
  181727. #endif
  181728. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181729. # define PNG_IMPEXP
  181730. #endif
  181731. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181732. (( defined(_Windows) || defined(_WINDOWS) || \
  181733. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181734. # ifndef PNGAPI
  181735. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181736. # define PNGAPI __cdecl
  181737. # else
  181738. # define PNGAPI _cdecl
  181739. # endif
  181740. # endif
  181741. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181742. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181743. # define PNG_IMPEXP
  181744. # endif
  181745. # if !defined(PNG_IMPEXP)
  181746. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181747. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181748. /* Borland/Microsoft */
  181749. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181750. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181751. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181752. # else
  181753. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181754. # if defined(PNG_BUILD_DLL)
  181755. # define PNG_IMPEXP __export
  181756. # else
  181757. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181758. VC++ */
  181759. # endif /* Exists in Borland C++ for
  181760. C++ classes (== huge) */
  181761. # endif
  181762. # endif
  181763. # if !defined(PNG_IMPEXP)
  181764. # if defined(PNG_BUILD_DLL)
  181765. # define PNG_IMPEXP __declspec(dllexport)
  181766. # else
  181767. # define PNG_IMPEXP __declspec(dllimport)
  181768. # endif
  181769. # endif
  181770. # endif /* PNG_IMPEXP */
  181771. #else /* !(DLL || non-cygwin WINDOWS) */
  181772. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181773. # ifndef PNGAPI
  181774. # define PNGAPI _System
  181775. # endif
  181776. # else
  181777. # if 0 /* ... other platforms, with other meanings */
  181778. # endif
  181779. # endif
  181780. #endif
  181781. #ifndef PNGAPI
  181782. # define PNGAPI
  181783. #endif
  181784. #ifndef PNG_IMPEXP
  181785. # define PNG_IMPEXP
  181786. #endif
  181787. #ifdef PNG_BUILDSYMS
  181788. # ifndef PNG_EXPORT
  181789. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181790. # endif
  181791. # ifdef PNG_USE_GLOBAL_ARRAYS
  181792. # ifndef PNG_EXPORT_VAR
  181793. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181794. # endif
  181795. # endif
  181796. #endif
  181797. #ifndef PNG_EXPORT
  181798. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181799. #endif
  181800. #ifdef PNG_USE_GLOBAL_ARRAYS
  181801. # ifndef PNG_EXPORT_VAR
  181802. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181803. # endif
  181804. #endif
  181805. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181806. * functions that are passed far data must be model independent.
  181807. */
  181808. #ifndef PNG_ABORT
  181809. # define PNG_ABORT() abort()
  181810. #endif
  181811. #ifdef PNG_SETJMP_SUPPORTED
  181812. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181813. #else
  181814. # define png_jmpbuf(png_ptr) \
  181815. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181816. #endif
  181817. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181818. /* use this to make far-to-near assignments */
  181819. # define CHECK 1
  181820. # define NOCHECK 0
  181821. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181822. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181823. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181824. # define png_strcpy _fstrcpy
  181825. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181826. # define png_strlen _fstrlen
  181827. # define png_memcmp _fmemcmp /* SJT: added */
  181828. # define png_memcpy _fmemcpy
  181829. # define png_memset _fmemset
  181830. #else /* use the usual functions */
  181831. # define CVT_PTR(ptr) (ptr)
  181832. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181833. # ifndef PNG_NO_SNPRINTF
  181834. # ifdef _MSC_VER
  181835. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181836. # define png_snprintf2 _snprintf
  181837. # define png_snprintf6 _snprintf
  181838. # else
  181839. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181840. # define png_snprintf2 snprintf
  181841. # define png_snprintf6 snprintf
  181842. # endif
  181843. # else
  181844. /* You don't have or don't want to use snprintf(). Caution: Using
  181845. * sprintf instead of snprintf exposes your application to accidental
  181846. * or malevolent buffer overflows. If you don't have snprintf()
  181847. * as a general rule you should provide one (you can get one from
  181848. * Portable OpenSSH). */
  181849. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181850. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181851. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181852. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181853. # endif
  181854. # define png_strcpy strcpy
  181855. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181856. # define png_strlen strlen
  181857. # define png_memcmp memcmp /* SJT: added */
  181858. # define png_memcpy memcpy
  181859. # define png_memset memset
  181860. #endif
  181861. /* End of memory model independent support */
  181862. /* Just a little check that someone hasn't tried to define something
  181863. * contradictory.
  181864. */
  181865. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181866. # undef PNG_ZBUF_SIZE
  181867. # define PNG_ZBUF_SIZE 65536L
  181868. #endif
  181869. /* Added at libpng-1.2.8 */
  181870. #endif /* PNG_VERSION_INFO_ONLY */
  181871. #endif /* PNGCONF_H */
  181872. /*** End of inlined file: pngconf.h ***/
  181873. #ifdef _MSC_VER
  181874. #pragma warning (disable: 4996 4100)
  181875. #endif
  181876. /*
  181877. * Added at libpng-1.2.8 */
  181878. /* Ref MSDN: Private as priority over Special
  181879. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181880. * procedures. If this value is given, the StringFileInfo block must
  181881. * contain a PrivateBuild string.
  181882. *
  181883. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181884. * standard release procedures but is a variation of the standard
  181885. * file of the same version number. If this value is given, the
  181886. * StringFileInfo block must contain a SpecialBuild string.
  181887. */
  181888. #if defined(PNG_USER_PRIVATEBUILD)
  181889. # define PNG_LIBPNG_BUILD_TYPE \
  181890. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181891. #else
  181892. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181893. # define PNG_LIBPNG_BUILD_TYPE \
  181894. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181895. # else
  181896. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181897. # endif
  181898. #endif
  181899. #ifndef PNG_VERSION_INFO_ONLY
  181900. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181901. #ifdef __cplusplus
  181902. //extern "C" {
  181903. #endif /* __cplusplus */
  181904. /* This file is arranged in several sections. The first section contains
  181905. * structure and type definitions. The second section contains the external
  181906. * library functions, while the third has the internal library functions,
  181907. * which applications aren't expected to use directly.
  181908. */
  181909. #ifndef PNG_NO_TYPECAST_NULL
  181910. #define int_p_NULL (int *)NULL
  181911. #define png_bytep_NULL (png_bytep)NULL
  181912. #define png_bytepp_NULL (png_bytepp)NULL
  181913. #define png_doublep_NULL (png_doublep)NULL
  181914. #define png_error_ptr_NULL (png_error_ptr)NULL
  181915. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181916. #define png_free_ptr_NULL (png_free_ptr)NULL
  181917. #define png_infopp_NULL (png_infopp)NULL
  181918. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181919. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181920. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181921. #define png_structp_NULL (png_structp)NULL
  181922. #define png_uint_16p_NULL (png_uint_16p)NULL
  181923. #define png_voidp_NULL (png_voidp)NULL
  181924. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181925. #else
  181926. #define int_p_NULL NULL
  181927. #define png_bytep_NULL NULL
  181928. #define png_bytepp_NULL NULL
  181929. #define png_doublep_NULL NULL
  181930. #define png_error_ptr_NULL NULL
  181931. #define png_flush_ptr_NULL NULL
  181932. #define png_free_ptr_NULL NULL
  181933. #define png_infopp_NULL NULL
  181934. #define png_malloc_ptr_NULL NULL
  181935. #define png_read_status_ptr_NULL NULL
  181936. #define png_rw_ptr_NULL NULL
  181937. #define png_structp_NULL NULL
  181938. #define png_uint_16p_NULL NULL
  181939. #define png_voidp_NULL NULL
  181940. #define png_write_status_ptr_NULL NULL
  181941. #endif
  181942. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181943. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181944. /* Version information for C files, stored in png.c. This had better match
  181945. * the version above.
  181946. */
  181947. #ifdef PNG_USE_GLOBAL_ARRAYS
  181948. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181949. /* need room for 99.99.99beta99z */
  181950. #else
  181951. #define png_libpng_ver png_get_header_ver(NULL)
  181952. #endif
  181953. #ifdef PNG_USE_GLOBAL_ARRAYS
  181954. /* This was removed in version 1.0.5c */
  181955. /* Structures to facilitate easy interlacing. See png.c for more details */
  181956. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181957. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181958. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181959. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181960. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181961. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181962. /* This isn't currently used. If you need it, see png.c for more details.
  181963. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181964. */
  181965. #endif
  181966. #endif /* PNG_NO_EXTERN */
  181967. /* Three color definitions. The order of the red, green, and blue, (and the
  181968. * exact size) is not important, although the size of the fields need to
  181969. * be png_byte or png_uint_16 (as defined below).
  181970. */
  181971. typedef struct png_color_struct
  181972. {
  181973. png_byte red;
  181974. png_byte green;
  181975. png_byte blue;
  181976. } png_color;
  181977. typedef png_color FAR * png_colorp;
  181978. typedef png_color FAR * FAR * png_colorpp;
  181979. typedef struct png_color_16_struct
  181980. {
  181981. png_byte index; /* used for palette files */
  181982. png_uint_16 red; /* for use in red green blue files */
  181983. png_uint_16 green;
  181984. png_uint_16 blue;
  181985. png_uint_16 gray; /* for use in grayscale files */
  181986. } png_color_16;
  181987. typedef png_color_16 FAR * png_color_16p;
  181988. typedef png_color_16 FAR * FAR * png_color_16pp;
  181989. typedef struct png_color_8_struct
  181990. {
  181991. png_byte red; /* for use in red green blue files */
  181992. png_byte green;
  181993. png_byte blue;
  181994. png_byte gray; /* for use in grayscale files */
  181995. png_byte alpha; /* for alpha channel files */
  181996. } png_color_8;
  181997. typedef png_color_8 FAR * png_color_8p;
  181998. typedef png_color_8 FAR * FAR * png_color_8pp;
  181999. /*
  182000. * The following two structures are used for the in-core representation
  182001. * of sPLT chunks.
  182002. */
  182003. typedef struct png_sPLT_entry_struct
  182004. {
  182005. png_uint_16 red;
  182006. png_uint_16 green;
  182007. png_uint_16 blue;
  182008. png_uint_16 alpha;
  182009. png_uint_16 frequency;
  182010. } png_sPLT_entry;
  182011. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182012. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182013. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182014. * occupy the LSB of their respective members, and the MSB of each member
  182015. * is zero-filled. The frequency member always occupies the full 16 bits.
  182016. */
  182017. typedef struct png_sPLT_struct
  182018. {
  182019. png_charp name; /* palette name */
  182020. png_byte depth; /* depth of palette samples */
  182021. png_sPLT_entryp entries; /* palette entries */
  182022. png_int_32 nentries; /* number of palette entries */
  182023. } png_sPLT_t;
  182024. typedef png_sPLT_t FAR * png_sPLT_tp;
  182025. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182026. #ifdef PNG_TEXT_SUPPORTED
  182027. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182028. * and whether that contents is compressed or not. The "key" field
  182029. * points to a regular zero-terminated C string. The "text", "lang", and
  182030. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182031. * However, the * structure returned by png_get_text() will always contain
  182032. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182033. * so they can be safely used in printf() and other string-handling functions.
  182034. */
  182035. typedef struct png_text_struct
  182036. {
  182037. int compression; /* compression value:
  182038. -1: tEXt, none
  182039. 0: zTXt, deflate
  182040. 1: iTXt, none
  182041. 2: iTXt, deflate */
  182042. png_charp key; /* keyword, 1-79 character description of "text" */
  182043. png_charp text; /* comment, may be an empty string (ie "")
  182044. or a NULL pointer */
  182045. png_size_t text_length; /* length of the text string */
  182046. #ifdef PNG_iTXt_SUPPORTED
  182047. png_size_t itxt_length; /* length of the itxt string */
  182048. png_charp lang; /* language code, 0-79 characters
  182049. or a NULL pointer */
  182050. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182051. chars or a NULL pointer */
  182052. #endif
  182053. } png_text;
  182054. typedef png_text FAR * png_textp;
  182055. typedef png_text FAR * FAR * png_textpp;
  182056. #endif
  182057. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182058. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182059. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182060. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182061. #define PNG_TEXT_COMPRESSION_NONE -1
  182062. #define PNG_TEXT_COMPRESSION_zTXt 0
  182063. #define PNG_ITXT_COMPRESSION_NONE 1
  182064. #define PNG_ITXT_COMPRESSION_zTXt 2
  182065. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182066. /* png_time is a way to hold the time in an machine independent way.
  182067. * Two conversions are provided, both from time_t and struct tm. There
  182068. * is no portable way to convert to either of these structures, as far
  182069. * as I know. If you know of a portable way, send it to me. As a side
  182070. * note - PNG has always been Year 2000 compliant!
  182071. */
  182072. typedef struct png_time_struct
  182073. {
  182074. png_uint_16 year; /* full year, as in, 1995 */
  182075. png_byte month; /* month of year, 1 - 12 */
  182076. png_byte day; /* day of month, 1 - 31 */
  182077. png_byte hour; /* hour of day, 0 - 23 */
  182078. png_byte minute; /* minute of hour, 0 - 59 */
  182079. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182080. } png_time;
  182081. typedef png_time FAR * png_timep;
  182082. typedef png_time FAR * FAR * png_timepp;
  182083. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182084. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182085. * no specific support. The idea is that we can use this to queue
  182086. * up private chunks for output even though the library doesn't actually
  182087. * know about their semantics.
  182088. */
  182089. typedef struct png_unknown_chunk_t
  182090. {
  182091. png_byte name[5];
  182092. png_byte *data;
  182093. png_size_t size;
  182094. /* libpng-using applications should NOT directly modify this byte. */
  182095. png_byte location; /* mode of operation at read time */
  182096. }
  182097. png_unknown_chunk;
  182098. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182099. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182100. #endif
  182101. /* png_info is a structure that holds the information in a PNG file so
  182102. * that the application can find out the characteristics of the image.
  182103. * If you are reading the file, this structure will tell you what is
  182104. * in the PNG file. If you are writing the file, fill in the information
  182105. * you want to put into the PNG file, then call png_write_info().
  182106. * The names chosen should be very close to the PNG specification, so
  182107. * consult that document for information about the meaning of each field.
  182108. *
  182109. * With libpng < 0.95, it was only possible to directly set and read the
  182110. * the values in the png_info_struct, which meant that the contents and
  182111. * order of the values had to remain fixed. With libpng 0.95 and later,
  182112. * however, there are now functions that abstract the contents of
  182113. * png_info_struct from the application, so this makes it easier to use
  182114. * libpng with dynamic libraries, and even makes it possible to use
  182115. * libraries that don't have all of the libpng ancillary chunk-handing
  182116. * functionality.
  182117. *
  182118. * In any case, the order of the parameters in png_info_struct should NOT
  182119. * be changed for as long as possible to keep compatibility with applications
  182120. * that use the old direct-access method with png_info_struct.
  182121. *
  182122. * The following members may have allocated storage attached that should be
  182123. * cleaned up before the structure is discarded: palette, trans, text,
  182124. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182125. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182126. * are automatically freed when the info structure is deallocated, if they were
  182127. * allocated internally by libpng. This behavior can be changed by means
  182128. * of the png_data_freer() function.
  182129. *
  182130. * More allocation details: all the chunk-reading functions that
  182131. * change these members go through the corresponding png_set_*
  182132. * functions. A function to clear these members is available: see
  182133. * png_free_data(). The png_set_* functions do not depend on being
  182134. * able to point info structure members to any of the storage they are
  182135. * passed (they make their own copies), EXCEPT that the png_set_text
  182136. * functions use the same storage passed to them in the text_ptr or
  182137. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182138. * functions do not make their own copies.
  182139. */
  182140. typedef struct png_info_struct
  182141. {
  182142. /* the following are necessary for every PNG file */
  182143. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182144. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182145. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182146. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182147. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182148. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182149. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182150. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182151. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182152. /* The following three should have been named *_method not *_type */
  182153. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182154. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182155. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182156. /* The following is informational only on read, and not used on writes. */
  182157. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182158. png_byte pixel_depth; /* number of bits per pixel */
  182159. png_byte spare_byte; /* to align the data, and for future use */
  182160. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182161. /* The rest of the data is optional. If you are reading, check the
  182162. * valid field to see if the information in these are valid. If you
  182163. * are writing, set the valid field to those chunks you want written,
  182164. * and initialize the appropriate fields below.
  182165. */
  182166. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182167. /* The gAMA chunk describes the gamma characteristics of the system
  182168. * on which the image was created, normally in the range [1.0, 2.5].
  182169. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182170. */
  182171. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182172. #endif
  182173. #if defined(PNG_sRGB_SUPPORTED)
  182174. /* GR-P, 0.96a */
  182175. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182176. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182177. #endif
  182178. #if defined(PNG_TEXT_SUPPORTED)
  182179. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182180. * uncompressed, compressed, and optionally compressed forms, respectively.
  182181. * The data in "text" is an array of pointers to uncompressed,
  182182. * null-terminated C strings. Each chunk has a keyword that describes the
  182183. * textual data contained in that chunk. Keywords are not required to be
  182184. * unique, and the text string may be empty. Any number of text chunks may
  182185. * be in an image.
  182186. */
  182187. int num_text; /* number of comments read/to write */
  182188. int max_text; /* current size of text array */
  182189. png_textp text; /* array of comments read/to write */
  182190. #endif /* PNG_TEXT_SUPPORTED */
  182191. #if defined(PNG_tIME_SUPPORTED)
  182192. /* The tIME chunk holds the last time the displayed image data was
  182193. * modified. See the png_time struct for the contents of this struct.
  182194. */
  182195. png_time mod_time;
  182196. #endif
  182197. #if defined(PNG_sBIT_SUPPORTED)
  182198. /* The sBIT chunk specifies the number of significant high-order bits
  182199. * in the pixel data. Values are in the range [1, bit_depth], and are
  182200. * only specified for the channels in the pixel data. The contents of
  182201. * the low-order bits is not specified. Data is valid if
  182202. * (valid & PNG_INFO_sBIT) is non-zero.
  182203. */
  182204. png_color_8 sig_bit; /* significant bits in color channels */
  182205. #endif
  182206. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182207. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182208. /* The tRNS chunk supplies transparency data for paletted images and
  182209. * other image types that don't need a full alpha channel. There are
  182210. * "num_trans" transparency values for a paletted image, stored in the
  182211. * same order as the palette colors, starting from index 0. Values
  182212. * for the data are in the range [0, 255], ranging from fully transparent
  182213. * to fully opaque, respectively. For non-paletted images, there is a
  182214. * single color specified that should be treated as fully transparent.
  182215. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182216. */
  182217. png_bytep trans; /* transparent values for paletted image */
  182218. png_color_16 trans_values; /* transparent color for non-palette image */
  182219. #endif
  182220. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182221. /* The bKGD chunk gives the suggested image background color if the
  182222. * display program does not have its own background color and the image
  182223. * is needs to composited onto a background before display. The colors
  182224. * in "background" are normally in the same color space/depth as the
  182225. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182226. */
  182227. png_color_16 background;
  182228. #endif
  182229. #if defined(PNG_oFFs_SUPPORTED)
  182230. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182231. * and downwards from the top-left corner of the display, page, or other
  182232. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182233. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182234. */
  182235. png_int_32 x_offset; /* x offset on page */
  182236. png_int_32 y_offset; /* y offset on page */
  182237. png_byte offset_unit_type; /* offset units type */
  182238. #endif
  182239. #if defined(PNG_pHYs_SUPPORTED)
  182240. /* The pHYs chunk gives the physical pixel density of the image for
  182241. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182242. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182243. */
  182244. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182245. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182246. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182247. #endif
  182248. #if defined(PNG_hIST_SUPPORTED)
  182249. /* The hIST chunk contains the relative frequency or importance of the
  182250. * various palette entries, so that a viewer can intelligently select a
  182251. * reduced-color palette, if required. Data is an array of "num_palette"
  182252. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182253. * is non-zero.
  182254. */
  182255. png_uint_16p hist;
  182256. #endif
  182257. #ifdef PNG_cHRM_SUPPORTED
  182258. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182259. * on which the PNG was created. This data allows the viewer to do gamut
  182260. * mapping of the input image to ensure that the viewer sees the same
  182261. * colors in the image as the creator. Values are in the range
  182262. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182263. */
  182264. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182265. float x_white;
  182266. float y_white;
  182267. float x_red;
  182268. float y_red;
  182269. float x_green;
  182270. float y_green;
  182271. float x_blue;
  182272. float y_blue;
  182273. #endif
  182274. #endif
  182275. #if defined(PNG_pCAL_SUPPORTED)
  182276. /* The pCAL chunk describes a transformation between the stored pixel
  182277. * values and original physical data values used to create the image.
  182278. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182279. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182280. * (possibly non-linear) transformation function given by "pcal_type"
  182281. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182282. * defines below, and the PNG-Group's PNG extensions document for a
  182283. * complete description of the transformations and how they should be
  182284. * implemented, and for a description of the ASCII parameter strings.
  182285. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182286. */
  182287. png_charp pcal_purpose; /* pCAL chunk description string */
  182288. png_int_32 pcal_X0; /* minimum value */
  182289. png_int_32 pcal_X1; /* maximum value */
  182290. png_charp pcal_units; /* Latin-1 string giving physical units */
  182291. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182292. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182293. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182294. #endif
  182295. /* New members added in libpng-1.0.6 */
  182296. #ifdef PNG_FREE_ME_SUPPORTED
  182297. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182298. #endif
  182299. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182300. /* storage for unknown chunks that the library doesn't recognize. */
  182301. png_unknown_chunkp unknown_chunks;
  182302. png_size_t unknown_chunks_num;
  182303. #endif
  182304. #if defined(PNG_iCCP_SUPPORTED)
  182305. /* iCCP chunk data. */
  182306. png_charp iccp_name; /* profile name */
  182307. png_charp iccp_profile; /* International Color Consortium profile data */
  182308. /* Note to maintainer: should be png_bytep */
  182309. png_uint_32 iccp_proflen; /* ICC profile data length */
  182310. png_byte iccp_compression; /* Always zero */
  182311. #endif
  182312. #if defined(PNG_sPLT_SUPPORTED)
  182313. /* data on sPLT chunks (there may be more than one). */
  182314. png_sPLT_tp splt_palettes;
  182315. png_uint_32 splt_palettes_num;
  182316. #endif
  182317. #if defined(PNG_sCAL_SUPPORTED)
  182318. /* The sCAL chunk describes the actual physical dimensions of the
  182319. * subject matter of the graphic. The chunk contains a unit specification
  182320. * a byte value, and two ASCII strings representing floating-point
  182321. * values. The values are width and height corresponsing to one pixel
  182322. * in the image. This external representation is converted to double
  182323. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182324. */
  182325. png_byte scal_unit; /* unit of physical scale */
  182326. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182327. double scal_pixel_width; /* width of one pixel */
  182328. double scal_pixel_height; /* height of one pixel */
  182329. #endif
  182330. #ifdef PNG_FIXED_POINT_SUPPORTED
  182331. png_charp scal_s_width; /* string containing height */
  182332. png_charp scal_s_height; /* string containing width */
  182333. #endif
  182334. #endif
  182335. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182336. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182337. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182338. png_bytepp row_pointers; /* the image bits */
  182339. #endif
  182340. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182341. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182342. #endif
  182343. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182344. png_fixed_point int_x_white;
  182345. png_fixed_point int_y_white;
  182346. png_fixed_point int_x_red;
  182347. png_fixed_point int_y_red;
  182348. png_fixed_point int_x_green;
  182349. png_fixed_point int_y_green;
  182350. png_fixed_point int_x_blue;
  182351. png_fixed_point int_y_blue;
  182352. #endif
  182353. } png_info;
  182354. typedef png_info FAR * png_infop;
  182355. typedef png_info FAR * FAR * png_infopp;
  182356. /* Maximum positive integer used in PNG is (2^31)-1 */
  182357. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182358. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182359. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182360. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182361. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182362. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182363. #endif
  182364. /* These describe the color_type field in png_info. */
  182365. /* color type masks */
  182366. #define PNG_COLOR_MASK_PALETTE 1
  182367. #define PNG_COLOR_MASK_COLOR 2
  182368. #define PNG_COLOR_MASK_ALPHA 4
  182369. /* color types. Note that not all combinations are legal */
  182370. #define PNG_COLOR_TYPE_GRAY 0
  182371. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182372. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182373. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182374. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182375. /* aliases */
  182376. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182377. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182378. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182379. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182380. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182381. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182382. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182383. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182384. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182385. /* These are for the interlacing type. These values should NOT be changed. */
  182386. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182387. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182388. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182389. /* These are for the oFFs chunk. These values should NOT be changed. */
  182390. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182391. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182392. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182393. /* These are for the pCAL chunk. These values should NOT be changed. */
  182394. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182395. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182396. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182397. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182398. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182399. /* These are for the sCAL chunk. These values should NOT be changed. */
  182400. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182401. #define PNG_SCALE_METER 1 /* meters per pixel */
  182402. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182403. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182404. /* These are for the pHYs chunk. These values should NOT be changed. */
  182405. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182406. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182407. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182408. /* These are for the sRGB chunk. These values should NOT be changed. */
  182409. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182410. #define PNG_sRGB_INTENT_RELATIVE 1
  182411. #define PNG_sRGB_INTENT_SATURATION 2
  182412. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182413. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182414. /* This is for text chunks */
  182415. #define PNG_KEYWORD_MAX_LENGTH 79
  182416. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182417. #define PNG_MAX_PALETTE_LENGTH 256
  182418. /* These determine if an ancillary chunk's data has been successfully read
  182419. * from the PNG header, or if the application has filled in the corresponding
  182420. * data in the info_struct to be written into the output file. The values
  182421. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182422. */
  182423. #define PNG_INFO_gAMA 0x0001
  182424. #define PNG_INFO_sBIT 0x0002
  182425. #define PNG_INFO_cHRM 0x0004
  182426. #define PNG_INFO_PLTE 0x0008
  182427. #define PNG_INFO_tRNS 0x0010
  182428. #define PNG_INFO_bKGD 0x0020
  182429. #define PNG_INFO_hIST 0x0040
  182430. #define PNG_INFO_pHYs 0x0080
  182431. #define PNG_INFO_oFFs 0x0100
  182432. #define PNG_INFO_tIME 0x0200
  182433. #define PNG_INFO_pCAL 0x0400
  182434. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182435. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182436. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182437. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182438. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182439. /* This is used for the transformation routines, as some of them
  182440. * change these values for the row. It also should enable using
  182441. * the routines for other purposes.
  182442. */
  182443. typedef struct png_row_info_struct
  182444. {
  182445. png_uint_32 width; /* width of row */
  182446. png_uint_32 rowbytes; /* number of bytes in row */
  182447. png_byte color_type; /* color type of row */
  182448. png_byte bit_depth; /* bit depth of row */
  182449. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182450. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182451. } png_row_info;
  182452. typedef png_row_info FAR * png_row_infop;
  182453. typedef png_row_info FAR * FAR * png_row_infopp;
  182454. /* These are the function types for the I/O functions and for the functions
  182455. * that allow the user to override the default I/O functions with his or her
  182456. * own. The png_error_ptr type should match that of user-supplied warning
  182457. * and error functions, while the png_rw_ptr type should match that of the
  182458. * user read/write data functions.
  182459. */
  182460. typedef struct png_struct_def png_struct;
  182461. typedef png_struct FAR * png_structp;
  182462. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182463. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182464. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182465. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182466. int));
  182467. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182468. int));
  182469. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182470. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182471. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182472. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182473. png_uint_32, int));
  182474. #endif
  182475. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182476. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182477. defined(PNG_LEGACY_SUPPORTED)
  182478. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182479. png_row_infop, png_bytep));
  182480. #endif
  182481. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182482. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182483. #endif
  182484. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182485. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182486. #endif
  182487. /* Transform masks for the high-level interface */
  182488. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182489. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182490. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182491. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182492. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182493. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182494. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182495. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182496. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182497. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182498. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182499. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182500. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182501. /* Flags for MNG supported features */
  182502. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182503. #define PNG_FLAG_MNG_FILTER_64 0x04
  182504. #define PNG_ALL_MNG_FEATURES 0x05
  182505. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182506. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182507. /* The structure that holds the information to read and write PNG files.
  182508. * The only people who need to care about what is inside of this are the
  182509. * people who will be modifying the library for their own special needs.
  182510. * It should NOT be accessed directly by an application, except to store
  182511. * the jmp_buf.
  182512. */
  182513. struct png_struct_def
  182514. {
  182515. #ifdef PNG_SETJMP_SUPPORTED
  182516. jmp_buf jmpbuf; /* used in png_error */
  182517. #endif
  182518. png_error_ptr error_fn; /* function for printing errors and aborting */
  182519. png_error_ptr warning_fn; /* function for printing warnings */
  182520. png_voidp error_ptr; /* user supplied struct for error functions */
  182521. png_rw_ptr write_data_fn; /* function for writing output data */
  182522. png_rw_ptr read_data_fn; /* function for reading input data */
  182523. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182524. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182525. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182526. #endif
  182527. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182528. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182529. #endif
  182530. /* These were added in libpng-1.0.2 */
  182531. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182532. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182533. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182534. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182535. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182536. png_byte user_transform_channels; /* channels in user transformed pixels */
  182537. #endif
  182538. #endif
  182539. png_uint_32 mode; /* tells us where we are in the PNG file */
  182540. png_uint_32 flags; /* flags indicating various things to libpng */
  182541. png_uint_32 transformations; /* which transformations to perform */
  182542. z_stream zstream; /* pointer to decompression structure (below) */
  182543. png_bytep zbuf; /* buffer for zlib */
  182544. png_size_t zbuf_size; /* size of zbuf */
  182545. int zlib_level; /* holds zlib compression level */
  182546. int zlib_method; /* holds zlib compression method */
  182547. int zlib_window_bits; /* holds zlib compression window bits */
  182548. int zlib_mem_level; /* holds zlib compression memory level */
  182549. int zlib_strategy; /* holds zlib compression strategy */
  182550. png_uint_32 width; /* width of image in pixels */
  182551. png_uint_32 height; /* height of image in pixels */
  182552. png_uint_32 num_rows; /* number of rows in current pass */
  182553. png_uint_32 usr_width; /* width of row at start of write */
  182554. png_uint_32 rowbytes; /* size of row in bytes */
  182555. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182556. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182557. png_uint_32 row_number; /* current row in interlace pass */
  182558. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182559. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182560. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182561. png_bytep up_row; /* buffer to save "up" row when filtering */
  182562. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182563. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182564. png_row_info row_info; /* used for transformation routines */
  182565. png_uint_32 idat_size; /* current IDAT size for read */
  182566. png_uint_32 crc; /* current chunk CRC value */
  182567. png_colorp palette; /* palette from the input file */
  182568. png_uint_16 num_palette; /* number of color entries in palette */
  182569. png_uint_16 num_trans; /* number of transparency values */
  182570. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182571. png_byte compression; /* file compression type (always 0) */
  182572. png_byte filter; /* file filter type (always 0) */
  182573. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182574. png_byte pass; /* current interlace pass (0 - 6) */
  182575. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182576. png_byte color_type; /* color type of file */
  182577. png_byte bit_depth; /* bit depth of file */
  182578. png_byte usr_bit_depth; /* bit depth of users row */
  182579. png_byte pixel_depth; /* number of bits per pixel */
  182580. png_byte channels; /* number of channels in file */
  182581. png_byte usr_channels; /* channels at start of write */
  182582. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182583. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182584. #ifdef PNG_LEGACY_SUPPORTED
  182585. png_byte filler; /* filler byte for pixel expansion */
  182586. #else
  182587. png_uint_16 filler; /* filler bytes for pixel expansion */
  182588. #endif
  182589. #endif
  182590. #if defined(PNG_bKGD_SUPPORTED)
  182591. png_byte background_gamma_type;
  182592. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182593. float background_gamma;
  182594. # endif
  182595. png_color_16 background; /* background color in screen gamma space */
  182596. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182597. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182598. #endif
  182599. #endif /* PNG_bKGD_SUPPORTED */
  182600. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182601. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182602. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182603. png_uint_32 flush_rows; /* number of rows written since last flush */
  182604. #endif
  182605. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182606. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182607. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182608. float gamma; /* file gamma value */
  182609. float screen_gamma; /* screen gamma value (display_exponent) */
  182610. #endif
  182611. #endif
  182612. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182613. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182614. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182615. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182616. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182617. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182618. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182619. #endif
  182620. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182621. png_color_8 sig_bit; /* significant bits in each available channel */
  182622. #endif
  182623. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182624. png_color_8 shift; /* shift for significant bit tranformation */
  182625. #endif
  182626. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182627. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182628. png_bytep trans; /* transparency values for paletted files */
  182629. png_color_16 trans_values; /* transparency values for non-paletted files */
  182630. #endif
  182631. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182632. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182633. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182634. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182635. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182636. png_progressive_end_ptr end_fn; /* called after image is complete */
  182637. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182638. png_bytep save_buffer; /* buffer for previously read data */
  182639. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182640. png_bytep current_buffer; /* buffer for recently used data */
  182641. png_uint_32 push_length; /* size of current input chunk */
  182642. png_uint_32 skip_length; /* bytes to skip in input data */
  182643. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182644. png_size_t save_buffer_max; /* total size of save_buffer */
  182645. png_size_t buffer_size; /* total amount of available input data */
  182646. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182647. int process_mode; /* what push library is currently doing */
  182648. int cur_palette; /* current push library palette index */
  182649. # if defined(PNG_TEXT_SUPPORTED)
  182650. png_size_t current_text_size; /* current size of text input data */
  182651. png_size_t current_text_left; /* how much text left to read in input */
  182652. png_charp current_text; /* current text chunk buffer */
  182653. png_charp current_text_ptr; /* current location in current_text */
  182654. # endif /* PNG_TEXT_SUPPORTED */
  182655. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182656. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182657. /* for the Borland special 64K segment handler */
  182658. png_bytepp offset_table_ptr;
  182659. png_bytep offset_table;
  182660. png_uint_16 offset_table_number;
  182661. png_uint_16 offset_table_count;
  182662. png_uint_16 offset_table_count_free;
  182663. #endif
  182664. #if defined(PNG_READ_DITHER_SUPPORTED)
  182665. png_bytep palette_lookup; /* lookup table for dithering */
  182666. png_bytep dither_index; /* index translation for palette files */
  182667. #endif
  182668. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182669. png_uint_16p hist; /* histogram */
  182670. #endif
  182671. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182672. png_byte heuristic_method; /* heuristic for row filter selection */
  182673. png_byte num_prev_filters; /* number of weights for previous rows */
  182674. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182675. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182676. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182677. png_uint_16p filter_costs; /* relative filter calculation cost */
  182678. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182679. #endif
  182680. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182681. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182682. #endif
  182683. /* New members added in libpng-1.0.6 */
  182684. #ifdef PNG_FREE_ME_SUPPORTED
  182685. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182686. #endif
  182687. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182688. png_voidp user_chunk_ptr;
  182689. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182690. #endif
  182691. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182692. int num_chunk_list;
  182693. png_bytep chunk_list;
  182694. #endif
  182695. /* New members added in libpng-1.0.3 */
  182696. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182697. png_byte rgb_to_gray_status;
  182698. /* These were changed from png_byte in libpng-1.0.6 */
  182699. png_uint_16 rgb_to_gray_red_coeff;
  182700. png_uint_16 rgb_to_gray_green_coeff;
  182701. png_uint_16 rgb_to_gray_blue_coeff;
  182702. #endif
  182703. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182704. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182705. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182706. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182707. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182708. #ifdef PNG_1_0_X
  182709. png_byte mng_features_permitted;
  182710. #else
  182711. png_uint_32 mng_features_permitted;
  182712. #endif /* PNG_1_0_X */
  182713. #endif
  182714. /* New member added in libpng-1.0.7 */
  182715. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182716. png_fixed_point int_gamma;
  182717. #endif
  182718. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182719. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182720. png_byte filter_type;
  182721. #endif
  182722. #if defined(PNG_1_0_X)
  182723. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182724. png_uint_32 row_buf_size;
  182725. #endif
  182726. /* New members added in libpng-1.2.0 */
  182727. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182728. # if !defined(PNG_1_0_X)
  182729. # if defined(PNG_MMX_CODE_SUPPORTED)
  182730. png_byte mmx_bitdepth_threshold;
  182731. png_uint_32 mmx_rowbytes_threshold;
  182732. # endif
  182733. png_uint_32 asm_flags;
  182734. # endif
  182735. #endif
  182736. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182737. #ifdef PNG_USER_MEM_SUPPORTED
  182738. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182739. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182740. png_free_ptr free_fn; /* function for freeing memory */
  182741. #endif
  182742. /* New member added in libpng-1.0.13 and 1.2.0 */
  182743. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182744. #if defined(PNG_READ_DITHER_SUPPORTED)
  182745. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182746. png_bytep dither_sort; /* working sort array */
  182747. png_bytep index_to_palette; /* where the original index currently is */
  182748. /* in the palette */
  182749. png_bytep palette_to_index; /* which original index points to this */
  182750. /* palette color */
  182751. #endif
  182752. /* New members added in libpng-1.0.16 and 1.2.6 */
  182753. png_byte compression_type;
  182754. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182755. png_uint_32 user_width_max;
  182756. png_uint_32 user_height_max;
  182757. #endif
  182758. /* New member added in libpng-1.0.25 and 1.2.17 */
  182759. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182760. /* storage for unknown chunk that the library doesn't recognize. */
  182761. png_unknown_chunk unknown_chunk;
  182762. #endif
  182763. };
  182764. /* This triggers a compiler error in png.c, if png.c and png.h
  182765. * do not agree upon the version number.
  182766. */
  182767. typedef png_structp version_1_2_21;
  182768. typedef png_struct FAR * FAR * png_structpp;
  182769. /* Here are the function definitions most commonly used. This is not
  182770. * the place to find out how to use libpng. See libpng.txt for the
  182771. * full explanation, see example.c for the summary. This just provides
  182772. * a simple one line description of the use of each function.
  182773. */
  182774. /* Returns the version number of the library */
  182775. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182776. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182777. * Handling more than 8 bytes from the beginning of the file is an error.
  182778. */
  182779. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182780. int num_bytes));
  182781. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182782. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182783. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182784. * start > 7 will always fail (ie return non-zero).
  182785. */
  182786. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182787. png_size_t num_to_check));
  182788. /* Simple signature checking function. This is the same as calling
  182789. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182790. */
  182791. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182792. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182793. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182794. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182795. png_error_ptr error_fn, png_error_ptr warn_fn));
  182796. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182797. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182798. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182799. png_error_ptr error_fn, png_error_ptr warn_fn));
  182800. #ifdef PNG_WRITE_SUPPORTED
  182801. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182802. PNGARG((png_structp png_ptr));
  182803. #endif
  182804. #ifdef PNG_WRITE_SUPPORTED
  182805. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182806. PNGARG((png_structp png_ptr, png_uint_32 size));
  182807. #endif
  182808. /* Reset the compression stream */
  182809. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182810. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182811. #ifdef PNG_USER_MEM_SUPPORTED
  182812. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182813. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182814. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182815. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182816. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182817. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182818. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182819. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182820. #endif
  182821. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182822. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182823. png_bytep chunk_name, png_bytep data, png_size_t length));
  182824. /* Write the start of a PNG chunk - length and chunk name. */
  182825. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182826. png_bytep chunk_name, png_uint_32 length));
  182827. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182828. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182829. png_bytep data, png_size_t length));
  182830. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182831. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182832. /* Allocate and initialize the info structure */
  182833. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182834. PNGARG((png_structp png_ptr));
  182835. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182836. /* Initialize the info structure (old interface - DEPRECATED) */
  182837. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182838. #undef png_info_init
  182839. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182840. png_sizeof(png_info));
  182841. #endif
  182842. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182843. png_size_t png_info_struct_size));
  182844. /* Writes all the PNG information before the image. */
  182845. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182846. png_infop info_ptr));
  182847. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182848. png_infop info_ptr));
  182849. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182850. /* read the information before the actual image data. */
  182851. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182852. png_infop info_ptr));
  182853. #endif
  182854. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182855. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182856. PNGARG((png_structp png_ptr, png_timep ptime));
  182857. #endif
  182858. #if !defined(_WIN32_WCE)
  182859. /* "time.h" functions are not supported on WindowsCE */
  182860. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182861. /* convert from a struct tm to png_time */
  182862. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182863. struct tm FAR * ttime));
  182864. /* convert from time_t to png_time. Uses gmtime() */
  182865. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182866. time_t ttime));
  182867. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182868. #endif /* _WIN32_WCE */
  182869. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182870. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182871. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182872. #if !defined(PNG_1_0_X)
  182873. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182874. png_ptr));
  182875. #endif
  182876. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182877. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182878. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182879. /* Deprecated */
  182880. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182881. #endif
  182882. #endif
  182883. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182884. /* Use blue, green, red order for pixels. */
  182885. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182886. #endif
  182887. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182888. /* Expand the grayscale to 24-bit RGB if necessary. */
  182889. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182890. #endif
  182891. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182892. /* Reduce RGB to grayscale. */
  182893. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182894. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182895. int error_action, double red, double green ));
  182896. #endif
  182897. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182898. int error_action, png_fixed_point red, png_fixed_point green ));
  182899. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182900. png_ptr));
  182901. #endif
  182902. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182903. png_colorp palette));
  182904. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182905. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182906. #endif
  182907. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182908. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182909. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182910. #endif
  182911. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182912. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182913. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182914. #endif
  182915. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182916. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182917. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182918. png_uint_32 filler, int flags));
  182919. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182920. #define PNG_FILLER_BEFORE 0
  182921. #define PNG_FILLER_AFTER 1
  182922. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182923. #if !defined(PNG_1_0_X)
  182924. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182925. png_uint_32 filler, int flags));
  182926. #endif
  182927. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182928. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182929. /* Swap bytes in 16-bit depth files. */
  182930. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182931. #endif
  182932. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182933. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182934. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182935. #endif
  182936. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182937. /* Swap packing order of pixels in bytes. */
  182938. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182939. #endif
  182940. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182941. /* Converts files to legal bit depths. */
  182942. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182943. png_color_8p true_bits));
  182944. #endif
  182945. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182946. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182947. /* Have the code handle the interlacing. Returns the number of passes. */
  182948. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182949. #endif
  182950. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182951. /* Invert monochrome files */
  182952. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182953. #endif
  182954. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182955. /* Handle alpha and tRNS by replacing with a background color. */
  182956. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182957. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182958. png_color_16p background_color, int background_gamma_code,
  182959. int need_expand, double background_gamma));
  182960. #endif
  182961. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182962. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182963. #define PNG_BACKGROUND_GAMMA_FILE 2
  182964. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182965. #endif
  182966. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182967. /* strip the second byte of information from a 16-bit depth file. */
  182968. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182969. #endif
  182970. #if defined(PNG_READ_DITHER_SUPPORTED)
  182971. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182972. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182973. png_colorp palette, int num_palette, int maximum_colors,
  182974. png_uint_16p histogram, int full_dither));
  182975. #endif
  182976. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182977. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182978. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182979. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182980. double screen_gamma, double default_file_gamma));
  182981. #endif
  182982. #endif
  182983. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182984. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182985. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182986. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182987. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182988. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182989. int empty_plte_permitted));
  182990. #endif
  182991. #endif
  182992. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182993. /* Set how many lines between output flushes - 0 for no flushing */
  182994. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182995. /* Flush the current PNG output buffer */
  182996. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182997. #endif
  182998. /* optional update palette with requested transformations */
  182999. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183000. /* optional call to update the users info structure */
  183001. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183002. png_infop info_ptr));
  183003. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183004. /* read one or more rows of image data. */
  183005. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183006. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183007. #endif
  183008. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183009. /* read a row of data. */
  183010. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183011. png_bytep row,
  183012. png_bytep display_row));
  183013. #endif
  183014. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183015. /* read the whole image into memory at once. */
  183016. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183017. png_bytepp image));
  183018. #endif
  183019. /* write a row of image data */
  183020. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183021. png_bytep row));
  183022. /* write a few rows of image data */
  183023. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183024. png_bytepp row, png_uint_32 num_rows));
  183025. /* write the image data */
  183026. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183027. png_bytepp image));
  183028. /* writes the end of the PNG file. */
  183029. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183030. png_infop info_ptr));
  183031. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183032. /* read the end of the PNG file. */
  183033. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183034. png_infop info_ptr));
  183035. #endif
  183036. /* free any memory associated with the png_info_struct */
  183037. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183038. png_infopp info_ptr_ptr));
  183039. /* free any memory associated with the png_struct and the png_info_structs */
  183040. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183041. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183042. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183043. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183044. png_infop end_info_ptr));
  183045. /* free any memory associated with the png_struct and the png_info_structs */
  183046. extern PNG_EXPORT(void,png_destroy_write_struct)
  183047. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183048. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183049. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183050. /* set the libpng method of handling chunk CRC errors */
  183051. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183052. int crit_action, int ancil_action));
  183053. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183054. * ancillary and critical chunks, and whether to use the data contained
  183055. * therein. Note that it is impossible to "discard" data in a critical
  183056. * chunk. For versions prior to 0.90, the action was always error/quit,
  183057. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183058. * chunks is warn/discard. These values should NOT be changed.
  183059. *
  183060. * value action:critical action:ancillary
  183061. */
  183062. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183063. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183064. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183065. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183066. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183067. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183068. /* These functions give the user control over the scan-line filtering in
  183069. * libpng and the compression methods used by zlib. These functions are
  183070. * mainly useful for testing, as the defaults should work with most users.
  183071. * Those users who are tight on memory or want faster performance at the
  183072. * expense of compression can modify them. See the compression library
  183073. * header file (zlib.h) for an explination of the compression functions.
  183074. */
  183075. /* set the filtering method(s) used by libpng. Currently, the only valid
  183076. * value for "method" is 0.
  183077. */
  183078. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183079. int filters));
  183080. /* Flags for png_set_filter() to say which filters to use. The flags
  183081. * are chosen so that they don't conflict with real filter types
  183082. * below, in case they are supplied instead of the #defined constants.
  183083. * These values should NOT be changed.
  183084. */
  183085. #define PNG_NO_FILTERS 0x00
  183086. #define PNG_FILTER_NONE 0x08
  183087. #define PNG_FILTER_SUB 0x10
  183088. #define PNG_FILTER_UP 0x20
  183089. #define PNG_FILTER_AVG 0x40
  183090. #define PNG_FILTER_PAETH 0x80
  183091. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183092. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183093. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183094. * These defines should NOT be changed.
  183095. */
  183096. #define PNG_FILTER_VALUE_NONE 0
  183097. #define PNG_FILTER_VALUE_SUB 1
  183098. #define PNG_FILTER_VALUE_UP 2
  183099. #define PNG_FILTER_VALUE_AVG 3
  183100. #define PNG_FILTER_VALUE_PAETH 4
  183101. #define PNG_FILTER_VALUE_LAST 5
  183102. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183103. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183104. * defines, either the default (minimum-sum-of-absolute-differences), or
  183105. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183106. *
  183107. * Weights are factors >= 1.0, indicating how important it is to keep the
  183108. * filter type consistent between rows. Larger numbers mean the current
  183109. * filter is that many times as likely to be the same as the "num_weights"
  183110. * previous filters. This is cumulative for each previous row with a weight.
  183111. * There needs to be "num_weights" values in "filter_weights", or it can be
  183112. * NULL if the weights aren't being specified. Weights have no influence on
  183113. * the selection of the first row filter. Well chosen weights can (in theory)
  183114. * improve the compression for a given image.
  183115. *
  183116. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183117. * filter type. Higher costs indicate more decoding expense, and are
  183118. * therefore less likely to be selected over a filter with lower computational
  183119. * costs. There needs to be a value in "filter_costs" for each valid filter
  183120. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183121. * setting the costs. Costs try to improve the speed of decompression without
  183122. * unduly increasing the compressed image size.
  183123. *
  183124. * A negative weight or cost indicates the default value is to be used, and
  183125. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183126. * The default values for both weights and costs are currently 1.0, but may
  183127. * change if good general weighting/cost heuristics can be found. If both
  183128. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183129. * to the UNWEIGHTED method, but with added encoding time/computation.
  183130. */
  183131. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183132. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183133. int heuristic_method, int num_weights, png_doublep filter_weights,
  183134. png_doublep filter_costs));
  183135. #endif
  183136. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183137. /* Heuristic used for row filter selection. These defines should NOT be
  183138. * changed.
  183139. */
  183140. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183141. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183142. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183143. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183144. /* Set the library compression level. Currently, valid values range from
  183145. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183146. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183147. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183148. * for PNG images, and do considerably fewer caclulations. In the future,
  183149. * these values may not correspond directly to the zlib compression levels.
  183150. */
  183151. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183152. int level));
  183153. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183154. PNGARG((png_structp png_ptr, int mem_level));
  183155. extern PNG_EXPORT(void,png_set_compression_strategy)
  183156. PNGARG((png_structp png_ptr, int strategy));
  183157. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183158. PNGARG((png_structp png_ptr, int window_bits));
  183159. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183160. int method));
  183161. /* These next functions are called for input/output, memory, and error
  183162. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183163. * and call standard C I/O routines such as fread(), fwrite(), and
  183164. * fprintf(). These functions can be made to use other I/O routines
  183165. * at run time for those applications that need to handle I/O in a
  183166. * different manner by calling png_set_???_fn(). See libpng.txt for
  183167. * more information.
  183168. */
  183169. #if !defined(PNG_NO_STDIO)
  183170. /* Initialize the input/output for the PNG file to the default functions. */
  183171. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183172. #endif
  183173. /* Replace the (error and abort), and warning functions with user
  183174. * supplied functions. If no messages are to be printed you must still
  183175. * write and use replacement functions. The replacement error_fn should
  183176. * still do a longjmp to the last setjmp location if you are using this
  183177. * method of error handling. If error_fn or warning_fn is NULL, the
  183178. * default function will be used.
  183179. */
  183180. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183181. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183182. /* Return the user pointer associated with the error functions */
  183183. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183184. /* Replace the default data output functions with a user supplied one(s).
  183185. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183186. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183187. * output_flush_fn will be ignored (and thus can be NULL).
  183188. */
  183189. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183190. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183191. /* Replace the default data input function with a user supplied one. */
  183192. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183193. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183194. /* Return the user pointer associated with the I/O functions */
  183195. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183196. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183197. png_read_status_ptr read_row_fn));
  183198. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183199. png_write_status_ptr write_row_fn));
  183200. #ifdef PNG_USER_MEM_SUPPORTED
  183201. /* Replace the default memory allocation functions with user supplied one(s). */
  183202. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183203. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183204. /* Return the user pointer associated with the memory functions */
  183205. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183206. #endif
  183207. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183208. defined(PNG_LEGACY_SUPPORTED)
  183209. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183210. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183211. #endif
  183212. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183213. defined(PNG_LEGACY_SUPPORTED)
  183214. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183215. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183216. #endif
  183217. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183218. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183219. defined(PNG_LEGACY_SUPPORTED)
  183220. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183221. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183222. int user_transform_channels));
  183223. /* Return the user pointer associated with the user transform functions */
  183224. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183225. PNGARG((png_structp png_ptr));
  183226. #endif
  183227. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183228. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183229. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183230. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183231. png_ptr));
  183232. #endif
  183233. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183234. /* Sets the function callbacks for the push reader, and a pointer to a
  183235. * user-defined structure available to the callback functions.
  183236. */
  183237. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183238. png_voidp progressive_ptr,
  183239. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183240. png_progressive_end_ptr end_fn));
  183241. /* returns the user pointer associated with the push read functions */
  183242. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183243. PNGARG((png_structp png_ptr));
  183244. /* function to be called when data becomes available */
  183245. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183246. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183247. /* function that combines rows. Not very much different than the
  183248. * png_combine_row() call. Is this even used?????
  183249. */
  183250. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183251. png_bytep old_row, png_bytep new_row));
  183252. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183253. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183254. png_uint_32 size));
  183255. #if defined(PNG_1_0_X)
  183256. # define png_malloc_warn png_malloc
  183257. #else
  183258. /* Added at libpng version 1.2.4 */
  183259. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183260. png_uint_32 size));
  183261. #endif
  183262. /* frees a pointer allocated by png_malloc() */
  183263. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183264. #if defined(PNG_1_0_X)
  183265. /* Function to allocate memory for zlib. */
  183266. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183267. uInt size));
  183268. /* Function to free memory for zlib */
  183269. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183270. #endif
  183271. /* Free data that was allocated internally */
  183272. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183273. png_infop info_ptr, png_uint_32 free_me, int num));
  183274. #ifdef PNG_FREE_ME_SUPPORTED
  183275. /* Reassign responsibility for freeing existing data, whether allocated
  183276. * by libpng or by the application */
  183277. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183278. png_infop info_ptr, int freer, png_uint_32 mask));
  183279. #endif
  183280. /* assignments for png_data_freer */
  183281. #define PNG_DESTROY_WILL_FREE_DATA 1
  183282. #define PNG_SET_WILL_FREE_DATA 1
  183283. #define PNG_USER_WILL_FREE_DATA 2
  183284. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183285. #define PNG_FREE_HIST 0x0008
  183286. #define PNG_FREE_ICCP 0x0010
  183287. #define PNG_FREE_SPLT 0x0020
  183288. #define PNG_FREE_ROWS 0x0040
  183289. #define PNG_FREE_PCAL 0x0080
  183290. #define PNG_FREE_SCAL 0x0100
  183291. #define PNG_FREE_UNKN 0x0200
  183292. #define PNG_FREE_LIST 0x0400
  183293. #define PNG_FREE_PLTE 0x1000
  183294. #define PNG_FREE_TRNS 0x2000
  183295. #define PNG_FREE_TEXT 0x4000
  183296. #define PNG_FREE_ALL 0x7fff
  183297. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183298. #ifdef PNG_USER_MEM_SUPPORTED
  183299. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183300. png_uint_32 size));
  183301. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183302. png_voidp ptr));
  183303. #endif
  183304. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183305. png_voidp s1, png_voidp s2, png_uint_32 size));
  183306. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183307. png_voidp s1, int value, png_uint_32 size));
  183308. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183309. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183310. int check));
  183311. #endif /* USE_FAR_KEYWORD */
  183312. #ifndef PNG_NO_ERROR_TEXT
  183313. /* Fatal error in PNG image of libpng - can't continue */
  183314. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183315. png_const_charp error_message));
  183316. /* The same, but the chunk name is prepended to the error string. */
  183317. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183318. png_const_charp error_message));
  183319. #else
  183320. /* Fatal error in PNG image of libpng - can't continue */
  183321. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183322. #endif
  183323. #ifndef PNG_NO_WARNINGS
  183324. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183325. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183326. png_const_charp warning_message));
  183327. #ifdef PNG_READ_SUPPORTED
  183328. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183329. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183330. png_const_charp warning_message));
  183331. #endif /* PNG_READ_SUPPORTED */
  183332. #endif /* PNG_NO_WARNINGS */
  183333. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183334. * Similarly, the png_get_<chunk> calls are used to read values from the
  183335. * png_info_struct, either storing the parameters in the passed variables, or
  183336. * setting pointers into the png_info_struct where the data is stored. The
  183337. * png_get_<chunk> functions return a non-zero value if the data was available
  183338. * in info_ptr, or return zero and do not change any of the parameters if the
  183339. * data was not available.
  183340. *
  183341. * These functions should be used instead of directly accessing png_info
  183342. * to avoid problems with future changes in the size and internal layout of
  183343. * png_info_struct.
  183344. */
  183345. /* Returns "flag" if chunk data is valid in info_ptr. */
  183346. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183347. png_infop info_ptr, png_uint_32 flag));
  183348. /* Returns number of bytes needed to hold a transformed row. */
  183349. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183350. png_infop info_ptr));
  183351. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183352. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183353. returned from png_read_png(). */
  183354. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183355. png_infop info_ptr));
  183356. /* Set row_pointers, which is an array of pointers to scanlines for use
  183357. by png_write_png(). */
  183358. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183359. png_infop info_ptr, png_bytepp row_pointers));
  183360. #endif
  183361. /* Returns number of color channels in image. */
  183362. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183363. png_infop info_ptr));
  183364. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183365. /* Returns image width in pixels. */
  183366. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183367. png_ptr, png_infop info_ptr));
  183368. /* Returns image height in pixels. */
  183369. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183370. png_ptr, png_infop info_ptr));
  183371. /* Returns image bit_depth. */
  183372. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183373. png_ptr, png_infop info_ptr));
  183374. /* Returns image color_type. */
  183375. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183376. png_ptr, png_infop info_ptr));
  183377. /* Returns image filter_type. */
  183378. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183379. png_ptr, png_infop info_ptr));
  183380. /* Returns image interlace_type. */
  183381. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183382. png_ptr, png_infop info_ptr));
  183383. /* Returns image compression_type. */
  183384. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183385. png_ptr, png_infop info_ptr));
  183386. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183387. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183388. png_ptr, png_infop info_ptr));
  183389. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183390. png_ptr, png_infop info_ptr));
  183391. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183392. png_ptr, png_infop info_ptr));
  183393. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183394. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183395. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183396. png_ptr, png_infop info_ptr));
  183397. #endif
  183398. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183399. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183400. png_ptr, png_infop info_ptr));
  183401. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183402. png_ptr, png_infop info_ptr));
  183403. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183404. png_ptr, png_infop info_ptr));
  183405. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183406. png_ptr, png_infop info_ptr));
  183407. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183408. /* Returns pointer to signature string read from PNG header */
  183409. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183410. png_infop info_ptr));
  183411. #if defined(PNG_bKGD_SUPPORTED)
  183412. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183413. png_infop info_ptr, png_color_16p *background));
  183414. #endif
  183415. #if defined(PNG_bKGD_SUPPORTED)
  183416. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183417. png_infop info_ptr, png_color_16p background));
  183418. #endif
  183419. #if defined(PNG_cHRM_SUPPORTED)
  183420. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183421. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183422. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183423. double *red_y, double *green_x, double *green_y, double *blue_x,
  183424. double *blue_y));
  183425. #endif
  183426. #ifdef PNG_FIXED_POINT_SUPPORTED
  183427. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183428. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183429. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183430. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183431. *int_blue_x, png_fixed_point *int_blue_y));
  183432. #endif
  183433. #endif
  183434. #if defined(PNG_cHRM_SUPPORTED)
  183435. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183436. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183437. png_infop info_ptr, double white_x, double white_y, double red_x,
  183438. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183439. #endif
  183440. #ifdef PNG_FIXED_POINT_SUPPORTED
  183441. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183442. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183443. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183444. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183445. png_fixed_point int_blue_y));
  183446. #endif
  183447. #endif
  183448. #if defined(PNG_gAMA_SUPPORTED)
  183449. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183450. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183451. png_infop info_ptr, double *file_gamma));
  183452. #endif
  183453. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183454. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183455. #endif
  183456. #if defined(PNG_gAMA_SUPPORTED)
  183457. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183458. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183459. png_infop info_ptr, double file_gamma));
  183460. #endif
  183461. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183462. png_infop info_ptr, png_fixed_point int_file_gamma));
  183463. #endif
  183464. #if defined(PNG_hIST_SUPPORTED)
  183465. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183466. png_infop info_ptr, png_uint_16p *hist));
  183467. #endif
  183468. #if defined(PNG_hIST_SUPPORTED)
  183469. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183470. png_infop info_ptr, png_uint_16p hist));
  183471. #endif
  183472. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183473. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183474. int *bit_depth, int *color_type, int *interlace_method,
  183475. int *compression_method, int *filter_method));
  183476. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183477. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183478. int color_type, int interlace_method, int compression_method,
  183479. int filter_method));
  183480. #if defined(PNG_oFFs_SUPPORTED)
  183481. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183482. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183483. int *unit_type));
  183484. #endif
  183485. #if defined(PNG_oFFs_SUPPORTED)
  183486. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183487. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183488. int unit_type));
  183489. #endif
  183490. #if defined(PNG_pCAL_SUPPORTED)
  183491. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183492. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183493. int *type, int *nparams, png_charp *units, png_charpp *params));
  183494. #endif
  183495. #if defined(PNG_pCAL_SUPPORTED)
  183496. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183497. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183498. int type, int nparams, png_charp units, png_charpp params));
  183499. #endif
  183500. #if defined(PNG_pHYs_SUPPORTED)
  183501. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183502. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183503. #endif
  183504. #if defined(PNG_pHYs_SUPPORTED)
  183505. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183506. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183507. #endif
  183508. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183509. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183510. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183511. png_infop info_ptr, png_colorp palette, int num_palette));
  183512. #if defined(PNG_sBIT_SUPPORTED)
  183513. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183514. png_infop info_ptr, png_color_8p *sig_bit));
  183515. #endif
  183516. #if defined(PNG_sBIT_SUPPORTED)
  183517. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183518. png_infop info_ptr, png_color_8p sig_bit));
  183519. #endif
  183520. #if defined(PNG_sRGB_SUPPORTED)
  183521. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183522. png_infop info_ptr, int *intent));
  183523. #endif
  183524. #if defined(PNG_sRGB_SUPPORTED)
  183525. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183526. png_infop info_ptr, int intent));
  183527. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183528. png_infop info_ptr, int intent));
  183529. #endif
  183530. #if defined(PNG_iCCP_SUPPORTED)
  183531. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183532. png_infop info_ptr, png_charpp name, int *compression_type,
  183533. png_charpp profile, png_uint_32 *proflen));
  183534. /* Note to maintainer: profile should be png_bytepp */
  183535. #endif
  183536. #if defined(PNG_iCCP_SUPPORTED)
  183537. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183538. png_infop info_ptr, png_charp name, int compression_type,
  183539. png_charp profile, png_uint_32 proflen));
  183540. /* Note to maintainer: profile should be png_bytep */
  183541. #endif
  183542. #if defined(PNG_sPLT_SUPPORTED)
  183543. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183544. png_infop info_ptr, png_sPLT_tpp entries));
  183545. #endif
  183546. #if defined(PNG_sPLT_SUPPORTED)
  183547. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183548. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183549. #endif
  183550. #if defined(PNG_TEXT_SUPPORTED)
  183551. /* png_get_text also returns the number of text chunks in *num_text */
  183552. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183553. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183554. #endif
  183555. /*
  183556. * Note while png_set_text() will accept a structure whose text,
  183557. * language, and translated keywords are NULL pointers, the structure
  183558. * returned by png_get_text will always contain regular
  183559. * zero-terminated C strings. They might be empty strings but
  183560. * they will never be NULL pointers.
  183561. */
  183562. #if defined(PNG_TEXT_SUPPORTED)
  183563. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183564. png_infop info_ptr, png_textp text_ptr, int num_text));
  183565. #endif
  183566. #if defined(PNG_tIME_SUPPORTED)
  183567. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183568. png_infop info_ptr, png_timep *mod_time));
  183569. #endif
  183570. #if defined(PNG_tIME_SUPPORTED)
  183571. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183572. png_infop info_ptr, png_timep mod_time));
  183573. #endif
  183574. #if defined(PNG_tRNS_SUPPORTED)
  183575. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183576. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183577. png_color_16p *trans_values));
  183578. #endif
  183579. #if defined(PNG_tRNS_SUPPORTED)
  183580. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183581. png_infop info_ptr, png_bytep trans, int num_trans,
  183582. png_color_16p trans_values));
  183583. #endif
  183584. #if defined(PNG_tRNS_SUPPORTED)
  183585. #endif
  183586. #if defined(PNG_sCAL_SUPPORTED)
  183587. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183588. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183589. png_infop info_ptr, int *unit, double *width, double *height));
  183590. #else
  183591. #ifdef PNG_FIXED_POINT_SUPPORTED
  183592. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183593. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183594. #endif
  183595. #endif
  183596. #endif /* PNG_sCAL_SUPPORTED */
  183597. #if defined(PNG_sCAL_SUPPORTED)
  183598. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183599. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183600. png_infop info_ptr, int unit, double width, double height));
  183601. #else
  183602. #ifdef PNG_FIXED_POINT_SUPPORTED
  183603. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183604. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183605. #endif
  183606. #endif
  183607. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183608. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183609. /* provide a list of chunks and how they are to be handled, if the built-in
  183610. handling or default unknown chunk handling is not desired. Any chunks not
  183611. listed will be handled in the default manner. The IHDR and IEND chunks
  183612. must not be listed.
  183613. keep = 0: follow default behaviour
  183614. = 1: do not keep
  183615. = 2: keep only if safe-to-copy
  183616. = 3: keep even if unsafe-to-copy
  183617. */
  183618. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183619. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183620. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183621. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183622. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183623. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183624. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183625. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183626. #endif
  183627. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183628. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183629. chunk_name));
  183630. #endif
  183631. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183632. If you need to turn it off for a chunk that your application has freed,
  183633. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183634. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183635. png_infop info_ptr, int mask));
  183636. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183637. /* The "params" pointer is currently not used and is for future expansion. */
  183638. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183639. png_infop info_ptr,
  183640. int transforms,
  183641. png_voidp params));
  183642. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183643. png_infop info_ptr,
  183644. int transforms,
  183645. png_voidp params));
  183646. #endif
  183647. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183648. * numbers for PNG_DEBUG mean more debugging information. This has
  183649. * only been added since version 0.95 so it is not implemented throughout
  183650. * libpng yet, but more support will be added as needed.
  183651. */
  183652. #ifdef PNG_DEBUG
  183653. #if (PNG_DEBUG > 0)
  183654. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183655. #include <crtdbg.h>
  183656. #if (PNG_DEBUG > 1)
  183657. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183658. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183659. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183660. #endif
  183661. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183662. #ifndef PNG_DEBUG_FILE
  183663. #define PNG_DEBUG_FILE stderr
  183664. #endif /* PNG_DEBUG_FILE */
  183665. #if (PNG_DEBUG > 1)
  183666. #define png_debug(l,m) \
  183667. { \
  183668. int num_tabs=l; \
  183669. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183670. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183671. }
  183672. #define png_debug1(l,m,p1) \
  183673. { \
  183674. int num_tabs=l; \
  183675. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183676. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183677. }
  183678. #define png_debug2(l,m,p1,p2) \
  183679. { \
  183680. int num_tabs=l; \
  183681. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183682. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183683. }
  183684. #endif /* (PNG_DEBUG > 1) */
  183685. #endif /* _MSC_VER */
  183686. #endif /* (PNG_DEBUG > 0) */
  183687. #endif /* PNG_DEBUG */
  183688. #ifndef png_debug
  183689. #define png_debug(l, m)
  183690. #endif
  183691. #ifndef png_debug1
  183692. #define png_debug1(l, m, p1)
  183693. #endif
  183694. #ifndef png_debug2
  183695. #define png_debug2(l, m, p1, p2)
  183696. #endif
  183697. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183698. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183699. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183700. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183701. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183702. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183703. png_ptr, png_uint_32 mng_features_permitted));
  183704. #endif
  183705. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183706. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183707. #define PNG_HANDLE_CHUNK_NEVER 1
  183708. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183709. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183710. /* Added to version 1.2.0 */
  183711. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183712. #if defined(PNG_MMX_CODE_SUPPORTED)
  183713. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183714. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183715. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183716. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183717. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183718. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183719. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183720. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183721. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183722. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183723. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183724. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183725. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183726. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183727. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183728. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183729. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183730. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183731. | PNG_MMX_READ_FLAGS \
  183732. | PNG_MMX_WRITE_FLAGS )
  183733. #define PNG_SELECT_READ 1
  183734. #define PNG_SELECT_WRITE 2
  183735. #endif /* PNG_MMX_CODE_SUPPORTED */
  183736. #if !defined(PNG_1_0_X)
  183737. /* pngget.c */
  183738. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183739. PNGARG((int flag_select, int *compilerID));
  183740. /* pngget.c */
  183741. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183742. PNGARG((int flag_select));
  183743. /* pngget.c */
  183744. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183745. PNGARG((png_structp png_ptr));
  183746. /* pngget.c */
  183747. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183748. PNGARG((png_structp png_ptr));
  183749. /* pngget.c */
  183750. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183751. PNGARG((png_structp png_ptr));
  183752. /* pngset.c */
  183753. extern PNG_EXPORT(void,png_set_asm_flags)
  183754. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183755. /* pngset.c */
  183756. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183757. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183758. png_uint_32 mmx_rowbytes_threshold));
  183759. #endif /* PNG_1_0_X */
  183760. #if !defined(PNG_1_0_X)
  183761. /* png.c, pnggccrd.c, or pngvcrd.c */
  183762. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183763. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183764. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183765. * messages before passing them to the error or warning handler. */
  183766. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183767. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183768. png_ptr, png_uint_32 strip_mode));
  183769. #endif
  183770. #endif /* PNG_1_0_X */
  183771. /* Added at libpng-1.2.6 */
  183772. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183773. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183774. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183775. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183776. png_ptr));
  183777. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183778. png_ptr));
  183779. #endif
  183780. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183781. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183782. /* With these routines we avoid an integer divide, which will be slower on
  183783. * most machines. However, it does take more operations than the corresponding
  183784. * divide method, so it may be slower on a few RISC systems. There are two
  183785. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183786. *
  183787. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183788. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183789. * standard method.
  183790. *
  183791. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183792. */
  183793. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183794. # define png_composite(composite, fg, alpha, bg) \
  183795. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183796. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183797. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183798. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183799. # define png_composite_16(composite, fg, alpha, bg) \
  183800. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183801. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183802. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183803. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183804. #else /* standard method using integer division */
  183805. # define png_composite(composite, fg, alpha, bg) \
  183806. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183807. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183808. (png_uint_16)127) / 255)
  183809. # define png_composite_16(composite, fg, alpha, bg) \
  183810. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183811. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183812. (png_uint_32)32767) / (png_uint_32)65535L)
  183813. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183814. /* Inline macros to do direct reads of bytes from the input buffer. These
  183815. * require that you are using an architecture that uses PNG byte ordering
  183816. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183817. * in big-endian mode and 680x0 are the only ones that will support this.
  183818. * The x86 line of processors definitely do not. The png_get_int_32()
  183819. * routine also assumes we are using two's complement format for negative
  183820. * values, which is almost certainly true.
  183821. */
  183822. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183823. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183824. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183825. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183826. #else
  183827. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183828. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183829. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183830. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183831. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183832. PNGARG((png_structp png_ptr, png_bytep buf));
  183833. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183834. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183835. */
  183836. extern PNG_EXPORT(void,png_save_uint_32)
  183837. PNGARG((png_bytep buf, png_uint_32 i));
  183838. extern PNG_EXPORT(void,png_save_int_32)
  183839. PNGARG((png_bytep buf, png_int_32 i));
  183840. /* Place a 16-bit number into a buffer in PNG byte order.
  183841. * The parameter is declared unsigned int, not png_uint_16,
  183842. * just to avoid potential problems on pre-ANSI C compilers.
  183843. */
  183844. extern PNG_EXPORT(void,png_save_uint_16)
  183845. PNGARG((png_bytep buf, unsigned int i));
  183846. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183847. /* ************************************************************************* */
  183848. /* These next functions are used internally in the code. They generally
  183849. * shouldn't be used unless you are writing code to add or replace some
  183850. * functionality in libpng. More information about most functions can
  183851. * be found in the files where the functions are located.
  183852. */
  183853. /* Various modes of operation, that are visible to applications because
  183854. * they are used for unknown chunk location.
  183855. */
  183856. #define PNG_HAVE_IHDR 0x01
  183857. #define PNG_HAVE_PLTE 0x02
  183858. #define PNG_HAVE_IDAT 0x04
  183859. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183860. #define PNG_HAVE_IEND 0x10
  183861. #if defined(PNG_INTERNAL)
  183862. /* More modes of operation. Note that after an init, mode is set to
  183863. * zero automatically when the structure is created.
  183864. */
  183865. #define PNG_HAVE_gAMA 0x20
  183866. #define PNG_HAVE_cHRM 0x40
  183867. #define PNG_HAVE_sRGB 0x80
  183868. #define PNG_HAVE_CHUNK_HEADER 0x100
  183869. #define PNG_WROTE_tIME 0x200
  183870. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183871. #define PNG_BACKGROUND_IS_GRAY 0x800
  183872. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183873. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183874. /* flags for the transformations the PNG library does on the image data */
  183875. #define PNG_BGR 0x0001
  183876. #define PNG_INTERLACE 0x0002
  183877. #define PNG_PACK 0x0004
  183878. #define PNG_SHIFT 0x0008
  183879. #define PNG_SWAP_BYTES 0x0010
  183880. #define PNG_INVERT_MONO 0x0020
  183881. #define PNG_DITHER 0x0040
  183882. #define PNG_BACKGROUND 0x0080
  183883. #define PNG_BACKGROUND_EXPAND 0x0100
  183884. /* 0x0200 unused */
  183885. #define PNG_16_TO_8 0x0400
  183886. #define PNG_RGBA 0x0800
  183887. #define PNG_EXPAND 0x1000
  183888. #define PNG_GAMMA 0x2000
  183889. #define PNG_GRAY_TO_RGB 0x4000
  183890. #define PNG_FILLER 0x8000L
  183891. #define PNG_PACKSWAP 0x10000L
  183892. #define PNG_SWAP_ALPHA 0x20000L
  183893. #define PNG_STRIP_ALPHA 0x40000L
  183894. #define PNG_INVERT_ALPHA 0x80000L
  183895. #define PNG_USER_TRANSFORM 0x100000L
  183896. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183897. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183898. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183899. /* 0x800000L Unused */
  183900. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183901. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183902. /* 0x4000000L unused */
  183903. /* 0x8000000L unused */
  183904. /* 0x10000000L unused */
  183905. /* 0x20000000L unused */
  183906. /* 0x40000000L unused */
  183907. /* flags for png_create_struct */
  183908. #define PNG_STRUCT_PNG 0x0001
  183909. #define PNG_STRUCT_INFO 0x0002
  183910. /* Scaling factor for filter heuristic weighting calculations */
  183911. #define PNG_WEIGHT_SHIFT 8
  183912. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183913. #define PNG_COST_SHIFT 3
  183914. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183915. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183916. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183917. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183918. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183919. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183920. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183921. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183922. #define PNG_FLAG_ROW_INIT 0x0040
  183923. #define PNG_FLAG_FILLER_AFTER 0x0080
  183924. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183925. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183926. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183927. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183928. #define PNG_FLAG_FREE_PLTE 0x1000
  183929. #define PNG_FLAG_FREE_TRNS 0x2000
  183930. #define PNG_FLAG_FREE_HIST 0x4000
  183931. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183932. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183933. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183934. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183935. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183936. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183937. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183938. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183939. /* 0x800000L unused */
  183940. /* 0x1000000L unused */
  183941. /* 0x2000000L unused */
  183942. /* 0x4000000L unused */
  183943. /* 0x8000000L unused */
  183944. /* 0x10000000L unused */
  183945. /* 0x20000000L unused */
  183946. /* 0x40000000L unused */
  183947. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183948. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183949. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183950. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183951. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183952. PNG_FLAG_CRC_CRITICAL_MASK)
  183953. /* save typing and make code easier to understand */
  183954. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183955. abs((int)((c1).green) - (int)((c2).green)) + \
  183956. abs((int)((c1).blue) - (int)((c2).blue)))
  183957. /* Added to libpng-1.2.6 JB */
  183958. #define PNG_ROWBYTES(pixel_bits, width) \
  183959. ((pixel_bits) >= 8 ? \
  183960. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183961. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183962. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183963. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183964. "ideal" and "delta" should be constants, normally simple
  183965. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183966. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183967. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183968. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183969. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183970. /* place to hold the signature string for a PNG file. */
  183971. #ifdef PNG_USE_GLOBAL_ARRAYS
  183972. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183973. #else
  183974. #endif
  183975. #endif /* PNG_NO_EXTERN */
  183976. /* Constant strings for known chunk types. If you need to add a chunk,
  183977. * define the name here, and add an invocation of the macro in png.c and
  183978. * wherever it's needed.
  183979. */
  183980. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183981. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183982. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183983. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183984. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183985. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183986. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183987. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183988. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183989. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183990. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183991. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183992. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183993. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183994. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183995. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183996. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183997. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183998. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183999. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184000. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184001. #ifdef PNG_USE_GLOBAL_ARRAYS
  184002. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184003. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184004. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184005. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184006. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184007. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184008. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184009. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184010. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184011. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184012. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184013. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184014. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184015. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184016. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184017. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184018. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184019. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184020. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184021. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184022. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184023. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184024. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184025. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184026. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184027. */
  184028. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184029. #undef png_read_init
  184030. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184031. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184032. #endif
  184033. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184034. png_const_charp user_png_ver, png_size_t png_struct_size));
  184035. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184036. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184037. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184038. png_info_size));
  184039. #endif
  184040. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184041. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184042. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184043. */
  184044. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184045. #undef png_write_init
  184046. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184047. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184048. #endif
  184049. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184050. png_const_charp user_png_ver, png_size_t png_struct_size));
  184051. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184052. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184053. png_info_size));
  184054. /* Allocate memory for an internal libpng struct */
  184055. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184056. /* Free memory from internal libpng struct */
  184057. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184058. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184059. malloc_fn, png_voidp mem_ptr));
  184060. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184061. png_free_ptr free_fn, png_voidp mem_ptr));
  184062. /* Free any memory that info_ptr points to and reset struct. */
  184063. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184064. png_infop info_ptr));
  184065. #ifndef PNG_1_0_X
  184066. /* Function to allocate memory for zlib. */
  184067. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184068. /* Function to free memory for zlib */
  184069. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184070. #ifdef PNG_SIZE_T
  184071. /* Function to convert a sizeof an item to png_sizeof item */
  184072. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184073. #endif
  184074. /* Next four functions are used internally as callbacks. PNGAPI is required
  184075. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184076. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184077. png_bytep data, png_size_t length));
  184078. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184079. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184080. png_bytep buffer, png_size_t length));
  184081. #endif
  184082. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184083. png_bytep data, png_size_t length));
  184084. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184085. #if !defined(PNG_NO_STDIO)
  184086. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184087. #endif
  184088. #endif
  184089. #else /* PNG_1_0_X */
  184090. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184091. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184092. png_bytep buffer, png_size_t length));
  184093. #endif
  184094. #endif /* PNG_1_0_X */
  184095. /* Reset the CRC variable */
  184096. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184097. /* Write the "data" buffer to whatever output you are using. */
  184098. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184099. png_size_t length));
  184100. /* Read data from whatever input you are using into the "data" buffer */
  184101. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184102. png_size_t length));
  184103. /* Read bytes into buf, and update png_ptr->crc */
  184104. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184105. png_size_t length));
  184106. /* Decompress data in a chunk that uses compression */
  184107. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184108. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184109. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184110. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184111. png_size_t prefix_length, png_size_t *data_length));
  184112. #endif
  184113. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184114. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184115. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184116. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184117. /* Calculate the CRC over a section of data. Note that we are only
  184118. * passing a maximum of 64K on systems that have this as a memory limit,
  184119. * since this is the maximum buffer size we can specify.
  184120. */
  184121. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184122. png_size_t length));
  184123. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184124. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184125. #endif
  184126. /* simple function to write the signature */
  184127. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184128. /* write various chunks */
  184129. /* Write the IHDR chunk, and update the png_struct with the necessary
  184130. * information.
  184131. */
  184132. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184133. png_uint_32 height,
  184134. int bit_depth, int color_type, int compression_method, int filter_method,
  184135. int interlace_method));
  184136. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184137. png_uint_32 num_pal));
  184138. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184139. png_size_t length));
  184140. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184141. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184142. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184143. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184144. #endif
  184145. #ifdef PNG_FIXED_POINT_SUPPORTED
  184146. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184147. file_gamma));
  184148. #endif
  184149. #endif
  184150. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184151. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184152. int color_type));
  184153. #endif
  184154. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184155. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184156. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184157. double white_x, double white_y,
  184158. double red_x, double red_y, double green_x, double green_y,
  184159. double blue_x, double blue_y));
  184160. #endif
  184161. #ifdef PNG_FIXED_POINT_SUPPORTED
  184162. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184163. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184164. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184165. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184166. png_fixed_point int_blue_y));
  184167. #endif
  184168. #endif
  184169. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184170. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184171. int intent));
  184172. #endif
  184173. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184174. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184175. png_charp name, int compression_type,
  184176. png_charp profile, int proflen));
  184177. /* Note to maintainer: profile should be png_bytep */
  184178. #endif
  184179. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184180. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184181. png_sPLT_tp palette));
  184182. #endif
  184183. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184184. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184185. png_color_16p values, int number, int color_type));
  184186. #endif
  184187. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184188. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184189. png_color_16p values, int color_type));
  184190. #endif
  184191. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184192. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184193. int num_hist));
  184194. #endif
  184195. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184196. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184197. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184198. png_charp key, png_charpp new_key));
  184199. #endif
  184200. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184201. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184202. png_charp text, png_size_t text_len));
  184203. #endif
  184204. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184205. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184206. png_charp text, png_size_t text_len, int compression));
  184207. #endif
  184208. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184209. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184210. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184211. png_charp text));
  184212. #endif
  184213. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184214. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184215. png_infop info_ptr, png_textp text_ptr, int num_text));
  184216. #endif
  184217. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184218. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184219. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184220. #endif
  184221. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184222. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184223. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184224. png_charp units, png_charpp params));
  184225. #endif
  184226. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184227. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184228. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184229. int unit_type));
  184230. #endif
  184231. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184232. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184233. png_timep mod_time));
  184234. #endif
  184235. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184236. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184237. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184238. int unit, double width, double height));
  184239. #else
  184240. #ifdef PNG_FIXED_POINT_SUPPORTED
  184241. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184242. int unit, png_charp width, png_charp height));
  184243. #endif
  184244. #endif
  184245. #endif
  184246. /* Called when finished processing a row of data */
  184247. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184248. /* Internal use only. Called before first row of data */
  184249. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184250. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184251. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184252. #endif
  184253. /* combine a row of data, dealing with alpha, etc. if requested */
  184254. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184255. int mask));
  184256. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184257. /* expand an interlaced row */
  184258. /* OLD pre-1.0.9 interface:
  184259. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184260. png_bytep row, int pass, png_uint_32 transformations));
  184261. */
  184262. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184263. #endif
  184264. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184265. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184266. /* grab pixels out of a row for an interlaced pass */
  184267. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184268. png_bytep row, int pass));
  184269. #endif
  184270. /* unfilter a row */
  184271. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184272. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184273. /* Choose the best filter to use and filter the row data */
  184274. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184275. png_row_infop row_info));
  184276. /* Write out the filtered row. */
  184277. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184278. png_bytep filtered_row));
  184279. /* finish a row while reading, dealing with interlacing passes, etc. */
  184280. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184281. /* initialize the row buffers, etc. */
  184282. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184283. /* optional call to update the users info structure */
  184284. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184285. png_infop info_ptr));
  184286. /* these are the functions that do the transformations */
  184287. #if defined(PNG_READ_FILLER_SUPPORTED)
  184288. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184289. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184290. #endif
  184291. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184292. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184293. png_bytep row));
  184294. #endif
  184295. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184296. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184297. png_bytep row));
  184298. #endif
  184299. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184300. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184301. png_bytep row));
  184302. #endif
  184303. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184304. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184305. png_bytep row));
  184306. #endif
  184307. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184308. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184309. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184310. png_bytep row, png_uint_32 flags));
  184311. #endif
  184312. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184313. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184314. #endif
  184315. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184316. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184317. #endif
  184318. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184319. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184320. row_info, png_bytep row));
  184321. #endif
  184322. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184323. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184324. png_bytep row));
  184325. #endif
  184326. #if defined(PNG_READ_PACK_SUPPORTED)
  184327. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184328. #endif
  184329. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184330. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184331. png_color_8p sig_bits));
  184332. #endif
  184333. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184334. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184335. #endif
  184336. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184337. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184338. #endif
  184339. #if defined(PNG_READ_DITHER_SUPPORTED)
  184340. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184341. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184342. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184343. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184344. png_colorp palette, int num_palette));
  184345. # endif
  184346. #endif
  184347. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184348. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184349. #endif
  184350. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184351. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184352. png_bytep row, png_uint_32 bit_depth));
  184353. #endif
  184354. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184355. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184356. png_color_8p bit_depth));
  184357. #endif
  184358. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184359. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184360. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184361. png_color_16p trans_values, png_color_16p background,
  184362. png_color_16p background_1,
  184363. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184364. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184365. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184366. #else
  184367. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184368. png_color_16p trans_values, png_color_16p background));
  184369. #endif
  184370. #endif
  184371. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184372. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184373. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184374. int gamma_shift));
  184375. #endif
  184376. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184377. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184378. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184379. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184380. png_bytep row, png_color_16p trans_value));
  184381. #endif
  184382. /* The following decodes the appropriate chunks, and does error correction,
  184383. * then calls the appropriate callback for the chunk if it is valid.
  184384. */
  184385. /* decode the IHDR chunk */
  184386. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184387. png_uint_32 length));
  184388. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184389. png_uint_32 length));
  184390. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184391. png_uint_32 length));
  184392. #if defined(PNG_READ_bKGD_SUPPORTED)
  184393. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184394. png_uint_32 length));
  184395. #endif
  184396. #if defined(PNG_READ_cHRM_SUPPORTED)
  184397. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184398. png_uint_32 length));
  184399. #endif
  184400. #if defined(PNG_READ_gAMA_SUPPORTED)
  184401. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184402. png_uint_32 length));
  184403. #endif
  184404. #if defined(PNG_READ_hIST_SUPPORTED)
  184405. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184406. png_uint_32 length));
  184407. #endif
  184408. #if defined(PNG_READ_iCCP_SUPPORTED)
  184409. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184410. png_uint_32 length));
  184411. #endif /* PNG_READ_iCCP_SUPPORTED */
  184412. #if defined(PNG_READ_iTXt_SUPPORTED)
  184413. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184414. png_uint_32 length));
  184415. #endif
  184416. #if defined(PNG_READ_oFFs_SUPPORTED)
  184417. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184418. png_uint_32 length));
  184419. #endif
  184420. #if defined(PNG_READ_pCAL_SUPPORTED)
  184421. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184422. png_uint_32 length));
  184423. #endif
  184424. #if defined(PNG_READ_pHYs_SUPPORTED)
  184425. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184426. png_uint_32 length));
  184427. #endif
  184428. #if defined(PNG_READ_sBIT_SUPPORTED)
  184429. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184430. png_uint_32 length));
  184431. #endif
  184432. #if defined(PNG_READ_sCAL_SUPPORTED)
  184433. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184434. png_uint_32 length));
  184435. #endif
  184436. #if defined(PNG_READ_sPLT_SUPPORTED)
  184437. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184438. png_uint_32 length));
  184439. #endif /* PNG_READ_sPLT_SUPPORTED */
  184440. #if defined(PNG_READ_sRGB_SUPPORTED)
  184441. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184442. png_uint_32 length));
  184443. #endif
  184444. #if defined(PNG_READ_tEXt_SUPPORTED)
  184445. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184446. png_uint_32 length));
  184447. #endif
  184448. #if defined(PNG_READ_tIME_SUPPORTED)
  184449. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184450. png_uint_32 length));
  184451. #endif
  184452. #if defined(PNG_READ_tRNS_SUPPORTED)
  184453. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184454. png_uint_32 length));
  184455. #endif
  184456. #if defined(PNG_READ_zTXt_SUPPORTED)
  184457. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184458. png_uint_32 length));
  184459. #endif
  184460. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184461. png_infop info_ptr, png_uint_32 length));
  184462. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184463. png_bytep chunk_name));
  184464. /* handle the transformations for reading and writing */
  184465. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184466. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184467. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184468. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184469. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184470. png_infop info_ptr));
  184471. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184472. png_infop info_ptr));
  184473. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184474. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184475. png_uint_32 length));
  184476. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184477. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184478. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184479. png_bytep buffer, png_size_t buffer_length));
  184480. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184481. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184482. png_bytep buffer, png_size_t buffer_length));
  184483. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184484. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184485. png_infop info_ptr, png_uint_32 length));
  184486. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184487. png_infop info_ptr));
  184488. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184489. png_infop info_ptr));
  184490. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184491. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184492. png_infop info_ptr));
  184493. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184494. png_infop info_ptr));
  184495. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184496. #if defined(PNG_READ_tEXt_SUPPORTED)
  184497. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184498. png_infop info_ptr, png_uint_32 length));
  184499. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184500. png_infop info_ptr));
  184501. #endif
  184502. #if defined(PNG_READ_zTXt_SUPPORTED)
  184503. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184504. png_infop info_ptr, png_uint_32 length));
  184505. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184506. png_infop info_ptr));
  184507. #endif
  184508. #if defined(PNG_READ_iTXt_SUPPORTED)
  184509. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184510. png_infop info_ptr, png_uint_32 length));
  184511. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184512. png_infop info_ptr));
  184513. #endif
  184514. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184515. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184516. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184517. png_bytep row));
  184518. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184519. png_bytep row));
  184520. #endif
  184521. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184522. #if defined(PNG_MMX_CODE_SUPPORTED)
  184523. /* png.c */ /* PRIVATE */
  184524. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184525. #endif
  184526. #endif
  184527. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184528. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184529. png_infop info_ptr));
  184530. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184531. png_infop info_ptr));
  184532. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184533. png_infop info_ptr));
  184534. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184535. png_infop info_ptr));
  184536. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184537. png_infop info_ptr));
  184538. #if defined(PNG_pHYs_SUPPORTED)
  184539. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184540. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184541. #endif /* PNG_pHYs_SUPPORTED */
  184542. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184543. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184544. #endif /* PNG_INTERNAL */
  184545. #ifdef __cplusplus
  184546. //}
  184547. #endif
  184548. #endif /* PNG_VERSION_INFO_ONLY */
  184549. /* do not put anything past this line */
  184550. #endif /* PNG_H */
  184551. /*** End of inlined file: png.h ***/
  184552. #define PNG_NO_EXTERN
  184553. /*** Start of inlined file: png.c ***/
  184554. /* png.c - location for general purpose libpng functions
  184555. *
  184556. * Last changed in libpng 1.2.21 [October 4, 2007]
  184557. * For conditions of distribution and use, see copyright notice in png.h
  184558. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184559. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184560. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184561. */
  184562. #define PNG_INTERNAL
  184563. #define PNG_NO_EXTERN
  184564. /* Generate a compiler error if there is an old png.h in the search path. */
  184565. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184566. /* Version information for C files. This had better match the version
  184567. * string defined in png.h. */
  184568. #ifdef PNG_USE_GLOBAL_ARRAYS
  184569. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184570. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184571. #ifdef PNG_READ_SUPPORTED
  184572. /* png_sig was changed to a function in version 1.0.5c */
  184573. /* Place to hold the signature string for a PNG file. */
  184574. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184575. #endif /* PNG_READ_SUPPORTED */
  184576. /* Invoke global declarations for constant strings for known chunk types */
  184577. PNG_IHDR;
  184578. PNG_IDAT;
  184579. PNG_IEND;
  184580. PNG_PLTE;
  184581. PNG_bKGD;
  184582. PNG_cHRM;
  184583. PNG_gAMA;
  184584. PNG_hIST;
  184585. PNG_iCCP;
  184586. PNG_iTXt;
  184587. PNG_oFFs;
  184588. PNG_pCAL;
  184589. PNG_sCAL;
  184590. PNG_pHYs;
  184591. PNG_sBIT;
  184592. PNG_sPLT;
  184593. PNG_sRGB;
  184594. PNG_tEXt;
  184595. PNG_tIME;
  184596. PNG_tRNS;
  184597. PNG_zTXt;
  184598. #ifdef PNG_READ_SUPPORTED
  184599. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184600. /* start of interlace block */
  184601. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184602. /* offset to next interlace block */
  184603. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184604. /* start of interlace block in the y direction */
  184605. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184606. /* offset to next interlace block in the y direction */
  184607. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184608. /* Height of interlace block. This is not currently used - if you need
  184609. * it, uncomment it here and in png.h
  184610. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184611. */
  184612. /* Mask to determine which pixels are valid in a pass */
  184613. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184614. /* Mask to determine which pixels to overwrite while displaying */
  184615. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184616. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184617. #endif /* PNG_READ_SUPPORTED */
  184618. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184619. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184620. * of the PNG file signature. If the PNG data is embedded into another
  184621. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184622. * or write any of the magic bytes before it starts on the IHDR.
  184623. */
  184624. #ifdef PNG_READ_SUPPORTED
  184625. void PNGAPI
  184626. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184627. {
  184628. if(png_ptr == NULL) return;
  184629. png_debug(1, "in png_set_sig_bytes\n");
  184630. if (num_bytes > 8)
  184631. png_error(png_ptr, "Too many bytes for PNG signature.");
  184632. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184633. }
  184634. /* Checks whether the supplied bytes match the PNG signature. We allow
  184635. * checking less than the full 8-byte signature so that those apps that
  184636. * already read the first few bytes of a file to determine the file type
  184637. * can simply check the remaining bytes for extra assurance. Returns
  184638. * an integer less than, equal to, or greater than zero if sig is found,
  184639. * respectively, to be less than, to match, or be greater than the correct
  184640. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184641. */
  184642. int PNGAPI
  184643. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184644. {
  184645. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184646. if (num_to_check > 8)
  184647. num_to_check = 8;
  184648. else if (num_to_check < 1)
  184649. return (-1);
  184650. if (start > 7)
  184651. return (-1);
  184652. if (start + num_to_check > 8)
  184653. num_to_check = 8 - start;
  184654. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184655. }
  184656. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184657. /* (Obsolete) function to check signature bytes. It does not allow one
  184658. * to check a partial signature. This function might be removed in the
  184659. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184660. */
  184661. int PNGAPI
  184662. png_check_sig(png_bytep sig, int num)
  184663. {
  184664. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184665. }
  184666. #endif
  184667. #endif /* PNG_READ_SUPPORTED */
  184668. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184669. /* Function to allocate memory for zlib and clear it to 0. */
  184670. #ifdef PNG_1_0_X
  184671. voidpf PNGAPI
  184672. #else
  184673. voidpf /* private */
  184674. #endif
  184675. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184676. {
  184677. png_voidp ptr;
  184678. png_structp p=(png_structp)png_ptr;
  184679. png_uint_32 save_flags=p->flags;
  184680. png_uint_32 num_bytes;
  184681. if(png_ptr == NULL) return (NULL);
  184682. if (items > PNG_UINT_32_MAX/size)
  184683. {
  184684. png_warning (p, "Potential overflow in png_zalloc()");
  184685. return (NULL);
  184686. }
  184687. num_bytes = (png_uint_32)items * size;
  184688. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184689. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184690. p->flags=save_flags;
  184691. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184692. if (ptr == NULL)
  184693. return ((voidpf)ptr);
  184694. if (num_bytes > (png_uint_32)0x8000L)
  184695. {
  184696. png_memset(ptr, 0, (png_size_t)0x8000L);
  184697. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184698. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184699. }
  184700. else
  184701. {
  184702. png_memset(ptr, 0, (png_size_t)num_bytes);
  184703. }
  184704. #endif
  184705. return ((voidpf)ptr);
  184706. }
  184707. /* function to free memory for zlib */
  184708. #ifdef PNG_1_0_X
  184709. void PNGAPI
  184710. #else
  184711. void /* private */
  184712. #endif
  184713. png_zfree(voidpf png_ptr, voidpf ptr)
  184714. {
  184715. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184716. }
  184717. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184718. * in case CRC is > 32 bits to leave the top bits 0.
  184719. */
  184720. void /* PRIVATE */
  184721. png_reset_crc(png_structp png_ptr)
  184722. {
  184723. png_ptr->crc = crc32(0, Z_NULL, 0);
  184724. }
  184725. /* Calculate the CRC over a section of data. We can only pass as
  184726. * much data to this routine as the largest single buffer size. We
  184727. * also check that this data will actually be used before going to the
  184728. * trouble of calculating it.
  184729. */
  184730. void /* PRIVATE */
  184731. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184732. {
  184733. int need_crc = 1;
  184734. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184735. {
  184736. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184737. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184738. need_crc = 0;
  184739. }
  184740. else /* critical */
  184741. {
  184742. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184743. need_crc = 0;
  184744. }
  184745. if (need_crc)
  184746. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184747. }
  184748. /* Allocate the memory for an info_struct for the application. We don't
  184749. * really need the png_ptr, but it could potentially be useful in the
  184750. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184751. * and png_info_init() so that applications that want to use a shared
  184752. * libpng don't have to be recompiled if png_info changes size.
  184753. */
  184754. png_infop PNGAPI
  184755. png_create_info_struct(png_structp png_ptr)
  184756. {
  184757. png_infop info_ptr;
  184758. png_debug(1, "in png_create_info_struct\n");
  184759. if(png_ptr == NULL) return (NULL);
  184760. #ifdef PNG_USER_MEM_SUPPORTED
  184761. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184762. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184763. #else
  184764. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184765. #endif
  184766. if (info_ptr != NULL)
  184767. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184768. return (info_ptr);
  184769. }
  184770. /* This function frees the memory associated with a single info struct.
  184771. * Normally, one would use either png_destroy_read_struct() or
  184772. * png_destroy_write_struct() to free an info struct, but this may be
  184773. * useful for some applications.
  184774. */
  184775. void PNGAPI
  184776. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184777. {
  184778. png_infop info_ptr = NULL;
  184779. if(png_ptr == NULL) return;
  184780. png_debug(1, "in png_destroy_info_struct\n");
  184781. if (info_ptr_ptr != NULL)
  184782. info_ptr = *info_ptr_ptr;
  184783. if (info_ptr != NULL)
  184784. {
  184785. png_info_destroy(png_ptr, info_ptr);
  184786. #ifdef PNG_USER_MEM_SUPPORTED
  184787. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184788. png_ptr->mem_ptr);
  184789. #else
  184790. png_destroy_struct((png_voidp)info_ptr);
  184791. #endif
  184792. *info_ptr_ptr = NULL;
  184793. }
  184794. }
  184795. /* Initialize the info structure. This is now an internal function (0.89)
  184796. * and applications using it are urged to use png_create_info_struct()
  184797. * instead.
  184798. */
  184799. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184800. #undef png_info_init
  184801. void PNGAPI
  184802. png_info_init(png_infop info_ptr)
  184803. {
  184804. /* We only come here via pre-1.0.12-compiled applications */
  184805. png_info_init_3(&info_ptr, 0);
  184806. }
  184807. #endif
  184808. void PNGAPI
  184809. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184810. {
  184811. png_infop info_ptr = *ptr_ptr;
  184812. if(info_ptr == NULL) return;
  184813. png_debug(1, "in png_info_init_3\n");
  184814. if(png_sizeof(png_info) > png_info_struct_size)
  184815. {
  184816. png_destroy_struct(info_ptr);
  184817. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184818. *ptr_ptr = info_ptr;
  184819. }
  184820. /* set everything to 0 */
  184821. png_memset(info_ptr, 0, png_sizeof (png_info));
  184822. }
  184823. #ifdef PNG_FREE_ME_SUPPORTED
  184824. void PNGAPI
  184825. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184826. int freer, png_uint_32 mask)
  184827. {
  184828. png_debug(1, "in png_data_freer\n");
  184829. if (png_ptr == NULL || info_ptr == NULL)
  184830. return;
  184831. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184832. info_ptr->free_me |= mask;
  184833. else if(freer == PNG_USER_WILL_FREE_DATA)
  184834. info_ptr->free_me &= ~mask;
  184835. else
  184836. png_warning(png_ptr,
  184837. "Unknown freer parameter in png_data_freer.");
  184838. }
  184839. #endif
  184840. void PNGAPI
  184841. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184842. int num)
  184843. {
  184844. png_debug(1, "in png_free_data\n");
  184845. if (png_ptr == NULL || info_ptr == NULL)
  184846. return;
  184847. #if defined(PNG_TEXT_SUPPORTED)
  184848. /* free text item num or (if num == -1) all text items */
  184849. #ifdef PNG_FREE_ME_SUPPORTED
  184850. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184851. #else
  184852. if (mask & PNG_FREE_TEXT)
  184853. #endif
  184854. {
  184855. if (num != -1)
  184856. {
  184857. if (info_ptr->text && info_ptr->text[num].key)
  184858. {
  184859. png_free(png_ptr, info_ptr->text[num].key);
  184860. info_ptr->text[num].key = NULL;
  184861. }
  184862. }
  184863. else
  184864. {
  184865. int i;
  184866. for (i = 0; i < info_ptr->num_text; i++)
  184867. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184868. png_free(png_ptr, info_ptr->text);
  184869. info_ptr->text = NULL;
  184870. info_ptr->num_text=0;
  184871. }
  184872. }
  184873. #endif
  184874. #if defined(PNG_tRNS_SUPPORTED)
  184875. /* free any tRNS entry */
  184876. #ifdef PNG_FREE_ME_SUPPORTED
  184877. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184878. #else
  184879. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184880. #endif
  184881. {
  184882. png_free(png_ptr, info_ptr->trans);
  184883. info_ptr->valid &= ~PNG_INFO_tRNS;
  184884. #ifndef PNG_FREE_ME_SUPPORTED
  184885. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184886. #endif
  184887. info_ptr->trans = NULL;
  184888. }
  184889. #endif
  184890. #if defined(PNG_sCAL_SUPPORTED)
  184891. /* free any sCAL entry */
  184892. #ifdef PNG_FREE_ME_SUPPORTED
  184893. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184894. #else
  184895. if (mask & PNG_FREE_SCAL)
  184896. #endif
  184897. {
  184898. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184899. png_free(png_ptr, info_ptr->scal_s_width);
  184900. png_free(png_ptr, info_ptr->scal_s_height);
  184901. info_ptr->scal_s_width = NULL;
  184902. info_ptr->scal_s_height = NULL;
  184903. #endif
  184904. info_ptr->valid &= ~PNG_INFO_sCAL;
  184905. }
  184906. #endif
  184907. #if defined(PNG_pCAL_SUPPORTED)
  184908. /* free any pCAL entry */
  184909. #ifdef PNG_FREE_ME_SUPPORTED
  184910. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184911. #else
  184912. if (mask & PNG_FREE_PCAL)
  184913. #endif
  184914. {
  184915. png_free(png_ptr, info_ptr->pcal_purpose);
  184916. png_free(png_ptr, info_ptr->pcal_units);
  184917. info_ptr->pcal_purpose = NULL;
  184918. info_ptr->pcal_units = NULL;
  184919. if (info_ptr->pcal_params != NULL)
  184920. {
  184921. int i;
  184922. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184923. {
  184924. png_free(png_ptr, info_ptr->pcal_params[i]);
  184925. info_ptr->pcal_params[i]=NULL;
  184926. }
  184927. png_free(png_ptr, info_ptr->pcal_params);
  184928. info_ptr->pcal_params = NULL;
  184929. }
  184930. info_ptr->valid &= ~PNG_INFO_pCAL;
  184931. }
  184932. #endif
  184933. #if defined(PNG_iCCP_SUPPORTED)
  184934. /* free any iCCP entry */
  184935. #ifdef PNG_FREE_ME_SUPPORTED
  184936. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184937. #else
  184938. if (mask & PNG_FREE_ICCP)
  184939. #endif
  184940. {
  184941. png_free(png_ptr, info_ptr->iccp_name);
  184942. png_free(png_ptr, info_ptr->iccp_profile);
  184943. info_ptr->iccp_name = NULL;
  184944. info_ptr->iccp_profile = NULL;
  184945. info_ptr->valid &= ~PNG_INFO_iCCP;
  184946. }
  184947. #endif
  184948. #if defined(PNG_sPLT_SUPPORTED)
  184949. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184950. #ifdef PNG_FREE_ME_SUPPORTED
  184951. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184952. #else
  184953. if (mask & PNG_FREE_SPLT)
  184954. #endif
  184955. {
  184956. if (num != -1)
  184957. {
  184958. if(info_ptr->splt_palettes)
  184959. {
  184960. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184961. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184962. info_ptr->splt_palettes[num].name = NULL;
  184963. info_ptr->splt_palettes[num].entries = NULL;
  184964. }
  184965. }
  184966. else
  184967. {
  184968. if(info_ptr->splt_palettes_num)
  184969. {
  184970. int i;
  184971. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184972. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184973. png_free(png_ptr, info_ptr->splt_palettes);
  184974. info_ptr->splt_palettes = NULL;
  184975. info_ptr->splt_palettes_num = 0;
  184976. }
  184977. info_ptr->valid &= ~PNG_INFO_sPLT;
  184978. }
  184979. }
  184980. #endif
  184981. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184982. if(png_ptr->unknown_chunk.data)
  184983. {
  184984. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184985. png_ptr->unknown_chunk.data = NULL;
  184986. }
  184987. #ifdef PNG_FREE_ME_SUPPORTED
  184988. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184989. #else
  184990. if (mask & PNG_FREE_UNKN)
  184991. #endif
  184992. {
  184993. if (num != -1)
  184994. {
  184995. if(info_ptr->unknown_chunks)
  184996. {
  184997. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184998. info_ptr->unknown_chunks[num].data = NULL;
  184999. }
  185000. }
  185001. else
  185002. {
  185003. int i;
  185004. if(info_ptr->unknown_chunks_num)
  185005. {
  185006. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185007. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185008. png_free(png_ptr, info_ptr->unknown_chunks);
  185009. info_ptr->unknown_chunks = NULL;
  185010. info_ptr->unknown_chunks_num = 0;
  185011. }
  185012. }
  185013. }
  185014. #endif
  185015. #if defined(PNG_hIST_SUPPORTED)
  185016. /* free any hIST entry */
  185017. #ifdef PNG_FREE_ME_SUPPORTED
  185018. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185019. #else
  185020. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185021. #endif
  185022. {
  185023. png_free(png_ptr, info_ptr->hist);
  185024. info_ptr->hist = NULL;
  185025. info_ptr->valid &= ~PNG_INFO_hIST;
  185026. #ifndef PNG_FREE_ME_SUPPORTED
  185027. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185028. #endif
  185029. }
  185030. #endif
  185031. /* free any PLTE entry that was internally allocated */
  185032. #ifdef PNG_FREE_ME_SUPPORTED
  185033. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185034. #else
  185035. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185036. #endif
  185037. {
  185038. png_zfree(png_ptr, info_ptr->palette);
  185039. info_ptr->palette = NULL;
  185040. info_ptr->valid &= ~PNG_INFO_PLTE;
  185041. #ifndef PNG_FREE_ME_SUPPORTED
  185042. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185043. #endif
  185044. info_ptr->num_palette = 0;
  185045. }
  185046. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185047. /* free any image bits attached to the info structure */
  185048. #ifdef PNG_FREE_ME_SUPPORTED
  185049. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185050. #else
  185051. if (mask & PNG_FREE_ROWS)
  185052. #endif
  185053. {
  185054. if(info_ptr->row_pointers)
  185055. {
  185056. int row;
  185057. for (row = 0; row < (int)info_ptr->height; row++)
  185058. {
  185059. png_free(png_ptr, info_ptr->row_pointers[row]);
  185060. info_ptr->row_pointers[row]=NULL;
  185061. }
  185062. png_free(png_ptr, info_ptr->row_pointers);
  185063. info_ptr->row_pointers=NULL;
  185064. }
  185065. info_ptr->valid &= ~PNG_INFO_IDAT;
  185066. }
  185067. #endif
  185068. #ifdef PNG_FREE_ME_SUPPORTED
  185069. if(num == -1)
  185070. info_ptr->free_me &= ~mask;
  185071. else
  185072. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185073. #endif
  185074. }
  185075. /* This is an internal routine to free any memory that the info struct is
  185076. * pointing to before re-using it or freeing the struct itself. Recall
  185077. * that png_free() checks for NULL pointers for us.
  185078. */
  185079. void /* PRIVATE */
  185080. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185081. {
  185082. png_debug(1, "in png_info_destroy\n");
  185083. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185084. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185085. if (png_ptr->num_chunk_list)
  185086. {
  185087. png_free(png_ptr, png_ptr->chunk_list);
  185088. png_ptr->chunk_list=NULL;
  185089. png_ptr->num_chunk_list=0;
  185090. }
  185091. #endif
  185092. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185093. }
  185094. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185095. /* This function returns a pointer to the io_ptr associated with the user
  185096. * functions. The application should free any memory associated with this
  185097. * pointer before png_write_destroy() or png_read_destroy() are called.
  185098. */
  185099. png_voidp PNGAPI
  185100. png_get_io_ptr(png_structp png_ptr)
  185101. {
  185102. if(png_ptr == NULL) return (NULL);
  185103. return (png_ptr->io_ptr);
  185104. }
  185105. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185106. #if !defined(PNG_NO_STDIO)
  185107. /* Initialize the default input/output functions for the PNG file. If you
  185108. * use your own read or write routines, you can call either png_set_read_fn()
  185109. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185110. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185111. * necessarily available.
  185112. */
  185113. void PNGAPI
  185114. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185115. {
  185116. png_debug(1, "in png_init_io\n");
  185117. if(png_ptr == NULL) return;
  185118. png_ptr->io_ptr = (png_voidp)fp;
  185119. }
  185120. #endif
  185121. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185122. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185123. * a "Creation Time" or other text-based time string.
  185124. */
  185125. png_charp PNGAPI
  185126. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185127. {
  185128. static PNG_CONST char short_months[12][4] =
  185129. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185130. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185131. if(png_ptr == NULL) return (NULL);
  185132. if (png_ptr->time_buffer == NULL)
  185133. {
  185134. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185135. png_sizeof(char)));
  185136. }
  185137. #if defined(_WIN32_WCE)
  185138. {
  185139. wchar_t time_buf[29];
  185140. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185141. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185142. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185143. ptime->second % 61);
  185144. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185145. NULL, NULL);
  185146. }
  185147. #else
  185148. #ifdef USE_FAR_KEYWORD
  185149. {
  185150. char near_time_buf[29];
  185151. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185152. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185153. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185154. ptime->second % 61);
  185155. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185156. 29*png_sizeof(char));
  185157. }
  185158. #else
  185159. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185160. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185161. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185162. ptime->second % 61);
  185163. #endif
  185164. #endif /* _WIN32_WCE */
  185165. return ((png_charp)png_ptr->time_buffer);
  185166. }
  185167. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185168. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185169. png_charp PNGAPI
  185170. png_get_copyright(png_structp png_ptr)
  185171. {
  185172. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185173. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185174. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185175. Copyright (c) 1996-1997 Andreas Dilger\n\
  185176. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185177. }
  185178. /* The following return the library version as a short string in the
  185179. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185180. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185181. * is defined in png.h.
  185182. * Note: now there is no difference between png_get_libpng_ver() and
  185183. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185184. * it is guaranteed that png.c uses the correct version of png.h.
  185185. */
  185186. png_charp PNGAPI
  185187. png_get_libpng_ver(png_structp png_ptr)
  185188. {
  185189. /* Version of *.c files used when building libpng */
  185190. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185191. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185192. }
  185193. png_charp PNGAPI
  185194. png_get_header_ver(png_structp png_ptr)
  185195. {
  185196. /* Version of *.h files used when building libpng */
  185197. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185198. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185199. }
  185200. png_charp PNGAPI
  185201. png_get_header_version(png_structp png_ptr)
  185202. {
  185203. /* Returns longer string containing both version and date */
  185204. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185205. return ((png_charp) PNG_HEADER_VERSION_STRING
  185206. #ifndef PNG_READ_SUPPORTED
  185207. " (NO READ SUPPORT)"
  185208. #endif
  185209. "\n");
  185210. }
  185211. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185212. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185213. int PNGAPI
  185214. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185215. {
  185216. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185217. int i;
  185218. png_bytep p;
  185219. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185220. return 0;
  185221. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185222. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185223. if (!png_memcmp(chunk_name, p, 4))
  185224. return ((int)*(p+4));
  185225. return 0;
  185226. }
  185227. #endif
  185228. /* This function, added to libpng-1.0.6g, is untested. */
  185229. int PNGAPI
  185230. png_reset_zstream(png_structp png_ptr)
  185231. {
  185232. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185233. return (inflateReset(&png_ptr->zstream));
  185234. }
  185235. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185236. /* This function was added to libpng-1.0.7 */
  185237. png_uint_32 PNGAPI
  185238. png_access_version_number(void)
  185239. {
  185240. /* Version of *.c files used when building libpng */
  185241. return((png_uint_32) PNG_LIBPNG_VER);
  185242. }
  185243. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185244. #if !defined(PNG_1_0_X)
  185245. /* this function was added to libpng 1.2.0 */
  185246. int PNGAPI
  185247. png_mmx_support(void)
  185248. {
  185249. /* obsolete, to be removed from libpng-1.4.0 */
  185250. return -1;
  185251. }
  185252. #endif /* PNG_1_0_X */
  185253. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185254. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185255. #ifdef PNG_SIZE_T
  185256. /* Added at libpng version 1.2.6 */
  185257. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185258. png_size_t PNGAPI
  185259. png_convert_size(size_t size)
  185260. {
  185261. if (size > (png_size_t)-1)
  185262. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185263. return ((png_size_t)size);
  185264. }
  185265. #endif /* PNG_SIZE_T */
  185266. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185267. /*** End of inlined file: png.c ***/
  185268. /*** Start of inlined file: pngerror.c ***/
  185269. /* pngerror.c - stub functions for i/o and memory allocation
  185270. *
  185271. * Last changed in libpng 1.2.20 October 4, 2007
  185272. * For conditions of distribution and use, see copyright notice in png.h
  185273. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185274. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185275. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185276. *
  185277. * This file provides a location for all error handling. Users who
  185278. * need special error handling are expected to write replacement functions
  185279. * and use png_set_error_fn() to use those functions. See the instructions
  185280. * at each function.
  185281. */
  185282. #define PNG_INTERNAL
  185283. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185284. static void /* PRIVATE */
  185285. png_default_error PNGARG((png_structp png_ptr,
  185286. png_const_charp error_message));
  185287. #ifndef PNG_NO_WARNINGS
  185288. static void /* PRIVATE */
  185289. png_default_warning PNGARG((png_structp png_ptr,
  185290. png_const_charp warning_message));
  185291. #endif /* PNG_NO_WARNINGS */
  185292. /* This function is called whenever there is a fatal error. This function
  185293. * should not be changed. If there is a need to handle errors differently,
  185294. * you should supply a replacement error function and use png_set_error_fn()
  185295. * to replace the error function at run-time.
  185296. */
  185297. #ifndef PNG_NO_ERROR_TEXT
  185298. void PNGAPI
  185299. png_error(png_structp png_ptr, png_const_charp error_message)
  185300. {
  185301. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185302. char msg[16];
  185303. if (png_ptr != NULL)
  185304. {
  185305. if (png_ptr->flags&
  185306. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185307. {
  185308. if (*error_message == '#')
  185309. {
  185310. int offset;
  185311. for (offset=1; offset<15; offset++)
  185312. if (*(error_message+offset) == ' ')
  185313. break;
  185314. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185315. {
  185316. int i;
  185317. for (i=0; i<offset-1; i++)
  185318. msg[i]=error_message[i+1];
  185319. msg[i]='\0';
  185320. error_message=msg;
  185321. }
  185322. else
  185323. error_message+=offset;
  185324. }
  185325. else
  185326. {
  185327. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185328. {
  185329. msg[0]='0';
  185330. msg[1]='\0';
  185331. error_message=msg;
  185332. }
  185333. }
  185334. }
  185335. }
  185336. #endif
  185337. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185338. (*(png_ptr->error_fn))(png_ptr, error_message);
  185339. /* If the custom handler doesn't exist, or if it returns,
  185340. use the default handler, which will not return. */
  185341. png_default_error(png_ptr, error_message);
  185342. }
  185343. #else
  185344. void PNGAPI
  185345. png_err(png_structp png_ptr)
  185346. {
  185347. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185348. (*(png_ptr->error_fn))(png_ptr, '\0');
  185349. /* If the custom handler doesn't exist, or if it returns,
  185350. use the default handler, which will not return. */
  185351. png_default_error(png_ptr, '\0');
  185352. }
  185353. #endif /* PNG_NO_ERROR_TEXT */
  185354. #ifndef PNG_NO_WARNINGS
  185355. /* This function is called whenever there is a non-fatal error. This function
  185356. * should not be changed. If there is a need to handle warnings differently,
  185357. * you should supply a replacement warning function and use
  185358. * png_set_error_fn() to replace the warning function at run-time.
  185359. */
  185360. void PNGAPI
  185361. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185362. {
  185363. int offset = 0;
  185364. if (png_ptr != NULL)
  185365. {
  185366. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185367. if (png_ptr->flags&
  185368. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185369. #endif
  185370. {
  185371. if (*warning_message == '#')
  185372. {
  185373. for (offset=1; offset<15; offset++)
  185374. if (*(warning_message+offset) == ' ')
  185375. break;
  185376. }
  185377. }
  185378. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185379. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185380. }
  185381. else
  185382. png_default_warning(png_ptr, warning_message+offset);
  185383. }
  185384. #endif /* PNG_NO_WARNINGS */
  185385. /* These utilities are used internally to build an error message that relates
  185386. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185387. * this is used to prefix the message. The message is limited in length
  185388. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185389. * if the character is invalid.
  185390. */
  185391. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185392. /*static PNG_CONST char png_digit[16] = {
  185393. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185394. 'A', 'B', 'C', 'D', 'E', 'F'
  185395. };*/
  185396. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185397. static void /* PRIVATE */
  185398. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185399. error_message)
  185400. {
  185401. int iout = 0, iin = 0;
  185402. while (iin < 4)
  185403. {
  185404. int c = png_ptr->chunk_name[iin++];
  185405. if (isnonalpha(c))
  185406. {
  185407. buffer[iout++] = '[';
  185408. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185409. buffer[iout++] = png_digit[c & 0x0f];
  185410. buffer[iout++] = ']';
  185411. }
  185412. else
  185413. {
  185414. buffer[iout++] = (png_byte)c;
  185415. }
  185416. }
  185417. if (error_message == NULL)
  185418. buffer[iout] = 0;
  185419. else
  185420. {
  185421. buffer[iout++] = ':';
  185422. buffer[iout++] = ' ';
  185423. png_strncpy(buffer+iout, error_message, 63);
  185424. buffer[iout+63] = 0;
  185425. }
  185426. }
  185427. #ifdef PNG_READ_SUPPORTED
  185428. void PNGAPI
  185429. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185430. {
  185431. char msg[18+64];
  185432. if (png_ptr == NULL)
  185433. png_error(png_ptr, error_message);
  185434. else
  185435. {
  185436. png_format_buffer(png_ptr, msg, error_message);
  185437. png_error(png_ptr, msg);
  185438. }
  185439. }
  185440. #endif /* PNG_READ_SUPPORTED */
  185441. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185442. #ifndef PNG_NO_WARNINGS
  185443. void PNGAPI
  185444. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185445. {
  185446. char msg[18+64];
  185447. if (png_ptr == NULL)
  185448. png_warning(png_ptr, warning_message);
  185449. else
  185450. {
  185451. png_format_buffer(png_ptr, msg, warning_message);
  185452. png_warning(png_ptr, msg);
  185453. }
  185454. }
  185455. #endif /* PNG_NO_WARNINGS */
  185456. /* This is the default error handling function. Note that replacements for
  185457. * this function MUST NOT RETURN, or the program will likely crash. This
  185458. * function is used by default, or if the program supplies NULL for the
  185459. * error function pointer in png_set_error_fn().
  185460. */
  185461. static void /* PRIVATE */
  185462. png_default_error(png_structp, png_const_charp error_message)
  185463. {
  185464. #ifndef PNG_NO_CONSOLE_IO
  185465. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185466. if (*error_message == '#')
  185467. {
  185468. int offset;
  185469. char error_number[16];
  185470. for (offset=0; offset<15; offset++)
  185471. {
  185472. error_number[offset] = *(error_message+offset+1);
  185473. if (*(error_message+offset) == ' ')
  185474. break;
  185475. }
  185476. if((offset > 1) && (offset < 15))
  185477. {
  185478. error_number[offset-1]='\0';
  185479. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185480. error_message+offset);
  185481. }
  185482. else
  185483. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185484. }
  185485. else
  185486. #endif
  185487. fprintf(stderr, "libpng error: %s\n", error_message);
  185488. #endif
  185489. #ifdef PNG_SETJMP_SUPPORTED
  185490. if (png_ptr)
  185491. {
  185492. # ifdef USE_FAR_KEYWORD
  185493. {
  185494. jmp_buf jmpbuf;
  185495. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185496. longjmp(jmpbuf, 1);
  185497. }
  185498. # else
  185499. longjmp(png_ptr->jmpbuf, 1);
  185500. # endif
  185501. }
  185502. #else
  185503. PNG_ABORT();
  185504. #endif
  185505. #ifdef PNG_NO_CONSOLE_IO
  185506. error_message = error_message; /* make compiler happy */
  185507. #endif
  185508. }
  185509. #ifndef PNG_NO_WARNINGS
  185510. /* This function is called when there is a warning, but the library thinks
  185511. * it can continue anyway. Replacement functions don't have to do anything
  185512. * here if you don't want them to. In the default configuration, png_ptr is
  185513. * not used, but it is passed in case it may be useful.
  185514. */
  185515. static void /* PRIVATE */
  185516. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185517. {
  185518. #ifndef PNG_NO_CONSOLE_IO
  185519. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185520. if (*warning_message == '#')
  185521. {
  185522. int offset;
  185523. char warning_number[16];
  185524. for (offset=0; offset<15; offset++)
  185525. {
  185526. warning_number[offset]=*(warning_message+offset+1);
  185527. if (*(warning_message+offset) == ' ')
  185528. break;
  185529. }
  185530. if((offset > 1) && (offset < 15))
  185531. {
  185532. warning_number[offset-1]='\0';
  185533. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185534. warning_message+offset);
  185535. }
  185536. else
  185537. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185538. }
  185539. else
  185540. # endif
  185541. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185542. #else
  185543. warning_message = warning_message; /* make compiler happy */
  185544. #endif
  185545. png_ptr = png_ptr; /* make compiler happy */
  185546. }
  185547. #endif /* PNG_NO_WARNINGS */
  185548. /* This function is called when the application wants to use another method
  185549. * of handling errors and warnings. Note that the error function MUST NOT
  185550. * return to the calling routine or serious problems will occur. The return
  185551. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185552. */
  185553. void PNGAPI
  185554. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185555. png_error_ptr error_fn, png_error_ptr warning_fn)
  185556. {
  185557. if (png_ptr == NULL)
  185558. return;
  185559. png_ptr->error_ptr = error_ptr;
  185560. png_ptr->error_fn = error_fn;
  185561. png_ptr->warning_fn = warning_fn;
  185562. }
  185563. /* This function returns a pointer to the error_ptr associated with the user
  185564. * functions. The application should free any memory associated with this
  185565. * pointer before png_write_destroy and png_read_destroy are called.
  185566. */
  185567. png_voidp PNGAPI
  185568. png_get_error_ptr(png_structp png_ptr)
  185569. {
  185570. if (png_ptr == NULL)
  185571. return NULL;
  185572. return ((png_voidp)png_ptr->error_ptr);
  185573. }
  185574. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185575. void PNGAPI
  185576. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185577. {
  185578. if(png_ptr != NULL)
  185579. {
  185580. png_ptr->flags &=
  185581. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185582. }
  185583. }
  185584. #endif
  185585. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185586. /*** End of inlined file: pngerror.c ***/
  185587. /*** Start of inlined file: pngget.c ***/
  185588. /* pngget.c - retrieval of values from info struct
  185589. *
  185590. * Last changed in libpng 1.2.15 January 5, 2007
  185591. * For conditions of distribution and use, see copyright notice in png.h
  185592. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185593. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185594. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185595. */
  185596. #define PNG_INTERNAL
  185597. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185598. png_uint_32 PNGAPI
  185599. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185600. {
  185601. if (png_ptr != NULL && info_ptr != NULL)
  185602. return(info_ptr->valid & flag);
  185603. else
  185604. return(0);
  185605. }
  185606. png_uint_32 PNGAPI
  185607. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185608. {
  185609. if (png_ptr != NULL && info_ptr != NULL)
  185610. return(info_ptr->rowbytes);
  185611. else
  185612. return(0);
  185613. }
  185614. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185615. png_bytepp PNGAPI
  185616. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185617. {
  185618. if (png_ptr != NULL && info_ptr != NULL)
  185619. return(info_ptr->row_pointers);
  185620. else
  185621. return(0);
  185622. }
  185623. #endif
  185624. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185625. /* easy access to info, added in libpng-0.99 */
  185626. png_uint_32 PNGAPI
  185627. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185628. {
  185629. if (png_ptr != NULL && info_ptr != NULL)
  185630. {
  185631. return info_ptr->width;
  185632. }
  185633. return (0);
  185634. }
  185635. png_uint_32 PNGAPI
  185636. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185637. {
  185638. if (png_ptr != NULL && info_ptr != NULL)
  185639. {
  185640. return info_ptr->height;
  185641. }
  185642. return (0);
  185643. }
  185644. png_byte PNGAPI
  185645. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185646. {
  185647. if (png_ptr != NULL && info_ptr != NULL)
  185648. {
  185649. return info_ptr->bit_depth;
  185650. }
  185651. return (0);
  185652. }
  185653. png_byte PNGAPI
  185654. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185655. {
  185656. if (png_ptr != NULL && info_ptr != NULL)
  185657. {
  185658. return info_ptr->color_type;
  185659. }
  185660. return (0);
  185661. }
  185662. png_byte PNGAPI
  185663. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185664. {
  185665. if (png_ptr != NULL && info_ptr != NULL)
  185666. {
  185667. return info_ptr->filter_type;
  185668. }
  185669. return (0);
  185670. }
  185671. png_byte PNGAPI
  185672. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185673. {
  185674. if (png_ptr != NULL && info_ptr != NULL)
  185675. {
  185676. return info_ptr->interlace_type;
  185677. }
  185678. return (0);
  185679. }
  185680. png_byte PNGAPI
  185681. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185682. {
  185683. if (png_ptr != NULL && info_ptr != NULL)
  185684. {
  185685. return info_ptr->compression_type;
  185686. }
  185687. return (0);
  185688. }
  185689. png_uint_32 PNGAPI
  185690. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185691. {
  185692. if (png_ptr != NULL && info_ptr != NULL)
  185693. #if defined(PNG_pHYs_SUPPORTED)
  185694. if (info_ptr->valid & PNG_INFO_pHYs)
  185695. {
  185696. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185697. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185698. return (0);
  185699. else return (info_ptr->x_pixels_per_unit);
  185700. }
  185701. #else
  185702. return (0);
  185703. #endif
  185704. return (0);
  185705. }
  185706. png_uint_32 PNGAPI
  185707. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185708. {
  185709. if (png_ptr != NULL && info_ptr != NULL)
  185710. #if defined(PNG_pHYs_SUPPORTED)
  185711. if (info_ptr->valid & PNG_INFO_pHYs)
  185712. {
  185713. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185714. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185715. return (0);
  185716. else return (info_ptr->y_pixels_per_unit);
  185717. }
  185718. #else
  185719. return (0);
  185720. #endif
  185721. return (0);
  185722. }
  185723. png_uint_32 PNGAPI
  185724. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185725. {
  185726. if (png_ptr != NULL && info_ptr != NULL)
  185727. #if defined(PNG_pHYs_SUPPORTED)
  185728. if (info_ptr->valid & PNG_INFO_pHYs)
  185729. {
  185730. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185731. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185732. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185733. return (0);
  185734. else return (info_ptr->x_pixels_per_unit);
  185735. }
  185736. #else
  185737. return (0);
  185738. #endif
  185739. return (0);
  185740. }
  185741. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185742. float PNGAPI
  185743. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185744. {
  185745. if (png_ptr != NULL && info_ptr != NULL)
  185746. #if defined(PNG_pHYs_SUPPORTED)
  185747. if (info_ptr->valid & PNG_INFO_pHYs)
  185748. {
  185749. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185750. if (info_ptr->x_pixels_per_unit == 0)
  185751. return ((float)0.0);
  185752. else
  185753. return ((float)((float)info_ptr->y_pixels_per_unit
  185754. /(float)info_ptr->x_pixels_per_unit));
  185755. }
  185756. #else
  185757. return (0.0);
  185758. #endif
  185759. return ((float)0.0);
  185760. }
  185761. #endif
  185762. png_int_32 PNGAPI
  185763. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185764. {
  185765. if (png_ptr != NULL && info_ptr != NULL)
  185766. #if defined(PNG_oFFs_SUPPORTED)
  185767. if (info_ptr->valid & PNG_INFO_oFFs)
  185768. {
  185769. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185770. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185771. return (0);
  185772. else return (info_ptr->x_offset);
  185773. }
  185774. #else
  185775. return (0);
  185776. #endif
  185777. return (0);
  185778. }
  185779. png_int_32 PNGAPI
  185780. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185781. {
  185782. if (png_ptr != NULL && info_ptr != NULL)
  185783. #if defined(PNG_oFFs_SUPPORTED)
  185784. if (info_ptr->valid & PNG_INFO_oFFs)
  185785. {
  185786. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185787. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185788. return (0);
  185789. else return (info_ptr->y_offset);
  185790. }
  185791. #else
  185792. return (0);
  185793. #endif
  185794. return (0);
  185795. }
  185796. png_int_32 PNGAPI
  185797. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185798. {
  185799. if (png_ptr != NULL && info_ptr != NULL)
  185800. #if defined(PNG_oFFs_SUPPORTED)
  185801. if (info_ptr->valid & PNG_INFO_oFFs)
  185802. {
  185803. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185804. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185805. return (0);
  185806. else return (info_ptr->x_offset);
  185807. }
  185808. #else
  185809. return (0);
  185810. #endif
  185811. return (0);
  185812. }
  185813. png_int_32 PNGAPI
  185814. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185815. {
  185816. if (png_ptr != NULL && info_ptr != NULL)
  185817. #if defined(PNG_oFFs_SUPPORTED)
  185818. if (info_ptr->valid & PNG_INFO_oFFs)
  185819. {
  185820. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185821. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185822. return (0);
  185823. else return (info_ptr->y_offset);
  185824. }
  185825. #else
  185826. return (0);
  185827. #endif
  185828. return (0);
  185829. }
  185830. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185831. png_uint_32 PNGAPI
  185832. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185833. {
  185834. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185835. *.0254 +.5));
  185836. }
  185837. png_uint_32 PNGAPI
  185838. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185839. {
  185840. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185841. *.0254 +.5));
  185842. }
  185843. png_uint_32 PNGAPI
  185844. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185845. {
  185846. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185847. *.0254 +.5));
  185848. }
  185849. float PNGAPI
  185850. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185851. {
  185852. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185853. *.00003937);
  185854. }
  185855. float PNGAPI
  185856. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185857. {
  185858. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185859. *.00003937);
  185860. }
  185861. #if defined(PNG_pHYs_SUPPORTED)
  185862. png_uint_32 PNGAPI
  185863. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185864. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185865. {
  185866. png_uint_32 retval = 0;
  185867. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185868. {
  185869. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185870. if (res_x != NULL)
  185871. {
  185872. *res_x = info_ptr->x_pixels_per_unit;
  185873. retval |= PNG_INFO_pHYs;
  185874. }
  185875. if (res_y != NULL)
  185876. {
  185877. *res_y = info_ptr->y_pixels_per_unit;
  185878. retval |= PNG_INFO_pHYs;
  185879. }
  185880. if (unit_type != NULL)
  185881. {
  185882. *unit_type = (int)info_ptr->phys_unit_type;
  185883. retval |= PNG_INFO_pHYs;
  185884. if(*unit_type == 1)
  185885. {
  185886. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185887. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185888. }
  185889. }
  185890. }
  185891. return (retval);
  185892. }
  185893. #endif /* PNG_pHYs_SUPPORTED */
  185894. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185895. /* png_get_channels really belongs in here, too, but it's been around longer */
  185896. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185897. png_byte PNGAPI
  185898. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185899. {
  185900. if (png_ptr != NULL && info_ptr != NULL)
  185901. return(info_ptr->channels);
  185902. else
  185903. return (0);
  185904. }
  185905. png_bytep PNGAPI
  185906. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185907. {
  185908. if (png_ptr != NULL && info_ptr != NULL)
  185909. return(info_ptr->signature);
  185910. else
  185911. return (NULL);
  185912. }
  185913. #if defined(PNG_bKGD_SUPPORTED)
  185914. png_uint_32 PNGAPI
  185915. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185916. png_color_16p *background)
  185917. {
  185918. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185919. && background != NULL)
  185920. {
  185921. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185922. *background = &(info_ptr->background);
  185923. return (PNG_INFO_bKGD);
  185924. }
  185925. return (0);
  185926. }
  185927. #endif
  185928. #if defined(PNG_cHRM_SUPPORTED)
  185929. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185930. png_uint_32 PNGAPI
  185931. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185932. double *white_x, double *white_y, double *red_x, double *red_y,
  185933. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185934. {
  185935. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185936. {
  185937. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185938. if (white_x != NULL)
  185939. *white_x = (double)info_ptr->x_white;
  185940. if (white_y != NULL)
  185941. *white_y = (double)info_ptr->y_white;
  185942. if (red_x != NULL)
  185943. *red_x = (double)info_ptr->x_red;
  185944. if (red_y != NULL)
  185945. *red_y = (double)info_ptr->y_red;
  185946. if (green_x != NULL)
  185947. *green_x = (double)info_ptr->x_green;
  185948. if (green_y != NULL)
  185949. *green_y = (double)info_ptr->y_green;
  185950. if (blue_x != NULL)
  185951. *blue_x = (double)info_ptr->x_blue;
  185952. if (blue_y != NULL)
  185953. *blue_y = (double)info_ptr->y_blue;
  185954. return (PNG_INFO_cHRM);
  185955. }
  185956. return (0);
  185957. }
  185958. #endif
  185959. #ifdef PNG_FIXED_POINT_SUPPORTED
  185960. png_uint_32 PNGAPI
  185961. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185962. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185963. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185964. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185965. {
  185966. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185967. {
  185968. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185969. if (white_x != NULL)
  185970. *white_x = info_ptr->int_x_white;
  185971. if (white_y != NULL)
  185972. *white_y = info_ptr->int_y_white;
  185973. if (red_x != NULL)
  185974. *red_x = info_ptr->int_x_red;
  185975. if (red_y != NULL)
  185976. *red_y = info_ptr->int_y_red;
  185977. if (green_x != NULL)
  185978. *green_x = info_ptr->int_x_green;
  185979. if (green_y != NULL)
  185980. *green_y = info_ptr->int_y_green;
  185981. if (blue_x != NULL)
  185982. *blue_x = info_ptr->int_x_blue;
  185983. if (blue_y != NULL)
  185984. *blue_y = info_ptr->int_y_blue;
  185985. return (PNG_INFO_cHRM);
  185986. }
  185987. return (0);
  185988. }
  185989. #endif
  185990. #endif
  185991. #if defined(PNG_gAMA_SUPPORTED)
  185992. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185993. png_uint_32 PNGAPI
  185994. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185995. {
  185996. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185997. && file_gamma != NULL)
  185998. {
  185999. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186000. *file_gamma = (double)info_ptr->gamma;
  186001. return (PNG_INFO_gAMA);
  186002. }
  186003. return (0);
  186004. }
  186005. #endif
  186006. #ifdef PNG_FIXED_POINT_SUPPORTED
  186007. png_uint_32 PNGAPI
  186008. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186009. png_fixed_point *int_file_gamma)
  186010. {
  186011. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186012. && int_file_gamma != NULL)
  186013. {
  186014. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186015. *int_file_gamma = info_ptr->int_gamma;
  186016. return (PNG_INFO_gAMA);
  186017. }
  186018. return (0);
  186019. }
  186020. #endif
  186021. #endif
  186022. #if defined(PNG_sRGB_SUPPORTED)
  186023. png_uint_32 PNGAPI
  186024. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186025. {
  186026. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186027. && file_srgb_intent != NULL)
  186028. {
  186029. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186030. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186031. return (PNG_INFO_sRGB);
  186032. }
  186033. return (0);
  186034. }
  186035. #endif
  186036. #if defined(PNG_iCCP_SUPPORTED)
  186037. png_uint_32 PNGAPI
  186038. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186039. png_charpp name, int *compression_type,
  186040. png_charpp profile, png_uint_32 *proflen)
  186041. {
  186042. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186043. && name != NULL && profile != NULL && proflen != NULL)
  186044. {
  186045. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186046. *name = info_ptr->iccp_name;
  186047. *profile = info_ptr->iccp_profile;
  186048. /* compression_type is a dummy so the API won't have to change
  186049. if we introduce multiple compression types later. */
  186050. *proflen = (int)info_ptr->iccp_proflen;
  186051. *compression_type = (int)info_ptr->iccp_compression;
  186052. return (PNG_INFO_iCCP);
  186053. }
  186054. return (0);
  186055. }
  186056. #endif
  186057. #if defined(PNG_sPLT_SUPPORTED)
  186058. png_uint_32 PNGAPI
  186059. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186060. png_sPLT_tpp spalettes)
  186061. {
  186062. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186063. {
  186064. *spalettes = info_ptr->splt_palettes;
  186065. return ((png_uint_32)info_ptr->splt_palettes_num);
  186066. }
  186067. return (0);
  186068. }
  186069. #endif
  186070. #if defined(PNG_hIST_SUPPORTED)
  186071. png_uint_32 PNGAPI
  186072. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186073. {
  186074. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186075. && hist != NULL)
  186076. {
  186077. png_debug1(1, "in %s retrieval function\n", "hIST");
  186078. *hist = info_ptr->hist;
  186079. return (PNG_INFO_hIST);
  186080. }
  186081. return (0);
  186082. }
  186083. #endif
  186084. png_uint_32 PNGAPI
  186085. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186086. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186087. int *color_type, int *interlace_type, int *compression_type,
  186088. int *filter_type)
  186089. {
  186090. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186091. bit_depth != NULL && color_type != NULL)
  186092. {
  186093. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186094. *width = info_ptr->width;
  186095. *height = info_ptr->height;
  186096. *bit_depth = info_ptr->bit_depth;
  186097. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186098. png_error(png_ptr, "Invalid bit depth");
  186099. *color_type = info_ptr->color_type;
  186100. if (info_ptr->color_type > 6)
  186101. png_error(png_ptr, "Invalid color type");
  186102. if (compression_type != NULL)
  186103. *compression_type = info_ptr->compression_type;
  186104. if (filter_type != NULL)
  186105. *filter_type = info_ptr->filter_type;
  186106. if (interlace_type != NULL)
  186107. *interlace_type = info_ptr->interlace_type;
  186108. /* check for potential overflow of rowbytes */
  186109. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186110. png_error(png_ptr, "Invalid image width");
  186111. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186112. png_error(png_ptr, "Invalid image height");
  186113. if (info_ptr->width > (PNG_UINT_32_MAX
  186114. >> 3) /* 8-byte RGBA pixels */
  186115. - 64 /* bigrowbuf hack */
  186116. - 1 /* filter byte */
  186117. - 7*8 /* rounding of width to multiple of 8 pixels */
  186118. - 8) /* extra max_pixel_depth pad */
  186119. {
  186120. png_warning(png_ptr,
  186121. "Width too large for libpng to process image data.");
  186122. }
  186123. return (1);
  186124. }
  186125. return (0);
  186126. }
  186127. #if defined(PNG_oFFs_SUPPORTED)
  186128. png_uint_32 PNGAPI
  186129. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186130. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186131. {
  186132. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186133. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186134. {
  186135. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186136. *offset_x = info_ptr->x_offset;
  186137. *offset_y = info_ptr->y_offset;
  186138. *unit_type = (int)info_ptr->offset_unit_type;
  186139. return (PNG_INFO_oFFs);
  186140. }
  186141. return (0);
  186142. }
  186143. #endif
  186144. #if defined(PNG_pCAL_SUPPORTED)
  186145. png_uint_32 PNGAPI
  186146. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186147. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186148. png_charp *units, png_charpp *params)
  186149. {
  186150. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186151. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186152. nparams != NULL && units != NULL && params != NULL)
  186153. {
  186154. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186155. *purpose = info_ptr->pcal_purpose;
  186156. *X0 = info_ptr->pcal_X0;
  186157. *X1 = info_ptr->pcal_X1;
  186158. *type = (int)info_ptr->pcal_type;
  186159. *nparams = (int)info_ptr->pcal_nparams;
  186160. *units = info_ptr->pcal_units;
  186161. *params = info_ptr->pcal_params;
  186162. return (PNG_INFO_pCAL);
  186163. }
  186164. return (0);
  186165. }
  186166. #endif
  186167. #if defined(PNG_sCAL_SUPPORTED)
  186168. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186169. png_uint_32 PNGAPI
  186170. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186171. int *unit, double *width, double *height)
  186172. {
  186173. if (png_ptr != NULL && info_ptr != NULL &&
  186174. (info_ptr->valid & PNG_INFO_sCAL))
  186175. {
  186176. *unit = info_ptr->scal_unit;
  186177. *width = info_ptr->scal_pixel_width;
  186178. *height = info_ptr->scal_pixel_height;
  186179. return (PNG_INFO_sCAL);
  186180. }
  186181. return(0);
  186182. }
  186183. #else
  186184. #ifdef PNG_FIXED_POINT_SUPPORTED
  186185. png_uint_32 PNGAPI
  186186. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186187. int *unit, png_charpp width, png_charpp height)
  186188. {
  186189. if (png_ptr != NULL && info_ptr != NULL &&
  186190. (info_ptr->valid & PNG_INFO_sCAL))
  186191. {
  186192. *unit = info_ptr->scal_unit;
  186193. *width = info_ptr->scal_s_width;
  186194. *height = info_ptr->scal_s_height;
  186195. return (PNG_INFO_sCAL);
  186196. }
  186197. return(0);
  186198. }
  186199. #endif
  186200. #endif
  186201. #endif
  186202. #if defined(PNG_pHYs_SUPPORTED)
  186203. png_uint_32 PNGAPI
  186204. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186205. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186206. {
  186207. png_uint_32 retval = 0;
  186208. if (png_ptr != NULL && info_ptr != NULL &&
  186209. (info_ptr->valid & PNG_INFO_pHYs))
  186210. {
  186211. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186212. if (res_x != NULL)
  186213. {
  186214. *res_x = info_ptr->x_pixels_per_unit;
  186215. retval |= PNG_INFO_pHYs;
  186216. }
  186217. if (res_y != NULL)
  186218. {
  186219. *res_y = info_ptr->y_pixels_per_unit;
  186220. retval |= PNG_INFO_pHYs;
  186221. }
  186222. if (unit_type != NULL)
  186223. {
  186224. *unit_type = (int)info_ptr->phys_unit_type;
  186225. retval |= PNG_INFO_pHYs;
  186226. }
  186227. }
  186228. return (retval);
  186229. }
  186230. #endif
  186231. png_uint_32 PNGAPI
  186232. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186233. int *num_palette)
  186234. {
  186235. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186236. && palette != NULL)
  186237. {
  186238. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186239. *palette = info_ptr->palette;
  186240. *num_palette = info_ptr->num_palette;
  186241. png_debug1(3, "num_palette = %d\n", *num_palette);
  186242. return (PNG_INFO_PLTE);
  186243. }
  186244. return (0);
  186245. }
  186246. #if defined(PNG_sBIT_SUPPORTED)
  186247. png_uint_32 PNGAPI
  186248. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186249. {
  186250. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186251. && sig_bit != NULL)
  186252. {
  186253. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186254. *sig_bit = &(info_ptr->sig_bit);
  186255. return (PNG_INFO_sBIT);
  186256. }
  186257. return (0);
  186258. }
  186259. #endif
  186260. #if defined(PNG_TEXT_SUPPORTED)
  186261. png_uint_32 PNGAPI
  186262. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186263. int *num_text)
  186264. {
  186265. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186266. {
  186267. png_debug1(1, "in %s retrieval function\n",
  186268. (png_ptr->chunk_name[0] == '\0' ? "text"
  186269. : (png_const_charp)png_ptr->chunk_name));
  186270. if (text_ptr != NULL)
  186271. *text_ptr = info_ptr->text;
  186272. if (num_text != NULL)
  186273. *num_text = info_ptr->num_text;
  186274. return ((png_uint_32)info_ptr->num_text);
  186275. }
  186276. if (num_text != NULL)
  186277. *num_text = 0;
  186278. return(0);
  186279. }
  186280. #endif
  186281. #if defined(PNG_tIME_SUPPORTED)
  186282. png_uint_32 PNGAPI
  186283. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186284. {
  186285. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186286. && mod_time != NULL)
  186287. {
  186288. png_debug1(1, "in %s retrieval function\n", "tIME");
  186289. *mod_time = &(info_ptr->mod_time);
  186290. return (PNG_INFO_tIME);
  186291. }
  186292. return (0);
  186293. }
  186294. #endif
  186295. #if defined(PNG_tRNS_SUPPORTED)
  186296. png_uint_32 PNGAPI
  186297. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186298. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186299. {
  186300. png_uint_32 retval = 0;
  186301. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186302. {
  186303. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186304. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186305. {
  186306. if (trans != NULL)
  186307. {
  186308. *trans = info_ptr->trans;
  186309. retval |= PNG_INFO_tRNS;
  186310. }
  186311. if (trans_values != NULL)
  186312. *trans_values = &(info_ptr->trans_values);
  186313. }
  186314. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186315. {
  186316. if (trans_values != NULL)
  186317. {
  186318. *trans_values = &(info_ptr->trans_values);
  186319. retval |= PNG_INFO_tRNS;
  186320. }
  186321. if(trans != NULL)
  186322. *trans = NULL;
  186323. }
  186324. if(num_trans != NULL)
  186325. {
  186326. *num_trans = info_ptr->num_trans;
  186327. retval |= PNG_INFO_tRNS;
  186328. }
  186329. }
  186330. return (retval);
  186331. }
  186332. #endif
  186333. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186334. png_uint_32 PNGAPI
  186335. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186336. png_unknown_chunkpp unknowns)
  186337. {
  186338. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186339. {
  186340. *unknowns = info_ptr->unknown_chunks;
  186341. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186342. }
  186343. return (0);
  186344. }
  186345. #endif
  186346. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186347. png_byte PNGAPI
  186348. png_get_rgb_to_gray_status (png_structp png_ptr)
  186349. {
  186350. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186351. }
  186352. #endif
  186353. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186354. png_voidp PNGAPI
  186355. png_get_user_chunk_ptr(png_structp png_ptr)
  186356. {
  186357. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186358. }
  186359. #endif
  186360. #ifdef PNG_WRITE_SUPPORTED
  186361. png_uint_32 PNGAPI
  186362. png_get_compression_buffer_size(png_structp png_ptr)
  186363. {
  186364. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186365. }
  186366. #endif
  186367. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186368. #ifndef PNG_1_0_X
  186369. /* this function was added to libpng 1.2.0 and should exist by default */
  186370. png_uint_32 PNGAPI
  186371. png_get_asm_flags (png_structp png_ptr)
  186372. {
  186373. /* obsolete, to be removed from libpng-1.4.0 */
  186374. return (png_ptr? 0L: 0L);
  186375. }
  186376. /* this function was added to libpng 1.2.0 and should exist by default */
  186377. png_uint_32 PNGAPI
  186378. png_get_asm_flagmask (int flag_select)
  186379. {
  186380. /* obsolete, to be removed from libpng-1.4.0 */
  186381. flag_select=flag_select;
  186382. return 0L;
  186383. }
  186384. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186385. /* this function was added to libpng 1.2.0 */
  186386. png_uint_32 PNGAPI
  186387. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186388. {
  186389. /* obsolete, to be removed from libpng-1.4.0 */
  186390. flag_select=flag_select;
  186391. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186392. return 0L;
  186393. }
  186394. /* this function was added to libpng 1.2.0 */
  186395. png_byte PNGAPI
  186396. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186397. {
  186398. /* obsolete, to be removed from libpng-1.4.0 */
  186399. return (png_ptr? 0: 0);
  186400. }
  186401. /* this function was added to libpng 1.2.0 */
  186402. png_uint_32 PNGAPI
  186403. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186404. {
  186405. /* obsolete, to be removed from libpng-1.4.0 */
  186406. return (png_ptr? 0L: 0L);
  186407. }
  186408. #endif /* ?PNG_1_0_X */
  186409. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186410. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186411. /* these functions were added to libpng 1.2.6 */
  186412. png_uint_32 PNGAPI
  186413. png_get_user_width_max (png_structp png_ptr)
  186414. {
  186415. return (png_ptr? png_ptr->user_width_max : 0);
  186416. }
  186417. png_uint_32 PNGAPI
  186418. png_get_user_height_max (png_structp png_ptr)
  186419. {
  186420. return (png_ptr? png_ptr->user_height_max : 0);
  186421. }
  186422. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186423. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186424. /*** End of inlined file: pngget.c ***/
  186425. /*** Start of inlined file: pngmem.c ***/
  186426. /* pngmem.c - stub functions for memory allocation
  186427. *
  186428. * Last changed in libpng 1.2.13 November 13, 2006
  186429. * For conditions of distribution and use, see copyright notice in png.h
  186430. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186431. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186432. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186433. *
  186434. * This file provides a location for all memory allocation. Users who
  186435. * need special memory handling are expected to supply replacement
  186436. * functions for png_malloc() and png_free(), and to use
  186437. * png_create_read_struct_2() and png_create_write_struct_2() to
  186438. * identify the replacement functions.
  186439. */
  186440. #define PNG_INTERNAL
  186441. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186442. /* Borland DOS special memory handler */
  186443. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186444. /* if you change this, be sure to change the one in png.h also */
  186445. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186446. by a single call to calloc() if this is thought to improve performance. */
  186447. png_voidp /* PRIVATE */
  186448. png_create_struct(int type)
  186449. {
  186450. #ifdef PNG_USER_MEM_SUPPORTED
  186451. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186452. }
  186453. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186454. png_voidp /* PRIVATE */
  186455. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186456. {
  186457. #endif /* PNG_USER_MEM_SUPPORTED */
  186458. png_size_t size;
  186459. png_voidp struct_ptr;
  186460. if (type == PNG_STRUCT_INFO)
  186461. size = png_sizeof(png_info);
  186462. else if (type == PNG_STRUCT_PNG)
  186463. size = png_sizeof(png_struct);
  186464. else
  186465. return (png_get_copyright(NULL));
  186466. #ifdef PNG_USER_MEM_SUPPORTED
  186467. if(malloc_fn != NULL)
  186468. {
  186469. png_struct dummy_struct;
  186470. png_structp png_ptr = &dummy_struct;
  186471. png_ptr->mem_ptr=mem_ptr;
  186472. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186473. }
  186474. else
  186475. #endif /* PNG_USER_MEM_SUPPORTED */
  186476. struct_ptr = (png_voidp)farmalloc(size);
  186477. if (struct_ptr != NULL)
  186478. png_memset(struct_ptr, 0, size);
  186479. return (struct_ptr);
  186480. }
  186481. /* Free memory allocated by a png_create_struct() call */
  186482. void /* PRIVATE */
  186483. png_destroy_struct(png_voidp struct_ptr)
  186484. {
  186485. #ifdef PNG_USER_MEM_SUPPORTED
  186486. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186487. }
  186488. /* Free memory allocated by a png_create_struct() call */
  186489. void /* PRIVATE */
  186490. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186491. png_voidp mem_ptr)
  186492. {
  186493. #endif
  186494. if (struct_ptr != NULL)
  186495. {
  186496. #ifdef PNG_USER_MEM_SUPPORTED
  186497. if(free_fn != NULL)
  186498. {
  186499. png_struct dummy_struct;
  186500. png_structp png_ptr = &dummy_struct;
  186501. png_ptr->mem_ptr=mem_ptr;
  186502. (*(free_fn))(png_ptr, struct_ptr);
  186503. return;
  186504. }
  186505. #endif /* PNG_USER_MEM_SUPPORTED */
  186506. farfree (struct_ptr);
  186507. }
  186508. }
  186509. /* Allocate memory. For reasonable files, size should never exceed
  186510. * 64K. However, zlib may allocate more then 64K if you don't tell
  186511. * it not to. See zconf.h and png.h for more information. zlib does
  186512. * need to allocate exactly 64K, so whatever you call here must
  186513. * have the ability to do that.
  186514. *
  186515. * Borland seems to have a problem in DOS mode for exactly 64K.
  186516. * It gives you a segment with an offset of 8 (perhaps to store its
  186517. * memory stuff). zlib doesn't like this at all, so we have to
  186518. * detect and deal with it. This code should not be needed in
  186519. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186520. * been updated by Alexander Lehmann for version 0.89 to waste less
  186521. * memory.
  186522. *
  186523. * Note that we can't use png_size_t for the "size" declaration,
  186524. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186525. * result, we would be truncating potentially larger memory requests
  186526. * (which should cause a fatal error) and introducing major problems.
  186527. */
  186528. png_voidp PNGAPI
  186529. png_malloc(png_structp png_ptr, png_uint_32 size)
  186530. {
  186531. png_voidp ret;
  186532. if (png_ptr == NULL || size == 0)
  186533. return (NULL);
  186534. #ifdef PNG_USER_MEM_SUPPORTED
  186535. if(png_ptr->malloc_fn != NULL)
  186536. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186537. else
  186538. ret = (png_malloc_default(png_ptr, size));
  186539. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186540. png_error(png_ptr, "Out of memory!");
  186541. return (ret);
  186542. }
  186543. png_voidp PNGAPI
  186544. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186545. {
  186546. png_voidp ret;
  186547. #endif /* PNG_USER_MEM_SUPPORTED */
  186548. if (png_ptr == NULL || size == 0)
  186549. return (NULL);
  186550. #ifdef PNG_MAX_MALLOC_64K
  186551. if (size > (png_uint_32)65536L)
  186552. {
  186553. png_warning(png_ptr, "Cannot Allocate > 64K");
  186554. ret = NULL;
  186555. }
  186556. else
  186557. #endif
  186558. if (size != (size_t)size)
  186559. ret = NULL;
  186560. else if (size == (png_uint_32)65536L)
  186561. {
  186562. if (png_ptr->offset_table == NULL)
  186563. {
  186564. /* try to see if we need to do any of this fancy stuff */
  186565. ret = farmalloc(size);
  186566. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186567. {
  186568. int num_blocks;
  186569. png_uint_32 total_size;
  186570. png_bytep table;
  186571. int i;
  186572. png_byte huge * hptr;
  186573. if (ret != NULL)
  186574. {
  186575. farfree(ret);
  186576. ret = NULL;
  186577. }
  186578. if(png_ptr->zlib_window_bits > 14)
  186579. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186580. else
  186581. num_blocks = 1;
  186582. if (png_ptr->zlib_mem_level >= 7)
  186583. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186584. else
  186585. num_blocks++;
  186586. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186587. table = farmalloc(total_size);
  186588. if (table == NULL)
  186589. {
  186590. #ifndef PNG_USER_MEM_SUPPORTED
  186591. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186592. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186593. else
  186594. png_warning(png_ptr, "Out Of Memory.");
  186595. #endif
  186596. return (NULL);
  186597. }
  186598. if ((png_size_t)table & 0xfff0)
  186599. {
  186600. #ifndef PNG_USER_MEM_SUPPORTED
  186601. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186602. png_error(png_ptr,
  186603. "Farmalloc didn't return normalized pointer");
  186604. else
  186605. png_warning(png_ptr,
  186606. "Farmalloc didn't return normalized pointer");
  186607. #endif
  186608. return (NULL);
  186609. }
  186610. png_ptr->offset_table = table;
  186611. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186612. png_sizeof (png_bytep));
  186613. if (png_ptr->offset_table_ptr == NULL)
  186614. {
  186615. #ifndef PNG_USER_MEM_SUPPORTED
  186616. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186617. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186618. else
  186619. png_warning(png_ptr, "Out Of memory.");
  186620. #endif
  186621. return (NULL);
  186622. }
  186623. hptr = (png_byte huge *)table;
  186624. if ((png_size_t)hptr & 0xf)
  186625. {
  186626. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186627. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186628. }
  186629. for (i = 0; i < num_blocks; i++)
  186630. {
  186631. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186632. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186633. }
  186634. png_ptr->offset_table_number = num_blocks;
  186635. png_ptr->offset_table_count = 0;
  186636. png_ptr->offset_table_count_free = 0;
  186637. }
  186638. }
  186639. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186640. {
  186641. #ifndef PNG_USER_MEM_SUPPORTED
  186642. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186643. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186644. else
  186645. png_warning(png_ptr, "Out of Memory.");
  186646. #endif
  186647. return (NULL);
  186648. }
  186649. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186650. }
  186651. else
  186652. ret = farmalloc(size);
  186653. #ifndef PNG_USER_MEM_SUPPORTED
  186654. if (ret == NULL)
  186655. {
  186656. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186657. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186658. else
  186659. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186660. }
  186661. #endif
  186662. return (ret);
  186663. }
  186664. /* free a pointer allocated by png_malloc(). In the default
  186665. configuration, png_ptr is not used, but is passed in case it
  186666. is needed. If ptr is NULL, return without taking any action. */
  186667. void PNGAPI
  186668. png_free(png_structp png_ptr, png_voidp ptr)
  186669. {
  186670. if (png_ptr == NULL || ptr == NULL)
  186671. return;
  186672. #ifdef PNG_USER_MEM_SUPPORTED
  186673. if (png_ptr->free_fn != NULL)
  186674. {
  186675. (*(png_ptr->free_fn))(png_ptr, ptr);
  186676. return;
  186677. }
  186678. else png_free_default(png_ptr, ptr);
  186679. }
  186680. void PNGAPI
  186681. png_free_default(png_structp png_ptr, png_voidp ptr)
  186682. {
  186683. #endif /* PNG_USER_MEM_SUPPORTED */
  186684. if(png_ptr == NULL) return;
  186685. if (png_ptr->offset_table != NULL)
  186686. {
  186687. int i;
  186688. for (i = 0; i < png_ptr->offset_table_count; i++)
  186689. {
  186690. if (ptr == png_ptr->offset_table_ptr[i])
  186691. {
  186692. ptr = NULL;
  186693. png_ptr->offset_table_count_free++;
  186694. break;
  186695. }
  186696. }
  186697. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186698. {
  186699. farfree(png_ptr->offset_table);
  186700. farfree(png_ptr->offset_table_ptr);
  186701. png_ptr->offset_table = NULL;
  186702. png_ptr->offset_table_ptr = NULL;
  186703. }
  186704. }
  186705. if (ptr != NULL)
  186706. {
  186707. farfree(ptr);
  186708. }
  186709. }
  186710. #else /* Not the Borland DOS special memory handler */
  186711. /* Allocate memory for a png_struct or a png_info. The malloc and
  186712. memset can be replaced by a single call to calloc() if this is thought
  186713. to improve performance noticably. */
  186714. png_voidp /* PRIVATE */
  186715. png_create_struct(int type)
  186716. {
  186717. #ifdef PNG_USER_MEM_SUPPORTED
  186718. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186719. }
  186720. /* Allocate memory for a png_struct or a png_info. The malloc and
  186721. memset can be replaced by a single call to calloc() if this is thought
  186722. to improve performance noticably. */
  186723. png_voidp /* PRIVATE */
  186724. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186725. {
  186726. #endif /* PNG_USER_MEM_SUPPORTED */
  186727. png_size_t size;
  186728. png_voidp struct_ptr;
  186729. if (type == PNG_STRUCT_INFO)
  186730. size = png_sizeof(png_info);
  186731. else if (type == PNG_STRUCT_PNG)
  186732. size = png_sizeof(png_struct);
  186733. else
  186734. return (NULL);
  186735. #ifdef PNG_USER_MEM_SUPPORTED
  186736. if(malloc_fn != NULL)
  186737. {
  186738. png_struct dummy_struct;
  186739. png_structp png_ptr = &dummy_struct;
  186740. png_ptr->mem_ptr=mem_ptr;
  186741. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186742. if (struct_ptr != NULL)
  186743. png_memset(struct_ptr, 0, size);
  186744. return (struct_ptr);
  186745. }
  186746. #endif /* PNG_USER_MEM_SUPPORTED */
  186747. #if defined(__TURBOC__) && !defined(__FLAT__)
  186748. struct_ptr = (png_voidp)farmalloc(size);
  186749. #else
  186750. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186751. struct_ptr = (png_voidp)halloc(size,1);
  186752. # else
  186753. struct_ptr = (png_voidp)malloc(size);
  186754. # endif
  186755. #endif
  186756. if (struct_ptr != NULL)
  186757. png_memset(struct_ptr, 0, size);
  186758. return (struct_ptr);
  186759. }
  186760. /* Free memory allocated by a png_create_struct() call */
  186761. void /* PRIVATE */
  186762. png_destroy_struct(png_voidp struct_ptr)
  186763. {
  186764. #ifdef PNG_USER_MEM_SUPPORTED
  186765. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186766. }
  186767. /* Free memory allocated by a png_create_struct() call */
  186768. void /* PRIVATE */
  186769. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186770. png_voidp mem_ptr)
  186771. {
  186772. #endif /* PNG_USER_MEM_SUPPORTED */
  186773. if (struct_ptr != NULL)
  186774. {
  186775. #ifdef PNG_USER_MEM_SUPPORTED
  186776. if(free_fn != NULL)
  186777. {
  186778. png_struct dummy_struct;
  186779. png_structp png_ptr = &dummy_struct;
  186780. png_ptr->mem_ptr=mem_ptr;
  186781. (*(free_fn))(png_ptr, struct_ptr);
  186782. return;
  186783. }
  186784. #endif /* PNG_USER_MEM_SUPPORTED */
  186785. #if defined(__TURBOC__) && !defined(__FLAT__)
  186786. farfree(struct_ptr);
  186787. #else
  186788. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186789. hfree(struct_ptr);
  186790. # else
  186791. free(struct_ptr);
  186792. # endif
  186793. #endif
  186794. }
  186795. }
  186796. /* Allocate memory. For reasonable files, size should never exceed
  186797. 64K. However, zlib may allocate more then 64K if you don't tell
  186798. it not to. See zconf.h and png.h for more information. zlib does
  186799. need to allocate exactly 64K, so whatever you call here must
  186800. have the ability to do that. */
  186801. png_voidp PNGAPI
  186802. png_malloc(png_structp png_ptr, png_uint_32 size)
  186803. {
  186804. png_voidp ret;
  186805. #ifdef PNG_USER_MEM_SUPPORTED
  186806. if (png_ptr == NULL || size == 0)
  186807. return (NULL);
  186808. if(png_ptr->malloc_fn != NULL)
  186809. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186810. else
  186811. ret = (png_malloc_default(png_ptr, size));
  186812. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186813. png_error(png_ptr, "Out of Memory!");
  186814. return (ret);
  186815. }
  186816. png_voidp PNGAPI
  186817. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186818. {
  186819. png_voidp ret;
  186820. #endif /* PNG_USER_MEM_SUPPORTED */
  186821. if (png_ptr == NULL || size == 0)
  186822. return (NULL);
  186823. #ifdef PNG_MAX_MALLOC_64K
  186824. if (size > (png_uint_32)65536L)
  186825. {
  186826. #ifndef PNG_USER_MEM_SUPPORTED
  186827. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186828. png_error(png_ptr, "Cannot Allocate > 64K");
  186829. else
  186830. #endif
  186831. return NULL;
  186832. }
  186833. #endif
  186834. /* Check for overflow */
  186835. #if defined(__TURBOC__) && !defined(__FLAT__)
  186836. if (size != (unsigned long)size)
  186837. ret = NULL;
  186838. else
  186839. ret = farmalloc(size);
  186840. #else
  186841. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186842. if (size != (unsigned long)size)
  186843. ret = NULL;
  186844. else
  186845. ret = halloc(size, 1);
  186846. # else
  186847. if (size != (size_t)size)
  186848. ret = NULL;
  186849. else
  186850. ret = malloc((size_t)size);
  186851. # endif
  186852. #endif
  186853. #ifndef PNG_USER_MEM_SUPPORTED
  186854. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186855. png_error(png_ptr, "Out of Memory");
  186856. #endif
  186857. return (ret);
  186858. }
  186859. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186860. without taking any action. */
  186861. void PNGAPI
  186862. png_free(png_structp png_ptr, png_voidp ptr)
  186863. {
  186864. if (png_ptr == NULL || ptr == NULL)
  186865. return;
  186866. #ifdef PNG_USER_MEM_SUPPORTED
  186867. if (png_ptr->free_fn != NULL)
  186868. {
  186869. (*(png_ptr->free_fn))(png_ptr, ptr);
  186870. return;
  186871. }
  186872. else png_free_default(png_ptr, ptr);
  186873. }
  186874. void PNGAPI
  186875. png_free_default(png_structp png_ptr, png_voidp ptr)
  186876. {
  186877. if (png_ptr == NULL || ptr == NULL)
  186878. return;
  186879. #endif /* PNG_USER_MEM_SUPPORTED */
  186880. #if defined(__TURBOC__) && !defined(__FLAT__)
  186881. farfree(ptr);
  186882. #else
  186883. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186884. hfree(ptr);
  186885. # else
  186886. free(ptr);
  186887. # endif
  186888. #endif
  186889. }
  186890. #endif /* Not Borland DOS special memory handler */
  186891. #if defined(PNG_1_0_X)
  186892. # define png_malloc_warn png_malloc
  186893. #else
  186894. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186895. * function will set up png_malloc() to issue a png_warning and return NULL
  186896. * instead of issuing a png_error, if it fails to allocate the requested
  186897. * memory.
  186898. */
  186899. png_voidp PNGAPI
  186900. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186901. {
  186902. png_voidp ptr;
  186903. png_uint_32 save_flags;
  186904. if(png_ptr == NULL) return (NULL);
  186905. save_flags=png_ptr->flags;
  186906. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186907. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186908. png_ptr->flags=save_flags;
  186909. return(ptr);
  186910. }
  186911. #endif
  186912. png_voidp PNGAPI
  186913. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186914. png_uint_32 length)
  186915. {
  186916. png_size_t size;
  186917. size = (png_size_t)length;
  186918. if ((png_uint_32)size != length)
  186919. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186920. return(png_memcpy (s1, s2, size));
  186921. }
  186922. png_voidp PNGAPI
  186923. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186924. png_uint_32 length)
  186925. {
  186926. png_size_t size;
  186927. size = (png_size_t)length;
  186928. if ((png_uint_32)size != length)
  186929. png_error(png_ptr,"Overflow in png_memset_check.");
  186930. return (png_memset (s1, value, size));
  186931. }
  186932. #ifdef PNG_USER_MEM_SUPPORTED
  186933. /* This function is called when the application wants to use another method
  186934. * of allocating and freeing memory.
  186935. */
  186936. void PNGAPI
  186937. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186938. malloc_fn, png_free_ptr free_fn)
  186939. {
  186940. if(png_ptr != NULL) {
  186941. png_ptr->mem_ptr = mem_ptr;
  186942. png_ptr->malloc_fn = malloc_fn;
  186943. png_ptr->free_fn = free_fn;
  186944. }
  186945. }
  186946. /* This function returns a pointer to the mem_ptr associated with the user
  186947. * functions. The application should free any memory associated with this
  186948. * pointer before png_write_destroy and png_read_destroy are called.
  186949. */
  186950. png_voidp PNGAPI
  186951. png_get_mem_ptr(png_structp png_ptr)
  186952. {
  186953. if(png_ptr == NULL) return (NULL);
  186954. return ((png_voidp)png_ptr->mem_ptr);
  186955. }
  186956. #endif /* PNG_USER_MEM_SUPPORTED */
  186957. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186958. /*** End of inlined file: pngmem.c ***/
  186959. /*** Start of inlined file: pngread.c ***/
  186960. /* pngread.c - read a PNG file
  186961. *
  186962. * Last changed in libpng 1.2.20 September 7, 2007
  186963. * For conditions of distribution and use, see copyright notice in png.h
  186964. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186965. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186966. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186967. *
  186968. * This file contains routines that an application calls directly to
  186969. * read a PNG file or stream.
  186970. */
  186971. #define PNG_INTERNAL
  186972. #if defined(PNG_READ_SUPPORTED)
  186973. /* Create a PNG structure for reading, and allocate any memory needed. */
  186974. png_structp PNGAPI
  186975. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186976. png_error_ptr error_fn, png_error_ptr warn_fn)
  186977. {
  186978. #ifdef PNG_USER_MEM_SUPPORTED
  186979. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186980. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186981. }
  186982. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186983. png_structp PNGAPI
  186984. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186985. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186986. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186987. {
  186988. #endif /* PNG_USER_MEM_SUPPORTED */
  186989. png_structp png_ptr;
  186990. #ifdef PNG_SETJMP_SUPPORTED
  186991. #ifdef USE_FAR_KEYWORD
  186992. jmp_buf jmpbuf;
  186993. #endif
  186994. #endif
  186995. int i;
  186996. png_debug(1, "in png_create_read_struct\n");
  186997. #ifdef PNG_USER_MEM_SUPPORTED
  186998. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186999. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187000. #else
  187001. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187002. #endif
  187003. if (png_ptr == NULL)
  187004. return (NULL);
  187005. /* added at libpng-1.2.6 */
  187006. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187007. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187008. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187009. #endif
  187010. #ifdef PNG_SETJMP_SUPPORTED
  187011. #ifdef USE_FAR_KEYWORD
  187012. if (setjmp(jmpbuf))
  187013. #else
  187014. if (setjmp(png_ptr->jmpbuf))
  187015. #endif
  187016. {
  187017. png_free(png_ptr, png_ptr->zbuf);
  187018. png_ptr->zbuf=NULL;
  187019. #ifdef PNG_USER_MEM_SUPPORTED
  187020. png_destroy_struct_2((png_voidp)png_ptr,
  187021. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187022. #else
  187023. png_destroy_struct((png_voidp)png_ptr);
  187024. #endif
  187025. return (NULL);
  187026. }
  187027. #ifdef USE_FAR_KEYWORD
  187028. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187029. #endif
  187030. #endif
  187031. #ifdef PNG_USER_MEM_SUPPORTED
  187032. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187033. #endif
  187034. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187035. i=0;
  187036. do
  187037. {
  187038. if(user_png_ver[i] != png_libpng_ver[i])
  187039. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187040. } while (png_libpng_ver[i++]);
  187041. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187042. {
  187043. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187044. * we must recompile any applications that use any older library version.
  187045. * For versions after libpng 1.0, we will be compatible, so we need
  187046. * only check the first digit.
  187047. */
  187048. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187049. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187050. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187051. {
  187052. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187053. char msg[80];
  187054. if (user_png_ver)
  187055. {
  187056. png_snprintf(msg, 80,
  187057. "Application was compiled with png.h from libpng-%.20s",
  187058. user_png_ver);
  187059. png_warning(png_ptr, msg);
  187060. }
  187061. png_snprintf(msg, 80,
  187062. "Application is running with png.c from libpng-%.20s",
  187063. png_libpng_ver);
  187064. png_warning(png_ptr, msg);
  187065. #endif
  187066. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187067. png_ptr->flags=0;
  187068. #endif
  187069. png_error(png_ptr,
  187070. "Incompatible libpng version in application and library");
  187071. }
  187072. }
  187073. /* initialize zbuf - compression buffer */
  187074. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187075. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187076. (png_uint_32)png_ptr->zbuf_size);
  187077. png_ptr->zstream.zalloc = png_zalloc;
  187078. png_ptr->zstream.zfree = png_zfree;
  187079. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187080. switch (inflateInit(&png_ptr->zstream))
  187081. {
  187082. case Z_OK: /* Do nothing */ break;
  187083. case Z_MEM_ERROR:
  187084. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187085. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187086. default: png_error(png_ptr, "Unknown zlib error");
  187087. }
  187088. png_ptr->zstream.next_out = png_ptr->zbuf;
  187089. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187090. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187091. #ifdef PNG_SETJMP_SUPPORTED
  187092. /* Applications that neglect to set up their own setjmp() and then encounter
  187093. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187094. abort instead of returning. */
  187095. #ifdef USE_FAR_KEYWORD
  187096. if (setjmp(jmpbuf))
  187097. PNG_ABORT();
  187098. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187099. #else
  187100. if (setjmp(png_ptr->jmpbuf))
  187101. PNG_ABORT();
  187102. #endif
  187103. #endif
  187104. return (png_ptr);
  187105. }
  187106. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187107. /* Initialize PNG structure for reading, and allocate any memory needed.
  187108. This interface is deprecated in favour of the png_create_read_struct(),
  187109. and it will disappear as of libpng-1.3.0. */
  187110. #undef png_read_init
  187111. void PNGAPI
  187112. png_read_init(png_structp png_ptr)
  187113. {
  187114. /* We only come here via pre-1.0.7-compiled applications */
  187115. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187116. }
  187117. void PNGAPI
  187118. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187119. png_size_t png_struct_size, png_size_t png_info_size)
  187120. {
  187121. /* We only come here via pre-1.0.12-compiled applications */
  187122. if(png_ptr == NULL) return;
  187123. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187124. if(png_sizeof(png_struct) > png_struct_size ||
  187125. png_sizeof(png_info) > png_info_size)
  187126. {
  187127. char msg[80];
  187128. png_ptr->warning_fn=NULL;
  187129. if (user_png_ver)
  187130. {
  187131. png_snprintf(msg, 80,
  187132. "Application was compiled with png.h from libpng-%.20s",
  187133. user_png_ver);
  187134. png_warning(png_ptr, msg);
  187135. }
  187136. png_snprintf(msg, 80,
  187137. "Application is running with png.c from libpng-%.20s",
  187138. png_libpng_ver);
  187139. png_warning(png_ptr, msg);
  187140. }
  187141. #endif
  187142. if(png_sizeof(png_struct) > png_struct_size)
  187143. {
  187144. png_ptr->error_fn=NULL;
  187145. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187146. png_ptr->flags=0;
  187147. #endif
  187148. png_error(png_ptr,
  187149. "The png struct allocated by the application for reading is too small.");
  187150. }
  187151. if(png_sizeof(png_info) > png_info_size)
  187152. {
  187153. png_ptr->error_fn=NULL;
  187154. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187155. png_ptr->flags=0;
  187156. #endif
  187157. png_error(png_ptr,
  187158. "The info struct allocated by application for reading is too small.");
  187159. }
  187160. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187161. }
  187162. #endif /* PNG_1_0_X || PNG_1_2_X */
  187163. void PNGAPI
  187164. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187165. png_size_t png_struct_size)
  187166. {
  187167. #ifdef PNG_SETJMP_SUPPORTED
  187168. jmp_buf tmp_jmp; /* to save current jump buffer */
  187169. #endif
  187170. int i=0;
  187171. png_structp png_ptr=*ptr_ptr;
  187172. if(png_ptr == NULL) return;
  187173. do
  187174. {
  187175. if(user_png_ver[i] != png_libpng_ver[i])
  187176. {
  187177. #ifdef PNG_LEGACY_SUPPORTED
  187178. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187179. #else
  187180. png_ptr->warning_fn=NULL;
  187181. png_warning(png_ptr,
  187182. "Application uses deprecated png_read_init() and should be recompiled.");
  187183. break;
  187184. #endif
  187185. }
  187186. } while (png_libpng_ver[i++]);
  187187. png_debug(1, "in png_read_init_3\n");
  187188. #ifdef PNG_SETJMP_SUPPORTED
  187189. /* save jump buffer and error functions */
  187190. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187191. #endif
  187192. if(png_sizeof(png_struct) > png_struct_size)
  187193. {
  187194. png_destroy_struct(png_ptr);
  187195. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187196. png_ptr = *ptr_ptr;
  187197. }
  187198. /* reset all variables to 0 */
  187199. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187200. #ifdef PNG_SETJMP_SUPPORTED
  187201. /* restore jump buffer */
  187202. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187203. #endif
  187204. /* added at libpng-1.2.6 */
  187205. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187206. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187207. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187208. #endif
  187209. /* initialize zbuf - compression buffer */
  187210. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187211. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187212. (png_uint_32)png_ptr->zbuf_size);
  187213. png_ptr->zstream.zalloc = png_zalloc;
  187214. png_ptr->zstream.zfree = png_zfree;
  187215. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187216. switch (inflateInit(&png_ptr->zstream))
  187217. {
  187218. case Z_OK: /* Do nothing */ break;
  187219. case Z_MEM_ERROR:
  187220. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187221. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187222. default: png_error(png_ptr, "Unknown zlib error");
  187223. }
  187224. png_ptr->zstream.next_out = png_ptr->zbuf;
  187225. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187226. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187227. }
  187228. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187229. /* Read the information before the actual image data. This has been
  187230. * changed in v0.90 to allow reading a file that already has the magic
  187231. * bytes read from the stream. You can tell libpng how many bytes have
  187232. * been read from the beginning of the stream (up to the maximum of 8)
  187233. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187234. * here. The application can then have access to the signature bytes we
  187235. * read if it is determined that this isn't a valid PNG file.
  187236. */
  187237. void PNGAPI
  187238. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187239. {
  187240. if(png_ptr == NULL) return;
  187241. png_debug(1, "in png_read_info\n");
  187242. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187243. if (png_ptr->sig_bytes < 8)
  187244. {
  187245. png_size_t num_checked = png_ptr->sig_bytes,
  187246. num_to_check = 8 - num_checked;
  187247. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187248. png_ptr->sig_bytes = 8;
  187249. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187250. {
  187251. if (num_checked < 4 &&
  187252. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187253. png_error(png_ptr, "Not a PNG file");
  187254. else
  187255. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187256. }
  187257. if (num_checked < 3)
  187258. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187259. }
  187260. for(;;)
  187261. {
  187262. #ifdef PNG_USE_LOCAL_ARRAYS
  187263. PNG_CONST PNG_IHDR;
  187264. PNG_CONST PNG_IDAT;
  187265. PNG_CONST PNG_IEND;
  187266. PNG_CONST PNG_PLTE;
  187267. #if defined(PNG_READ_bKGD_SUPPORTED)
  187268. PNG_CONST PNG_bKGD;
  187269. #endif
  187270. #if defined(PNG_READ_cHRM_SUPPORTED)
  187271. PNG_CONST PNG_cHRM;
  187272. #endif
  187273. #if defined(PNG_READ_gAMA_SUPPORTED)
  187274. PNG_CONST PNG_gAMA;
  187275. #endif
  187276. #if defined(PNG_READ_hIST_SUPPORTED)
  187277. PNG_CONST PNG_hIST;
  187278. #endif
  187279. #if defined(PNG_READ_iCCP_SUPPORTED)
  187280. PNG_CONST PNG_iCCP;
  187281. #endif
  187282. #if defined(PNG_READ_iTXt_SUPPORTED)
  187283. PNG_CONST PNG_iTXt;
  187284. #endif
  187285. #if defined(PNG_READ_oFFs_SUPPORTED)
  187286. PNG_CONST PNG_oFFs;
  187287. #endif
  187288. #if defined(PNG_READ_pCAL_SUPPORTED)
  187289. PNG_CONST PNG_pCAL;
  187290. #endif
  187291. #if defined(PNG_READ_pHYs_SUPPORTED)
  187292. PNG_CONST PNG_pHYs;
  187293. #endif
  187294. #if defined(PNG_READ_sBIT_SUPPORTED)
  187295. PNG_CONST PNG_sBIT;
  187296. #endif
  187297. #if defined(PNG_READ_sCAL_SUPPORTED)
  187298. PNG_CONST PNG_sCAL;
  187299. #endif
  187300. #if defined(PNG_READ_sPLT_SUPPORTED)
  187301. PNG_CONST PNG_sPLT;
  187302. #endif
  187303. #if defined(PNG_READ_sRGB_SUPPORTED)
  187304. PNG_CONST PNG_sRGB;
  187305. #endif
  187306. #if defined(PNG_READ_tEXt_SUPPORTED)
  187307. PNG_CONST PNG_tEXt;
  187308. #endif
  187309. #if defined(PNG_READ_tIME_SUPPORTED)
  187310. PNG_CONST PNG_tIME;
  187311. #endif
  187312. #if defined(PNG_READ_tRNS_SUPPORTED)
  187313. PNG_CONST PNG_tRNS;
  187314. #endif
  187315. #if defined(PNG_READ_zTXt_SUPPORTED)
  187316. PNG_CONST PNG_zTXt;
  187317. #endif
  187318. #endif /* PNG_USE_LOCAL_ARRAYS */
  187319. png_byte chunk_length[4];
  187320. png_uint_32 length;
  187321. png_read_data(png_ptr, chunk_length, 4);
  187322. length = png_get_uint_31(png_ptr,chunk_length);
  187323. png_reset_crc(png_ptr);
  187324. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187325. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187326. length);
  187327. /* This should be a binary subdivision search or a hash for
  187328. * matching the chunk name rather than a linear search.
  187329. */
  187330. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187331. if(png_ptr->mode & PNG_AFTER_IDAT)
  187332. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187333. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187334. png_handle_IHDR(png_ptr, info_ptr, length);
  187335. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187336. png_handle_IEND(png_ptr, info_ptr, length);
  187337. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187338. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187339. {
  187340. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187341. png_ptr->mode |= PNG_HAVE_IDAT;
  187342. png_handle_unknown(png_ptr, info_ptr, length);
  187343. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187344. png_ptr->mode |= PNG_HAVE_PLTE;
  187345. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187346. {
  187347. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187348. png_error(png_ptr, "Missing IHDR before IDAT");
  187349. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187350. !(png_ptr->mode & PNG_HAVE_PLTE))
  187351. png_error(png_ptr, "Missing PLTE before IDAT");
  187352. break;
  187353. }
  187354. }
  187355. #endif
  187356. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187357. png_handle_PLTE(png_ptr, info_ptr, length);
  187358. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187359. {
  187360. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187361. png_error(png_ptr, "Missing IHDR before IDAT");
  187362. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187363. !(png_ptr->mode & PNG_HAVE_PLTE))
  187364. png_error(png_ptr, "Missing PLTE before IDAT");
  187365. png_ptr->idat_size = length;
  187366. png_ptr->mode |= PNG_HAVE_IDAT;
  187367. break;
  187368. }
  187369. #if defined(PNG_READ_bKGD_SUPPORTED)
  187370. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187371. png_handle_bKGD(png_ptr, info_ptr, length);
  187372. #endif
  187373. #if defined(PNG_READ_cHRM_SUPPORTED)
  187374. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187375. png_handle_cHRM(png_ptr, info_ptr, length);
  187376. #endif
  187377. #if defined(PNG_READ_gAMA_SUPPORTED)
  187378. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187379. png_handle_gAMA(png_ptr, info_ptr, length);
  187380. #endif
  187381. #if defined(PNG_READ_hIST_SUPPORTED)
  187382. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187383. png_handle_hIST(png_ptr, info_ptr, length);
  187384. #endif
  187385. #if defined(PNG_READ_oFFs_SUPPORTED)
  187386. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187387. png_handle_oFFs(png_ptr, info_ptr, length);
  187388. #endif
  187389. #if defined(PNG_READ_pCAL_SUPPORTED)
  187390. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187391. png_handle_pCAL(png_ptr, info_ptr, length);
  187392. #endif
  187393. #if defined(PNG_READ_sCAL_SUPPORTED)
  187394. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187395. png_handle_sCAL(png_ptr, info_ptr, length);
  187396. #endif
  187397. #if defined(PNG_READ_pHYs_SUPPORTED)
  187398. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187399. png_handle_pHYs(png_ptr, info_ptr, length);
  187400. #endif
  187401. #if defined(PNG_READ_sBIT_SUPPORTED)
  187402. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187403. png_handle_sBIT(png_ptr, info_ptr, length);
  187404. #endif
  187405. #if defined(PNG_READ_sRGB_SUPPORTED)
  187406. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187407. png_handle_sRGB(png_ptr, info_ptr, length);
  187408. #endif
  187409. #if defined(PNG_READ_iCCP_SUPPORTED)
  187410. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187411. png_handle_iCCP(png_ptr, info_ptr, length);
  187412. #endif
  187413. #if defined(PNG_READ_sPLT_SUPPORTED)
  187414. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187415. png_handle_sPLT(png_ptr, info_ptr, length);
  187416. #endif
  187417. #if defined(PNG_READ_tEXt_SUPPORTED)
  187418. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187419. png_handle_tEXt(png_ptr, info_ptr, length);
  187420. #endif
  187421. #if defined(PNG_READ_tIME_SUPPORTED)
  187422. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187423. png_handle_tIME(png_ptr, info_ptr, length);
  187424. #endif
  187425. #if defined(PNG_READ_tRNS_SUPPORTED)
  187426. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187427. png_handle_tRNS(png_ptr, info_ptr, length);
  187428. #endif
  187429. #if defined(PNG_READ_zTXt_SUPPORTED)
  187430. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187431. png_handle_zTXt(png_ptr, info_ptr, length);
  187432. #endif
  187433. #if defined(PNG_READ_iTXt_SUPPORTED)
  187434. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187435. png_handle_iTXt(png_ptr, info_ptr, length);
  187436. #endif
  187437. else
  187438. png_handle_unknown(png_ptr, info_ptr, length);
  187439. }
  187440. }
  187441. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187442. /* optional call to update the users info_ptr structure */
  187443. void PNGAPI
  187444. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187445. {
  187446. png_debug(1, "in png_read_update_info\n");
  187447. if(png_ptr == NULL) return;
  187448. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187449. png_read_start_row(png_ptr);
  187450. else
  187451. png_warning(png_ptr,
  187452. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187453. png_read_transform_info(png_ptr, info_ptr);
  187454. }
  187455. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187456. /* Initialize palette, background, etc, after transformations
  187457. * are set, but before any reading takes place. This allows
  187458. * the user to obtain a gamma-corrected palette, for example.
  187459. * If the user doesn't call this, we will do it ourselves.
  187460. */
  187461. void PNGAPI
  187462. png_start_read_image(png_structp png_ptr)
  187463. {
  187464. png_debug(1, "in png_start_read_image\n");
  187465. if(png_ptr == NULL) return;
  187466. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187467. png_read_start_row(png_ptr);
  187468. }
  187469. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187470. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187471. void PNGAPI
  187472. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187473. {
  187474. #ifdef PNG_USE_LOCAL_ARRAYS
  187475. PNG_CONST PNG_IDAT;
  187476. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187477. 0xff};
  187478. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187479. #endif
  187480. int ret;
  187481. if(png_ptr == NULL) return;
  187482. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187483. png_ptr->row_number, png_ptr->pass);
  187484. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187485. png_read_start_row(png_ptr);
  187486. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187487. {
  187488. /* check for transforms that have been set but were defined out */
  187489. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187490. if (png_ptr->transformations & PNG_INVERT_MONO)
  187491. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187492. #endif
  187493. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187494. if (png_ptr->transformations & PNG_FILLER)
  187495. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187496. #endif
  187497. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187498. if (png_ptr->transformations & PNG_PACKSWAP)
  187499. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187500. #endif
  187501. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187502. if (png_ptr->transformations & PNG_PACK)
  187503. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187504. #endif
  187505. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187506. if (png_ptr->transformations & PNG_SHIFT)
  187507. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187508. #endif
  187509. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187510. if (png_ptr->transformations & PNG_BGR)
  187511. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187512. #endif
  187513. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187514. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187515. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187516. #endif
  187517. }
  187518. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187519. /* if interlaced and we do not need a new row, combine row and return */
  187520. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187521. {
  187522. switch (png_ptr->pass)
  187523. {
  187524. case 0:
  187525. if (png_ptr->row_number & 0x07)
  187526. {
  187527. if (dsp_row != NULL)
  187528. png_combine_row(png_ptr, dsp_row,
  187529. png_pass_dsp_mask[png_ptr->pass]);
  187530. png_read_finish_row(png_ptr);
  187531. return;
  187532. }
  187533. break;
  187534. case 1:
  187535. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187536. {
  187537. if (dsp_row != NULL)
  187538. png_combine_row(png_ptr, dsp_row,
  187539. png_pass_dsp_mask[png_ptr->pass]);
  187540. png_read_finish_row(png_ptr);
  187541. return;
  187542. }
  187543. break;
  187544. case 2:
  187545. if ((png_ptr->row_number & 0x07) != 4)
  187546. {
  187547. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187548. png_combine_row(png_ptr, dsp_row,
  187549. png_pass_dsp_mask[png_ptr->pass]);
  187550. png_read_finish_row(png_ptr);
  187551. return;
  187552. }
  187553. break;
  187554. case 3:
  187555. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187556. {
  187557. if (dsp_row != NULL)
  187558. png_combine_row(png_ptr, dsp_row,
  187559. png_pass_dsp_mask[png_ptr->pass]);
  187560. png_read_finish_row(png_ptr);
  187561. return;
  187562. }
  187563. break;
  187564. case 4:
  187565. if ((png_ptr->row_number & 3) != 2)
  187566. {
  187567. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187568. png_combine_row(png_ptr, dsp_row,
  187569. png_pass_dsp_mask[png_ptr->pass]);
  187570. png_read_finish_row(png_ptr);
  187571. return;
  187572. }
  187573. break;
  187574. case 5:
  187575. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187576. {
  187577. if (dsp_row != NULL)
  187578. png_combine_row(png_ptr, dsp_row,
  187579. png_pass_dsp_mask[png_ptr->pass]);
  187580. png_read_finish_row(png_ptr);
  187581. return;
  187582. }
  187583. break;
  187584. case 6:
  187585. if (!(png_ptr->row_number & 1))
  187586. {
  187587. png_read_finish_row(png_ptr);
  187588. return;
  187589. }
  187590. break;
  187591. }
  187592. }
  187593. #endif
  187594. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187595. png_error(png_ptr, "Invalid attempt to read row data");
  187596. png_ptr->zstream.next_out = png_ptr->row_buf;
  187597. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187598. do
  187599. {
  187600. if (!(png_ptr->zstream.avail_in))
  187601. {
  187602. while (!png_ptr->idat_size)
  187603. {
  187604. png_byte chunk_length[4];
  187605. png_crc_finish(png_ptr, 0);
  187606. png_read_data(png_ptr, chunk_length, 4);
  187607. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187608. png_reset_crc(png_ptr);
  187609. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187610. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187611. png_error(png_ptr, "Not enough image data");
  187612. }
  187613. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187614. png_ptr->zstream.next_in = png_ptr->zbuf;
  187615. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187616. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187617. png_crc_read(png_ptr, png_ptr->zbuf,
  187618. (png_size_t)png_ptr->zstream.avail_in);
  187619. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187620. }
  187621. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187622. if (ret == Z_STREAM_END)
  187623. {
  187624. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187625. png_ptr->idat_size)
  187626. png_error(png_ptr, "Extra compressed data");
  187627. png_ptr->mode |= PNG_AFTER_IDAT;
  187628. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187629. break;
  187630. }
  187631. if (ret != Z_OK)
  187632. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187633. "Decompression error");
  187634. } while (png_ptr->zstream.avail_out);
  187635. png_ptr->row_info.color_type = png_ptr->color_type;
  187636. png_ptr->row_info.width = png_ptr->iwidth;
  187637. png_ptr->row_info.channels = png_ptr->channels;
  187638. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187639. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187640. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187641. png_ptr->row_info.width);
  187642. if(png_ptr->row_buf[0])
  187643. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187644. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187645. (int)(png_ptr->row_buf[0]));
  187646. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187647. png_ptr->rowbytes + 1);
  187648. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187649. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187650. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187651. {
  187652. /* Intrapixel differencing */
  187653. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187654. }
  187655. #endif
  187656. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187657. png_do_read_transformations(png_ptr);
  187658. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187659. /* blow up interlaced rows to full size */
  187660. if (png_ptr->interlaced &&
  187661. (png_ptr->transformations & PNG_INTERLACE))
  187662. {
  187663. if (png_ptr->pass < 6)
  187664. /* old interface (pre-1.0.9):
  187665. png_do_read_interlace(&(png_ptr->row_info),
  187666. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187667. */
  187668. png_do_read_interlace(png_ptr);
  187669. if (dsp_row != NULL)
  187670. png_combine_row(png_ptr, dsp_row,
  187671. png_pass_dsp_mask[png_ptr->pass]);
  187672. if (row != NULL)
  187673. png_combine_row(png_ptr, row,
  187674. png_pass_mask[png_ptr->pass]);
  187675. }
  187676. else
  187677. #endif
  187678. {
  187679. if (row != NULL)
  187680. png_combine_row(png_ptr, row, 0xff);
  187681. if (dsp_row != NULL)
  187682. png_combine_row(png_ptr, dsp_row, 0xff);
  187683. }
  187684. png_read_finish_row(png_ptr);
  187685. if (png_ptr->read_row_fn != NULL)
  187686. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187687. }
  187688. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187689. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187690. /* Read one or more rows of image data. If the image is interlaced,
  187691. * and png_set_interlace_handling() has been called, the rows need to
  187692. * contain the contents of the rows from the previous pass. If the
  187693. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187694. * called, the rows contents must be initialized to the contents of the
  187695. * screen.
  187696. *
  187697. * "row" holds the actual image, and pixels are placed in it
  187698. * as they arrive. If the image is displayed after each pass, it will
  187699. * appear to "sparkle" in. "display_row" can be used to display a
  187700. * "chunky" progressive image, with finer detail added as it becomes
  187701. * available. If you do not want this "chunky" display, you may pass
  187702. * NULL for display_row. If you do not want the sparkle display, and
  187703. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187704. * If you have called png_handle_alpha(), and the image has either an
  187705. * alpha channel or a transparency chunk, you must provide a buffer for
  187706. * rows. In this case, you do not have to provide a display_row buffer
  187707. * also, but you may. If the image is not interlaced, or if you have
  187708. * not called png_set_interlace_handling(), the display_row buffer will
  187709. * be ignored, so pass NULL to it.
  187710. *
  187711. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187712. */
  187713. void PNGAPI
  187714. png_read_rows(png_structp png_ptr, png_bytepp row,
  187715. png_bytepp display_row, png_uint_32 num_rows)
  187716. {
  187717. png_uint_32 i;
  187718. png_bytepp rp;
  187719. png_bytepp dp;
  187720. png_debug(1, "in png_read_rows\n");
  187721. if(png_ptr == NULL) return;
  187722. rp = row;
  187723. dp = display_row;
  187724. if (rp != NULL && dp != NULL)
  187725. for (i = 0; i < num_rows; i++)
  187726. {
  187727. png_bytep rptr = *rp++;
  187728. png_bytep dptr = *dp++;
  187729. png_read_row(png_ptr, rptr, dptr);
  187730. }
  187731. else if(rp != NULL)
  187732. for (i = 0; i < num_rows; i++)
  187733. {
  187734. png_bytep rptr = *rp;
  187735. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187736. rp++;
  187737. }
  187738. else if(dp != NULL)
  187739. for (i = 0; i < num_rows; i++)
  187740. {
  187741. png_bytep dptr = *dp;
  187742. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187743. dp++;
  187744. }
  187745. }
  187746. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187747. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187748. /* Read the entire image. If the image has an alpha channel or a tRNS
  187749. * chunk, and you have called png_handle_alpha()[*], you will need to
  187750. * initialize the image to the current image that PNG will be overlaying.
  187751. * We set the num_rows again here, in case it was incorrectly set in
  187752. * png_read_start_row() by a call to png_read_update_info() or
  187753. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187754. * prior to either of these functions like it should have been. You can
  187755. * only call this function once. If you desire to have an image for
  187756. * each pass of a interlaced image, use png_read_rows() instead.
  187757. *
  187758. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187759. */
  187760. void PNGAPI
  187761. png_read_image(png_structp png_ptr, png_bytepp image)
  187762. {
  187763. png_uint_32 i,image_height;
  187764. int pass, j;
  187765. png_bytepp rp;
  187766. png_debug(1, "in png_read_image\n");
  187767. if(png_ptr == NULL) return;
  187768. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187769. pass = png_set_interlace_handling(png_ptr);
  187770. #else
  187771. if (png_ptr->interlaced)
  187772. png_error(png_ptr,
  187773. "Cannot read interlaced image -- interlace handler disabled.");
  187774. pass = 1;
  187775. #endif
  187776. image_height=png_ptr->height;
  187777. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187778. for (j = 0; j < pass; j++)
  187779. {
  187780. rp = image;
  187781. for (i = 0; i < image_height; i++)
  187782. {
  187783. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187784. rp++;
  187785. }
  187786. }
  187787. }
  187788. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187789. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187790. /* Read the end of the PNG file. Will not read past the end of the
  187791. * file, will verify the end is accurate, and will read any comments
  187792. * or time information at the end of the file, if info is not NULL.
  187793. */
  187794. void PNGAPI
  187795. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187796. {
  187797. png_byte chunk_length[4];
  187798. png_uint_32 length;
  187799. png_debug(1, "in png_read_end\n");
  187800. if(png_ptr == NULL) return;
  187801. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187802. do
  187803. {
  187804. #ifdef PNG_USE_LOCAL_ARRAYS
  187805. PNG_CONST PNG_IHDR;
  187806. PNG_CONST PNG_IDAT;
  187807. PNG_CONST PNG_IEND;
  187808. PNG_CONST PNG_PLTE;
  187809. #if defined(PNG_READ_bKGD_SUPPORTED)
  187810. PNG_CONST PNG_bKGD;
  187811. #endif
  187812. #if defined(PNG_READ_cHRM_SUPPORTED)
  187813. PNG_CONST PNG_cHRM;
  187814. #endif
  187815. #if defined(PNG_READ_gAMA_SUPPORTED)
  187816. PNG_CONST PNG_gAMA;
  187817. #endif
  187818. #if defined(PNG_READ_hIST_SUPPORTED)
  187819. PNG_CONST PNG_hIST;
  187820. #endif
  187821. #if defined(PNG_READ_iCCP_SUPPORTED)
  187822. PNG_CONST PNG_iCCP;
  187823. #endif
  187824. #if defined(PNG_READ_iTXt_SUPPORTED)
  187825. PNG_CONST PNG_iTXt;
  187826. #endif
  187827. #if defined(PNG_READ_oFFs_SUPPORTED)
  187828. PNG_CONST PNG_oFFs;
  187829. #endif
  187830. #if defined(PNG_READ_pCAL_SUPPORTED)
  187831. PNG_CONST PNG_pCAL;
  187832. #endif
  187833. #if defined(PNG_READ_pHYs_SUPPORTED)
  187834. PNG_CONST PNG_pHYs;
  187835. #endif
  187836. #if defined(PNG_READ_sBIT_SUPPORTED)
  187837. PNG_CONST PNG_sBIT;
  187838. #endif
  187839. #if defined(PNG_READ_sCAL_SUPPORTED)
  187840. PNG_CONST PNG_sCAL;
  187841. #endif
  187842. #if defined(PNG_READ_sPLT_SUPPORTED)
  187843. PNG_CONST PNG_sPLT;
  187844. #endif
  187845. #if defined(PNG_READ_sRGB_SUPPORTED)
  187846. PNG_CONST PNG_sRGB;
  187847. #endif
  187848. #if defined(PNG_READ_tEXt_SUPPORTED)
  187849. PNG_CONST PNG_tEXt;
  187850. #endif
  187851. #if defined(PNG_READ_tIME_SUPPORTED)
  187852. PNG_CONST PNG_tIME;
  187853. #endif
  187854. #if defined(PNG_READ_tRNS_SUPPORTED)
  187855. PNG_CONST PNG_tRNS;
  187856. #endif
  187857. #if defined(PNG_READ_zTXt_SUPPORTED)
  187858. PNG_CONST PNG_zTXt;
  187859. #endif
  187860. #endif /* PNG_USE_LOCAL_ARRAYS */
  187861. png_read_data(png_ptr, chunk_length, 4);
  187862. length = png_get_uint_31(png_ptr,chunk_length);
  187863. png_reset_crc(png_ptr);
  187864. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187865. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187866. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187867. png_handle_IHDR(png_ptr, info_ptr, length);
  187868. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187869. png_handle_IEND(png_ptr, info_ptr, length);
  187870. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187871. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187872. {
  187873. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187874. {
  187875. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187876. png_error(png_ptr, "Too many IDAT's found");
  187877. }
  187878. png_handle_unknown(png_ptr, info_ptr, length);
  187879. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187880. png_ptr->mode |= PNG_HAVE_PLTE;
  187881. }
  187882. #endif
  187883. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187884. {
  187885. /* Zero length IDATs are legal after the last IDAT has been
  187886. * read, but not after other chunks have been read.
  187887. */
  187888. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187889. png_error(png_ptr, "Too many IDAT's found");
  187890. png_crc_finish(png_ptr, length);
  187891. }
  187892. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187893. png_handle_PLTE(png_ptr, info_ptr, length);
  187894. #if defined(PNG_READ_bKGD_SUPPORTED)
  187895. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187896. png_handle_bKGD(png_ptr, info_ptr, length);
  187897. #endif
  187898. #if defined(PNG_READ_cHRM_SUPPORTED)
  187899. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187900. png_handle_cHRM(png_ptr, info_ptr, length);
  187901. #endif
  187902. #if defined(PNG_READ_gAMA_SUPPORTED)
  187903. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187904. png_handle_gAMA(png_ptr, info_ptr, length);
  187905. #endif
  187906. #if defined(PNG_READ_hIST_SUPPORTED)
  187907. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187908. png_handle_hIST(png_ptr, info_ptr, length);
  187909. #endif
  187910. #if defined(PNG_READ_oFFs_SUPPORTED)
  187911. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187912. png_handle_oFFs(png_ptr, info_ptr, length);
  187913. #endif
  187914. #if defined(PNG_READ_pCAL_SUPPORTED)
  187915. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187916. png_handle_pCAL(png_ptr, info_ptr, length);
  187917. #endif
  187918. #if defined(PNG_READ_sCAL_SUPPORTED)
  187919. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187920. png_handle_sCAL(png_ptr, info_ptr, length);
  187921. #endif
  187922. #if defined(PNG_READ_pHYs_SUPPORTED)
  187923. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187924. png_handle_pHYs(png_ptr, info_ptr, length);
  187925. #endif
  187926. #if defined(PNG_READ_sBIT_SUPPORTED)
  187927. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187928. png_handle_sBIT(png_ptr, info_ptr, length);
  187929. #endif
  187930. #if defined(PNG_READ_sRGB_SUPPORTED)
  187931. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187932. png_handle_sRGB(png_ptr, info_ptr, length);
  187933. #endif
  187934. #if defined(PNG_READ_iCCP_SUPPORTED)
  187935. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187936. png_handle_iCCP(png_ptr, info_ptr, length);
  187937. #endif
  187938. #if defined(PNG_READ_sPLT_SUPPORTED)
  187939. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187940. png_handle_sPLT(png_ptr, info_ptr, length);
  187941. #endif
  187942. #if defined(PNG_READ_tEXt_SUPPORTED)
  187943. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187944. png_handle_tEXt(png_ptr, info_ptr, length);
  187945. #endif
  187946. #if defined(PNG_READ_tIME_SUPPORTED)
  187947. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187948. png_handle_tIME(png_ptr, info_ptr, length);
  187949. #endif
  187950. #if defined(PNG_READ_tRNS_SUPPORTED)
  187951. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187952. png_handle_tRNS(png_ptr, info_ptr, length);
  187953. #endif
  187954. #if defined(PNG_READ_zTXt_SUPPORTED)
  187955. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187956. png_handle_zTXt(png_ptr, info_ptr, length);
  187957. #endif
  187958. #if defined(PNG_READ_iTXt_SUPPORTED)
  187959. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187960. png_handle_iTXt(png_ptr, info_ptr, length);
  187961. #endif
  187962. else
  187963. png_handle_unknown(png_ptr, info_ptr, length);
  187964. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187965. }
  187966. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187967. /* free all memory used by the read */
  187968. void PNGAPI
  187969. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187970. png_infopp end_info_ptr_ptr)
  187971. {
  187972. png_structp png_ptr = NULL;
  187973. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187974. #ifdef PNG_USER_MEM_SUPPORTED
  187975. png_free_ptr free_fn;
  187976. png_voidp mem_ptr;
  187977. #endif
  187978. png_debug(1, "in png_destroy_read_struct\n");
  187979. if (png_ptr_ptr != NULL)
  187980. png_ptr = *png_ptr_ptr;
  187981. if (info_ptr_ptr != NULL)
  187982. info_ptr = *info_ptr_ptr;
  187983. if (end_info_ptr_ptr != NULL)
  187984. end_info_ptr = *end_info_ptr_ptr;
  187985. #ifdef PNG_USER_MEM_SUPPORTED
  187986. free_fn = png_ptr->free_fn;
  187987. mem_ptr = png_ptr->mem_ptr;
  187988. #endif
  187989. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187990. if (info_ptr != NULL)
  187991. {
  187992. #if defined(PNG_TEXT_SUPPORTED)
  187993. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187994. #endif
  187995. #ifdef PNG_USER_MEM_SUPPORTED
  187996. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187997. (png_voidp)mem_ptr);
  187998. #else
  187999. png_destroy_struct((png_voidp)info_ptr);
  188000. #endif
  188001. *info_ptr_ptr = NULL;
  188002. }
  188003. if (end_info_ptr != NULL)
  188004. {
  188005. #if defined(PNG_READ_TEXT_SUPPORTED)
  188006. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188007. #endif
  188008. #ifdef PNG_USER_MEM_SUPPORTED
  188009. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188010. (png_voidp)mem_ptr);
  188011. #else
  188012. png_destroy_struct((png_voidp)end_info_ptr);
  188013. #endif
  188014. *end_info_ptr_ptr = NULL;
  188015. }
  188016. if (png_ptr != NULL)
  188017. {
  188018. #ifdef PNG_USER_MEM_SUPPORTED
  188019. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188020. (png_voidp)mem_ptr);
  188021. #else
  188022. png_destroy_struct((png_voidp)png_ptr);
  188023. #endif
  188024. *png_ptr_ptr = NULL;
  188025. }
  188026. }
  188027. /* free all memory used by the read (old method) */
  188028. void /* PRIVATE */
  188029. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188030. {
  188031. #ifdef PNG_SETJMP_SUPPORTED
  188032. jmp_buf tmp_jmp;
  188033. #endif
  188034. png_error_ptr error_fn;
  188035. png_error_ptr warning_fn;
  188036. png_voidp error_ptr;
  188037. #ifdef PNG_USER_MEM_SUPPORTED
  188038. png_free_ptr free_fn;
  188039. #endif
  188040. png_debug(1, "in png_read_destroy\n");
  188041. if (info_ptr != NULL)
  188042. png_info_destroy(png_ptr, info_ptr);
  188043. if (end_info_ptr != NULL)
  188044. png_info_destroy(png_ptr, end_info_ptr);
  188045. png_free(png_ptr, png_ptr->zbuf);
  188046. png_free(png_ptr, png_ptr->big_row_buf);
  188047. png_free(png_ptr, png_ptr->prev_row);
  188048. #if defined(PNG_READ_DITHER_SUPPORTED)
  188049. png_free(png_ptr, png_ptr->palette_lookup);
  188050. png_free(png_ptr, png_ptr->dither_index);
  188051. #endif
  188052. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188053. png_free(png_ptr, png_ptr->gamma_table);
  188054. #endif
  188055. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188056. png_free(png_ptr, png_ptr->gamma_from_1);
  188057. png_free(png_ptr, png_ptr->gamma_to_1);
  188058. #endif
  188059. #ifdef PNG_FREE_ME_SUPPORTED
  188060. if (png_ptr->free_me & PNG_FREE_PLTE)
  188061. png_zfree(png_ptr, png_ptr->palette);
  188062. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188063. #else
  188064. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188065. png_zfree(png_ptr, png_ptr->palette);
  188066. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188067. #endif
  188068. #if defined(PNG_tRNS_SUPPORTED) || \
  188069. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188070. #ifdef PNG_FREE_ME_SUPPORTED
  188071. if (png_ptr->free_me & PNG_FREE_TRNS)
  188072. png_free(png_ptr, png_ptr->trans);
  188073. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188074. #else
  188075. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188076. png_free(png_ptr, png_ptr->trans);
  188077. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188078. #endif
  188079. #endif
  188080. #if defined(PNG_READ_hIST_SUPPORTED)
  188081. #ifdef PNG_FREE_ME_SUPPORTED
  188082. if (png_ptr->free_me & PNG_FREE_HIST)
  188083. png_free(png_ptr, png_ptr->hist);
  188084. png_ptr->free_me &= ~PNG_FREE_HIST;
  188085. #else
  188086. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188087. png_free(png_ptr, png_ptr->hist);
  188088. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188089. #endif
  188090. #endif
  188091. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188092. if (png_ptr->gamma_16_table != NULL)
  188093. {
  188094. int i;
  188095. int istop = (1 << (8 - png_ptr->gamma_shift));
  188096. for (i = 0; i < istop; i++)
  188097. {
  188098. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188099. }
  188100. png_free(png_ptr, png_ptr->gamma_16_table);
  188101. }
  188102. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188103. if (png_ptr->gamma_16_from_1 != NULL)
  188104. {
  188105. int i;
  188106. int istop = (1 << (8 - png_ptr->gamma_shift));
  188107. for (i = 0; i < istop; i++)
  188108. {
  188109. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188110. }
  188111. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188112. }
  188113. if (png_ptr->gamma_16_to_1 != NULL)
  188114. {
  188115. int i;
  188116. int istop = (1 << (8 - png_ptr->gamma_shift));
  188117. for (i = 0; i < istop; i++)
  188118. {
  188119. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188120. }
  188121. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188122. }
  188123. #endif
  188124. #endif
  188125. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188126. png_free(png_ptr, png_ptr->time_buffer);
  188127. #endif
  188128. inflateEnd(&png_ptr->zstream);
  188129. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188130. png_free(png_ptr, png_ptr->save_buffer);
  188131. #endif
  188132. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188133. #ifdef PNG_TEXT_SUPPORTED
  188134. png_free(png_ptr, png_ptr->current_text);
  188135. #endif /* PNG_TEXT_SUPPORTED */
  188136. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188137. /* Save the important info out of the png_struct, in case it is
  188138. * being used again.
  188139. */
  188140. #ifdef PNG_SETJMP_SUPPORTED
  188141. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188142. #endif
  188143. error_fn = png_ptr->error_fn;
  188144. warning_fn = png_ptr->warning_fn;
  188145. error_ptr = png_ptr->error_ptr;
  188146. #ifdef PNG_USER_MEM_SUPPORTED
  188147. free_fn = png_ptr->free_fn;
  188148. #endif
  188149. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188150. png_ptr->error_fn = error_fn;
  188151. png_ptr->warning_fn = warning_fn;
  188152. png_ptr->error_ptr = error_ptr;
  188153. #ifdef PNG_USER_MEM_SUPPORTED
  188154. png_ptr->free_fn = free_fn;
  188155. #endif
  188156. #ifdef PNG_SETJMP_SUPPORTED
  188157. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188158. #endif
  188159. }
  188160. void PNGAPI
  188161. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188162. {
  188163. if(png_ptr == NULL) return;
  188164. png_ptr->read_row_fn = read_row_fn;
  188165. }
  188166. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188167. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188168. void PNGAPI
  188169. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188170. int transforms,
  188171. voidp params)
  188172. {
  188173. int row;
  188174. if(png_ptr == NULL) return;
  188175. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188176. /* invert the alpha channel from opacity to transparency
  188177. */
  188178. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188179. png_set_invert_alpha(png_ptr);
  188180. #endif
  188181. /* png_read_info() gives us all of the information from the
  188182. * PNG file before the first IDAT (image data chunk).
  188183. */
  188184. png_read_info(png_ptr, info_ptr);
  188185. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188186. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188187. /* -------------- image transformations start here ------------------- */
  188188. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188189. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188190. */
  188191. if (transforms & PNG_TRANSFORM_STRIP_16)
  188192. png_set_strip_16(png_ptr);
  188193. #endif
  188194. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188195. /* Strip alpha bytes from the input data without combining with
  188196. * the background (not recommended).
  188197. */
  188198. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188199. png_set_strip_alpha(png_ptr);
  188200. #endif
  188201. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188202. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188203. * byte into separate bytes (useful for paletted and grayscale images).
  188204. */
  188205. if (transforms & PNG_TRANSFORM_PACKING)
  188206. png_set_packing(png_ptr);
  188207. #endif
  188208. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188209. /* Change the order of packed pixels to least significant bit first
  188210. * (not useful if you are using png_set_packing).
  188211. */
  188212. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188213. png_set_packswap(png_ptr);
  188214. #endif
  188215. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188216. /* Expand paletted colors into true RGB triplets
  188217. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188218. * Expand paletted or RGB images with transparency to full alpha
  188219. * channels so the data will be available as RGBA quartets.
  188220. */
  188221. if (transforms & PNG_TRANSFORM_EXPAND)
  188222. if ((png_ptr->bit_depth < 8) ||
  188223. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188224. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188225. png_set_expand(png_ptr);
  188226. #endif
  188227. /* We don't handle background color or gamma transformation or dithering.
  188228. */
  188229. #if defined(PNG_READ_INVERT_SUPPORTED)
  188230. /* invert monochrome files to have 0 as white and 1 as black
  188231. */
  188232. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188233. png_set_invert_mono(png_ptr);
  188234. #endif
  188235. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188236. /* If you want to shift the pixel values from the range [0,255] or
  188237. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188238. * colors were originally in:
  188239. */
  188240. if ((transforms & PNG_TRANSFORM_SHIFT)
  188241. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188242. {
  188243. png_color_8p sig_bit;
  188244. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188245. png_set_shift(png_ptr, sig_bit);
  188246. }
  188247. #endif
  188248. #if defined(PNG_READ_BGR_SUPPORTED)
  188249. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188250. */
  188251. if (transforms & PNG_TRANSFORM_BGR)
  188252. png_set_bgr(png_ptr);
  188253. #endif
  188254. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188255. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188256. */
  188257. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188258. png_set_swap_alpha(png_ptr);
  188259. #endif
  188260. #if defined(PNG_READ_SWAP_SUPPORTED)
  188261. /* swap bytes of 16 bit files to least significant byte first
  188262. */
  188263. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188264. png_set_swap(png_ptr);
  188265. #endif
  188266. /* We don't handle adding filler bytes */
  188267. /* Optional call to gamma correct and add the background to the palette
  188268. * and update info structure. REQUIRED if you are expecting libpng to
  188269. * update the palette for you (i.e., you selected such a transform above).
  188270. */
  188271. png_read_update_info(png_ptr, info_ptr);
  188272. /* -------------- image transformations end here ------------------- */
  188273. #ifdef PNG_FREE_ME_SUPPORTED
  188274. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188275. #endif
  188276. if(info_ptr->row_pointers == NULL)
  188277. {
  188278. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188279. info_ptr->height * png_sizeof(png_bytep));
  188280. #ifdef PNG_FREE_ME_SUPPORTED
  188281. info_ptr->free_me |= PNG_FREE_ROWS;
  188282. #endif
  188283. for (row = 0; row < (int)info_ptr->height; row++)
  188284. {
  188285. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188286. png_get_rowbytes(png_ptr, info_ptr));
  188287. }
  188288. }
  188289. png_read_image(png_ptr, info_ptr->row_pointers);
  188290. info_ptr->valid |= PNG_INFO_IDAT;
  188291. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188292. png_read_end(png_ptr, info_ptr);
  188293. transforms = transforms; /* quiet compiler warnings */
  188294. params = params;
  188295. }
  188296. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188297. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188298. #endif /* PNG_READ_SUPPORTED */
  188299. /*** End of inlined file: pngread.c ***/
  188300. /*** Start of inlined file: pngpread.c ***/
  188301. /* pngpread.c - read a png file in push mode
  188302. *
  188303. * Last changed in libpng 1.2.21 October 4, 2007
  188304. * For conditions of distribution and use, see copyright notice in png.h
  188305. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188306. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188307. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188308. */
  188309. #define PNG_INTERNAL
  188310. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188311. /* push model modes */
  188312. #define PNG_READ_SIG_MODE 0
  188313. #define PNG_READ_CHUNK_MODE 1
  188314. #define PNG_READ_IDAT_MODE 2
  188315. #define PNG_SKIP_MODE 3
  188316. #define PNG_READ_tEXt_MODE 4
  188317. #define PNG_READ_zTXt_MODE 5
  188318. #define PNG_READ_DONE_MODE 6
  188319. #define PNG_READ_iTXt_MODE 7
  188320. #define PNG_ERROR_MODE 8
  188321. void PNGAPI
  188322. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188323. png_bytep buffer, png_size_t buffer_size)
  188324. {
  188325. if(png_ptr == NULL) return;
  188326. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188327. while (png_ptr->buffer_size)
  188328. {
  188329. png_process_some_data(png_ptr, info_ptr);
  188330. }
  188331. }
  188332. /* What we do with the incoming data depends on what we were previously
  188333. * doing before we ran out of data...
  188334. */
  188335. void /* PRIVATE */
  188336. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188337. {
  188338. if(png_ptr == NULL) return;
  188339. switch (png_ptr->process_mode)
  188340. {
  188341. case PNG_READ_SIG_MODE:
  188342. {
  188343. png_push_read_sig(png_ptr, info_ptr);
  188344. break;
  188345. }
  188346. case PNG_READ_CHUNK_MODE:
  188347. {
  188348. png_push_read_chunk(png_ptr, info_ptr);
  188349. break;
  188350. }
  188351. case PNG_READ_IDAT_MODE:
  188352. {
  188353. png_push_read_IDAT(png_ptr);
  188354. break;
  188355. }
  188356. #if defined(PNG_READ_tEXt_SUPPORTED)
  188357. case PNG_READ_tEXt_MODE:
  188358. {
  188359. png_push_read_tEXt(png_ptr, info_ptr);
  188360. break;
  188361. }
  188362. #endif
  188363. #if defined(PNG_READ_zTXt_SUPPORTED)
  188364. case PNG_READ_zTXt_MODE:
  188365. {
  188366. png_push_read_zTXt(png_ptr, info_ptr);
  188367. break;
  188368. }
  188369. #endif
  188370. #if defined(PNG_READ_iTXt_SUPPORTED)
  188371. case PNG_READ_iTXt_MODE:
  188372. {
  188373. png_push_read_iTXt(png_ptr, info_ptr);
  188374. break;
  188375. }
  188376. #endif
  188377. case PNG_SKIP_MODE:
  188378. {
  188379. png_push_crc_finish(png_ptr);
  188380. break;
  188381. }
  188382. default:
  188383. {
  188384. png_ptr->buffer_size = 0;
  188385. break;
  188386. }
  188387. }
  188388. }
  188389. /* Read any remaining signature bytes from the stream and compare them with
  188390. * the correct PNG signature. It is possible that this routine is called
  188391. * with bytes already read from the signature, either because they have been
  188392. * checked by the calling application, or because of multiple calls to this
  188393. * routine.
  188394. */
  188395. void /* PRIVATE */
  188396. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188397. {
  188398. png_size_t num_checked = png_ptr->sig_bytes,
  188399. num_to_check = 8 - num_checked;
  188400. if (png_ptr->buffer_size < num_to_check)
  188401. {
  188402. num_to_check = png_ptr->buffer_size;
  188403. }
  188404. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188405. num_to_check);
  188406. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188407. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188408. {
  188409. if (num_checked < 4 &&
  188410. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188411. png_error(png_ptr, "Not a PNG file");
  188412. else
  188413. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188414. }
  188415. else
  188416. {
  188417. if (png_ptr->sig_bytes >= 8)
  188418. {
  188419. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188420. }
  188421. }
  188422. }
  188423. void /* PRIVATE */
  188424. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188425. {
  188426. #ifdef PNG_USE_LOCAL_ARRAYS
  188427. PNG_CONST PNG_IHDR;
  188428. PNG_CONST PNG_IDAT;
  188429. PNG_CONST PNG_IEND;
  188430. PNG_CONST PNG_PLTE;
  188431. #if defined(PNG_READ_bKGD_SUPPORTED)
  188432. PNG_CONST PNG_bKGD;
  188433. #endif
  188434. #if defined(PNG_READ_cHRM_SUPPORTED)
  188435. PNG_CONST PNG_cHRM;
  188436. #endif
  188437. #if defined(PNG_READ_gAMA_SUPPORTED)
  188438. PNG_CONST PNG_gAMA;
  188439. #endif
  188440. #if defined(PNG_READ_hIST_SUPPORTED)
  188441. PNG_CONST PNG_hIST;
  188442. #endif
  188443. #if defined(PNG_READ_iCCP_SUPPORTED)
  188444. PNG_CONST PNG_iCCP;
  188445. #endif
  188446. #if defined(PNG_READ_iTXt_SUPPORTED)
  188447. PNG_CONST PNG_iTXt;
  188448. #endif
  188449. #if defined(PNG_READ_oFFs_SUPPORTED)
  188450. PNG_CONST PNG_oFFs;
  188451. #endif
  188452. #if defined(PNG_READ_pCAL_SUPPORTED)
  188453. PNG_CONST PNG_pCAL;
  188454. #endif
  188455. #if defined(PNG_READ_pHYs_SUPPORTED)
  188456. PNG_CONST PNG_pHYs;
  188457. #endif
  188458. #if defined(PNG_READ_sBIT_SUPPORTED)
  188459. PNG_CONST PNG_sBIT;
  188460. #endif
  188461. #if defined(PNG_READ_sCAL_SUPPORTED)
  188462. PNG_CONST PNG_sCAL;
  188463. #endif
  188464. #if defined(PNG_READ_sRGB_SUPPORTED)
  188465. PNG_CONST PNG_sRGB;
  188466. #endif
  188467. #if defined(PNG_READ_sPLT_SUPPORTED)
  188468. PNG_CONST PNG_sPLT;
  188469. #endif
  188470. #if defined(PNG_READ_tEXt_SUPPORTED)
  188471. PNG_CONST PNG_tEXt;
  188472. #endif
  188473. #if defined(PNG_READ_tIME_SUPPORTED)
  188474. PNG_CONST PNG_tIME;
  188475. #endif
  188476. #if defined(PNG_READ_tRNS_SUPPORTED)
  188477. PNG_CONST PNG_tRNS;
  188478. #endif
  188479. #if defined(PNG_READ_zTXt_SUPPORTED)
  188480. PNG_CONST PNG_zTXt;
  188481. #endif
  188482. #endif /* PNG_USE_LOCAL_ARRAYS */
  188483. /* First we make sure we have enough data for the 4 byte chunk name
  188484. * and the 4 byte chunk length before proceeding with decoding the
  188485. * chunk data. To fully decode each of these chunks, we also make
  188486. * sure we have enough data in the buffer for the 4 byte CRC at the
  188487. * end of every chunk (except IDAT, which is handled separately).
  188488. */
  188489. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188490. {
  188491. png_byte chunk_length[4];
  188492. if (png_ptr->buffer_size < 8)
  188493. {
  188494. png_push_save_buffer(png_ptr);
  188495. return;
  188496. }
  188497. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188498. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188499. png_reset_crc(png_ptr);
  188500. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188501. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188502. }
  188503. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188504. if(png_ptr->mode & PNG_AFTER_IDAT)
  188505. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188506. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188507. {
  188508. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188509. {
  188510. png_push_save_buffer(png_ptr);
  188511. return;
  188512. }
  188513. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188514. }
  188515. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188516. {
  188517. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188518. {
  188519. png_push_save_buffer(png_ptr);
  188520. return;
  188521. }
  188522. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188523. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188524. png_push_have_end(png_ptr, info_ptr);
  188525. }
  188526. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188527. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188528. {
  188529. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188530. {
  188531. png_push_save_buffer(png_ptr);
  188532. return;
  188533. }
  188534. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188535. png_ptr->mode |= PNG_HAVE_IDAT;
  188536. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188537. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188538. png_ptr->mode |= PNG_HAVE_PLTE;
  188539. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188540. {
  188541. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188542. png_error(png_ptr, "Missing IHDR before IDAT");
  188543. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188544. !(png_ptr->mode & PNG_HAVE_PLTE))
  188545. png_error(png_ptr, "Missing PLTE before IDAT");
  188546. }
  188547. }
  188548. #endif
  188549. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188550. {
  188551. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188552. {
  188553. png_push_save_buffer(png_ptr);
  188554. return;
  188555. }
  188556. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188557. }
  188558. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188559. {
  188560. /* If we reach an IDAT chunk, this means we have read all of the
  188561. * header chunks, and we can start reading the image (or if this
  188562. * is called after the image has been read - we have an error).
  188563. */
  188564. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188565. png_error(png_ptr, "Missing IHDR before IDAT");
  188566. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188567. !(png_ptr->mode & PNG_HAVE_PLTE))
  188568. png_error(png_ptr, "Missing PLTE before IDAT");
  188569. if (png_ptr->mode & PNG_HAVE_IDAT)
  188570. {
  188571. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188572. if (png_ptr->push_length == 0)
  188573. return;
  188574. if (png_ptr->mode & PNG_AFTER_IDAT)
  188575. png_error(png_ptr, "Too many IDAT's found");
  188576. }
  188577. png_ptr->idat_size = png_ptr->push_length;
  188578. png_ptr->mode |= PNG_HAVE_IDAT;
  188579. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188580. png_push_have_info(png_ptr, info_ptr);
  188581. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188582. png_ptr->zstream.next_out = png_ptr->row_buf;
  188583. return;
  188584. }
  188585. #if defined(PNG_READ_gAMA_SUPPORTED)
  188586. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188587. {
  188588. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188589. {
  188590. png_push_save_buffer(png_ptr);
  188591. return;
  188592. }
  188593. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188594. }
  188595. #endif
  188596. #if defined(PNG_READ_sBIT_SUPPORTED)
  188597. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188598. {
  188599. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188600. {
  188601. png_push_save_buffer(png_ptr);
  188602. return;
  188603. }
  188604. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188605. }
  188606. #endif
  188607. #if defined(PNG_READ_cHRM_SUPPORTED)
  188608. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188609. {
  188610. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188611. {
  188612. png_push_save_buffer(png_ptr);
  188613. return;
  188614. }
  188615. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188616. }
  188617. #endif
  188618. #if defined(PNG_READ_sRGB_SUPPORTED)
  188619. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188620. {
  188621. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188622. {
  188623. png_push_save_buffer(png_ptr);
  188624. return;
  188625. }
  188626. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188627. }
  188628. #endif
  188629. #if defined(PNG_READ_iCCP_SUPPORTED)
  188630. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188631. {
  188632. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188633. {
  188634. png_push_save_buffer(png_ptr);
  188635. return;
  188636. }
  188637. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188638. }
  188639. #endif
  188640. #if defined(PNG_READ_sPLT_SUPPORTED)
  188641. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188642. {
  188643. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188644. {
  188645. png_push_save_buffer(png_ptr);
  188646. return;
  188647. }
  188648. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188649. }
  188650. #endif
  188651. #if defined(PNG_READ_tRNS_SUPPORTED)
  188652. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188653. {
  188654. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188655. {
  188656. png_push_save_buffer(png_ptr);
  188657. return;
  188658. }
  188659. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188660. }
  188661. #endif
  188662. #if defined(PNG_READ_bKGD_SUPPORTED)
  188663. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188664. {
  188665. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188666. {
  188667. png_push_save_buffer(png_ptr);
  188668. return;
  188669. }
  188670. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188671. }
  188672. #endif
  188673. #if defined(PNG_READ_hIST_SUPPORTED)
  188674. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188675. {
  188676. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188677. {
  188678. png_push_save_buffer(png_ptr);
  188679. return;
  188680. }
  188681. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188682. }
  188683. #endif
  188684. #if defined(PNG_READ_pHYs_SUPPORTED)
  188685. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188686. {
  188687. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188688. {
  188689. png_push_save_buffer(png_ptr);
  188690. return;
  188691. }
  188692. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188693. }
  188694. #endif
  188695. #if defined(PNG_READ_oFFs_SUPPORTED)
  188696. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188697. {
  188698. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188699. {
  188700. png_push_save_buffer(png_ptr);
  188701. return;
  188702. }
  188703. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188704. }
  188705. #endif
  188706. #if defined(PNG_READ_pCAL_SUPPORTED)
  188707. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188708. {
  188709. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188710. {
  188711. png_push_save_buffer(png_ptr);
  188712. return;
  188713. }
  188714. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188715. }
  188716. #endif
  188717. #if defined(PNG_READ_sCAL_SUPPORTED)
  188718. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188719. {
  188720. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188721. {
  188722. png_push_save_buffer(png_ptr);
  188723. return;
  188724. }
  188725. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188726. }
  188727. #endif
  188728. #if defined(PNG_READ_tIME_SUPPORTED)
  188729. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188730. {
  188731. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188732. {
  188733. png_push_save_buffer(png_ptr);
  188734. return;
  188735. }
  188736. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188737. }
  188738. #endif
  188739. #if defined(PNG_READ_tEXt_SUPPORTED)
  188740. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188741. {
  188742. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188743. {
  188744. png_push_save_buffer(png_ptr);
  188745. return;
  188746. }
  188747. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188748. }
  188749. #endif
  188750. #if defined(PNG_READ_zTXt_SUPPORTED)
  188751. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188752. {
  188753. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188754. {
  188755. png_push_save_buffer(png_ptr);
  188756. return;
  188757. }
  188758. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188759. }
  188760. #endif
  188761. #if defined(PNG_READ_iTXt_SUPPORTED)
  188762. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188763. {
  188764. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188765. {
  188766. png_push_save_buffer(png_ptr);
  188767. return;
  188768. }
  188769. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188770. }
  188771. #endif
  188772. else
  188773. {
  188774. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188775. {
  188776. png_push_save_buffer(png_ptr);
  188777. return;
  188778. }
  188779. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188780. }
  188781. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188782. }
  188783. void /* PRIVATE */
  188784. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188785. {
  188786. png_ptr->process_mode = PNG_SKIP_MODE;
  188787. png_ptr->skip_length = skip;
  188788. }
  188789. void /* PRIVATE */
  188790. png_push_crc_finish(png_structp png_ptr)
  188791. {
  188792. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188793. {
  188794. png_size_t save_size;
  188795. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188796. save_size = (png_size_t)png_ptr->skip_length;
  188797. else
  188798. save_size = png_ptr->save_buffer_size;
  188799. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188800. png_ptr->skip_length -= save_size;
  188801. png_ptr->buffer_size -= save_size;
  188802. png_ptr->save_buffer_size -= save_size;
  188803. png_ptr->save_buffer_ptr += save_size;
  188804. }
  188805. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188806. {
  188807. png_size_t save_size;
  188808. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188809. save_size = (png_size_t)png_ptr->skip_length;
  188810. else
  188811. save_size = png_ptr->current_buffer_size;
  188812. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188813. png_ptr->skip_length -= save_size;
  188814. png_ptr->buffer_size -= save_size;
  188815. png_ptr->current_buffer_size -= save_size;
  188816. png_ptr->current_buffer_ptr += save_size;
  188817. }
  188818. if (!png_ptr->skip_length)
  188819. {
  188820. if (png_ptr->buffer_size < 4)
  188821. {
  188822. png_push_save_buffer(png_ptr);
  188823. return;
  188824. }
  188825. png_crc_finish(png_ptr, 0);
  188826. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188827. }
  188828. }
  188829. void PNGAPI
  188830. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188831. {
  188832. png_bytep ptr;
  188833. if(png_ptr == NULL) return;
  188834. ptr = buffer;
  188835. if (png_ptr->save_buffer_size)
  188836. {
  188837. png_size_t save_size;
  188838. if (length < png_ptr->save_buffer_size)
  188839. save_size = length;
  188840. else
  188841. save_size = png_ptr->save_buffer_size;
  188842. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188843. length -= save_size;
  188844. ptr += save_size;
  188845. png_ptr->buffer_size -= save_size;
  188846. png_ptr->save_buffer_size -= save_size;
  188847. png_ptr->save_buffer_ptr += save_size;
  188848. }
  188849. if (length && png_ptr->current_buffer_size)
  188850. {
  188851. png_size_t save_size;
  188852. if (length < png_ptr->current_buffer_size)
  188853. save_size = length;
  188854. else
  188855. save_size = png_ptr->current_buffer_size;
  188856. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188857. png_ptr->buffer_size -= save_size;
  188858. png_ptr->current_buffer_size -= save_size;
  188859. png_ptr->current_buffer_ptr += save_size;
  188860. }
  188861. }
  188862. void /* PRIVATE */
  188863. png_push_save_buffer(png_structp png_ptr)
  188864. {
  188865. if (png_ptr->save_buffer_size)
  188866. {
  188867. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188868. {
  188869. png_size_t i,istop;
  188870. png_bytep sp;
  188871. png_bytep dp;
  188872. istop = png_ptr->save_buffer_size;
  188873. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188874. i < istop; i++, sp++, dp++)
  188875. {
  188876. *dp = *sp;
  188877. }
  188878. }
  188879. }
  188880. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188881. png_ptr->save_buffer_max)
  188882. {
  188883. png_size_t new_max;
  188884. png_bytep old_buffer;
  188885. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188886. (png_ptr->current_buffer_size + 256))
  188887. {
  188888. png_error(png_ptr, "Potential overflow of save_buffer");
  188889. }
  188890. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188891. old_buffer = png_ptr->save_buffer;
  188892. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188893. (png_uint_32)new_max);
  188894. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188895. png_free(png_ptr, old_buffer);
  188896. png_ptr->save_buffer_max = new_max;
  188897. }
  188898. if (png_ptr->current_buffer_size)
  188899. {
  188900. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188901. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188902. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188903. png_ptr->current_buffer_size = 0;
  188904. }
  188905. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188906. png_ptr->buffer_size = 0;
  188907. }
  188908. void /* PRIVATE */
  188909. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188910. png_size_t buffer_length)
  188911. {
  188912. png_ptr->current_buffer = buffer;
  188913. png_ptr->current_buffer_size = buffer_length;
  188914. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188915. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188916. }
  188917. void /* PRIVATE */
  188918. png_push_read_IDAT(png_structp png_ptr)
  188919. {
  188920. #ifdef PNG_USE_LOCAL_ARRAYS
  188921. PNG_CONST PNG_IDAT;
  188922. #endif
  188923. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188924. {
  188925. png_byte chunk_length[4];
  188926. if (png_ptr->buffer_size < 8)
  188927. {
  188928. png_push_save_buffer(png_ptr);
  188929. return;
  188930. }
  188931. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188932. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188933. png_reset_crc(png_ptr);
  188934. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188935. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188936. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188937. {
  188938. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188939. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188940. png_error(png_ptr, "Not enough compressed data");
  188941. return;
  188942. }
  188943. png_ptr->idat_size = png_ptr->push_length;
  188944. }
  188945. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188946. {
  188947. png_size_t save_size;
  188948. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188949. {
  188950. save_size = (png_size_t)png_ptr->idat_size;
  188951. /* check for overflow */
  188952. if((png_uint_32)save_size != png_ptr->idat_size)
  188953. png_error(png_ptr, "save_size overflowed in pngpread");
  188954. }
  188955. else
  188956. save_size = png_ptr->save_buffer_size;
  188957. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188958. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188959. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188960. png_ptr->idat_size -= save_size;
  188961. png_ptr->buffer_size -= save_size;
  188962. png_ptr->save_buffer_size -= save_size;
  188963. png_ptr->save_buffer_ptr += save_size;
  188964. }
  188965. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188966. {
  188967. png_size_t save_size;
  188968. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188969. {
  188970. save_size = (png_size_t)png_ptr->idat_size;
  188971. /* check for overflow */
  188972. if((png_uint_32)save_size != png_ptr->idat_size)
  188973. png_error(png_ptr, "save_size overflowed in pngpread");
  188974. }
  188975. else
  188976. save_size = png_ptr->current_buffer_size;
  188977. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188978. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188979. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188980. png_ptr->idat_size -= save_size;
  188981. png_ptr->buffer_size -= save_size;
  188982. png_ptr->current_buffer_size -= save_size;
  188983. png_ptr->current_buffer_ptr += save_size;
  188984. }
  188985. if (!png_ptr->idat_size)
  188986. {
  188987. if (png_ptr->buffer_size < 4)
  188988. {
  188989. png_push_save_buffer(png_ptr);
  188990. return;
  188991. }
  188992. png_crc_finish(png_ptr, 0);
  188993. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188994. png_ptr->mode |= PNG_AFTER_IDAT;
  188995. }
  188996. }
  188997. void /* PRIVATE */
  188998. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188999. png_size_t buffer_length)
  189000. {
  189001. int ret;
  189002. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189003. png_error(png_ptr, "Extra compression data");
  189004. png_ptr->zstream.next_in = buffer;
  189005. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189006. for(;;)
  189007. {
  189008. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189009. if (ret != Z_OK)
  189010. {
  189011. if (ret == Z_STREAM_END)
  189012. {
  189013. if (png_ptr->zstream.avail_in)
  189014. png_error(png_ptr, "Extra compressed data");
  189015. if (!(png_ptr->zstream.avail_out))
  189016. {
  189017. png_push_process_row(png_ptr);
  189018. }
  189019. png_ptr->mode |= PNG_AFTER_IDAT;
  189020. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189021. break;
  189022. }
  189023. else if (ret == Z_BUF_ERROR)
  189024. break;
  189025. else
  189026. png_error(png_ptr, "Decompression Error");
  189027. }
  189028. if (!(png_ptr->zstream.avail_out))
  189029. {
  189030. if ((
  189031. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189032. png_ptr->interlaced && png_ptr->pass > 6) ||
  189033. (!png_ptr->interlaced &&
  189034. #endif
  189035. png_ptr->row_number == png_ptr->num_rows))
  189036. {
  189037. if (png_ptr->zstream.avail_in)
  189038. {
  189039. png_warning(png_ptr, "Too much data in IDAT chunks");
  189040. }
  189041. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189042. break;
  189043. }
  189044. png_push_process_row(png_ptr);
  189045. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189046. png_ptr->zstream.next_out = png_ptr->row_buf;
  189047. }
  189048. else
  189049. break;
  189050. }
  189051. }
  189052. void /* PRIVATE */
  189053. png_push_process_row(png_structp png_ptr)
  189054. {
  189055. png_ptr->row_info.color_type = png_ptr->color_type;
  189056. png_ptr->row_info.width = png_ptr->iwidth;
  189057. png_ptr->row_info.channels = png_ptr->channels;
  189058. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189059. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189060. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189061. png_ptr->row_info.width);
  189062. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189063. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189064. (int)(png_ptr->row_buf[0]));
  189065. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189066. png_ptr->rowbytes + 1);
  189067. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189068. png_do_read_transformations(png_ptr);
  189069. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189070. /* blow up interlaced rows to full size */
  189071. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189072. {
  189073. if (png_ptr->pass < 6)
  189074. /* old interface (pre-1.0.9):
  189075. png_do_read_interlace(&(png_ptr->row_info),
  189076. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189077. */
  189078. png_do_read_interlace(png_ptr);
  189079. switch (png_ptr->pass)
  189080. {
  189081. case 0:
  189082. {
  189083. int i;
  189084. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189085. {
  189086. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189087. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189088. }
  189089. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189090. {
  189091. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189092. {
  189093. png_push_have_row(png_ptr, png_bytep_NULL);
  189094. png_read_push_finish_row(png_ptr);
  189095. }
  189096. }
  189097. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189098. {
  189099. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189100. {
  189101. png_push_have_row(png_ptr, png_bytep_NULL);
  189102. png_read_push_finish_row(png_ptr);
  189103. }
  189104. }
  189105. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189106. {
  189107. png_push_have_row(png_ptr, png_bytep_NULL);
  189108. png_read_push_finish_row(png_ptr);
  189109. }
  189110. break;
  189111. }
  189112. case 1:
  189113. {
  189114. int i;
  189115. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189116. {
  189117. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189118. png_read_push_finish_row(png_ptr);
  189119. }
  189120. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189121. {
  189122. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189123. {
  189124. png_push_have_row(png_ptr, png_bytep_NULL);
  189125. png_read_push_finish_row(png_ptr);
  189126. }
  189127. }
  189128. break;
  189129. }
  189130. case 2:
  189131. {
  189132. int i;
  189133. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189134. {
  189135. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189136. png_read_push_finish_row(png_ptr);
  189137. }
  189138. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189139. {
  189140. png_push_have_row(png_ptr, png_bytep_NULL);
  189141. png_read_push_finish_row(png_ptr);
  189142. }
  189143. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189144. {
  189145. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189146. {
  189147. png_push_have_row(png_ptr, png_bytep_NULL);
  189148. png_read_push_finish_row(png_ptr);
  189149. }
  189150. }
  189151. break;
  189152. }
  189153. case 3:
  189154. {
  189155. int i;
  189156. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189157. {
  189158. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189159. png_read_push_finish_row(png_ptr);
  189160. }
  189161. if (png_ptr->pass == 4) /* skip top two generated rows */
  189162. {
  189163. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189164. {
  189165. png_push_have_row(png_ptr, png_bytep_NULL);
  189166. png_read_push_finish_row(png_ptr);
  189167. }
  189168. }
  189169. break;
  189170. }
  189171. case 4:
  189172. {
  189173. int i;
  189174. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189175. {
  189176. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189177. png_read_push_finish_row(png_ptr);
  189178. }
  189179. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189180. {
  189181. png_push_have_row(png_ptr, png_bytep_NULL);
  189182. png_read_push_finish_row(png_ptr);
  189183. }
  189184. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189185. {
  189186. png_push_have_row(png_ptr, png_bytep_NULL);
  189187. png_read_push_finish_row(png_ptr);
  189188. }
  189189. break;
  189190. }
  189191. case 5:
  189192. {
  189193. int i;
  189194. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189195. {
  189196. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189197. png_read_push_finish_row(png_ptr);
  189198. }
  189199. if (png_ptr->pass == 6) /* skip top generated row */
  189200. {
  189201. png_push_have_row(png_ptr, png_bytep_NULL);
  189202. png_read_push_finish_row(png_ptr);
  189203. }
  189204. break;
  189205. }
  189206. case 6:
  189207. {
  189208. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189209. png_read_push_finish_row(png_ptr);
  189210. if (png_ptr->pass != 6)
  189211. break;
  189212. png_push_have_row(png_ptr, png_bytep_NULL);
  189213. png_read_push_finish_row(png_ptr);
  189214. }
  189215. }
  189216. }
  189217. else
  189218. #endif
  189219. {
  189220. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189221. png_read_push_finish_row(png_ptr);
  189222. }
  189223. }
  189224. void /* PRIVATE */
  189225. png_read_push_finish_row(png_structp png_ptr)
  189226. {
  189227. #ifdef PNG_USE_LOCAL_ARRAYS
  189228. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189229. /* start of interlace block */
  189230. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189231. /* offset to next interlace block */
  189232. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189233. /* start of interlace block in the y direction */
  189234. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189235. /* offset to next interlace block in the y direction */
  189236. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189237. /* Height of interlace block. This is not currently used - if you need
  189238. * it, uncomment it here and in png.h
  189239. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189240. */
  189241. #endif
  189242. png_ptr->row_number++;
  189243. if (png_ptr->row_number < png_ptr->num_rows)
  189244. return;
  189245. if (png_ptr->interlaced)
  189246. {
  189247. png_ptr->row_number = 0;
  189248. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189249. png_ptr->rowbytes + 1);
  189250. do
  189251. {
  189252. png_ptr->pass++;
  189253. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189254. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189255. (png_ptr->pass == 5 && png_ptr->width < 2))
  189256. png_ptr->pass++;
  189257. if (png_ptr->pass > 7)
  189258. png_ptr->pass--;
  189259. if (png_ptr->pass >= 7)
  189260. break;
  189261. png_ptr->iwidth = (png_ptr->width +
  189262. png_pass_inc[png_ptr->pass] - 1 -
  189263. png_pass_start[png_ptr->pass]) /
  189264. png_pass_inc[png_ptr->pass];
  189265. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189266. png_ptr->iwidth) + 1;
  189267. if (png_ptr->transformations & PNG_INTERLACE)
  189268. break;
  189269. png_ptr->num_rows = (png_ptr->height +
  189270. png_pass_yinc[png_ptr->pass] - 1 -
  189271. png_pass_ystart[png_ptr->pass]) /
  189272. png_pass_yinc[png_ptr->pass];
  189273. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189274. }
  189275. }
  189276. #if defined(PNG_READ_tEXt_SUPPORTED)
  189277. void /* PRIVATE */
  189278. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189279. length)
  189280. {
  189281. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189282. {
  189283. png_error(png_ptr, "Out of place tEXt");
  189284. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189285. }
  189286. #ifdef PNG_MAX_MALLOC_64K
  189287. png_ptr->skip_length = 0; /* This may not be necessary */
  189288. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189289. {
  189290. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189291. png_ptr->skip_length = length - (png_uint_32)65535L;
  189292. length = (png_uint_32)65535L;
  189293. }
  189294. #endif
  189295. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189296. (png_uint_32)(length+1));
  189297. png_ptr->current_text[length] = '\0';
  189298. png_ptr->current_text_ptr = png_ptr->current_text;
  189299. png_ptr->current_text_size = (png_size_t)length;
  189300. png_ptr->current_text_left = (png_size_t)length;
  189301. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189302. }
  189303. void /* PRIVATE */
  189304. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189305. {
  189306. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189307. {
  189308. png_size_t text_size;
  189309. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189310. text_size = png_ptr->buffer_size;
  189311. else
  189312. text_size = png_ptr->current_text_left;
  189313. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189314. png_ptr->current_text_left -= text_size;
  189315. png_ptr->current_text_ptr += text_size;
  189316. }
  189317. if (!(png_ptr->current_text_left))
  189318. {
  189319. png_textp text_ptr;
  189320. png_charp text;
  189321. png_charp key;
  189322. int ret;
  189323. if (png_ptr->buffer_size < 4)
  189324. {
  189325. png_push_save_buffer(png_ptr);
  189326. return;
  189327. }
  189328. png_push_crc_finish(png_ptr);
  189329. #if defined(PNG_MAX_MALLOC_64K)
  189330. if (png_ptr->skip_length)
  189331. return;
  189332. #endif
  189333. key = png_ptr->current_text;
  189334. for (text = key; *text; text++)
  189335. /* empty loop */ ;
  189336. if (text < key + png_ptr->current_text_size)
  189337. text++;
  189338. text_ptr = (png_textp)png_malloc(png_ptr,
  189339. (png_uint_32)png_sizeof(png_text));
  189340. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189341. text_ptr->key = key;
  189342. #ifdef PNG_iTXt_SUPPORTED
  189343. text_ptr->lang = NULL;
  189344. text_ptr->lang_key = NULL;
  189345. #endif
  189346. text_ptr->text = text;
  189347. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189348. png_free(png_ptr, key);
  189349. png_free(png_ptr, text_ptr);
  189350. png_ptr->current_text = NULL;
  189351. if (ret)
  189352. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189353. }
  189354. }
  189355. #endif
  189356. #if defined(PNG_READ_zTXt_SUPPORTED)
  189357. void /* PRIVATE */
  189358. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189359. length)
  189360. {
  189361. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189362. {
  189363. png_error(png_ptr, "Out of place zTXt");
  189364. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189365. }
  189366. #ifdef PNG_MAX_MALLOC_64K
  189367. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189368. * to be able to store the uncompressed data. Actually, the threshold
  189369. * is probably around 32K, but it isn't as definite as 64K is.
  189370. */
  189371. if (length > (png_uint_32)65535L)
  189372. {
  189373. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189374. png_push_crc_skip(png_ptr, length);
  189375. return;
  189376. }
  189377. #endif
  189378. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189379. (png_uint_32)(length+1));
  189380. png_ptr->current_text[length] = '\0';
  189381. png_ptr->current_text_ptr = png_ptr->current_text;
  189382. png_ptr->current_text_size = (png_size_t)length;
  189383. png_ptr->current_text_left = (png_size_t)length;
  189384. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189385. }
  189386. void /* PRIVATE */
  189387. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189388. {
  189389. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189390. {
  189391. png_size_t text_size;
  189392. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189393. text_size = png_ptr->buffer_size;
  189394. else
  189395. text_size = png_ptr->current_text_left;
  189396. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189397. png_ptr->current_text_left -= text_size;
  189398. png_ptr->current_text_ptr += text_size;
  189399. }
  189400. if (!(png_ptr->current_text_left))
  189401. {
  189402. png_textp text_ptr;
  189403. png_charp text;
  189404. png_charp key;
  189405. int ret;
  189406. png_size_t text_size, key_size;
  189407. if (png_ptr->buffer_size < 4)
  189408. {
  189409. png_push_save_buffer(png_ptr);
  189410. return;
  189411. }
  189412. png_push_crc_finish(png_ptr);
  189413. key = png_ptr->current_text;
  189414. for (text = key; *text; text++)
  189415. /* empty loop */ ;
  189416. /* zTXt can't have zero text */
  189417. if (text >= key + png_ptr->current_text_size)
  189418. {
  189419. png_ptr->current_text = NULL;
  189420. png_free(png_ptr, key);
  189421. return;
  189422. }
  189423. text++;
  189424. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189425. {
  189426. png_ptr->current_text = NULL;
  189427. png_free(png_ptr, key);
  189428. return;
  189429. }
  189430. text++;
  189431. png_ptr->zstream.next_in = (png_bytep )text;
  189432. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189433. (text - key));
  189434. png_ptr->zstream.next_out = png_ptr->zbuf;
  189435. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189436. key_size = text - key;
  189437. text_size = 0;
  189438. text = NULL;
  189439. ret = Z_STREAM_END;
  189440. while (png_ptr->zstream.avail_in)
  189441. {
  189442. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189443. if (ret != Z_OK && ret != Z_STREAM_END)
  189444. {
  189445. inflateReset(&png_ptr->zstream);
  189446. png_ptr->zstream.avail_in = 0;
  189447. png_ptr->current_text = NULL;
  189448. png_free(png_ptr, key);
  189449. png_free(png_ptr, text);
  189450. return;
  189451. }
  189452. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189453. {
  189454. if (text == NULL)
  189455. {
  189456. text = (png_charp)png_malloc(png_ptr,
  189457. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189458. + key_size + 1));
  189459. png_memcpy(text + key_size, png_ptr->zbuf,
  189460. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189461. png_memcpy(text, key, key_size);
  189462. text_size = key_size + png_ptr->zbuf_size -
  189463. png_ptr->zstream.avail_out;
  189464. *(text + text_size) = '\0';
  189465. }
  189466. else
  189467. {
  189468. png_charp tmp;
  189469. tmp = text;
  189470. text = (png_charp)png_malloc(png_ptr, text_size +
  189471. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189472. + 1));
  189473. png_memcpy(text, tmp, text_size);
  189474. png_free(png_ptr, tmp);
  189475. png_memcpy(text + text_size, png_ptr->zbuf,
  189476. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189477. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189478. *(text + text_size) = '\0';
  189479. }
  189480. if (ret != Z_STREAM_END)
  189481. {
  189482. png_ptr->zstream.next_out = png_ptr->zbuf;
  189483. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189484. }
  189485. }
  189486. else
  189487. {
  189488. break;
  189489. }
  189490. if (ret == Z_STREAM_END)
  189491. break;
  189492. }
  189493. inflateReset(&png_ptr->zstream);
  189494. png_ptr->zstream.avail_in = 0;
  189495. if (ret != Z_STREAM_END)
  189496. {
  189497. png_ptr->current_text = NULL;
  189498. png_free(png_ptr, key);
  189499. png_free(png_ptr, text);
  189500. return;
  189501. }
  189502. png_ptr->current_text = NULL;
  189503. png_free(png_ptr, key);
  189504. key = text;
  189505. text += key_size;
  189506. text_ptr = (png_textp)png_malloc(png_ptr,
  189507. (png_uint_32)png_sizeof(png_text));
  189508. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189509. text_ptr->key = key;
  189510. #ifdef PNG_iTXt_SUPPORTED
  189511. text_ptr->lang = NULL;
  189512. text_ptr->lang_key = NULL;
  189513. #endif
  189514. text_ptr->text = text;
  189515. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189516. png_free(png_ptr, key);
  189517. png_free(png_ptr, text_ptr);
  189518. if (ret)
  189519. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189520. }
  189521. }
  189522. #endif
  189523. #if defined(PNG_READ_iTXt_SUPPORTED)
  189524. void /* PRIVATE */
  189525. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189526. length)
  189527. {
  189528. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189529. {
  189530. png_error(png_ptr, "Out of place iTXt");
  189531. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189532. }
  189533. #ifdef PNG_MAX_MALLOC_64K
  189534. png_ptr->skip_length = 0; /* This may not be necessary */
  189535. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189536. {
  189537. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189538. png_ptr->skip_length = length - (png_uint_32)65535L;
  189539. length = (png_uint_32)65535L;
  189540. }
  189541. #endif
  189542. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189543. (png_uint_32)(length+1));
  189544. png_ptr->current_text[length] = '\0';
  189545. png_ptr->current_text_ptr = png_ptr->current_text;
  189546. png_ptr->current_text_size = (png_size_t)length;
  189547. png_ptr->current_text_left = (png_size_t)length;
  189548. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189549. }
  189550. void /* PRIVATE */
  189551. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189552. {
  189553. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189554. {
  189555. png_size_t text_size;
  189556. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189557. text_size = png_ptr->buffer_size;
  189558. else
  189559. text_size = png_ptr->current_text_left;
  189560. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189561. png_ptr->current_text_left -= text_size;
  189562. png_ptr->current_text_ptr += text_size;
  189563. }
  189564. if (!(png_ptr->current_text_left))
  189565. {
  189566. png_textp text_ptr;
  189567. png_charp key;
  189568. int comp_flag;
  189569. png_charp lang;
  189570. png_charp lang_key;
  189571. png_charp text;
  189572. int ret;
  189573. if (png_ptr->buffer_size < 4)
  189574. {
  189575. png_push_save_buffer(png_ptr);
  189576. return;
  189577. }
  189578. png_push_crc_finish(png_ptr);
  189579. #if defined(PNG_MAX_MALLOC_64K)
  189580. if (png_ptr->skip_length)
  189581. return;
  189582. #endif
  189583. key = png_ptr->current_text;
  189584. for (lang = key; *lang; lang++)
  189585. /* empty loop */ ;
  189586. if (lang < key + png_ptr->current_text_size - 3)
  189587. lang++;
  189588. comp_flag = *lang++;
  189589. lang++; /* skip comp_type, always zero */
  189590. for (lang_key = lang; *lang_key; lang_key++)
  189591. /* empty loop */ ;
  189592. lang_key++; /* skip NUL separator */
  189593. text=lang_key;
  189594. if (lang_key < key + png_ptr->current_text_size - 1)
  189595. {
  189596. for (; *text; text++)
  189597. /* empty loop */ ;
  189598. }
  189599. if (text < key + png_ptr->current_text_size)
  189600. text++;
  189601. text_ptr = (png_textp)png_malloc(png_ptr,
  189602. (png_uint_32)png_sizeof(png_text));
  189603. text_ptr->compression = comp_flag + 2;
  189604. text_ptr->key = key;
  189605. text_ptr->lang = lang;
  189606. text_ptr->lang_key = lang_key;
  189607. text_ptr->text = text;
  189608. text_ptr->text_length = 0;
  189609. text_ptr->itxt_length = png_strlen(text);
  189610. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189611. png_ptr->current_text = NULL;
  189612. png_free(png_ptr, text_ptr);
  189613. if (ret)
  189614. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189615. }
  189616. }
  189617. #endif
  189618. /* This function is called when we haven't found a handler for this
  189619. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189620. * name or a critical chunk), the chunk is (currently) silently ignored.
  189621. */
  189622. void /* PRIVATE */
  189623. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189624. length)
  189625. {
  189626. png_uint_32 skip=0;
  189627. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189628. if (!(png_ptr->chunk_name[0] & 0x20))
  189629. {
  189630. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189631. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189632. PNG_HANDLE_CHUNK_ALWAYS
  189633. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189634. && png_ptr->read_user_chunk_fn == NULL
  189635. #endif
  189636. )
  189637. #endif
  189638. png_chunk_error(png_ptr, "unknown critical chunk");
  189639. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189640. }
  189641. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189642. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189643. {
  189644. #ifdef PNG_MAX_MALLOC_64K
  189645. if (length > (png_uint_32)65535L)
  189646. {
  189647. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189648. skip = length - (png_uint_32)65535L;
  189649. length = (png_uint_32)65535L;
  189650. }
  189651. #endif
  189652. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189653. (png_charp)png_ptr->chunk_name, 5);
  189654. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189655. png_ptr->unknown_chunk.size = (png_size_t)length;
  189656. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189657. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189658. if(png_ptr->read_user_chunk_fn != NULL)
  189659. {
  189660. /* callback to user unknown chunk handler */
  189661. int ret;
  189662. ret = (*(png_ptr->read_user_chunk_fn))
  189663. (png_ptr, &png_ptr->unknown_chunk);
  189664. if (ret < 0)
  189665. png_chunk_error(png_ptr, "error in user chunk");
  189666. if (ret == 0)
  189667. {
  189668. if (!(png_ptr->chunk_name[0] & 0x20))
  189669. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189670. PNG_HANDLE_CHUNK_ALWAYS)
  189671. png_chunk_error(png_ptr, "unknown critical chunk");
  189672. png_set_unknown_chunks(png_ptr, info_ptr,
  189673. &png_ptr->unknown_chunk, 1);
  189674. }
  189675. }
  189676. #else
  189677. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189678. #endif
  189679. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189680. png_ptr->unknown_chunk.data = NULL;
  189681. }
  189682. else
  189683. #endif
  189684. skip=length;
  189685. png_push_crc_skip(png_ptr, skip);
  189686. }
  189687. void /* PRIVATE */
  189688. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189689. {
  189690. if (png_ptr->info_fn != NULL)
  189691. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189692. }
  189693. void /* PRIVATE */
  189694. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189695. {
  189696. if (png_ptr->end_fn != NULL)
  189697. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189698. }
  189699. void /* PRIVATE */
  189700. png_push_have_row(png_structp png_ptr, png_bytep row)
  189701. {
  189702. if (png_ptr->row_fn != NULL)
  189703. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189704. (int)png_ptr->pass);
  189705. }
  189706. void PNGAPI
  189707. png_progressive_combine_row (png_structp png_ptr,
  189708. png_bytep old_row, png_bytep new_row)
  189709. {
  189710. #ifdef PNG_USE_LOCAL_ARRAYS
  189711. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189712. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189713. #endif
  189714. if(png_ptr == NULL) return;
  189715. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189716. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189717. }
  189718. void PNGAPI
  189719. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189720. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189721. png_progressive_end_ptr end_fn)
  189722. {
  189723. if(png_ptr == NULL) return;
  189724. png_ptr->info_fn = info_fn;
  189725. png_ptr->row_fn = row_fn;
  189726. png_ptr->end_fn = end_fn;
  189727. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189728. }
  189729. png_voidp PNGAPI
  189730. png_get_progressive_ptr(png_structp png_ptr)
  189731. {
  189732. if(png_ptr == NULL) return (NULL);
  189733. return png_ptr->io_ptr;
  189734. }
  189735. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189736. /*** End of inlined file: pngpread.c ***/
  189737. /*** Start of inlined file: pngrio.c ***/
  189738. /* pngrio.c - functions for data input
  189739. *
  189740. * Last changed in libpng 1.2.13 November 13, 2006
  189741. * For conditions of distribution and use, see copyright notice in png.h
  189742. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189743. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189744. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189745. *
  189746. * This file provides a location for all input. Users who need
  189747. * special handling are expected to write a function that has the same
  189748. * arguments as this and performs a similar function, but that possibly
  189749. * has a different input method. Note that you shouldn't change this
  189750. * function, but rather write a replacement function and then make
  189751. * libpng use it at run time with png_set_read_fn(...).
  189752. */
  189753. #define PNG_INTERNAL
  189754. #if defined(PNG_READ_SUPPORTED)
  189755. /* Read the data from whatever input you are using. The default routine
  189756. reads from a file pointer. Note that this routine sometimes gets called
  189757. with very small lengths, so you should implement some kind of simple
  189758. buffering if you are using unbuffered reads. This should never be asked
  189759. to read more then 64K on a 16 bit machine. */
  189760. void /* PRIVATE */
  189761. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189762. {
  189763. png_debug1(4,"reading %d bytes\n", (int)length);
  189764. if (png_ptr->read_data_fn != NULL)
  189765. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189766. else
  189767. png_error(png_ptr, "Call to NULL read function");
  189768. }
  189769. #if !defined(PNG_NO_STDIO)
  189770. /* This is the function that does the actual reading of data. If you are
  189771. not reading from a standard C stream, you should create a replacement
  189772. read_data function and use it at run time with png_set_read_fn(), rather
  189773. than changing the library. */
  189774. #ifndef USE_FAR_KEYWORD
  189775. void PNGAPI
  189776. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189777. {
  189778. png_size_t check;
  189779. if(png_ptr == NULL) return;
  189780. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189781. * instead of an int, which is what fread() actually returns.
  189782. */
  189783. #if defined(_WIN32_WCE)
  189784. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189785. check = 0;
  189786. #else
  189787. check = (png_size_t)fread(data, (png_size_t)1, length,
  189788. (png_FILE_p)png_ptr->io_ptr);
  189789. #endif
  189790. if (check != length)
  189791. png_error(png_ptr, "Read Error");
  189792. }
  189793. #else
  189794. /* this is the model-independent version. Since the standard I/O library
  189795. can't handle far buffers in the medium and small models, we have to copy
  189796. the data.
  189797. */
  189798. #define NEAR_BUF_SIZE 1024
  189799. #define MIN(a,b) (a <= b ? a : b)
  189800. static void PNGAPI
  189801. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189802. {
  189803. int check;
  189804. png_byte *n_data;
  189805. png_FILE_p io_ptr;
  189806. if(png_ptr == NULL) return;
  189807. /* Check if data really is near. If so, use usual code. */
  189808. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189809. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189810. if ((png_bytep)n_data == data)
  189811. {
  189812. #if defined(_WIN32_WCE)
  189813. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189814. check = 0;
  189815. #else
  189816. check = fread(n_data, 1, length, io_ptr);
  189817. #endif
  189818. }
  189819. else
  189820. {
  189821. png_byte buf[NEAR_BUF_SIZE];
  189822. png_size_t read, remaining, err;
  189823. check = 0;
  189824. remaining = length;
  189825. do
  189826. {
  189827. read = MIN(NEAR_BUF_SIZE, remaining);
  189828. #if defined(_WIN32_WCE)
  189829. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189830. err = 0;
  189831. #else
  189832. err = fread(buf, (png_size_t)1, read, io_ptr);
  189833. #endif
  189834. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189835. if(err != read)
  189836. break;
  189837. else
  189838. check += err;
  189839. data += read;
  189840. remaining -= read;
  189841. }
  189842. while (remaining != 0);
  189843. }
  189844. if ((png_uint_32)check != (png_uint_32)length)
  189845. png_error(png_ptr, "read Error");
  189846. }
  189847. #endif
  189848. #endif
  189849. /* This function allows the application to supply a new input function
  189850. for libpng if standard C streams aren't being used.
  189851. This function takes as its arguments:
  189852. png_ptr - pointer to a png input data structure
  189853. io_ptr - pointer to user supplied structure containing info about
  189854. the input functions. May be NULL.
  189855. read_data_fn - pointer to a new input function that takes as its
  189856. arguments a pointer to a png_struct, a pointer to
  189857. a location where input data can be stored, and a 32-bit
  189858. unsigned int that is the number of bytes to be read.
  189859. To exit and output any fatal error messages the new write
  189860. function should call png_error(png_ptr, "Error msg"). */
  189861. void PNGAPI
  189862. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189863. png_rw_ptr read_data_fn)
  189864. {
  189865. if(png_ptr == NULL) return;
  189866. png_ptr->io_ptr = io_ptr;
  189867. #if !defined(PNG_NO_STDIO)
  189868. if (read_data_fn != NULL)
  189869. png_ptr->read_data_fn = read_data_fn;
  189870. else
  189871. png_ptr->read_data_fn = png_default_read_data;
  189872. #else
  189873. png_ptr->read_data_fn = read_data_fn;
  189874. #endif
  189875. /* It is an error to write to a read device */
  189876. if (png_ptr->write_data_fn != NULL)
  189877. {
  189878. png_ptr->write_data_fn = NULL;
  189879. png_warning(png_ptr,
  189880. "It's an error to set both read_data_fn and write_data_fn in the ");
  189881. png_warning(png_ptr,
  189882. "same structure. Resetting write_data_fn to NULL.");
  189883. }
  189884. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189885. png_ptr->output_flush_fn = NULL;
  189886. #endif
  189887. }
  189888. #endif /* PNG_READ_SUPPORTED */
  189889. /*** End of inlined file: pngrio.c ***/
  189890. /*** Start of inlined file: pngrtran.c ***/
  189891. /* pngrtran.c - transforms the data in a row for PNG readers
  189892. *
  189893. * Last changed in libpng 1.2.21 [October 4, 2007]
  189894. * For conditions of distribution and use, see copyright notice in png.h
  189895. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189896. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189897. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189898. *
  189899. * This file contains functions optionally called by an application
  189900. * in order to tell libpng how to handle data when reading a PNG.
  189901. * Transformations that are used in both reading and writing are
  189902. * in pngtrans.c.
  189903. */
  189904. #define PNG_INTERNAL
  189905. #if defined(PNG_READ_SUPPORTED)
  189906. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189907. void PNGAPI
  189908. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189909. {
  189910. png_debug(1, "in png_set_crc_action\n");
  189911. /* Tell libpng how we react to CRC errors in critical chunks */
  189912. if(png_ptr == NULL) return;
  189913. switch (crit_action)
  189914. {
  189915. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189916. break;
  189917. case PNG_CRC_WARN_USE: /* warn/use data */
  189918. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189919. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189920. break;
  189921. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189922. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189923. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189924. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189925. break;
  189926. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189927. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189928. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189929. case PNG_CRC_DEFAULT:
  189930. default:
  189931. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189932. break;
  189933. }
  189934. switch (ancil_action)
  189935. {
  189936. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189937. break;
  189938. case PNG_CRC_WARN_USE: /* warn/use data */
  189939. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189940. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189941. break;
  189942. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189943. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189944. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189945. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189946. break;
  189947. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189948. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189949. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189950. break;
  189951. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189952. case PNG_CRC_DEFAULT:
  189953. default:
  189954. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189955. break;
  189956. }
  189957. }
  189958. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189959. defined(PNG_FLOATING_POINT_SUPPORTED)
  189960. /* handle alpha and tRNS via a background color */
  189961. void PNGAPI
  189962. png_set_background(png_structp png_ptr,
  189963. png_color_16p background_color, int background_gamma_code,
  189964. int need_expand, double background_gamma)
  189965. {
  189966. png_debug(1, "in png_set_background\n");
  189967. if(png_ptr == NULL) return;
  189968. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189969. {
  189970. png_warning(png_ptr, "Application must supply a known background gamma");
  189971. return;
  189972. }
  189973. png_ptr->transformations |= PNG_BACKGROUND;
  189974. png_memcpy(&(png_ptr->background), background_color,
  189975. png_sizeof(png_color_16));
  189976. png_ptr->background_gamma = (float)background_gamma;
  189977. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189978. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189979. }
  189980. #endif
  189981. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189982. /* strip 16 bit depth files to 8 bit depth */
  189983. void PNGAPI
  189984. png_set_strip_16(png_structp png_ptr)
  189985. {
  189986. png_debug(1, "in png_set_strip_16\n");
  189987. if(png_ptr == NULL) return;
  189988. png_ptr->transformations |= PNG_16_TO_8;
  189989. }
  189990. #endif
  189991. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189992. void PNGAPI
  189993. png_set_strip_alpha(png_structp png_ptr)
  189994. {
  189995. png_debug(1, "in png_set_strip_alpha\n");
  189996. if(png_ptr == NULL) return;
  189997. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189998. }
  189999. #endif
  190000. #if defined(PNG_READ_DITHER_SUPPORTED)
  190001. /* Dither file to 8 bit. Supply a palette, the current number
  190002. * of elements in the palette, the maximum number of elements
  190003. * allowed, and a histogram if possible. If the current number
  190004. * of colors is greater then the maximum number, the palette will be
  190005. * modified to fit in the maximum number. "full_dither" indicates
  190006. * whether we need a dithering cube set up for RGB images, or if we
  190007. * simply are reducing the number of colors in a paletted image.
  190008. */
  190009. typedef struct png_dsort_struct
  190010. {
  190011. struct png_dsort_struct FAR * next;
  190012. png_byte left;
  190013. png_byte right;
  190014. } png_dsort;
  190015. typedef png_dsort FAR * png_dsortp;
  190016. typedef png_dsort FAR * FAR * png_dsortpp;
  190017. void PNGAPI
  190018. png_set_dither(png_structp png_ptr, png_colorp palette,
  190019. int num_palette, int maximum_colors, png_uint_16p histogram,
  190020. int full_dither)
  190021. {
  190022. png_debug(1, "in png_set_dither\n");
  190023. if(png_ptr == NULL) return;
  190024. png_ptr->transformations |= PNG_DITHER;
  190025. if (!full_dither)
  190026. {
  190027. int i;
  190028. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190029. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190030. for (i = 0; i < num_palette; i++)
  190031. png_ptr->dither_index[i] = (png_byte)i;
  190032. }
  190033. if (num_palette > maximum_colors)
  190034. {
  190035. if (histogram != NULL)
  190036. {
  190037. /* This is easy enough, just throw out the least used colors.
  190038. Perhaps not the best solution, but good enough. */
  190039. int i;
  190040. /* initialize an array to sort colors */
  190041. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190042. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190043. /* initialize the dither_sort array */
  190044. for (i = 0; i < num_palette; i++)
  190045. png_ptr->dither_sort[i] = (png_byte)i;
  190046. /* Find the least used palette entries by starting a
  190047. bubble sort, and running it until we have sorted
  190048. out enough colors. Note that we don't care about
  190049. sorting all the colors, just finding which are
  190050. least used. */
  190051. for (i = num_palette - 1; i >= maximum_colors; i--)
  190052. {
  190053. int done; /* to stop early if the list is pre-sorted */
  190054. int j;
  190055. done = 1;
  190056. for (j = 0; j < i; j++)
  190057. {
  190058. if (histogram[png_ptr->dither_sort[j]]
  190059. < histogram[png_ptr->dither_sort[j + 1]])
  190060. {
  190061. png_byte t;
  190062. t = png_ptr->dither_sort[j];
  190063. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190064. png_ptr->dither_sort[j + 1] = t;
  190065. done = 0;
  190066. }
  190067. }
  190068. if (done)
  190069. break;
  190070. }
  190071. /* swap the palette around, and set up a table, if necessary */
  190072. if (full_dither)
  190073. {
  190074. int j = num_palette;
  190075. /* put all the useful colors within the max, but don't
  190076. move the others */
  190077. for (i = 0; i < maximum_colors; i++)
  190078. {
  190079. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190080. {
  190081. do
  190082. j--;
  190083. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190084. palette[i] = palette[j];
  190085. }
  190086. }
  190087. }
  190088. else
  190089. {
  190090. int j = num_palette;
  190091. /* move all the used colors inside the max limit, and
  190092. develop a translation table */
  190093. for (i = 0; i < maximum_colors; i++)
  190094. {
  190095. /* only move the colors we need to */
  190096. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190097. {
  190098. png_color tmp_color;
  190099. do
  190100. j--;
  190101. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190102. tmp_color = palette[j];
  190103. palette[j] = palette[i];
  190104. palette[i] = tmp_color;
  190105. /* indicate where the color went */
  190106. png_ptr->dither_index[j] = (png_byte)i;
  190107. png_ptr->dither_index[i] = (png_byte)j;
  190108. }
  190109. }
  190110. /* find closest color for those colors we are not using */
  190111. for (i = 0; i < num_palette; i++)
  190112. {
  190113. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190114. {
  190115. int min_d, k, min_k, d_index;
  190116. /* find the closest color to one we threw out */
  190117. d_index = png_ptr->dither_index[i];
  190118. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190119. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190120. {
  190121. int d;
  190122. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190123. if (d < min_d)
  190124. {
  190125. min_d = d;
  190126. min_k = k;
  190127. }
  190128. }
  190129. /* point to closest color */
  190130. png_ptr->dither_index[i] = (png_byte)min_k;
  190131. }
  190132. }
  190133. }
  190134. png_free(png_ptr, png_ptr->dither_sort);
  190135. png_ptr->dither_sort=NULL;
  190136. }
  190137. else
  190138. {
  190139. /* This is much harder to do simply (and quickly). Perhaps
  190140. we need to go through a median cut routine, but those
  190141. don't always behave themselves with only a few colors
  190142. as input. So we will just find the closest two colors,
  190143. and throw out one of them (chosen somewhat randomly).
  190144. [We don't understand this at all, so if someone wants to
  190145. work on improving it, be our guest - AED, GRP]
  190146. */
  190147. int i;
  190148. int max_d;
  190149. int num_new_palette;
  190150. png_dsortp t;
  190151. png_dsortpp hash;
  190152. t=NULL;
  190153. /* initialize palette index arrays */
  190154. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190155. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190156. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190157. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190158. /* initialize the sort array */
  190159. for (i = 0; i < num_palette; i++)
  190160. {
  190161. png_ptr->index_to_palette[i] = (png_byte)i;
  190162. png_ptr->palette_to_index[i] = (png_byte)i;
  190163. }
  190164. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190165. png_sizeof (png_dsortp)));
  190166. for (i = 0; i < 769; i++)
  190167. hash[i] = NULL;
  190168. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190169. num_new_palette = num_palette;
  190170. /* initial wild guess at how far apart the farthest pixel
  190171. pair we will be eliminating will be. Larger
  190172. numbers mean more areas will be allocated, Smaller
  190173. numbers run the risk of not saving enough data, and
  190174. having to do this all over again.
  190175. I have not done extensive checking on this number.
  190176. */
  190177. max_d = 96;
  190178. while (num_new_palette > maximum_colors)
  190179. {
  190180. for (i = 0; i < num_new_palette - 1; i++)
  190181. {
  190182. int j;
  190183. for (j = i + 1; j < num_new_palette; j++)
  190184. {
  190185. int d;
  190186. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190187. if (d <= max_d)
  190188. {
  190189. t = (png_dsortp)png_malloc_warn(png_ptr,
  190190. (png_uint_32)(png_sizeof(png_dsort)));
  190191. if (t == NULL)
  190192. break;
  190193. t->next = hash[d];
  190194. t->left = (png_byte)i;
  190195. t->right = (png_byte)j;
  190196. hash[d] = t;
  190197. }
  190198. }
  190199. if (t == NULL)
  190200. break;
  190201. }
  190202. if (t != NULL)
  190203. for (i = 0; i <= max_d; i++)
  190204. {
  190205. if (hash[i] != NULL)
  190206. {
  190207. png_dsortp p;
  190208. for (p = hash[i]; p; p = p->next)
  190209. {
  190210. if ((int)png_ptr->index_to_palette[p->left]
  190211. < num_new_palette &&
  190212. (int)png_ptr->index_to_palette[p->right]
  190213. < num_new_palette)
  190214. {
  190215. int j, next_j;
  190216. if (num_new_palette & 0x01)
  190217. {
  190218. j = p->left;
  190219. next_j = p->right;
  190220. }
  190221. else
  190222. {
  190223. j = p->right;
  190224. next_j = p->left;
  190225. }
  190226. num_new_palette--;
  190227. palette[png_ptr->index_to_palette[j]]
  190228. = palette[num_new_palette];
  190229. if (!full_dither)
  190230. {
  190231. int k;
  190232. for (k = 0; k < num_palette; k++)
  190233. {
  190234. if (png_ptr->dither_index[k] ==
  190235. png_ptr->index_to_palette[j])
  190236. png_ptr->dither_index[k] =
  190237. png_ptr->index_to_palette[next_j];
  190238. if ((int)png_ptr->dither_index[k] ==
  190239. num_new_palette)
  190240. png_ptr->dither_index[k] =
  190241. png_ptr->index_to_palette[j];
  190242. }
  190243. }
  190244. png_ptr->index_to_palette[png_ptr->palette_to_index
  190245. [num_new_palette]] = png_ptr->index_to_palette[j];
  190246. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190247. = png_ptr->palette_to_index[num_new_palette];
  190248. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190249. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190250. }
  190251. if (num_new_palette <= maximum_colors)
  190252. break;
  190253. }
  190254. if (num_new_palette <= maximum_colors)
  190255. break;
  190256. }
  190257. }
  190258. for (i = 0; i < 769; i++)
  190259. {
  190260. if (hash[i] != NULL)
  190261. {
  190262. png_dsortp p = hash[i];
  190263. while (p)
  190264. {
  190265. t = p->next;
  190266. png_free(png_ptr, p);
  190267. p = t;
  190268. }
  190269. }
  190270. hash[i] = 0;
  190271. }
  190272. max_d += 96;
  190273. }
  190274. png_free(png_ptr, hash);
  190275. png_free(png_ptr, png_ptr->palette_to_index);
  190276. png_free(png_ptr, png_ptr->index_to_palette);
  190277. png_ptr->palette_to_index=NULL;
  190278. png_ptr->index_to_palette=NULL;
  190279. }
  190280. num_palette = maximum_colors;
  190281. }
  190282. if (png_ptr->palette == NULL)
  190283. {
  190284. png_ptr->palette = palette;
  190285. }
  190286. png_ptr->num_palette = (png_uint_16)num_palette;
  190287. if (full_dither)
  190288. {
  190289. int i;
  190290. png_bytep distance;
  190291. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190292. PNG_DITHER_BLUE_BITS;
  190293. int num_red = (1 << PNG_DITHER_RED_BITS);
  190294. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190295. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190296. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190297. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190298. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190299. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190300. png_sizeof (png_byte));
  190301. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190302. png_sizeof(png_byte)));
  190303. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190304. for (i = 0; i < num_palette; i++)
  190305. {
  190306. int ir, ig, ib;
  190307. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190308. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190309. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190310. for (ir = 0; ir < num_red; ir++)
  190311. {
  190312. /* int dr = abs(ir - r); */
  190313. int dr = ((ir > r) ? ir - r : r - ir);
  190314. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190315. for (ig = 0; ig < num_green; ig++)
  190316. {
  190317. /* int dg = abs(ig - g); */
  190318. int dg = ((ig > g) ? ig - g : g - ig);
  190319. int dt = dr + dg;
  190320. int dm = ((dr > dg) ? dr : dg);
  190321. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190322. for (ib = 0; ib < num_blue; ib++)
  190323. {
  190324. int d_index = index_g | ib;
  190325. /* int db = abs(ib - b); */
  190326. int db = ((ib > b) ? ib - b : b - ib);
  190327. int dmax = ((dm > db) ? dm : db);
  190328. int d = dmax + dt + db;
  190329. if (d < (int)distance[d_index])
  190330. {
  190331. distance[d_index] = (png_byte)d;
  190332. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190333. }
  190334. }
  190335. }
  190336. }
  190337. }
  190338. png_free(png_ptr, distance);
  190339. }
  190340. }
  190341. #endif
  190342. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190343. /* Transform the image from the file_gamma to the screen_gamma. We
  190344. * only do transformations on images where the file_gamma and screen_gamma
  190345. * are not close reciprocals, otherwise it slows things down slightly, and
  190346. * also needlessly introduces small errors.
  190347. *
  190348. * We will turn off gamma transformation later if no semitransparent entries
  190349. * are present in the tRNS array for palette images. We can't do it here
  190350. * because we don't necessarily have the tRNS chunk yet.
  190351. */
  190352. void PNGAPI
  190353. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190354. {
  190355. png_debug(1, "in png_set_gamma\n");
  190356. if(png_ptr == NULL) return;
  190357. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190358. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190359. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190360. png_ptr->transformations |= PNG_GAMMA;
  190361. png_ptr->gamma = (float)file_gamma;
  190362. png_ptr->screen_gamma = (float)scrn_gamma;
  190363. }
  190364. #endif
  190365. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190366. /* Expand paletted images to RGB, expand grayscale images of
  190367. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190368. * to alpha channels.
  190369. */
  190370. void PNGAPI
  190371. png_set_expand(png_structp png_ptr)
  190372. {
  190373. png_debug(1, "in png_set_expand\n");
  190374. if(png_ptr == NULL) return;
  190375. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190376. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190377. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190378. #endif
  190379. }
  190380. /* GRR 19990627: the following three functions currently are identical
  190381. * to png_set_expand(). However, it is entirely reasonable that someone
  190382. * might wish to expand an indexed image to RGB but *not* expand a single,
  190383. * fully transparent palette entry to a full alpha channel--perhaps instead
  190384. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190385. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190386. * IOW, a future version of the library may make the transformations flag
  190387. * a bit more fine-grained, with separate bits for each of these three
  190388. * functions.
  190389. *
  190390. * More to the point, these functions make it obvious what libpng will be
  190391. * doing, whereas "expand" can (and does) mean any number of things.
  190392. *
  190393. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190394. * to expand only the sample depth but not to expand the tRNS to alpha.
  190395. */
  190396. /* Expand paletted images to RGB. */
  190397. void PNGAPI
  190398. png_set_palette_to_rgb(png_structp png_ptr)
  190399. {
  190400. png_debug(1, "in png_set_palette_to_rgb\n");
  190401. if(png_ptr == NULL) return;
  190402. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190403. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190404. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190405. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190406. #endif
  190407. }
  190408. #if !defined(PNG_1_0_X)
  190409. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190410. void PNGAPI
  190411. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190412. {
  190413. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190414. if(png_ptr == NULL) return;
  190415. png_ptr->transformations |= PNG_EXPAND;
  190416. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190417. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190418. #endif
  190419. }
  190420. #endif
  190421. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190422. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190423. /* Deprecated as of libpng-1.2.9 */
  190424. void PNGAPI
  190425. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190426. {
  190427. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190428. if(png_ptr == NULL) return;
  190429. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190430. }
  190431. #endif
  190432. /* Expand tRNS chunks to alpha channels. */
  190433. void PNGAPI
  190434. png_set_tRNS_to_alpha(png_structp png_ptr)
  190435. {
  190436. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190437. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190438. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190439. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190440. #endif
  190441. }
  190442. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190443. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190444. void PNGAPI
  190445. png_set_gray_to_rgb(png_structp png_ptr)
  190446. {
  190447. png_debug(1, "in png_set_gray_to_rgb\n");
  190448. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190449. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190450. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190451. #endif
  190452. }
  190453. #endif
  190454. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190455. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190456. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190457. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190458. */
  190459. void PNGAPI
  190460. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190461. double green)
  190462. {
  190463. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190464. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190465. if(png_ptr == NULL) return;
  190466. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190467. }
  190468. #endif
  190469. void PNGAPI
  190470. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190471. png_fixed_point red, png_fixed_point green)
  190472. {
  190473. png_debug(1, "in png_set_rgb_to_gray\n");
  190474. if(png_ptr == NULL) return;
  190475. switch(error_action)
  190476. {
  190477. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190478. break;
  190479. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190480. break;
  190481. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190482. }
  190483. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190484. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190485. png_ptr->transformations |= PNG_EXPAND;
  190486. #else
  190487. {
  190488. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190489. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190490. }
  190491. #endif
  190492. {
  190493. png_uint_16 red_int, green_int;
  190494. if(red < 0 || green < 0)
  190495. {
  190496. red_int = 6968; /* .212671 * 32768 + .5 */
  190497. green_int = 23434; /* .715160 * 32768 + .5 */
  190498. }
  190499. else if(red + green < 100000L)
  190500. {
  190501. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190502. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190503. }
  190504. else
  190505. {
  190506. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190507. red_int = 6968;
  190508. green_int = 23434;
  190509. }
  190510. png_ptr->rgb_to_gray_red_coeff = red_int;
  190511. png_ptr->rgb_to_gray_green_coeff = green_int;
  190512. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190513. }
  190514. }
  190515. #endif
  190516. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190517. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190518. defined(PNG_LEGACY_SUPPORTED)
  190519. void PNGAPI
  190520. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190521. read_user_transform_fn)
  190522. {
  190523. png_debug(1, "in png_set_read_user_transform_fn\n");
  190524. if(png_ptr == NULL) return;
  190525. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190526. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190527. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190528. #endif
  190529. #ifdef PNG_LEGACY_SUPPORTED
  190530. if(read_user_transform_fn)
  190531. png_warning(png_ptr,
  190532. "This version of libpng does not support user transforms");
  190533. #endif
  190534. }
  190535. #endif
  190536. /* Initialize everything needed for the read. This includes modifying
  190537. * the palette.
  190538. */
  190539. void /* PRIVATE */
  190540. png_init_read_transformations(png_structp png_ptr)
  190541. {
  190542. png_debug(1, "in png_init_read_transformations\n");
  190543. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190544. if(png_ptr != NULL)
  190545. #endif
  190546. {
  190547. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190548. || defined(PNG_READ_GAMMA_SUPPORTED)
  190549. int color_type = png_ptr->color_type;
  190550. #endif
  190551. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190552. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190553. /* Detect gray background and attempt to enable optimization
  190554. * for gray --> RGB case */
  190555. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190556. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190557. * background color might actually be gray yet not be flagged as such.
  190558. * This is not a problem for the current code, which uses
  190559. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190560. * png_do_gray_to_rgb() transformation.
  190561. */
  190562. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190563. !(color_type & PNG_COLOR_MASK_COLOR))
  190564. {
  190565. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190566. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190567. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190568. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190569. png_ptr->background.red == png_ptr->background.green &&
  190570. png_ptr->background.red == png_ptr->background.blue)
  190571. {
  190572. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190573. png_ptr->background.gray = png_ptr->background.red;
  190574. }
  190575. #endif
  190576. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190577. (png_ptr->transformations & PNG_EXPAND))
  190578. {
  190579. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190580. {
  190581. /* expand background and tRNS chunks */
  190582. switch (png_ptr->bit_depth)
  190583. {
  190584. case 1:
  190585. png_ptr->background.gray *= (png_uint_16)0xff;
  190586. png_ptr->background.red = png_ptr->background.green
  190587. = png_ptr->background.blue = png_ptr->background.gray;
  190588. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190589. {
  190590. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190591. png_ptr->trans_values.red = png_ptr->trans_values.green
  190592. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190593. }
  190594. break;
  190595. case 2:
  190596. png_ptr->background.gray *= (png_uint_16)0x55;
  190597. png_ptr->background.red = png_ptr->background.green
  190598. = png_ptr->background.blue = png_ptr->background.gray;
  190599. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190600. {
  190601. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190602. png_ptr->trans_values.red = png_ptr->trans_values.green
  190603. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190604. }
  190605. break;
  190606. case 4:
  190607. png_ptr->background.gray *= (png_uint_16)0x11;
  190608. png_ptr->background.red = png_ptr->background.green
  190609. = png_ptr->background.blue = png_ptr->background.gray;
  190610. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190611. {
  190612. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190613. png_ptr->trans_values.red = png_ptr->trans_values.green
  190614. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190615. }
  190616. break;
  190617. case 8:
  190618. case 16:
  190619. png_ptr->background.red = png_ptr->background.green
  190620. = png_ptr->background.blue = png_ptr->background.gray;
  190621. break;
  190622. }
  190623. }
  190624. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190625. {
  190626. png_ptr->background.red =
  190627. png_ptr->palette[png_ptr->background.index].red;
  190628. png_ptr->background.green =
  190629. png_ptr->palette[png_ptr->background.index].green;
  190630. png_ptr->background.blue =
  190631. png_ptr->palette[png_ptr->background.index].blue;
  190632. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190633. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190634. {
  190635. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190636. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190637. #endif
  190638. {
  190639. /* invert the alpha channel (in tRNS) unless the pixels are
  190640. going to be expanded, in which case leave it for later */
  190641. int i,istop;
  190642. istop=(int)png_ptr->num_trans;
  190643. for (i=0; i<istop; i++)
  190644. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190645. }
  190646. }
  190647. #endif
  190648. }
  190649. }
  190650. #endif
  190651. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190652. png_ptr->background_1 = png_ptr->background;
  190653. #endif
  190654. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190655. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190656. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190657. < PNG_GAMMA_THRESHOLD))
  190658. {
  190659. int i,k;
  190660. k=0;
  190661. for (i=0; i<png_ptr->num_trans; i++)
  190662. {
  190663. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190664. k=1; /* partial transparency is present */
  190665. }
  190666. if (k == 0)
  190667. png_ptr->transformations &= (~PNG_GAMMA);
  190668. }
  190669. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190670. png_ptr->gamma != 0.0)
  190671. {
  190672. png_build_gamma_table(png_ptr);
  190673. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190674. if (png_ptr->transformations & PNG_BACKGROUND)
  190675. {
  190676. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190677. {
  190678. /* could skip if no transparency and
  190679. */
  190680. png_color back, back_1;
  190681. png_colorp palette = png_ptr->palette;
  190682. int num_palette = png_ptr->num_palette;
  190683. int i;
  190684. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190685. {
  190686. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190687. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190688. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190689. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190690. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190691. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190692. }
  190693. else
  190694. {
  190695. double g, gs;
  190696. switch (png_ptr->background_gamma_type)
  190697. {
  190698. case PNG_BACKGROUND_GAMMA_SCREEN:
  190699. g = (png_ptr->screen_gamma);
  190700. gs = 1.0;
  190701. break;
  190702. case PNG_BACKGROUND_GAMMA_FILE:
  190703. g = 1.0 / (png_ptr->gamma);
  190704. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190705. break;
  190706. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190707. g = 1.0 / (png_ptr->background_gamma);
  190708. gs = 1.0 / (png_ptr->background_gamma *
  190709. png_ptr->screen_gamma);
  190710. break;
  190711. default:
  190712. g = 1.0; /* back_1 */
  190713. gs = 1.0; /* back */
  190714. }
  190715. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190716. {
  190717. back.red = (png_byte)png_ptr->background.red;
  190718. back.green = (png_byte)png_ptr->background.green;
  190719. back.blue = (png_byte)png_ptr->background.blue;
  190720. }
  190721. else
  190722. {
  190723. back.red = (png_byte)(pow(
  190724. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190725. back.green = (png_byte)(pow(
  190726. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190727. back.blue = (png_byte)(pow(
  190728. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190729. }
  190730. back_1.red = (png_byte)(pow(
  190731. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190732. back_1.green = (png_byte)(pow(
  190733. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190734. back_1.blue = (png_byte)(pow(
  190735. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190736. }
  190737. for (i = 0; i < num_palette; i++)
  190738. {
  190739. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190740. {
  190741. if (png_ptr->trans[i] == 0)
  190742. {
  190743. palette[i] = back;
  190744. }
  190745. else /* if (png_ptr->trans[i] != 0xff) */
  190746. {
  190747. png_byte v, w;
  190748. v = png_ptr->gamma_to_1[palette[i].red];
  190749. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190750. palette[i].red = png_ptr->gamma_from_1[w];
  190751. v = png_ptr->gamma_to_1[palette[i].green];
  190752. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190753. palette[i].green = png_ptr->gamma_from_1[w];
  190754. v = png_ptr->gamma_to_1[palette[i].blue];
  190755. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190756. palette[i].blue = png_ptr->gamma_from_1[w];
  190757. }
  190758. }
  190759. else
  190760. {
  190761. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190762. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190763. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190764. }
  190765. }
  190766. }
  190767. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190768. else
  190769. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190770. {
  190771. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190772. double g = 1.0;
  190773. double gs = 1.0;
  190774. switch (png_ptr->background_gamma_type)
  190775. {
  190776. case PNG_BACKGROUND_GAMMA_SCREEN:
  190777. g = (png_ptr->screen_gamma);
  190778. gs = 1.0;
  190779. break;
  190780. case PNG_BACKGROUND_GAMMA_FILE:
  190781. g = 1.0 / (png_ptr->gamma);
  190782. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190783. break;
  190784. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190785. g = 1.0 / (png_ptr->background_gamma);
  190786. gs = 1.0 / (png_ptr->background_gamma *
  190787. png_ptr->screen_gamma);
  190788. break;
  190789. }
  190790. png_ptr->background_1.gray = (png_uint_16)(pow(
  190791. (double)png_ptr->background.gray / m, g) * m + .5);
  190792. png_ptr->background.gray = (png_uint_16)(pow(
  190793. (double)png_ptr->background.gray / m, gs) * m + .5);
  190794. if ((png_ptr->background.red != png_ptr->background.green) ||
  190795. (png_ptr->background.red != png_ptr->background.blue) ||
  190796. (png_ptr->background.red != png_ptr->background.gray))
  190797. {
  190798. /* RGB or RGBA with color background */
  190799. png_ptr->background_1.red = (png_uint_16)(pow(
  190800. (double)png_ptr->background.red / m, g) * m + .5);
  190801. png_ptr->background_1.green = (png_uint_16)(pow(
  190802. (double)png_ptr->background.green / m, g) * m + .5);
  190803. png_ptr->background_1.blue = (png_uint_16)(pow(
  190804. (double)png_ptr->background.blue / m, g) * m + .5);
  190805. png_ptr->background.red = (png_uint_16)(pow(
  190806. (double)png_ptr->background.red / m, gs) * m + .5);
  190807. png_ptr->background.green = (png_uint_16)(pow(
  190808. (double)png_ptr->background.green / m, gs) * m + .5);
  190809. png_ptr->background.blue = (png_uint_16)(pow(
  190810. (double)png_ptr->background.blue / m, gs) * m + .5);
  190811. }
  190812. else
  190813. {
  190814. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190815. png_ptr->background_1.red = png_ptr->background_1.green
  190816. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190817. png_ptr->background.red = png_ptr->background.green
  190818. = png_ptr->background.blue = png_ptr->background.gray;
  190819. }
  190820. }
  190821. }
  190822. else
  190823. /* transformation does not include PNG_BACKGROUND */
  190824. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190825. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190826. {
  190827. png_colorp palette = png_ptr->palette;
  190828. int num_palette = png_ptr->num_palette;
  190829. int i;
  190830. for (i = 0; i < num_palette; i++)
  190831. {
  190832. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190833. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190834. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190835. }
  190836. }
  190837. }
  190838. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190839. else
  190840. #endif
  190841. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190842. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190843. /* No GAMMA transformation */
  190844. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190845. (color_type == PNG_COLOR_TYPE_PALETTE))
  190846. {
  190847. int i;
  190848. int istop = (int)png_ptr->num_trans;
  190849. png_color back;
  190850. png_colorp palette = png_ptr->palette;
  190851. back.red = (png_byte)png_ptr->background.red;
  190852. back.green = (png_byte)png_ptr->background.green;
  190853. back.blue = (png_byte)png_ptr->background.blue;
  190854. for (i = 0; i < istop; i++)
  190855. {
  190856. if (png_ptr->trans[i] == 0)
  190857. {
  190858. palette[i] = back;
  190859. }
  190860. else if (png_ptr->trans[i] != 0xff)
  190861. {
  190862. /* The png_composite() macro is defined in png.h */
  190863. png_composite(palette[i].red, palette[i].red,
  190864. png_ptr->trans[i], back.red);
  190865. png_composite(palette[i].green, palette[i].green,
  190866. png_ptr->trans[i], back.green);
  190867. png_composite(palette[i].blue, palette[i].blue,
  190868. png_ptr->trans[i], back.blue);
  190869. }
  190870. }
  190871. }
  190872. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190873. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190874. if ((png_ptr->transformations & PNG_SHIFT) &&
  190875. (color_type == PNG_COLOR_TYPE_PALETTE))
  190876. {
  190877. png_uint_16 i;
  190878. png_uint_16 istop = png_ptr->num_palette;
  190879. int sr = 8 - png_ptr->sig_bit.red;
  190880. int sg = 8 - png_ptr->sig_bit.green;
  190881. int sb = 8 - png_ptr->sig_bit.blue;
  190882. if (sr < 0 || sr > 8)
  190883. sr = 0;
  190884. if (sg < 0 || sg > 8)
  190885. sg = 0;
  190886. if (sb < 0 || sb > 8)
  190887. sb = 0;
  190888. for (i = 0; i < istop; i++)
  190889. {
  190890. png_ptr->palette[i].red >>= sr;
  190891. png_ptr->palette[i].green >>= sg;
  190892. png_ptr->palette[i].blue >>= sb;
  190893. }
  190894. }
  190895. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190896. }
  190897. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190898. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190899. if(png_ptr)
  190900. return;
  190901. #endif
  190902. }
  190903. /* Modify the info structure to reflect the transformations. The
  190904. * info should be updated so a PNG file could be written with it,
  190905. * assuming the transformations result in valid PNG data.
  190906. */
  190907. void /* PRIVATE */
  190908. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190909. {
  190910. png_debug(1, "in png_read_transform_info\n");
  190911. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190912. if (png_ptr->transformations & PNG_EXPAND)
  190913. {
  190914. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190915. {
  190916. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190917. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190918. else
  190919. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190920. info_ptr->bit_depth = 8;
  190921. info_ptr->num_trans = 0;
  190922. }
  190923. else
  190924. {
  190925. if (png_ptr->num_trans)
  190926. {
  190927. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190928. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190929. else
  190930. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190931. }
  190932. if (info_ptr->bit_depth < 8)
  190933. info_ptr->bit_depth = 8;
  190934. info_ptr->num_trans = 0;
  190935. }
  190936. }
  190937. #endif
  190938. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190939. if (png_ptr->transformations & PNG_BACKGROUND)
  190940. {
  190941. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190942. info_ptr->num_trans = 0;
  190943. info_ptr->background = png_ptr->background;
  190944. }
  190945. #endif
  190946. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190947. if (png_ptr->transformations & PNG_GAMMA)
  190948. {
  190949. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190950. info_ptr->gamma = png_ptr->gamma;
  190951. #endif
  190952. #ifdef PNG_FIXED_POINT_SUPPORTED
  190953. info_ptr->int_gamma = png_ptr->int_gamma;
  190954. #endif
  190955. }
  190956. #endif
  190957. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190958. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190959. info_ptr->bit_depth = 8;
  190960. #endif
  190961. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190962. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190963. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190964. #endif
  190965. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190966. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190967. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190968. #endif
  190969. #if defined(PNG_READ_DITHER_SUPPORTED)
  190970. if (png_ptr->transformations & PNG_DITHER)
  190971. {
  190972. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190973. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190974. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190975. {
  190976. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190977. }
  190978. }
  190979. #endif
  190980. #if defined(PNG_READ_PACK_SUPPORTED)
  190981. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190982. info_ptr->bit_depth = 8;
  190983. #endif
  190984. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190985. info_ptr->channels = 1;
  190986. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190987. info_ptr->channels = 3;
  190988. else
  190989. info_ptr->channels = 1;
  190990. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190991. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190992. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190993. #endif
  190994. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190995. info_ptr->channels++;
  190996. #if defined(PNG_READ_FILLER_SUPPORTED)
  190997. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190998. if ((png_ptr->transformations & PNG_FILLER) &&
  190999. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191000. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191001. {
  191002. info_ptr->channels++;
  191003. /* if adding a true alpha channel not just filler */
  191004. #if !defined(PNG_1_0_X)
  191005. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191006. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191007. #endif
  191008. }
  191009. #endif
  191010. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191011. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191012. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191013. {
  191014. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191015. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191016. if(info_ptr->channels < png_ptr->user_transform_channels)
  191017. info_ptr->channels = png_ptr->user_transform_channels;
  191018. }
  191019. #endif
  191020. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191021. info_ptr->bit_depth);
  191022. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191023. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191024. if(png_ptr)
  191025. return;
  191026. #endif
  191027. }
  191028. /* Transform the row. The order of transformations is significant,
  191029. * and is very touchy. If you add a transformation, take care to
  191030. * decide how it fits in with the other transformations here.
  191031. */
  191032. void /* PRIVATE */
  191033. png_do_read_transformations(png_structp png_ptr)
  191034. {
  191035. png_debug(1, "in png_do_read_transformations\n");
  191036. if (png_ptr->row_buf == NULL)
  191037. {
  191038. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191039. char msg[50];
  191040. png_snprintf2(msg, 50,
  191041. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191042. png_ptr->pass);
  191043. png_error(png_ptr, msg);
  191044. #else
  191045. png_error(png_ptr, "NULL row buffer");
  191046. #endif
  191047. }
  191048. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191049. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191050. /* Application has failed to call either png_read_start_image()
  191051. * or png_read_update_info() after setting transforms that expand
  191052. * pixels. This check added to libpng-1.2.19 */
  191053. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191054. png_error(png_ptr, "Uninitialized row");
  191055. #else
  191056. png_warning(png_ptr, "Uninitialized row");
  191057. #endif
  191058. #endif
  191059. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191060. if (png_ptr->transformations & PNG_EXPAND)
  191061. {
  191062. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191063. {
  191064. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191065. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191066. }
  191067. else
  191068. {
  191069. if (png_ptr->num_trans &&
  191070. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191071. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191072. &(png_ptr->trans_values));
  191073. else
  191074. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191075. NULL);
  191076. }
  191077. }
  191078. #endif
  191079. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191080. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191081. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191082. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191083. #endif
  191084. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191085. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191086. {
  191087. int rgb_error =
  191088. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191089. if(rgb_error)
  191090. {
  191091. png_ptr->rgb_to_gray_status=1;
  191092. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191093. PNG_RGB_TO_GRAY_WARN)
  191094. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191095. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191096. PNG_RGB_TO_GRAY_ERR)
  191097. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191098. }
  191099. }
  191100. #endif
  191101. /*
  191102. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191103. In most cases, the "simple transparency" should be done prior to doing
  191104. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191105. pixel is transparent. You would also need to make sure that the
  191106. transparency information is upgraded to RGB.
  191107. To summarize, the current flow is:
  191108. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191109. with background "in place" if transparent,
  191110. convert to RGB if necessary
  191111. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191112. convert to RGB if necessary
  191113. To support RGB backgrounds for gray images we need:
  191114. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191115. 3 or 6 bytes and composite with background
  191116. "in place" if transparent (3x compare/pixel
  191117. compared to doing composite with gray bkgrnd)
  191118. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191119. remove alpha bytes (3x float operations/pixel
  191120. compared with composite on gray background)
  191121. Greg's change will do this. The reason it wasn't done before is for
  191122. performance, as this increases the per-pixel operations. If we would check
  191123. in advance if the background was gray or RGB, and position the gray-to-RGB
  191124. transform appropriately, then it would save a lot of work/time.
  191125. */
  191126. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191127. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191128. * for performance reasons */
  191129. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191130. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191131. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191132. #endif
  191133. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191134. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191135. ((png_ptr->num_trans != 0 ) ||
  191136. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191137. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191138. &(png_ptr->trans_values), &(png_ptr->background)
  191139. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191140. , &(png_ptr->background_1),
  191141. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191142. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191143. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191144. png_ptr->gamma_shift
  191145. #endif
  191146. );
  191147. #endif
  191148. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191149. if ((png_ptr->transformations & PNG_GAMMA) &&
  191150. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191151. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191152. ((png_ptr->num_trans != 0) ||
  191153. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191154. #endif
  191155. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191156. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191157. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191158. png_ptr->gamma_shift);
  191159. #endif
  191160. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191161. if (png_ptr->transformations & PNG_16_TO_8)
  191162. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191163. #endif
  191164. #if defined(PNG_READ_DITHER_SUPPORTED)
  191165. if (png_ptr->transformations & PNG_DITHER)
  191166. {
  191167. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191168. png_ptr->palette_lookup, png_ptr->dither_index);
  191169. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191170. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191171. }
  191172. #endif
  191173. #if defined(PNG_READ_INVERT_SUPPORTED)
  191174. if (png_ptr->transformations & PNG_INVERT_MONO)
  191175. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191176. #endif
  191177. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191178. if (png_ptr->transformations & PNG_SHIFT)
  191179. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191180. &(png_ptr->shift));
  191181. #endif
  191182. #if defined(PNG_READ_PACK_SUPPORTED)
  191183. if (png_ptr->transformations & PNG_PACK)
  191184. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191185. #endif
  191186. #if defined(PNG_READ_BGR_SUPPORTED)
  191187. if (png_ptr->transformations & PNG_BGR)
  191188. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191189. #endif
  191190. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191191. if (png_ptr->transformations & PNG_PACKSWAP)
  191192. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191193. #endif
  191194. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191195. /* if gray -> RGB, do so now only if we did not do so above */
  191196. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191197. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191198. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191199. #endif
  191200. #if defined(PNG_READ_FILLER_SUPPORTED)
  191201. if (png_ptr->transformations & PNG_FILLER)
  191202. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191203. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191204. #endif
  191205. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191206. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191207. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191208. #endif
  191209. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191210. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191211. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191212. #endif
  191213. #if defined(PNG_READ_SWAP_SUPPORTED)
  191214. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191215. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191216. #endif
  191217. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191218. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191219. {
  191220. if(png_ptr->read_user_transform_fn != NULL)
  191221. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191222. (png_ptr, /* png_ptr */
  191223. &(png_ptr->row_info), /* row_info: */
  191224. /* png_uint_32 width; width of row */
  191225. /* png_uint_32 rowbytes; number of bytes in row */
  191226. /* png_byte color_type; color type of pixels */
  191227. /* png_byte bit_depth; bit depth of samples */
  191228. /* png_byte channels; number of channels (1-4) */
  191229. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191230. png_ptr->row_buf + 1); /* start of pixel data for row */
  191231. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191232. if(png_ptr->user_transform_depth)
  191233. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191234. if(png_ptr->user_transform_channels)
  191235. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191236. #endif
  191237. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191238. png_ptr->row_info.channels);
  191239. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191240. png_ptr->row_info.width);
  191241. }
  191242. #endif
  191243. }
  191244. #if defined(PNG_READ_PACK_SUPPORTED)
  191245. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191246. * without changing the actual values. Thus, if you had a row with
  191247. * a bit depth of 1, you would end up with bytes that only contained
  191248. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191249. * png_do_shift() after this.
  191250. */
  191251. void /* PRIVATE */
  191252. png_do_unpack(png_row_infop row_info, png_bytep row)
  191253. {
  191254. png_debug(1, "in png_do_unpack\n");
  191255. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191256. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191257. #else
  191258. if (row_info->bit_depth < 8)
  191259. #endif
  191260. {
  191261. png_uint_32 i;
  191262. png_uint_32 row_width=row_info->width;
  191263. switch (row_info->bit_depth)
  191264. {
  191265. case 1:
  191266. {
  191267. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191268. png_bytep dp = row + (png_size_t)row_width - 1;
  191269. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191270. for (i = 0; i < row_width; i++)
  191271. {
  191272. *dp = (png_byte)((*sp >> shift) & 0x01);
  191273. if (shift == 7)
  191274. {
  191275. shift = 0;
  191276. sp--;
  191277. }
  191278. else
  191279. shift++;
  191280. dp--;
  191281. }
  191282. break;
  191283. }
  191284. case 2:
  191285. {
  191286. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191287. png_bytep dp = row + (png_size_t)row_width - 1;
  191288. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191289. for (i = 0; i < row_width; i++)
  191290. {
  191291. *dp = (png_byte)((*sp >> shift) & 0x03);
  191292. if (shift == 6)
  191293. {
  191294. shift = 0;
  191295. sp--;
  191296. }
  191297. else
  191298. shift += 2;
  191299. dp--;
  191300. }
  191301. break;
  191302. }
  191303. case 4:
  191304. {
  191305. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191306. png_bytep dp = row + (png_size_t)row_width - 1;
  191307. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191308. for (i = 0; i < row_width; i++)
  191309. {
  191310. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191311. if (shift == 4)
  191312. {
  191313. shift = 0;
  191314. sp--;
  191315. }
  191316. else
  191317. shift = 4;
  191318. dp--;
  191319. }
  191320. break;
  191321. }
  191322. }
  191323. row_info->bit_depth = 8;
  191324. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191325. row_info->rowbytes = row_width * row_info->channels;
  191326. }
  191327. }
  191328. #endif
  191329. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191330. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191331. * pixels back to their significant bits values. Thus, if you have
  191332. * a row of bit depth 8, but only 5 are significant, this will shift
  191333. * the values back to 0 through 31.
  191334. */
  191335. void /* PRIVATE */
  191336. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191337. {
  191338. png_debug(1, "in png_do_unshift\n");
  191339. if (
  191340. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191341. row != NULL && row_info != NULL && sig_bits != NULL &&
  191342. #endif
  191343. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191344. {
  191345. int shift[4];
  191346. int channels = 0;
  191347. int c;
  191348. png_uint_16 value = 0;
  191349. png_uint_32 row_width = row_info->width;
  191350. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191351. {
  191352. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191353. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191354. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191355. }
  191356. else
  191357. {
  191358. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191359. }
  191360. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191361. {
  191362. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191363. }
  191364. for (c = 0; c < channels; c++)
  191365. {
  191366. if (shift[c] <= 0)
  191367. shift[c] = 0;
  191368. else
  191369. value = 1;
  191370. }
  191371. if (!value)
  191372. return;
  191373. switch (row_info->bit_depth)
  191374. {
  191375. case 2:
  191376. {
  191377. png_bytep bp;
  191378. png_uint_32 i;
  191379. png_uint_32 istop = row_info->rowbytes;
  191380. for (bp = row, i = 0; i < istop; i++)
  191381. {
  191382. *bp >>= 1;
  191383. *bp++ &= 0x55;
  191384. }
  191385. break;
  191386. }
  191387. case 4:
  191388. {
  191389. png_bytep bp = row;
  191390. png_uint_32 i;
  191391. png_uint_32 istop = row_info->rowbytes;
  191392. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191393. (png_byte)((int)0xf >> shift[0]));
  191394. for (i = 0; i < istop; i++)
  191395. {
  191396. *bp >>= shift[0];
  191397. *bp++ &= mask;
  191398. }
  191399. break;
  191400. }
  191401. case 8:
  191402. {
  191403. png_bytep bp = row;
  191404. png_uint_32 i;
  191405. png_uint_32 istop = row_width * channels;
  191406. for (i = 0; i < istop; i++)
  191407. {
  191408. *bp++ >>= shift[i%channels];
  191409. }
  191410. break;
  191411. }
  191412. case 16:
  191413. {
  191414. png_bytep bp = row;
  191415. png_uint_32 i;
  191416. png_uint_32 istop = channels * row_width;
  191417. for (i = 0; i < istop; i++)
  191418. {
  191419. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191420. value >>= shift[i%channels];
  191421. *bp++ = (png_byte)(value >> 8);
  191422. *bp++ = (png_byte)(value & 0xff);
  191423. }
  191424. break;
  191425. }
  191426. }
  191427. }
  191428. }
  191429. #endif
  191430. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191431. /* chop rows of bit depth 16 down to 8 */
  191432. void /* PRIVATE */
  191433. png_do_chop(png_row_infop row_info, png_bytep row)
  191434. {
  191435. png_debug(1, "in png_do_chop\n");
  191436. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191437. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191438. #else
  191439. if (row_info->bit_depth == 16)
  191440. #endif
  191441. {
  191442. png_bytep sp = row;
  191443. png_bytep dp = row;
  191444. png_uint_32 i;
  191445. png_uint_32 istop = row_info->width * row_info->channels;
  191446. for (i = 0; i<istop; i++, sp += 2, dp++)
  191447. {
  191448. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191449. /* This does a more accurate scaling of the 16-bit color
  191450. * value, rather than a simple low-byte truncation.
  191451. *
  191452. * What the ideal calculation should be:
  191453. * *dp = (((((png_uint_32)(*sp) << 8) |
  191454. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191455. *
  191456. * GRR: no, I think this is what it really should be:
  191457. * *dp = (((((png_uint_32)(*sp) << 8) |
  191458. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191459. *
  191460. * GRR: here's the exact calculation with shifts:
  191461. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191462. * *dp = (temp - (temp >> 8)) >> 8;
  191463. *
  191464. * Approximate calculation with shift/add instead of multiply/divide:
  191465. * *dp = ((((png_uint_32)(*sp) << 8) |
  191466. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191467. *
  191468. * What we actually do to avoid extra shifting and conversion:
  191469. */
  191470. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191471. #else
  191472. /* Simply discard the low order byte */
  191473. *dp = *sp;
  191474. #endif
  191475. }
  191476. row_info->bit_depth = 8;
  191477. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191478. row_info->rowbytes = row_info->width * row_info->channels;
  191479. }
  191480. }
  191481. #endif
  191482. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191483. void /* PRIVATE */
  191484. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191485. {
  191486. png_debug(1, "in png_do_read_swap_alpha\n");
  191487. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191488. if (row != NULL && row_info != NULL)
  191489. #endif
  191490. {
  191491. png_uint_32 row_width = row_info->width;
  191492. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191493. {
  191494. /* This converts from RGBA to ARGB */
  191495. if (row_info->bit_depth == 8)
  191496. {
  191497. png_bytep sp = row + row_info->rowbytes;
  191498. png_bytep dp = sp;
  191499. png_byte save;
  191500. png_uint_32 i;
  191501. for (i = 0; i < row_width; i++)
  191502. {
  191503. save = *(--sp);
  191504. *(--dp) = *(--sp);
  191505. *(--dp) = *(--sp);
  191506. *(--dp) = *(--sp);
  191507. *(--dp) = save;
  191508. }
  191509. }
  191510. /* This converts from RRGGBBAA to AARRGGBB */
  191511. else
  191512. {
  191513. png_bytep sp = row + row_info->rowbytes;
  191514. png_bytep dp = sp;
  191515. png_byte save[2];
  191516. png_uint_32 i;
  191517. for (i = 0; i < row_width; i++)
  191518. {
  191519. save[0] = *(--sp);
  191520. save[1] = *(--sp);
  191521. *(--dp) = *(--sp);
  191522. *(--dp) = *(--sp);
  191523. *(--dp) = *(--sp);
  191524. *(--dp) = *(--sp);
  191525. *(--dp) = *(--sp);
  191526. *(--dp) = *(--sp);
  191527. *(--dp) = save[0];
  191528. *(--dp) = save[1];
  191529. }
  191530. }
  191531. }
  191532. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191533. {
  191534. /* This converts from GA to AG */
  191535. if (row_info->bit_depth == 8)
  191536. {
  191537. png_bytep sp = row + row_info->rowbytes;
  191538. png_bytep dp = sp;
  191539. png_byte save;
  191540. png_uint_32 i;
  191541. for (i = 0; i < row_width; i++)
  191542. {
  191543. save = *(--sp);
  191544. *(--dp) = *(--sp);
  191545. *(--dp) = save;
  191546. }
  191547. }
  191548. /* This converts from GGAA to AAGG */
  191549. else
  191550. {
  191551. png_bytep sp = row + row_info->rowbytes;
  191552. png_bytep dp = sp;
  191553. png_byte save[2];
  191554. png_uint_32 i;
  191555. for (i = 0; i < row_width; i++)
  191556. {
  191557. save[0] = *(--sp);
  191558. save[1] = *(--sp);
  191559. *(--dp) = *(--sp);
  191560. *(--dp) = *(--sp);
  191561. *(--dp) = save[0];
  191562. *(--dp) = save[1];
  191563. }
  191564. }
  191565. }
  191566. }
  191567. }
  191568. #endif
  191569. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191570. void /* PRIVATE */
  191571. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191572. {
  191573. png_debug(1, "in png_do_read_invert_alpha\n");
  191574. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191575. if (row != NULL && row_info != NULL)
  191576. #endif
  191577. {
  191578. png_uint_32 row_width = row_info->width;
  191579. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191580. {
  191581. /* This inverts the alpha channel in RGBA */
  191582. if (row_info->bit_depth == 8)
  191583. {
  191584. png_bytep sp = row + row_info->rowbytes;
  191585. png_bytep dp = sp;
  191586. png_uint_32 i;
  191587. for (i = 0; i < row_width; i++)
  191588. {
  191589. *(--dp) = (png_byte)(255 - *(--sp));
  191590. /* This does nothing:
  191591. *(--dp) = *(--sp);
  191592. *(--dp) = *(--sp);
  191593. *(--dp) = *(--sp);
  191594. We can replace it with:
  191595. */
  191596. sp-=3;
  191597. dp=sp;
  191598. }
  191599. }
  191600. /* This inverts the alpha channel in RRGGBBAA */
  191601. else
  191602. {
  191603. png_bytep sp = row + row_info->rowbytes;
  191604. png_bytep dp = sp;
  191605. png_uint_32 i;
  191606. for (i = 0; i < row_width; i++)
  191607. {
  191608. *(--dp) = (png_byte)(255 - *(--sp));
  191609. *(--dp) = (png_byte)(255 - *(--sp));
  191610. /* This does nothing:
  191611. *(--dp) = *(--sp);
  191612. *(--dp) = *(--sp);
  191613. *(--dp) = *(--sp);
  191614. *(--dp) = *(--sp);
  191615. *(--dp) = *(--sp);
  191616. *(--dp) = *(--sp);
  191617. We can replace it with:
  191618. */
  191619. sp-=6;
  191620. dp=sp;
  191621. }
  191622. }
  191623. }
  191624. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191625. {
  191626. /* This inverts the alpha channel in GA */
  191627. if (row_info->bit_depth == 8)
  191628. {
  191629. png_bytep sp = row + row_info->rowbytes;
  191630. png_bytep dp = sp;
  191631. png_uint_32 i;
  191632. for (i = 0; i < row_width; i++)
  191633. {
  191634. *(--dp) = (png_byte)(255 - *(--sp));
  191635. *(--dp) = *(--sp);
  191636. }
  191637. }
  191638. /* This inverts the alpha channel in GGAA */
  191639. else
  191640. {
  191641. png_bytep sp = row + row_info->rowbytes;
  191642. png_bytep dp = sp;
  191643. png_uint_32 i;
  191644. for (i = 0; i < row_width; i++)
  191645. {
  191646. *(--dp) = (png_byte)(255 - *(--sp));
  191647. *(--dp) = (png_byte)(255 - *(--sp));
  191648. /*
  191649. *(--dp) = *(--sp);
  191650. *(--dp) = *(--sp);
  191651. */
  191652. sp-=2;
  191653. dp=sp;
  191654. }
  191655. }
  191656. }
  191657. }
  191658. }
  191659. #endif
  191660. #if defined(PNG_READ_FILLER_SUPPORTED)
  191661. /* Add filler channel if we have RGB color */
  191662. void /* PRIVATE */
  191663. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191664. png_uint_32 filler, png_uint_32 flags)
  191665. {
  191666. png_uint_32 i;
  191667. png_uint_32 row_width = row_info->width;
  191668. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191669. png_byte lo_filler = (png_byte)(filler & 0xff);
  191670. png_debug(1, "in png_do_read_filler\n");
  191671. if (
  191672. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191673. row != NULL && row_info != NULL &&
  191674. #endif
  191675. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191676. {
  191677. if(row_info->bit_depth == 8)
  191678. {
  191679. /* This changes the data from G to GX */
  191680. if (flags & PNG_FLAG_FILLER_AFTER)
  191681. {
  191682. png_bytep sp = row + (png_size_t)row_width;
  191683. png_bytep dp = sp + (png_size_t)row_width;
  191684. for (i = 1; i < row_width; i++)
  191685. {
  191686. *(--dp) = lo_filler;
  191687. *(--dp) = *(--sp);
  191688. }
  191689. *(--dp) = lo_filler;
  191690. row_info->channels = 2;
  191691. row_info->pixel_depth = 16;
  191692. row_info->rowbytes = row_width * 2;
  191693. }
  191694. /* This changes the data from G to XG */
  191695. else
  191696. {
  191697. png_bytep sp = row + (png_size_t)row_width;
  191698. png_bytep dp = sp + (png_size_t)row_width;
  191699. for (i = 0; i < row_width; i++)
  191700. {
  191701. *(--dp) = *(--sp);
  191702. *(--dp) = lo_filler;
  191703. }
  191704. row_info->channels = 2;
  191705. row_info->pixel_depth = 16;
  191706. row_info->rowbytes = row_width * 2;
  191707. }
  191708. }
  191709. else if(row_info->bit_depth == 16)
  191710. {
  191711. /* This changes the data from GG to GGXX */
  191712. if (flags & PNG_FLAG_FILLER_AFTER)
  191713. {
  191714. png_bytep sp = row + (png_size_t)row_width * 2;
  191715. png_bytep dp = sp + (png_size_t)row_width * 2;
  191716. for (i = 1; i < row_width; i++)
  191717. {
  191718. *(--dp) = hi_filler;
  191719. *(--dp) = lo_filler;
  191720. *(--dp) = *(--sp);
  191721. *(--dp) = *(--sp);
  191722. }
  191723. *(--dp) = hi_filler;
  191724. *(--dp) = lo_filler;
  191725. row_info->channels = 2;
  191726. row_info->pixel_depth = 32;
  191727. row_info->rowbytes = row_width * 4;
  191728. }
  191729. /* This changes the data from GG to XXGG */
  191730. else
  191731. {
  191732. png_bytep sp = row + (png_size_t)row_width * 2;
  191733. png_bytep dp = sp + (png_size_t)row_width * 2;
  191734. for (i = 0; i < row_width; i++)
  191735. {
  191736. *(--dp) = *(--sp);
  191737. *(--dp) = *(--sp);
  191738. *(--dp) = hi_filler;
  191739. *(--dp) = lo_filler;
  191740. }
  191741. row_info->channels = 2;
  191742. row_info->pixel_depth = 32;
  191743. row_info->rowbytes = row_width * 4;
  191744. }
  191745. }
  191746. } /* COLOR_TYPE == GRAY */
  191747. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191748. {
  191749. if(row_info->bit_depth == 8)
  191750. {
  191751. /* This changes the data from RGB to RGBX */
  191752. if (flags & PNG_FLAG_FILLER_AFTER)
  191753. {
  191754. png_bytep sp = row + (png_size_t)row_width * 3;
  191755. png_bytep dp = sp + (png_size_t)row_width;
  191756. for (i = 1; i < row_width; i++)
  191757. {
  191758. *(--dp) = lo_filler;
  191759. *(--dp) = *(--sp);
  191760. *(--dp) = *(--sp);
  191761. *(--dp) = *(--sp);
  191762. }
  191763. *(--dp) = lo_filler;
  191764. row_info->channels = 4;
  191765. row_info->pixel_depth = 32;
  191766. row_info->rowbytes = row_width * 4;
  191767. }
  191768. /* This changes the data from RGB to XRGB */
  191769. else
  191770. {
  191771. png_bytep sp = row + (png_size_t)row_width * 3;
  191772. png_bytep dp = sp + (png_size_t)row_width;
  191773. for (i = 0; i < row_width; i++)
  191774. {
  191775. *(--dp) = *(--sp);
  191776. *(--dp) = *(--sp);
  191777. *(--dp) = *(--sp);
  191778. *(--dp) = lo_filler;
  191779. }
  191780. row_info->channels = 4;
  191781. row_info->pixel_depth = 32;
  191782. row_info->rowbytes = row_width * 4;
  191783. }
  191784. }
  191785. else if(row_info->bit_depth == 16)
  191786. {
  191787. /* This changes the data from RRGGBB to RRGGBBXX */
  191788. if (flags & PNG_FLAG_FILLER_AFTER)
  191789. {
  191790. png_bytep sp = row + (png_size_t)row_width * 6;
  191791. png_bytep dp = sp + (png_size_t)row_width * 2;
  191792. for (i = 1; i < row_width; i++)
  191793. {
  191794. *(--dp) = hi_filler;
  191795. *(--dp) = lo_filler;
  191796. *(--dp) = *(--sp);
  191797. *(--dp) = *(--sp);
  191798. *(--dp) = *(--sp);
  191799. *(--dp) = *(--sp);
  191800. *(--dp) = *(--sp);
  191801. *(--dp) = *(--sp);
  191802. }
  191803. *(--dp) = hi_filler;
  191804. *(--dp) = lo_filler;
  191805. row_info->channels = 4;
  191806. row_info->pixel_depth = 64;
  191807. row_info->rowbytes = row_width * 8;
  191808. }
  191809. /* This changes the data from RRGGBB to XXRRGGBB */
  191810. else
  191811. {
  191812. png_bytep sp = row + (png_size_t)row_width * 6;
  191813. png_bytep dp = sp + (png_size_t)row_width * 2;
  191814. for (i = 0; i < row_width; i++)
  191815. {
  191816. *(--dp) = *(--sp);
  191817. *(--dp) = *(--sp);
  191818. *(--dp) = *(--sp);
  191819. *(--dp) = *(--sp);
  191820. *(--dp) = *(--sp);
  191821. *(--dp) = *(--sp);
  191822. *(--dp) = hi_filler;
  191823. *(--dp) = lo_filler;
  191824. }
  191825. row_info->channels = 4;
  191826. row_info->pixel_depth = 64;
  191827. row_info->rowbytes = row_width * 8;
  191828. }
  191829. }
  191830. } /* COLOR_TYPE == RGB */
  191831. }
  191832. #endif
  191833. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191834. /* expand grayscale files to RGB, with or without alpha */
  191835. void /* PRIVATE */
  191836. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191837. {
  191838. png_uint_32 i;
  191839. png_uint_32 row_width = row_info->width;
  191840. png_debug(1, "in png_do_gray_to_rgb\n");
  191841. if (row_info->bit_depth >= 8 &&
  191842. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191843. row != NULL && row_info != NULL &&
  191844. #endif
  191845. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191846. {
  191847. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191848. {
  191849. if (row_info->bit_depth == 8)
  191850. {
  191851. png_bytep sp = row + (png_size_t)row_width - 1;
  191852. png_bytep dp = sp + (png_size_t)row_width * 2;
  191853. for (i = 0; i < row_width; i++)
  191854. {
  191855. *(dp--) = *sp;
  191856. *(dp--) = *sp;
  191857. *(dp--) = *(sp--);
  191858. }
  191859. }
  191860. else
  191861. {
  191862. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191863. png_bytep dp = sp + (png_size_t)row_width * 4;
  191864. for (i = 0; i < row_width; i++)
  191865. {
  191866. *(dp--) = *sp;
  191867. *(dp--) = *(sp - 1);
  191868. *(dp--) = *sp;
  191869. *(dp--) = *(sp - 1);
  191870. *(dp--) = *(sp--);
  191871. *(dp--) = *(sp--);
  191872. }
  191873. }
  191874. }
  191875. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191876. {
  191877. if (row_info->bit_depth == 8)
  191878. {
  191879. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191880. png_bytep dp = sp + (png_size_t)row_width * 2;
  191881. for (i = 0; i < row_width; i++)
  191882. {
  191883. *(dp--) = *(sp--);
  191884. *(dp--) = *sp;
  191885. *(dp--) = *sp;
  191886. *(dp--) = *(sp--);
  191887. }
  191888. }
  191889. else
  191890. {
  191891. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191892. png_bytep dp = sp + (png_size_t)row_width * 4;
  191893. for (i = 0; i < row_width; i++)
  191894. {
  191895. *(dp--) = *(sp--);
  191896. *(dp--) = *(sp--);
  191897. *(dp--) = *sp;
  191898. *(dp--) = *(sp - 1);
  191899. *(dp--) = *sp;
  191900. *(dp--) = *(sp - 1);
  191901. *(dp--) = *(sp--);
  191902. *(dp--) = *(sp--);
  191903. }
  191904. }
  191905. }
  191906. row_info->channels += (png_byte)2;
  191907. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191908. row_info->pixel_depth = (png_byte)(row_info->channels *
  191909. row_info->bit_depth);
  191910. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191911. }
  191912. }
  191913. #endif
  191914. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191915. /* reduce RGB files to grayscale, with or without alpha
  191916. * using the equation given in Poynton's ColorFAQ at
  191917. * <http://www.inforamp.net/~poynton/>
  191918. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191919. *
  191920. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191921. *
  191922. * We approximate this with
  191923. *
  191924. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191925. *
  191926. * which can be expressed with integers as
  191927. *
  191928. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191929. *
  191930. * The calculation is to be done in a linear colorspace.
  191931. *
  191932. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191933. */
  191934. int /* PRIVATE */
  191935. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191936. {
  191937. png_uint_32 i;
  191938. png_uint_32 row_width = row_info->width;
  191939. int rgb_error = 0;
  191940. png_debug(1, "in png_do_rgb_to_gray\n");
  191941. if (
  191942. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191943. row != NULL && row_info != NULL &&
  191944. #endif
  191945. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191946. {
  191947. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191948. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191949. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191950. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191951. {
  191952. if (row_info->bit_depth == 8)
  191953. {
  191954. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191955. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191956. {
  191957. png_bytep sp = row;
  191958. png_bytep dp = row;
  191959. for (i = 0; i < row_width; i++)
  191960. {
  191961. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191962. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191963. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191964. if(red != green || red != blue)
  191965. {
  191966. rgb_error |= 1;
  191967. *(dp++) = png_ptr->gamma_from_1[
  191968. (rc*red+gc*green+bc*blue)>>15];
  191969. }
  191970. else
  191971. *(dp++) = *(sp-1);
  191972. }
  191973. }
  191974. else
  191975. #endif
  191976. {
  191977. png_bytep sp = row;
  191978. png_bytep dp = row;
  191979. for (i = 0; i < row_width; i++)
  191980. {
  191981. png_byte red = *(sp++);
  191982. png_byte green = *(sp++);
  191983. png_byte blue = *(sp++);
  191984. if(red != green || red != blue)
  191985. {
  191986. rgb_error |= 1;
  191987. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191988. }
  191989. else
  191990. *(dp++) = *(sp-1);
  191991. }
  191992. }
  191993. }
  191994. else /* RGB bit_depth == 16 */
  191995. {
  191996. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191997. if (png_ptr->gamma_16_to_1 != NULL &&
  191998. png_ptr->gamma_16_from_1 != NULL)
  191999. {
  192000. png_bytep sp = row;
  192001. png_bytep dp = row;
  192002. for (i = 0; i < row_width; i++)
  192003. {
  192004. png_uint_16 red, green, blue, w;
  192005. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192006. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192007. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192008. if(red == green && red == blue)
  192009. w = red;
  192010. else
  192011. {
  192012. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192013. png_ptr->gamma_shift][red>>8];
  192014. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192015. png_ptr->gamma_shift][green>>8];
  192016. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192017. png_ptr->gamma_shift][blue>>8];
  192018. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192019. + bc*blue_1)>>15);
  192020. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192021. png_ptr->gamma_shift][gray16 >> 8];
  192022. rgb_error |= 1;
  192023. }
  192024. *(dp++) = (png_byte)((w>>8) & 0xff);
  192025. *(dp++) = (png_byte)(w & 0xff);
  192026. }
  192027. }
  192028. else
  192029. #endif
  192030. {
  192031. png_bytep sp = row;
  192032. png_bytep dp = row;
  192033. for (i = 0; i < row_width; i++)
  192034. {
  192035. png_uint_16 red, green, blue, gray16;
  192036. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192037. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192038. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192039. if(red != green || red != blue)
  192040. rgb_error |= 1;
  192041. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192042. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192043. *(dp++) = (png_byte)(gray16 & 0xff);
  192044. }
  192045. }
  192046. }
  192047. }
  192048. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192049. {
  192050. if (row_info->bit_depth == 8)
  192051. {
  192052. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192053. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192054. {
  192055. png_bytep sp = row;
  192056. png_bytep dp = row;
  192057. for (i = 0; i < row_width; i++)
  192058. {
  192059. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192060. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192061. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192062. if(red != green || red != blue)
  192063. rgb_error |= 1;
  192064. *(dp++) = png_ptr->gamma_from_1
  192065. [(rc*red + gc*green + bc*blue)>>15];
  192066. *(dp++) = *(sp++); /* alpha */
  192067. }
  192068. }
  192069. else
  192070. #endif
  192071. {
  192072. png_bytep sp = row;
  192073. png_bytep dp = row;
  192074. for (i = 0; i < row_width; i++)
  192075. {
  192076. png_byte red = *(sp++);
  192077. png_byte green = *(sp++);
  192078. png_byte blue = *(sp++);
  192079. if(red != green || red != blue)
  192080. rgb_error |= 1;
  192081. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192082. *(dp++) = *(sp++); /* alpha */
  192083. }
  192084. }
  192085. }
  192086. else /* RGBA bit_depth == 16 */
  192087. {
  192088. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192089. if (png_ptr->gamma_16_to_1 != NULL &&
  192090. png_ptr->gamma_16_from_1 != NULL)
  192091. {
  192092. png_bytep sp = row;
  192093. png_bytep dp = row;
  192094. for (i = 0; i < row_width; i++)
  192095. {
  192096. png_uint_16 red, green, blue, w;
  192097. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192098. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192099. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192100. if(red == green && red == blue)
  192101. w = red;
  192102. else
  192103. {
  192104. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192105. png_ptr->gamma_shift][red>>8];
  192106. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192107. png_ptr->gamma_shift][green>>8];
  192108. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192109. png_ptr->gamma_shift][blue>>8];
  192110. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192111. + gc * green_1 + bc * blue_1)>>15);
  192112. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192113. png_ptr->gamma_shift][gray16 >> 8];
  192114. rgb_error |= 1;
  192115. }
  192116. *(dp++) = (png_byte)((w>>8) & 0xff);
  192117. *(dp++) = (png_byte)(w & 0xff);
  192118. *(dp++) = *(sp++); /* alpha */
  192119. *(dp++) = *(sp++);
  192120. }
  192121. }
  192122. else
  192123. #endif
  192124. {
  192125. png_bytep sp = row;
  192126. png_bytep dp = row;
  192127. for (i = 0; i < row_width; i++)
  192128. {
  192129. png_uint_16 red, green, blue, gray16;
  192130. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192131. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192132. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192133. if(red != green || red != blue)
  192134. rgb_error |= 1;
  192135. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192136. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192137. *(dp++) = (png_byte)(gray16 & 0xff);
  192138. *(dp++) = *(sp++); /* alpha */
  192139. *(dp++) = *(sp++);
  192140. }
  192141. }
  192142. }
  192143. }
  192144. row_info->channels -= (png_byte)2;
  192145. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192146. row_info->pixel_depth = (png_byte)(row_info->channels *
  192147. row_info->bit_depth);
  192148. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192149. }
  192150. return rgb_error;
  192151. }
  192152. #endif
  192153. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192154. * large of png_color. This lets grayscale images be treated as
  192155. * paletted. Most useful for gamma correction and simplification
  192156. * of code.
  192157. */
  192158. void PNGAPI
  192159. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192160. {
  192161. int num_palette;
  192162. int color_inc;
  192163. int i;
  192164. int v;
  192165. png_debug(1, "in png_do_build_grayscale_palette\n");
  192166. if (palette == NULL)
  192167. return;
  192168. switch (bit_depth)
  192169. {
  192170. case 1:
  192171. num_palette = 2;
  192172. color_inc = 0xff;
  192173. break;
  192174. case 2:
  192175. num_palette = 4;
  192176. color_inc = 0x55;
  192177. break;
  192178. case 4:
  192179. num_palette = 16;
  192180. color_inc = 0x11;
  192181. break;
  192182. case 8:
  192183. num_palette = 256;
  192184. color_inc = 1;
  192185. break;
  192186. default:
  192187. num_palette = 0;
  192188. color_inc = 0;
  192189. break;
  192190. }
  192191. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192192. {
  192193. palette[i].red = (png_byte)v;
  192194. palette[i].green = (png_byte)v;
  192195. palette[i].blue = (png_byte)v;
  192196. }
  192197. }
  192198. /* This function is currently unused. Do we really need it? */
  192199. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192200. void /* PRIVATE */
  192201. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192202. int num_palette)
  192203. {
  192204. png_debug(1, "in png_correct_palette\n");
  192205. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192206. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192207. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192208. {
  192209. png_color back, back_1;
  192210. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192211. {
  192212. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192213. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192214. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192215. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192216. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192217. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192218. }
  192219. else
  192220. {
  192221. double g;
  192222. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192223. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192224. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192225. {
  192226. back.red = png_ptr->background.red;
  192227. back.green = png_ptr->background.green;
  192228. back.blue = png_ptr->background.blue;
  192229. }
  192230. else
  192231. {
  192232. back.red =
  192233. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192234. 255.0 + 0.5);
  192235. back.green =
  192236. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192237. 255.0 + 0.5);
  192238. back.blue =
  192239. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192240. 255.0 + 0.5);
  192241. }
  192242. g = 1.0 / png_ptr->background_gamma;
  192243. back_1.red =
  192244. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192245. 255.0 + 0.5);
  192246. back_1.green =
  192247. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192248. 255.0 + 0.5);
  192249. back_1.blue =
  192250. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192251. 255.0 + 0.5);
  192252. }
  192253. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192254. {
  192255. png_uint_32 i;
  192256. for (i = 0; i < (png_uint_32)num_palette; i++)
  192257. {
  192258. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192259. {
  192260. palette[i] = back;
  192261. }
  192262. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192263. {
  192264. png_byte v, w;
  192265. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192266. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192267. palette[i].red = png_ptr->gamma_from_1[w];
  192268. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192269. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192270. palette[i].green = png_ptr->gamma_from_1[w];
  192271. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192272. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192273. palette[i].blue = png_ptr->gamma_from_1[w];
  192274. }
  192275. else
  192276. {
  192277. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192278. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192279. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192280. }
  192281. }
  192282. }
  192283. else
  192284. {
  192285. int i;
  192286. for (i = 0; i < num_palette; i++)
  192287. {
  192288. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192289. {
  192290. palette[i] = back;
  192291. }
  192292. else
  192293. {
  192294. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192295. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192296. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192297. }
  192298. }
  192299. }
  192300. }
  192301. else
  192302. #endif
  192303. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192304. if (png_ptr->transformations & PNG_GAMMA)
  192305. {
  192306. int i;
  192307. for (i = 0; i < num_palette; i++)
  192308. {
  192309. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192310. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192311. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192312. }
  192313. }
  192314. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192315. else
  192316. #endif
  192317. #endif
  192318. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192319. if (png_ptr->transformations & PNG_BACKGROUND)
  192320. {
  192321. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192322. {
  192323. png_color back;
  192324. back.red = (png_byte)png_ptr->background.red;
  192325. back.green = (png_byte)png_ptr->background.green;
  192326. back.blue = (png_byte)png_ptr->background.blue;
  192327. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192328. {
  192329. if (png_ptr->trans[i] == 0)
  192330. {
  192331. palette[i].red = back.red;
  192332. palette[i].green = back.green;
  192333. palette[i].blue = back.blue;
  192334. }
  192335. else if (png_ptr->trans[i] != 0xff)
  192336. {
  192337. png_composite(palette[i].red, png_ptr->palette[i].red,
  192338. png_ptr->trans[i], back.red);
  192339. png_composite(palette[i].green, png_ptr->palette[i].green,
  192340. png_ptr->trans[i], back.green);
  192341. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192342. png_ptr->trans[i], back.blue);
  192343. }
  192344. }
  192345. }
  192346. else /* assume grayscale palette (what else could it be?) */
  192347. {
  192348. int i;
  192349. for (i = 0; i < num_palette; i++)
  192350. {
  192351. if (i == (png_byte)png_ptr->trans_values.gray)
  192352. {
  192353. palette[i].red = (png_byte)png_ptr->background.red;
  192354. palette[i].green = (png_byte)png_ptr->background.green;
  192355. palette[i].blue = (png_byte)png_ptr->background.blue;
  192356. }
  192357. }
  192358. }
  192359. }
  192360. #endif
  192361. }
  192362. #endif
  192363. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192364. /* Replace any alpha or transparency with the supplied background color.
  192365. * "background" is already in the screen gamma, while "background_1" is
  192366. * at a gamma of 1.0. Paletted files have already been taken care of.
  192367. */
  192368. void /* PRIVATE */
  192369. png_do_background(png_row_infop row_info, png_bytep row,
  192370. png_color_16p trans_values, png_color_16p background
  192371. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192372. , png_color_16p background_1,
  192373. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192374. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192375. png_uint_16pp gamma_16_to_1, int gamma_shift
  192376. #endif
  192377. )
  192378. {
  192379. png_bytep sp, dp;
  192380. png_uint_32 i;
  192381. png_uint_32 row_width=row_info->width;
  192382. int shift;
  192383. png_debug(1, "in png_do_background\n");
  192384. if (background != NULL &&
  192385. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192386. row != NULL && row_info != NULL &&
  192387. #endif
  192388. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192389. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192390. {
  192391. switch (row_info->color_type)
  192392. {
  192393. case PNG_COLOR_TYPE_GRAY:
  192394. {
  192395. switch (row_info->bit_depth)
  192396. {
  192397. case 1:
  192398. {
  192399. sp = row;
  192400. shift = 7;
  192401. for (i = 0; i < row_width; i++)
  192402. {
  192403. if ((png_uint_16)((*sp >> shift) & 0x01)
  192404. == trans_values->gray)
  192405. {
  192406. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192407. *sp |= (png_byte)(background->gray << shift);
  192408. }
  192409. if (!shift)
  192410. {
  192411. shift = 7;
  192412. sp++;
  192413. }
  192414. else
  192415. shift--;
  192416. }
  192417. break;
  192418. }
  192419. case 2:
  192420. {
  192421. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192422. if (gamma_table != NULL)
  192423. {
  192424. sp = row;
  192425. shift = 6;
  192426. for (i = 0; i < row_width; i++)
  192427. {
  192428. if ((png_uint_16)((*sp >> shift) & 0x03)
  192429. == trans_values->gray)
  192430. {
  192431. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192432. *sp |= (png_byte)(background->gray << shift);
  192433. }
  192434. else
  192435. {
  192436. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192437. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192438. (p << 4) | (p << 6)] >> 6) & 0x03);
  192439. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192440. *sp |= (png_byte)(g << shift);
  192441. }
  192442. if (!shift)
  192443. {
  192444. shift = 6;
  192445. sp++;
  192446. }
  192447. else
  192448. shift -= 2;
  192449. }
  192450. }
  192451. else
  192452. #endif
  192453. {
  192454. sp = row;
  192455. shift = 6;
  192456. for (i = 0; i < row_width; i++)
  192457. {
  192458. if ((png_uint_16)((*sp >> shift) & 0x03)
  192459. == trans_values->gray)
  192460. {
  192461. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192462. *sp |= (png_byte)(background->gray << shift);
  192463. }
  192464. if (!shift)
  192465. {
  192466. shift = 6;
  192467. sp++;
  192468. }
  192469. else
  192470. shift -= 2;
  192471. }
  192472. }
  192473. break;
  192474. }
  192475. case 4:
  192476. {
  192477. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192478. if (gamma_table != NULL)
  192479. {
  192480. sp = row;
  192481. shift = 4;
  192482. for (i = 0; i < row_width; i++)
  192483. {
  192484. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192485. == trans_values->gray)
  192486. {
  192487. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192488. *sp |= (png_byte)(background->gray << shift);
  192489. }
  192490. else
  192491. {
  192492. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192493. png_byte g = (png_byte)((gamma_table[p |
  192494. (p << 4)] >> 4) & 0x0f);
  192495. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192496. *sp |= (png_byte)(g << shift);
  192497. }
  192498. if (!shift)
  192499. {
  192500. shift = 4;
  192501. sp++;
  192502. }
  192503. else
  192504. shift -= 4;
  192505. }
  192506. }
  192507. else
  192508. #endif
  192509. {
  192510. sp = row;
  192511. shift = 4;
  192512. for (i = 0; i < row_width; i++)
  192513. {
  192514. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192515. == trans_values->gray)
  192516. {
  192517. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192518. *sp |= (png_byte)(background->gray << shift);
  192519. }
  192520. if (!shift)
  192521. {
  192522. shift = 4;
  192523. sp++;
  192524. }
  192525. else
  192526. shift -= 4;
  192527. }
  192528. }
  192529. break;
  192530. }
  192531. case 8:
  192532. {
  192533. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192534. if (gamma_table != NULL)
  192535. {
  192536. sp = row;
  192537. for (i = 0; i < row_width; i++, sp++)
  192538. {
  192539. if (*sp == trans_values->gray)
  192540. {
  192541. *sp = (png_byte)background->gray;
  192542. }
  192543. else
  192544. {
  192545. *sp = gamma_table[*sp];
  192546. }
  192547. }
  192548. }
  192549. else
  192550. #endif
  192551. {
  192552. sp = row;
  192553. for (i = 0; i < row_width; i++, sp++)
  192554. {
  192555. if (*sp == trans_values->gray)
  192556. {
  192557. *sp = (png_byte)background->gray;
  192558. }
  192559. }
  192560. }
  192561. break;
  192562. }
  192563. case 16:
  192564. {
  192565. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192566. if (gamma_16 != NULL)
  192567. {
  192568. sp = row;
  192569. for (i = 0; i < row_width; i++, sp += 2)
  192570. {
  192571. png_uint_16 v;
  192572. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192573. if (v == trans_values->gray)
  192574. {
  192575. /* background is already in screen gamma */
  192576. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192577. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192578. }
  192579. else
  192580. {
  192581. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192582. *sp = (png_byte)((v >> 8) & 0xff);
  192583. *(sp + 1) = (png_byte)(v & 0xff);
  192584. }
  192585. }
  192586. }
  192587. else
  192588. #endif
  192589. {
  192590. sp = row;
  192591. for (i = 0; i < row_width; i++, sp += 2)
  192592. {
  192593. png_uint_16 v;
  192594. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192595. if (v == trans_values->gray)
  192596. {
  192597. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192598. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192599. }
  192600. }
  192601. }
  192602. break;
  192603. }
  192604. }
  192605. break;
  192606. }
  192607. case PNG_COLOR_TYPE_RGB:
  192608. {
  192609. if (row_info->bit_depth == 8)
  192610. {
  192611. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192612. if (gamma_table != NULL)
  192613. {
  192614. sp = row;
  192615. for (i = 0; i < row_width; i++, sp += 3)
  192616. {
  192617. if (*sp == trans_values->red &&
  192618. *(sp + 1) == trans_values->green &&
  192619. *(sp + 2) == trans_values->blue)
  192620. {
  192621. *sp = (png_byte)background->red;
  192622. *(sp + 1) = (png_byte)background->green;
  192623. *(sp + 2) = (png_byte)background->blue;
  192624. }
  192625. else
  192626. {
  192627. *sp = gamma_table[*sp];
  192628. *(sp + 1) = gamma_table[*(sp + 1)];
  192629. *(sp + 2) = gamma_table[*(sp + 2)];
  192630. }
  192631. }
  192632. }
  192633. else
  192634. #endif
  192635. {
  192636. sp = row;
  192637. for (i = 0; i < row_width; i++, sp += 3)
  192638. {
  192639. if (*sp == trans_values->red &&
  192640. *(sp + 1) == trans_values->green &&
  192641. *(sp + 2) == trans_values->blue)
  192642. {
  192643. *sp = (png_byte)background->red;
  192644. *(sp + 1) = (png_byte)background->green;
  192645. *(sp + 2) = (png_byte)background->blue;
  192646. }
  192647. }
  192648. }
  192649. }
  192650. else /* if (row_info->bit_depth == 16) */
  192651. {
  192652. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192653. if (gamma_16 != NULL)
  192654. {
  192655. sp = row;
  192656. for (i = 0; i < row_width; i++, sp += 6)
  192657. {
  192658. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192659. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192660. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192661. if (r == trans_values->red && g == trans_values->green &&
  192662. b == trans_values->blue)
  192663. {
  192664. /* background is already in screen gamma */
  192665. *sp = (png_byte)((background->red >> 8) & 0xff);
  192666. *(sp + 1) = (png_byte)(background->red & 0xff);
  192667. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192668. *(sp + 3) = (png_byte)(background->green & 0xff);
  192669. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192670. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192671. }
  192672. else
  192673. {
  192674. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192675. *sp = (png_byte)((v >> 8) & 0xff);
  192676. *(sp + 1) = (png_byte)(v & 0xff);
  192677. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192678. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192679. *(sp + 3) = (png_byte)(v & 0xff);
  192680. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192681. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192682. *(sp + 5) = (png_byte)(v & 0xff);
  192683. }
  192684. }
  192685. }
  192686. else
  192687. #endif
  192688. {
  192689. sp = row;
  192690. for (i = 0; i < row_width; i++, sp += 6)
  192691. {
  192692. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192693. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192694. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192695. if (r == trans_values->red && g == trans_values->green &&
  192696. b == trans_values->blue)
  192697. {
  192698. *sp = (png_byte)((background->red >> 8) & 0xff);
  192699. *(sp + 1) = (png_byte)(background->red & 0xff);
  192700. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192701. *(sp + 3) = (png_byte)(background->green & 0xff);
  192702. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192703. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192704. }
  192705. }
  192706. }
  192707. }
  192708. break;
  192709. }
  192710. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192711. {
  192712. if (row_info->bit_depth == 8)
  192713. {
  192714. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192715. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192716. gamma_table != NULL)
  192717. {
  192718. sp = row;
  192719. dp = row;
  192720. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192721. {
  192722. png_uint_16 a = *(sp + 1);
  192723. if (a == 0xff)
  192724. {
  192725. *dp = gamma_table[*sp];
  192726. }
  192727. else if (a == 0)
  192728. {
  192729. /* background is already in screen gamma */
  192730. *dp = (png_byte)background->gray;
  192731. }
  192732. else
  192733. {
  192734. png_byte v, w;
  192735. v = gamma_to_1[*sp];
  192736. png_composite(w, v, a, background_1->gray);
  192737. *dp = gamma_from_1[w];
  192738. }
  192739. }
  192740. }
  192741. else
  192742. #endif
  192743. {
  192744. sp = row;
  192745. dp = row;
  192746. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192747. {
  192748. png_byte a = *(sp + 1);
  192749. if (a == 0xff)
  192750. {
  192751. *dp = *sp;
  192752. }
  192753. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192754. else if (a == 0)
  192755. {
  192756. *dp = (png_byte)background->gray;
  192757. }
  192758. else
  192759. {
  192760. png_composite(*dp, *sp, a, background_1->gray);
  192761. }
  192762. #else
  192763. *dp = (png_byte)background->gray;
  192764. #endif
  192765. }
  192766. }
  192767. }
  192768. else /* if (png_ptr->bit_depth == 16) */
  192769. {
  192770. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192771. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192772. gamma_16_to_1 != NULL)
  192773. {
  192774. sp = row;
  192775. dp = row;
  192776. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192777. {
  192778. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192779. if (a == (png_uint_16)0xffff)
  192780. {
  192781. png_uint_16 v;
  192782. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192783. *dp = (png_byte)((v >> 8) & 0xff);
  192784. *(dp + 1) = (png_byte)(v & 0xff);
  192785. }
  192786. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192787. else if (a == 0)
  192788. #else
  192789. else
  192790. #endif
  192791. {
  192792. /* background is already in screen gamma */
  192793. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192794. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192795. }
  192796. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192797. else
  192798. {
  192799. png_uint_16 g, v, w;
  192800. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192801. png_composite_16(v, g, a, background_1->gray);
  192802. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192803. *dp = (png_byte)((w >> 8) & 0xff);
  192804. *(dp + 1) = (png_byte)(w & 0xff);
  192805. }
  192806. #endif
  192807. }
  192808. }
  192809. else
  192810. #endif
  192811. {
  192812. sp = row;
  192813. dp = row;
  192814. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192815. {
  192816. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192817. if (a == (png_uint_16)0xffff)
  192818. {
  192819. png_memcpy(dp, sp, 2);
  192820. }
  192821. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192822. else if (a == 0)
  192823. #else
  192824. else
  192825. #endif
  192826. {
  192827. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192828. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192829. }
  192830. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192831. else
  192832. {
  192833. png_uint_16 g, v;
  192834. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192835. png_composite_16(v, g, a, background_1->gray);
  192836. *dp = (png_byte)((v >> 8) & 0xff);
  192837. *(dp + 1) = (png_byte)(v & 0xff);
  192838. }
  192839. #endif
  192840. }
  192841. }
  192842. }
  192843. break;
  192844. }
  192845. case PNG_COLOR_TYPE_RGB_ALPHA:
  192846. {
  192847. if (row_info->bit_depth == 8)
  192848. {
  192849. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192850. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192851. gamma_table != NULL)
  192852. {
  192853. sp = row;
  192854. dp = row;
  192855. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192856. {
  192857. png_byte a = *(sp + 3);
  192858. if (a == 0xff)
  192859. {
  192860. *dp = gamma_table[*sp];
  192861. *(dp + 1) = gamma_table[*(sp + 1)];
  192862. *(dp + 2) = gamma_table[*(sp + 2)];
  192863. }
  192864. else if (a == 0)
  192865. {
  192866. /* background is already in screen gamma */
  192867. *dp = (png_byte)background->red;
  192868. *(dp + 1) = (png_byte)background->green;
  192869. *(dp + 2) = (png_byte)background->blue;
  192870. }
  192871. else
  192872. {
  192873. png_byte v, w;
  192874. v = gamma_to_1[*sp];
  192875. png_composite(w, v, a, background_1->red);
  192876. *dp = gamma_from_1[w];
  192877. v = gamma_to_1[*(sp + 1)];
  192878. png_composite(w, v, a, background_1->green);
  192879. *(dp + 1) = gamma_from_1[w];
  192880. v = gamma_to_1[*(sp + 2)];
  192881. png_composite(w, v, a, background_1->blue);
  192882. *(dp + 2) = gamma_from_1[w];
  192883. }
  192884. }
  192885. }
  192886. else
  192887. #endif
  192888. {
  192889. sp = row;
  192890. dp = row;
  192891. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192892. {
  192893. png_byte a = *(sp + 3);
  192894. if (a == 0xff)
  192895. {
  192896. *dp = *sp;
  192897. *(dp + 1) = *(sp + 1);
  192898. *(dp + 2) = *(sp + 2);
  192899. }
  192900. else if (a == 0)
  192901. {
  192902. *dp = (png_byte)background->red;
  192903. *(dp + 1) = (png_byte)background->green;
  192904. *(dp + 2) = (png_byte)background->blue;
  192905. }
  192906. else
  192907. {
  192908. png_composite(*dp, *sp, a, background->red);
  192909. png_composite(*(dp + 1), *(sp + 1), a,
  192910. background->green);
  192911. png_composite(*(dp + 2), *(sp + 2), a,
  192912. background->blue);
  192913. }
  192914. }
  192915. }
  192916. }
  192917. else /* if (row_info->bit_depth == 16) */
  192918. {
  192919. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192920. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192921. gamma_16_to_1 != NULL)
  192922. {
  192923. sp = row;
  192924. dp = row;
  192925. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192926. {
  192927. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192928. << 8) + (png_uint_16)(*(sp + 7)));
  192929. if (a == (png_uint_16)0xffff)
  192930. {
  192931. png_uint_16 v;
  192932. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192933. *dp = (png_byte)((v >> 8) & 0xff);
  192934. *(dp + 1) = (png_byte)(v & 0xff);
  192935. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192936. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192937. *(dp + 3) = (png_byte)(v & 0xff);
  192938. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192939. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192940. *(dp + 5) = (png_byte)(v & 0xff);
  192941. }
  192942. else if (a == 0)
  192943. {
  192944. /* background is already in screen gamma */
  192945. *dp = (png_byte)((background->red >> 8) & 0xff);
  192946. *(dp + 1) = (png_byte)(background->red & 0xff);
  192947. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192948. *(dp + 3) = (png_byte)(background->green & 0xff);
  192949. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192950. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192951. }
  192952. else
  192953. {
  192954. png_uint_16 v, w, x;
  192955. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192956. png_composite_16(w, v, a, background_1->red);
  192957. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192958. *dp = (png_byte)((x >> 8) & 0xff);
  192959. *(dp + 1) = (png_byte)(x & 0xff);
  192960. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192961. png_composite_16(w, v, a, background_1->green);
  192962. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192963. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192964. *(dp + 3) = (png_byte)(x & 0xff);
  192965. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192966. png_composite_16(w, v, a, background_1->blue);
  192967. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192968. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192969. *(dp + 5) = (png_byte)(x & 0xff);
  192970. }
  192971. }
  192972. }
  192973. else
  192974. #endif
  192975. {
  192976. sp = row;
  192977. dp = row;
  192978. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192979. {
  192980. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192981. << 8) + (png_uint_16)(*(sp + 7)));
  192982. if (a == (png_uint_16)0xffff)
  192983. {
  192984. png_memcpy(dp, sp, 6);
  192985. }
  192986. else if (a == 0)
  192987. {
  192988. *dp = (png_byte)((background->red >> 8) & 0xff);
  192989. *(dp + 1) = (png_byte)(background->red & 0xff);
  192990. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192991. *(dp + 3) = (png_byte)(background->green & 0xff);
  192992. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192993. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192994. }
  192995. else
  192996. {
  192997. png_uint_16 v;
  192998. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192999. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193000. + *(sp + 3));
  193001. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193002. + *(sp + 5));
  193003. png_composite_16(v, r, a, background->red);
  193004. *dp = (png_byte)((v >> 8) & 0xff);
  193005. *(dp + 1) = (png_byte)(v & 0xff);
  193006. png_composite_16(v, g, a, background->green);
  193007. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193008. *(dp + 3) = (png_byte)(v & 0xff);
  193009. png_composite_16(v, b, a, background->blue);
  193010. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193011. *(dp + 5) = (png_byte)(v & 0xff);
  193012. }
  193013. }
  193014. }
  193015. }
  193016. break;
  193017. }
  193018. }
  193019. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193020. {
  193021. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193022. row_info->channels--;
  193023. row_info->pixel_depth = (png_byte)(row_info->channels *
  193024. row_info->bit_depth);
  193025. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193026. }
  193027. }
  193028. }
  193029. #endif
  193030. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193031. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193032. * you do this after you deal with the transparency issue on grayscale
  193033. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193034. * is 16, use gamma_16_table and gamma_shift. Build these with
  193035. * build_gamma_table().
  193036. */
  193037. void /* PRIVATE */
  193038. png_do_gamma(png_row_infop row_info, png_bytep row,
  193039. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193040. int gamma_shift)
  193041. {
  193042. png_bytep sp;
  193043. png_uint_32 i;
  193044. png_uint_32 row_width=row_info->width;
  193045. png_debug(1, "in png_do_gamma\n");
  193046. if (
  193047. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193048. row != NULL && row_info != NULL &&
  193049. #endif
  193050. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193051. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193052. {
  193053. switch (row_info->color_type)
  193054. {
  193055. case PNG_COLOR_TYPE_RGB:
  193056. {
  193057. if (row_info->bit_depth == 8)
  193058. {
  193059. sp = row;
  193060. for (i = 0; i < row_width; i++)
  193061. {
  193062. *sp = gamma_table[*sp];
  193063. sp++;
  193064. *sp = gamma_table[*sp];
  193065. sp++;
  193066. *sp = gamma_table[*sp];
  193067. sp++;
  193068. }
  193069. }
  193070. else /* if (row_info->bit_depth == 16) */
  193071. {
  193072. sp = row;
  193073. for (i = 0; i < row_width; i++)
  193074. {
  193075. png_uint_16 v;
  193076. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193077. *sp = (png_byte)((v >> 8) & 0xff);
  193078. *(sp + 1) = (png_byte)(v & 0xff);
  193079. sp += 2;
  193080. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193081. *sp = (png_byte)((v >> 8) & 0xff);
  193082. *(sp + 1) = (png_byte)(v & 0xff);
  193083. sp += 2;
  193084. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193085. *sp = (png_byte)((v >> 8) & 0xff);
  193086. *(sp + 1) = (png_byte)(v & 0xff);
  193087. sp += 2;
  193088. }
  193089. }
  193090. break;
  193091. }
  193092. case PNG_COLOR_TYPE_RGB_ALPHA:
  193093. {
  193094. if (row_info->bit_depth == 8)
  193095. {
  193096. sp = row;
  193097. for (i = 0; i < row_width; i++)
  193098. {
  193099. *sp = gamma_table[*sp];
  193100. sp++;
  193101. *sp = gamma_table[*sp];
  193102. sp++;
  193103. *sp = gamma_table[*sp];
  193104. sp++;
  193105. sp++;
  193106. }
  193107. }
  193108. else /* if (row_info->bit_depth == 16) */
  193109. {
  193110. sp = row;
  193111. for (i = 0; i < row_width; i++)
  193112. {
  193113. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193114. *sp = (png_byte)((v >> 8) & 0xff);
  193115. *(sp + 1) = (png_byte)(v & 0xff);
  193116. sp += 2;
  193117. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193118. *sp = (png_byte)((v >> 8) & 0xff);
  193119. *(sp + 1) = (png_byte)(v & 0xff);
  193120. sp += 2;
  193121. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193122. *sp = (png_byte)((v >> 8) & 0xff);
  193123. *(sp + 1) = (png_byte)(v & 0xff);
  193124. sp += 4;
  193125. }
  193126. }
  193127. break;
  193128. }
  193129. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193130. {
  193131. if (row_info->bit_depth == 8)
  193132. {
  193133. sp = row;
  193134. for (i = 0; i < row_width; i++)
  193135. {
  193136. *sp = gamma_table[*sp];
  193137. sp += 2;
  193138. }
  193139. }
  193140. else /* if (row_info->bit_depth == 16) */
  193141. {
  193142. sp = row;
  193143. for (i = 0; i < row_width; i++)
  193144. {
  193145. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193146. *sp = (png_byte)((v >> 8) & 0xff);
  193147. *(sp + 1) = (png_byte)(v & 0xff);
  193148. sp += 4;
  193149. }
  193150. }
  193151. break;
  193152. }
  193153. case PNG_COLOR_TYPE_GRAY:
  193154. {
  193155. if (row_info->bit_depth == 2)
  193156. {
  193157. sp = row;
  193158. for (i = 0; i < row_width; i += 4)
  193159. {
  193160. int a = *sp & 0xc0;
  193161. int b = *sp & 0x30;
  193162. int c = *sp & 0x0c;
  193163. int d = *sp & 0x03;
  193164. *sp = (png_byte)(
  193165. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193166. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193167. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193168. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193169. sp++;
  193170. }
  193171. }
  193172. if (row_info->bit_depth == 4)
  193173. {
  193174. sp = row;
  193175. for (i = 0; i < row_width; i += 2)
  193176. {
  193177. int msb = *sp & 0xf0;
  193178. int lsb = *sp & 0x0f;
  193179. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193180. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193181. sp++;
  193182. }
  193183. }
  193184. else if (row_info->bit_depth == 8)
  193185. {
  193186. sp = row;
  193187. for (i = 0; i < row_width; i++)
  193188. {
  193189. *sp = gamma_table[*sp];
  193190. sp++;
  193191. }
  193192. }
  193193. else if (row_info->bit_depth == 16)
  193194. {
  193195. sp = row;
  193196. for (i = 0; i < row_width; i++)
  193197. {
  193198. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193199. *sp = (png_byte)((v >> 8) & 0xff);
  193200. *(sp + 1) = (png_byte)(v & 0xff);
  193201. sp += 2;
  193202. }
  193203. }
  193204. break;
  193205. }
  193206. }
  193207. }
  193208. }
  193209. #endif
  193210. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193211. /* Expands a palette row to an RGB or RGBA row depending
  193212. * upon whether you supply trans and num_trans.
  193213. */
  193214. void /* PRIVATE */
  193215. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193216. png_colorp palette, png_bytep trans, int num_trans)
  193217. {
  193218. int shift, value;
  193219. png_bytep sp, dp;
  193220. png_uint_32 i;
  193221. png_uint_32 row_width=row_info->width;
  193222. png_debug(1, "in png_do_expand_palette\n");
  193223. if (
  193224. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193225. row != NULL && row_info != NULL &&
  193226. #endif
  193227. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193228. {
  193229. if (row_info->bit_depth < 8)
  193230. {
  193231. switch (row_info->bit_depth)
  193232. {
  193233. case 1:
  193234. {
  193235. sp = row + (png_size_t)((row_width - 1) >> 3);
  193236. dp = row + (png_size_t)row_width - 1;
  193237. shift = 7 - (int)((row_width + 7) & 0x07);
  193238. for (i = 0; i < row_width; i++)
  193239. {
  193240. if ((*sp >> shift) & 0x01)
  193241. *dp = 1;
  193242. else
  193243. *dp = 0;
  193244. if (shift == 7)
  193245. {
  193246. shift = 0;
  193247. sp--;
  193248. }
  193249. else
  193250. shift++;
  193251. dp--;
  193252. }
  193253. break;
  193254. }
  193255. case 2:
  193256. {
  193257. sp = row + (png_size_t)((row_width - 1) >> 2);
  193258. dp = row + (png_size_t)row_width - 1;
  193259. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193260. for (i = 0; i < row_width; i++)
  193261. {
  193262. value = (*sp >> shift) & 0x03;
  193263. *dp = (png_byte)value;
  193264. if (shift == 6)
  193265. {
  193266. shift = 0;
  193267. sp--;
  193268. }
  193269. else
  193270. shift += 2;
  193271. dp--;
  193272. }
  193273. break;
  193274. }
  193275. case 4:
  193276. {
  193277. sp = row + (png_size_t)((row_width - 1) >> 1);
  193278. dp = row + (png_size_t)row_width - 1;
  193279. shift = (int)((row_width & 0x01) << 2);
  193280. for (i = 0; i < row_width; i++)
  193281. {
  193282. value = (*sp >> shift) & 0x0f;
  193283. *dp = (png_byte)value;
  193284. if (shift == 4)
  193285. {
  193286. shift = 0;
  193287. sp--;
  193288. }
  193289. else
  193290. shift += 4;
  193291. dp--;
  193292. }
  193293. break;
  193294. }
  193295. }
  193296. row_info->bit_depth = 8;
  193297. row_info->pixel_depth = 8;
  193298. row_info->rowbytes = row_width;
  193299. }
  193300. switch (row_info->bit_depth)
  193301. {
  193302. case 8:
  193303. {
  193304. if (trans != NULL)
  193305. {
  193306. sp = row + (png_size_t)row_width - 1;
  193307. dp = row + (png_size_t)(row_width << 2) - 1;
  193308. for (i = 0; i < row_width; i++)
  193309. {
  193310. if ((int)(*sp) >= num_trans)
  193311. *dp-- = 0xff;
  193312. else
  193313. *dp-- = trans[*sp];
  193314. *dp-- = palette[*sp].blue;
  193315. *dp-- = palette[*sp].green;
  193316. *dp-- = palette[*sp].red;
  193317. sp--;
  193318. }
  193319. row_info->bit_depth = 8;
  193320. row_info->pixel_depth = 32;
  193321. row_info->rowbytes = row_width * 4;
  193322. row_info->color_type = 6;
  193323. row_info->channels = 4;
  193324. }
  193325. else
  193326. {
  193327. sp = row + (png_size_t)row_width - 1;
  193328. dp = row + (png_size_t)(row_width * 3) - 1;
  193329. for (i = 0; i < row_width; i++)
  193330. {
  193331. *dp-- = palette[*sp].blue;
  193332. *dp-- = palette[*sp].green;
  193333. *dp-- = palette[*sp].red;
  193334. sp--;
  193335. }
  193336. row_info->bit_depth = 8;
  193337. row_info->pixel_depth = 24;
  193338. row_info->rowbytes = row_width * 3;
  193339. row_info->color_type = 2;
  193340. row_info->channels = 3;
  193341. }
  193342. break;
  193343. }
  193344. }
  193345. }
  193346. }
  193347. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193348. * expanded transparency value is supplied, an alpha channel is built.
  193349. */
  193350. void /* PRIVATE */
  193351. png_do_expand(png_row_infop row_info, png_bytep row,
  193352. png_color_16p trans_value)
  193353. {
  193354. int shift, value;
  193355. png_bytep sp, dp;
  193356. png_uint_32 i;
  193357. png_uint_32 row_width=row_info->width;
  193358. png_debug(1, "in png_do_expand\n");
  193359. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193360. if (row != NULL && row_info != NULL)
  193361. #endif
  193362. {
  193363. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193364. {
  193365. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193366. if (row_info->bit_depth < 8)
  193367. {
  193368. switch (row_info->bit_depth)
  193369. {
  193370. case 1:
  193371. {
  193372. gray = (png_uint_16)((gray&0x01)*0xff);
  193373. sp = row + (png_size_t)((row_width - 1) >> 3);
  193374. dp = row + (png_size_t)row_width - 1;
  193375. shift = 7 - (int)((row_width + 7) & 0x07);
  193376. for (i = 0; i < row_width; i++)
  193377. {
  193378. if ((*sp >> shift) & 0x01)
  193379. *dp = 0xff;
  193380. else
  193381. *dp = 0;
  193382. if (shift == 7)
  193383. {
  193384. shift = 0;
  193385. sp--;
  193386. }
  193387. else
  193388. shift++;
  193389. dp--;
  193390. }
  193391. break;
  193392. }
  193393. case 2:
  193394. {
  193395. gray = (png_uint_16)((gray&0x03)*0x55);
  193396. sp = row + (png_size_t)((row_width - 1) >> 2);
  193397. dp = row + (png_size_t)row_width - 1;
  193398. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193399. for (i = 0; i < row_width; i++)
  193400. {
  193401. value = (*sp >> shift) & 0x03;
  193402. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193403. (value << 6));
  193404. if (shift == 6)
  193405. {
  193406. shift = 0;
  193407. sp--;
  193408. }
  193409. else
  193410. shift += 2;
  193411. dp--;
  193412. }
  193413. break;
  193414. }
  193415. case 4:
  193416. {
  193417. gray = (png_uint_16)((gray&0x0f)*0x11);
  193418. sp = row + (png_size_t)((row_width - 1) >> 1);
  193419. dp = row + (png_size_t)row_width - 1;
  193420. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193421. for (i = 0; i < row_width; i++)
  193422. {
  193423. value = (*sp >> shift) & 0x0f;
  193424. *dp = (png_byte)(value | (value << 4));
  193425. if (shift == 4)
  193426. {
  193427. shift = 0;
  193428. sp--;
  193429. }
  193430. else
  193431. shift = 4;
  193432. dp--;
  193433. }
  193434. break;
  193435. }
  193436. }
  193437. row_info->bit_depth = 8;
  193438. row_info->pixel_depth = 8;
  193439. row_info->rowbytes = row_width;
  193440. }
  193441. if (trans_value != NULL)
  193442. {
  193443. if (row_info->bit_depth == 8)
  193444. {
  193445. gray = gray & 0xff;
  193446. sp = row + (png_size_t)row_width - 1;
  193447. dp = row + (png_size_t)(row_width << 1) - 1;
  193448. for (i = 0; i < row_width; i++)
  193449. {
  193450. if (*sp == gray)
  193451. *dp-- = 0;
  193452. else
  193453. *dp-- = 0xff;
  193454. *dp-- = *sp--;
  193455. }
  193456. }
  193457. else if (row_info->bit_depth == 16)
  193458. {
  193459. png_byte gray_high = (gray >> 8) & 0xff;
  193460. png_byte gray_low = gray & 0xff;
  193461. sp = row + row_info->rowbytes - 1;
  193462. dp = row + (row_info->rowbytes << 1) - 1;
  193463. for (i = 0; i < row_width; i++)
  193464. {
  193465. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193466. {
  193467. *dp-- = 0;
  193468. *dp-- = 0;
  193469. }
  193470. else
  193471. {
  193472. *dp-- = 0xff;
  193473. *dp-- = 0xff;
  193474. }
  193475. *dp-- = *sp--;
  193476. *dp-- = *sp--;
  193477. }
  193478. }
  193479. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193480. row_info->channels = 2;
  193481. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193482. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193483. row_width);
  193484. }
  193485. }
  193486. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193487. {
  193488. if (row_info->bit_depth == 8)
  193489. {
  193490. png_byte red = trans_value->red & 0xff;
  193491. png_byte green = trans_value->green & 0xff;
  193492. png_byte blue = trans_value->blue & 0xff;
  193493. sp = row + (png_size_t)row_info->rowbytes - 1;
  193494. dp = row + (png_size_t)(row_width << 2) - 1;
  193495. for (i = 0; i < row_width; i++)
  193496. {
  193497. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193498. *dp-- = 0;
  193499. else
  193500. *dp-- = 0xff;
  193501. *dp-- = *sp--;
  193502. *dp-- = *sp--;
  193503. *dp-- = *sp--;
  193504. }
  193505. }
  193506. else if (row_info->bit_depth == 16)
  193507. {
  193508. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193509. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193510. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193511. png_byte red_low = trans_value->red & 0xff;
  193512. png_byte green_low = trans_value->green & 0xff;
  193513. png_byte blue_low = trans_value->blue & 0xff;
  193514. sp = row + row_info->rowbytes - 1;
  193515. dp = row + (png_size_t)(row_width << 3) - 1;
  193516. for (i = 0; i < row_width; i++)
  193517. {
  193518. if (*(sp - 5) == red_high &&
  193519. *(sp - 4) == red_low &&
  193520. *(sp - 3) == green_high &&
  193521. *(sp - 2) == green_low &&
  193522. *(sp - 1) == blue_high &&
  193523. *(sp ) == blue_low)
  193524. {
  193525. *dp-- = 0;
  193526. *dp-- = 0;
  193527. }
  193528. else
  193529. {
  193530. *dp-- = 0xff;
  193531. *dp-- = 0xff;
  193532. }
  193533. *dp-- = *sp--;
  193534. *dp-- = *sp--;
  193535. *dp-- = *sp--;
  193536. *dp-- = *sp--;
  193537. *dp-- = *sp--;
  193538. *dp-- = *sp--;
  193539. }
  193540. }
  193541. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193542. row_info->channels = 4;
  193543. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193544. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193545. }
  193546. }
  193547. }
  193548. #endif
  193549. #if defined(PNG_READ_DITHER_SUPPORTED)
  193550. void /* PRIVATE */
  193551. png_do_dither(png_row_infop row_info, png_bytep row,
  193552. png_bytep palette_lookup, png_bytep dither_lookup)
  193553. {
  193554. png_bytep sp, dp;
  193555. png_uint_32 i;
  193556. png_uint_32 row_width=row_info->width;
  193557. png_debug(1, "in png_do_dither\n");
  193558. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193559. if (row != NULL && row_info != NULL)
  193560. #endif
  193561. {
  193562. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193563. palette_lookup && row_info->bit_depth == 8)
  193564. {
  193565. int r, g, b, p;
  193566. sp = row;
  193567. dp = row;
  193568. for (i = 0; i < row_width; i++)
  193569. {
  193570. r = *sp++;
  193571. g = *sp++;
  193572. b = *sp++;
  193573. /* this looks real messy, but the compiler will reduce
  193574. it down to a reasonable formula. For example, with
  193575. 5 bits per color, we get:
  193576. p = (((r >> 3) & 0x1f) << 10) |
  193577. (((g >> 3) & 0x1f) << 5) |
  193578. ((b >> 3) & 0x1f);
  193579. */
  193580. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193581. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193582. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193583. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193584. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193585. (PNG_DITHER_BLUE_BITS)) |
  193586. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193587. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193588. *dp++ = palette_lookup[p];
  193589. }
  193590. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193591. row_info->channels = 1;
  193592. row_info->pixel_depth = row_info->bit_depth;
  193593. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193594. }
  193595. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193596. palette_lookup != NULL && row_info->bit_depth == 8)
  193597. {
  193598. int r, g, b, p;
  193599. sp = row;
  193600. dp = row;
  193601. for (i = 0; i < row_width; i++)
  193602. {
  193603. r = *sp++;
  193604. g = *sp++;
  193605. b = *sp++;
  193606. sp++;
  193607. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193608. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193609. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193610. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193611. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193612. (PNG_DITHER_BLUE_BITS)) |
  193613. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193614. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193615. *dp++ = palette_lookup[p];
  193616. }
  193617. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193618. row_info->channels = 1;
  193619. row_info->pixel_depth = row_info->bit_depth;
  193620. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193621. }
  193622. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193623. dither_lookup && row_info->bit_depth == 8)
  193624. {
  193625. sp = row;
  193626. for (i = 0; i < row_width; i++, sp++)
  193627. {
  193628. *sp = dither_lookup[*sp];
  193629. }
  193630. }
  193631. }
  193632. }
  193633. #endif
  193634. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193635. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193636. static PNG_CONST int png_gamma_shift[] =
  193637. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193638. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193639. * tables, we don't make a full table if we are reducing to 8-bit in
  193640. * the future. Note also how the gamma_16 tables are segmented so that
  193641. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193642. */
  193643. void /* PRIVATE */
  193644. png_build_gamma_table(png_structp png_ptr)
  193645. {
  193646. png_debug(1, "in png_build_gamma_table\n");
  193647. if (png_ptr->bit_depth <= 8)
  193648. {
  193649. int i;
  193650. double g;
  193651. if (png_ptr->screen_gamma > .000001)
  193652. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193653. else
  193654. g = 1.0;
  193655. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193656. (png_uint_32)256);
  193657. for (i = 0; i < 256; i++)
  193658. {
  193659. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193660. g) * 255.0 + .5);
  193661. }
  193662. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193663. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193664. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193665. {
  193666. g = 1.0 / (png_ptr->gamma);
  193667. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193668. (png_uint_32)256);
  193669. for (i = 0; i < 256; i++)
  193670. {
  193671. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193672. g) * 255.0 + .5);
  193673. }
  193674. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193675. (png_uint_32)256);
  193676. if(png_ptr->screen_gamma > 0.000001)
  193677. g = 1.0 / png_ptr->screen_gamma;
  193678. else
  193679. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193680. for (i = 0; i < 256; i++)
  193681. {
  193682. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193683. g) * 255.0 + .5);
  193684. }
  193685. }
  193686. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193687. }
  193688. else
  193689. {
  193690. double g;
  193691. int i, j, shift, num;
  193692. int sig_bit;
  193693. png_uint_32 ig;
  193694. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193695. {
  193696. sig_bit = (int)png_ptr->sig_bit.red;
  193697. if ((int)png_ptr->sig_bit.green > sig_bit)
  193698. sig_bit = png_ptr->sig_bit.green;
  193699. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193700. sig_bit = png_ptr->sig_bit.blue;
  193701. }
  193702. else
  193703. {
  193704. sig_bit = (int)png_ptr->sig_bit.gray;
  193705. }
  193706. if (sig_bit > 0)
  193707. shift = 16 - sig_bit;
  193708. else
  193709. shift = 0;
  193710. if (png_ptr->transformations & PNG_16_TO_8)
  193711. {
  193712. if (shift < (16 - PNG_MAX_GAMMA_8))
  193713. shift = (16 - PNG_MAX_GAMMA_8);
  193714. }
  193715. if (shift > 8)
  193716. shift = 8;
  193717. if (shift < 0)
  193718. shift = 0;
  193719. png_ptr->gamma_shift = (png_byte)shift;
  193720. num = (1 << (8 - shift));
  193721. if (png_ptr->screen_gamma > .000001)
  193722. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193723. else
  193724. g = 1.0;
  193725. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193726. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193727. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193728. {
  193729. double fin, fout;
  193730. png_uint_32 last, max;
  193731. for (i = 0; i < num; i++)
  193732. {
  193733. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193734. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193735. }
  193736. g = 1.0 / g;
  193737. last = 0;
  193738. for (i = 0; i < 256; i++)
  193739. {
  193740. fout = ((double)i + 0.5) / 256.0;
  193741. fin = pow(fout, g);
  193742. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193743. while (last <= max)
  193744. {
  193745. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193746. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193747. (png_uint_16)i | ((png_uint_16)i << 8));
  193748. last++;
  193749. }
  193750. }
  193751. while (last < ((png_uint_32)num << 8))
  193752. {
  193753. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193754. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193755. last++;
  193756. }
  193757. }
  193758. else
  193759. {
  193760. for (i = 0; i < num; i++)
  193761. {
  193762. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193763. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193764. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193765. for (j = 0; j < 256; j++)
  193766. {
  193767. png_ptr->gamma_16_table[i][j] =
  193768. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193769. 65535.0, g) * 65535.0 + .5);
  193770. }
  193771. }
  193772. }
  193773. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193774. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193775. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193776. {
  193777. g = 1.0 / (png_ptr->gamma);
  193778. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193779. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193780. for (i = 0; i < num; i++)
  193781. {
  193782. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193783. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193784. ig = (((png_uint_32)i *
  193785. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193786. for (j = 0; j < 256; j++)
  193787. {
  193788. png_ptr->gamma_16_to_1[i][j] =
  193789. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193790. 65535.0, g) * 65535.0 + .5);
  193791. }
  193792. }
  193793. if(png_ptr->screen_gamma > 0.000001)
  193794. g = 1.0 / png_ptr->screen_gamma;
  193795. else
  193796. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193797. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193798. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193799. for (i = 0; i < num; i++)
  193800. {
  193801. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193802. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193803. ig = (((png_uint_32)i *
  193804. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193805. for (j = 0; j < 256; j++)
  193806. {
  193807. png_ptr->gamma_16_from_1[i][j] =
  193808. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193809. 65535.0, g) * 65535.0 + .5);
  193810. }
  193811. }
  193812. }
  193813. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193814. }
  193815. }
  193816. #endif
  193817. /* To do: install integer version of png_build_gamma_table here */
  193818. #endif
  193819. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193820. /* undoes intrapixel differencing */
  193821. void /* PRIVATE */
  193822. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193823. {
  193824. png_debug(1, "in png_do_read_intrapixel\n");
  193825. if (
  193826. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193827. row != NULL && row_info != NULL &&
  193828. #endif
  193829. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193830. {
  193831. int bytes_per_pixel;
  193832. png_uint_32 row_width = row_info->width;
  193833. if (row_info->bit_depth == 8)
  193834. {
  193835. png_bytep rp;
  193836. png_uint_32 i;
  193837. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193838. bytes_per_pixel = 3;
  193839. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193840. bytes_per_pixel = 4;
  193841. else
  193842. return;
  193843. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193844. {
  193845. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193846. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193847. }
  193848. }
  193849. else if (row_info->bit_depth == 16)
  193850. {
  193851. png_bytep rp;
  193852. png_uint_32 i;
  193853. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193854. bytes_per_pixel = 6;
  193855. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193856. bytes_per_pixel = 8;
  193857. else
  193858. return;
  193859. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193860. {
  193861. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193862. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193863. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193864. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193865. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193866. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193867. *(rp+1) = (png_byte)(red & 0xff);
  193868. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193869. *(rp+5) = (png_byte)(blue & 0xff);
  193870. }
  193871. }
  193872. }
  193873. }
  193874. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193875. #endif /* PNG_READ_SUPPORTED */
  193876. /*** End of inlined file: pngrtran.c ***/
  193877. /*** Start of inlined file: pngrutil.c ***/
  193878. /* pngrutil.c - utilities to read a PNG file
  193879. *
  193880. * Last changed in libpng 1.2.21 [October 4, 2007]
  193881. * For conditions of distribution and use, see copyright notice in png.h
  193882. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193883. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193884. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193885. *
  193886. * This file contains routines that are only called from within
  193887. * libpng itself during the course of reading an image.
  193888. */
  193889. #define PNG_INTERNAL
  193890. #if defined(PNG_READ_SUPPORTED)
  193891. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193892. # define WIN32_WCE_OLD
  193893. #endif
  193894. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193895. # if defined(WIN32_WCE_OLD)
  193896. /* strtod() function is not supported on WindowsCE */
  193897. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193898. {
  193899. double result = 0;
  193900. int len;
  193901. wchar_t *str, *end;
  193902. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193903. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193904. if ( NULL != str )
  193905. {
  193906. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193907. result = wcstod(str, &end);
  193908. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193909. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193910. png_free(png_ptr, str);
  193911. }
  193912. return result;
  193913. }
  193914. # else
  193915. # define png_strtod(p,a,b) strtod(a,b)
  193916. # endif
  193917. #endif
  193918. png_uint_32 PNGAPI
  193919. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193920. {
  193921. png_uint_32 i = png_get_uint_32(buf);
  193922. if (i > PNG_UINT_31_MAX)
  193923. png_error(png_ptr, "PNG unsigned integer out of range.");
  193924. return (i);
  193925. }
  193926. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193927. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193928. png_uint_32 PNGAPI
  193929. png_get_uint_32(png_bytep buf)
  193930. {
  193931. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193932. ((png_uint_32)(*(buf + 1)) << 16) +
  193933. ((png_uint_32)(*(buf + 2)) << 8) +
  193934. (png_uint_32)(*(buf + 3));
  193935. return (i);
  193936. }
  193937. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193938. * data is stored in the PNG file in two's complement format, and it is
  193939. * assumed that the machine format for signed integers is the same. */
  193940. png_int_32 PNGAPI
  193941. png_get_int_32(png_bytep buf)
  193942. {
  193943. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193944. ((png_int_32)(*(buf + 1)) << 16) +
  193945. ((png_int_32)(*(buf + 2)) << 8) +
  193946. (png_int_32)(*(buf + 3));
  193947. return (i);
  193948. }
  193949. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193950. png_uint_16 PNGAPI
  193951. png_get_uint_16(png_bytep buf)
  193952. {
  193953. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193954. (png_uint_16)(*(buf + 1)));
  193955. return (i);
  193956. }
  193957. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193958. /* Read data, and (optionally) run it through the CRC. */
  193959. void /* PRIVATE */
  193960. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193961. {
  193962. if(png_ptr == NULL) return;
  193963. png_read_data(png_ptr, buf, length);
  193964. png_calculate_crc(png_ptr, buf, length);
  193965. }
  193966. /* Optionally skip data and then check the CRC. Depending on whether we
  193967. are reading a ancillary or critical chunk, and how the program has set
  193968. things up, we may calculate the CRC on the data and print a message.
  193969. Returns '1' if there was a CRC error, '0' otherwise. */
  193970. int /* PRIVATE */
  193971. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193972. {
  193973. png_size_t i;
  193974. png_size_t istop = png_ptr->zbuf_size;
  193975. for (i = (png_size_t)skip; i > istop; i -= istop)
  193976. {
  193977. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193978. }
  193979. if (i)
  193980. {
  193981. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193982. }
  193983. if (png_crc_error(png_ptr))
  193984. {
  193985. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193986. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193987. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193988. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193989. {
  193990. png_chunk_warning(png_ptr, "CRC error");
  193991. }
  193992. else
  193993. {
  193994. png_chunk_error(png_ptr, "CRC error");
  193995. }
  193996. return (1);
  193997. }
  193998. return (0);
  193999. }
  194000. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194001. the data it has read thus far. */
  194002. int /* PRIVATE */
  194003. png_crc_error(png_structp png_ptr)
  194004. {
  194005. png_byte crc_bytes[4];
  194006. png_uint_32 crc;
  194007. int need_crc = 1;
  194008. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194009. {
  194010. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194011. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194012. need_crc = 0;
  194013. }
  194014. else /* critical */
  194015. {
  194016. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194017. need_crc = 0;
  194018. }
  194019. png_read_data(png_ptr, crc_bytes, 4);
  194020. if (need_crc)
  194021. {
  194022. crc = png_get_uint_32(crc_bytes);
  194023. return ((int)(crc != png_ptr->crc));
  194024. }
  194025. else
  194026. return (0);
  194027. }
  194028. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194029. defined(PNG_READ_iCCP_SUPPORTED)
  194030. /*
  194031. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194032. * points at an allocated area holding the contents of a chunk with a
  194033. * trailing compressed part. What we get back is an allocated area
  194034. * holding the original prefix part and an uncompressed version of the
  194035. * trailing part (the malloc area passed in is freed).
  194036. */
  194037. png_charp /* PRIVATE */
  194038. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194039. png_charp chunkdata, png_size_t chunklength,
  194040. png_size_t prefix_size, png_size_t *newlength)
  194041. {
  194042. static PNG_CONST char msg[] = "Error decoding compressed text";
  194043. png_charp text;
  194044. png_size_t text_size;
  194045. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194046. {
  194047. int ret = Z_OK;
  194048. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194049. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194050. png_ptr->zstream.next_out = png_ptr->zbuf;
  194051. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194052. text_size = 0;
  194053. text = NULL;
  194054. while (png_ptr->zstream.avail_in)
  194055. {
  194056. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194057. if (ret != Z_OK && ret != Z_STREAM_END)
  194058. {
  194059. if (png_ptr->zstream.msg != NULL)
  194060. png_warning(png_ptr, png_ptr->zstream.msg);
  194061. else
  194062. png_warning(png_ptr, msg);
  194063. inflateReset(&png_ptr->zstream);
  194064. png_ptr->zstream.avail_in = 0;
  194065. if (text == NULL)
  194066. {
  194067. text_size = prefix_size + png_sizeof(msg) + 1;
  194068. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194069. if (text == NULL)
  194070. {
  194071. png_free(png_ptr,chunkdata);
  194072. png_error(png_ptr,"Not enough memory to decompress chunk");
  194073. }
  194074. png_memcpy(text, chunkdata, prefix_size);
  194075. }
  194076. text[text_size - 1] = 0x00;
  194077. /* Copy what we can of the error message into the text chunk */
  194078. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194079. text_size = png_sizeof(msg) > text_size ? text_size :
  194080. png_sizeof(msg);
  194081. png_memcpy(text + prefix_size, msg, text_size + 1);
  194082. break;
  194083. }
  194084. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194085. {
  194086. if (text == NULL)
  194087. {
  194088. text_size = prefix_size +
  194089. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194090. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194091. if (text == NULL)
  194092. {
  194093. png_free(png_ptr,chunkdata);
  194094. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194095. }
  194096. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194097. text_size - prefix_size);
  194098. png_memcpy(text, chunkdata, prefix_size);
  194099. *(text + text_size) = 0x00;
  194100. }
  194101. else
  194102. {
  194103. png_charp tmp;
  194104. tmp = text;
  194105. text = (png_charp)png_malloc_warn(png_ptr,
  194106. (png_uint_32)(text_size +
  194107. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194108. if (text == NULL)
  194109. {
  194110. png_free(png_ptr, tmp);
  194111. png_free(png_ptr, chunkdata);
  194112. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194113. }
  194114. png_memcpy(text, tmp, text_size);
  194115. png_free(png_ptr, tmp);
  194116. png_memcpy(text + text_size, png_ptr->zbuf,
  194117. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194118. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194119. *(text + text_size) = 0x00;
  194120. }
  194121. if (ret == Z_STREAM_END)
  194122. break;
  194123. else
  194124. {
  194125. png_ptr->zstream.next_out = png_ptr->zbuf;
  194126. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194127. }
  194128. }
  194129. }
  194130. if (ret != Z_STREAM_END)
  194131. {
  194132. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194133. char umsg[52];
  194134. if (ret == Z_BUF_ERROR)
  194135. png_snprintf(umsg, 52,
  194136. "Buffer error in compressed datastream in %s chunk",
  194137. png_ptr->chunk_name);
  194138. else if (ret == Z_DATA_ERROR)
  194139. png_snprintf(umsg, 52,
  194140. "Data error in compressed datastream in %s chunk",
  194141. png_ptr->chunk_name);
  194142. else
  194143. png_snprintf(umsg, 52,
  194144. "Incomplete compressed datastream in %s chunk",
  194145. png_ptr->chunk_name);
  194146. png_warning(png_ptr, umsg);
  194147. #else
  194148. png_warning(png_ptr,
  194149. "Incomplete compressed datastream in chunk other than IDAT");
  194150. #endif
  194151. text_size=prefix_size;
  194152. if (text == NULL)
  194153. {
  194154. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194155. if (text == NULL)
  194156. {
  194157. png_free(png_ptr, chunkdata);
  194158. png_error(png_ptr,"Not enough memory for text.");
  194159. }
  194160. png_memcpy(text, chunkdata, prefix_size);
  194161. }
  194162. *(text + text_size) = 0x00;
  194163. }
  194164. inflateReset(&png_ptr->zstream);
  194165. png_ptr->zstream.avail_in = 0;
  194166. png_free(png_ptr, chunkdata);
  194167. chunkdata = text;
  194168. *newlength=text_size;
  194169. }
  194170. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194171. {
  194172. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194173. char umsg[50];
  194174. png_snprintf(umsg, 50,
  194175. "Unknown zTXt compression type %d", comp_type);
  194176. png_warning(png_ptr, umsg);
  194177. #else
  194178. png_warning(png_ptr, "Unknown zTXt compression type");
  194179. #endif
  194180. *(chunkdata + prefix_size) = 0x00;
  194181. *newlength=prefix_size;
  194182. }
  194183. return chunkdata;
  194184. }
  194185. #endif
  194186. /* read and check the IDHR chunk */
  194187. void /* PRIVATE */
  194188. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194189. {
  194190. png_byte buf[13];
  194191. png_uint_32 width, height;
  194192. int bit_depth, color_type, compression_type, filter_type;
  194193. int interlace_type;
  194194. png_debug(1, "in png_handle_IHDR\n");
  194195. if (png_ptr->mode & PNG_HAVE_IHDR)
  194196. png_error(png_ptr, "Out of place IHDR");
  194197. /* check the length */
  194198. if (length != 13)
  194199. png_error(png_ptr, "Invalid IHDR chunk");
  194200. png_ptr->mode |= PNG_HAVE_IHDR;
  194201. png_crc_read(png_ptr, buf, 13);
  194202. png_crc_finish(png_ptr, 0);
  194203. width = png_get_uint_31(png_ptr, buf);
  194204. height = png_get_uint_31(png_ptr, buf + 4);
  194205. bit_depth = buf[8];
  194206. color_type = buf[9];
  194207. compression_type = buf[10];
  194208. filter_type = buf[11];
  194209. interlace_type = buf[12];
  194210. /* set internal variables */
  194211. png_ptr->width = width;
  194212. png_ptr->height = height;
  194213. png_ptr->bit_depth = (png_byte)bit_depth;
  194214. png_ptr->interlaced = (png_byte)interlace_type;
  194215. png_ptr->color_type = (png_byte)color_type;
  194216. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194217. png_ptr->filter_type = (png_byte)filter_type;
  194218. #endif
  194219. png_ptr->compression_type = (png_byte)compression_type;
  194220. /* find number of channels */
  194221. switch (png_ptr->color_type)
  194222. {
  194223. case PNG_COLOR_TYPE_GRAY:
  194224. case PNG_COLOR_TYPE_PALETTE:
  194225. png_ptr->channels = 1;
  194226. break;
  194227. case PNG_COLOR_TYPE_RGB:
  194228. png_ptr->channels = 3;
  194229. break;
  194230. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194231. png_ptr->channels = 2;
  194232. break;
  194233. case PNG_COLOR_TYPE_RGB_ALPHA:
  194234. png_ptr->channels = 4;
  194235. break;
  194236. }
  194237. /* set up other useful info */
  194238. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194239. png_ptr->channels);
  194240. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194241. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194242. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194243. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194244. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194245. color_type, interlace_type, compression_type, filter_type);
  194246. }
  194247. /* read and check the palette */
  194248. void /* PRIVATE */
  194249. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194250. {
  194251. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194252. int num, i;
  194253. #ifndef PNG_NO_POINTER_INDEXING
  194254. png_colorp pal_ptr;
  194255. #endif
  194256. png_debug(1, "in png_handle_PLTE\n");
  194257. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194258. png_error(png_ptr, "Missing IHDR before PLTE");
  194259. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194260. {
  194261. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194262. png_crc_finish(png_ptr, length);
  194263. return;
  194264. }
  194265. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194266. png_error(png_ptr, "Duplicate PLTE chunk");
  194267. png_ptr->mode |= PNG_HAVE_PLTE;
  194268. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194269. {
  194270. png_warning(png_ptr,
  194271. "Ignoring PLTE chunk in grayscale PNG");
  194272. png_crc_finish(png_ptr, length);
  194273. return;
  194274. }
  194275. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194276. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194277. {
  194278. png_crc_finish(png_ptr, length);
  194279. return;
  194280. }
  194281. #endif
  194282. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194283. {
  194284. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194285. {
  194286. png_warning(png_ptr, "Invalid palette chunk");
  194287. png_crc_finish(png_ptr, length);
  194288. return;
  194289. }
  194290. else
  194291. {
  194292. png_error(png_ptr, "Invalid palette chunk");
  194293. }
  194294. }
  194295. num = (int)length / 3;
  194296. #ifndef PNG_NO_POINTER_INDEXING
  194297. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194298. {
  194299. png_byte buf[3];
  194300. png_crc_read(png_ptr, buf, 3);
  194301. pal_ptr->red = buf[0];
  194302. pal_ptr->green = buf[1];
  194303. pal_ptr->blue = buf[2];
  194304. }
  194305. #else
  194306. for (i = 0; i < num; i++)
  194307. {
  194308. png_byte buf[3];
  194309. png_crc_read(png_ptr, buf, 3);
  194310. /* don't depend upon png_color being any order */
  194311. palette[i].red = buf[0];
  194312. palette[i].green = buf[1];
  194313. palette[i].blue = buf[2];
  194314. }
  194315. #endif
  194316. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194317. whatever the normal CRC configuration tells us. However, if we
  194318. have an RGB image, the PLTE can be considered ancillary, so
  194319. we will act as though it is. */
  194320. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194321. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194322. #endif
  194323. {
  194324. png_crc_finish(png_ptr, 0);
  194325. }
  194326. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194327. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194328. {
  194329. /* If we don't want to use the data from an ancillary chunk,
  194330. we have two options: an error abort, or a warning and we
  194331. ignore the data in this chunk (which should be OK, since
  194332. it's considered ancillary for a RGB or RGBA image). */
  194333. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194334. {
  194335. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194336. {
  194337. png_chunk_error(png_ptr, "CRC error");
  194338. }
  194339. else
  194340. {
  194341. png_chunk_warning(png_ptr, "CRC error");
  194342. return;
  194343. }
  194344. }
  194345. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194346. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194347. {
  194348. png_chunk_warning(png_ptr, "CRC error");
  194349. }
  194350. }
  194351. #endif
  194352. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194353. #if defined(PNG_READ_tRNS_SUPPORTED)
  194354. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194355. {
  194356. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194357. {
  194358. if (png_ptr->num_trans > (png_uint_16)num)
  194359. {
  194360. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194361. png_ptr->num_trans = (png_uint_16)num;
  194362. }
  194363. if (info_ptr->num_trans > (png_uint_16)num)
  194364. {
  194365. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194366. info_ptr->num_trans = (png_uint_16)num;
  194367. }
  194368. }
  194369. }
  194370. #endif
  194371. }
  194372. void /* PRIVATE */
  194373. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194374. {
  194375. png_debug(1, "in png_handle_IEND\n");
  194376. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194377. {
  194378. png_error(png_ptr, "No image in file");
  194379. }
  194380. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194381. if (length != 0)
  194382. {
  194383. png_warning(png_ptr, "Incorrect IEND chunk length");
  194384. }
  194385. png_crc_finish(png_ptr, length);
  194386. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194387. }
  194388. #if defined(PNG_READ_gAMA_SUPPORTED)
  194389. void /* PRIVATE */
  194390. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194391. {
  194392. png_fixed_point igamma;
  194393. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194394. float file_gamma;
  194395. #endif
  194396. png_byte buf[4];
  194397. png_debug(1, "in png_handle_gAMA\n");
  194398. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194399. png_error(png_ptr, "Missing IHDR before gAMA");
  194400. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194401. {
  194402. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194403. png_crc_finish(png_ptr, length);
  194404. return;
  194405. }
  194406. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194407. /* Should be an error, but we can cope with it */
  194408. png_warning(png_ptr, "Out of place gAMA chunk");
  194409. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194410. #if defined(PNG_READ_sRGB_SUPPORTED)
  194411. && !(info_ptr->valid & PNG_INFO_sRGB)
  194412. #endif
  194413. )
  194414. {
  194415. png_warning(png_ptr, "Duplicate gAMA chunk");
  194416. png_crc_finish(png_ptr, length);
  194417. return;
  194418. }
  194419. if (length != 4)
  194420. {
  194421. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194422. png_crc_finish(png_ptr, length);
  194423. return;
  194424. }
  194425. png_crc_read(png_ptr, buf, 4);
  194426. if (png_crc_finish(png_ptr, 0))
  194427. return;
  194428. igamma = (png_fixed_point)png_get_uint_32(buf);
  194429. /* check for zero gamma */
  194430. if (igamma == 0)
  194431. {
  194432. png_warning(png_ptr,
  194433. "Ignoring gAMA chunk with gamma=0");
  194434. return;
  194435. }
  194436. #if defined(PNG_READ_sRGB_SUPPORTED)
  194437. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194438. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194439. {
  194440. png_warning(png_ptr,
  194441. "Ignoring incorrect gAMA value when sRGB is also present");
  194442. #ifndef PNG_NO_CONSOLE_IO
  194443. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194444. #endif
  194445. return;
  194446. }
  194447. #endif /* PNG_READ_sRGB_SUPPORTED */
  194448. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194449. file_gamma = (float)igamma / (float)100000.0;
  194450. # ifdef PNG_READ_GAMMA_SUPPORTED
  194451. png_ptr->gamma = file_gamma;
  194452. # endif
  194453. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194454. #endif
  194455. #ifdef PNG_FIXED_POINT_SUPPORTED
  194456. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194457. #endif
  194458. }
  194459. #endif
  194460. #if defined(PNG_READ_sBIT_SUPPORTED)
  194461. void /* PRIVATE */
  194462. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194463. {
  194464. png_size_t truelen;
  194465. png_byte buf[4];
  194466. png_debug(1, "in png_handle_sBIT\n");
  194467. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194468. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194469. png_error(png_ptr, "Missing IHDR before sBIT");
  194470. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194471. {
  194472. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194473. png_crc_finish(png_ptr, length);
  194474. return;
  194475. }
  194476. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194477. {
  194478. /* Should be an error, but we can cope with it */
  194479. png_warning(png_ptr, "Out of place sBIT chunk");
  194480. }
  194481. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194482. {
  194483. png_warning(png_ptr, "Duplicate sBIT chunk");
  194484. png_crc_finish(png_ptr, length);
  194485. return;
  194486. }
  194487. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194488. truelen = 3;
  194489. else
  194490. truelen = (png_size_t)png_ptr->channels;
  194491. if (length != truelen || length > 4)
  194492. {
  194493. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194494. png_crc_finish(png_ptr, length);
  194495. return;
  194496. }
  194497. png_crc_read(png_ptr, buf, truelen);
  194498. if (png_crc_finish(png_ptr, 0))
  194499. return;
  194500. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194501. {
  194502. png_ptr->sig_bit.red = buf[0];
  194503. png_ptr->sig_bit.green = buf[1];
  194504. png_ptr->sig_bit.blue = buf[2];
  194505. png_ptr->sig_bit.alpha = buf[3];
  194506. }
  194507. else
  194508. {
  194509. png_ptr->sig_bit.gray = buf[0];
  194510. png_ptr->sig_bit.red = buf[0];
  194511. png_ptr->sig_bit.green = buf[0];
  194512. png_ptr->sig_bit.blue = buf[0];
  194513. png_ptr->sig_bit.alpha = buf[1];
  194514. }
  194515. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194516. }
  194517. #endif
  194518. #if defined(PNG_READ_cHRM_SUPPORTED)
  194519. void /* PRIVATE */
  194520. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194521. {
  194522. png_byte buf[4];
  194523. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194524. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194525. #endif
  194526. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194527. int_y_green, int_x_blue, int_y_blue;
  194528. png_uint_32 uint_x, uint_y;
  194529. png_debug(1, "in png_handle_cHRM\n");
  194530. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194531. png_error(png_ptr, "Missing IHDR before cHRM");
  194532. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194533. {
  194534. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194535. png_crc_finish(png_ptr, length);
  194536. return;
  194537. }
  194538. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194539. /* Should be an error, but we can cope with it */
  194540. png_warning(png_ptr, "Missing PLTE before cHRM");
  194541. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194542. #if defined(PNG_READ_sRGB_SUPPORTED)
  194543. && !(info_ptr->valid & PNG_INFO_sRGB)
  194544. #endif
  194545. )
  194546. {
  194547. png_warning(png_ptr, "Duplicate cHRM chunk");
  194548. png_crc_finish(png_ptr, length);
  194549. return;
  194550. }
  194551. if (length != 32)
  194552. {
  194553. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194554. png_crc_finish(png_ptr, length);
  194555. return;
  194556. }
  194557. png_crc_read(png_ptr, buf, 4);
  194558. uint_x = png_get_uint_32(buf);
  194559. png_crc_read(png_ptr, buf, 4);
  194560. uint_y = png_get_uint_32(buf);
  194561. if (uint_x > 80000L || uint_y > 80000L ||
  194562. uint_x + uint_y > 100000L)
  194563. {
  194564. png_warning(png_ptr, "Invalid cHRM white point");
  194565. png_crc_finish(png_ptr, 24);
  194566. return;
  194567. }
  194568. int_x_white = (png_fixed_point)uint_x;
  194569. int_y_white = (png_fixed_point)uint_y;
  194570. png_crc_read(png_ptr, buf, 4);
  194571. uint_x = png_get_uint_32(buf);
  194572. png_crc_read(png_ptr, buf, 4);
  194573. uint_y = png_get_uint_32(buf);
  194574. if (uint_x + uint_y > 100000L)
  194575. {
  194576. png_warning(png_ptr, "Invalid cHRM red point");
  194577. png_crc_finish(png_ptr, 16);
  194578. return;
  194579. }
  194580. int_x_red = (png_fixed_point)uint_x;
  194581. int_y_red = (png_fixed_point)uint_y;
  194582. png_crc_read(png_ptr, buf, 4);
  194583. uint_x = png_get_uint_32(buf);
  194584. png_crc_read(png_ptr, buf, 4);
  194585. uint_y = png_get_uint_32(buf);
  194586. if (uint_x + uint_y > 100000L)
  194587. {
  194588. png_warning(png_ptr, "Invalid cHRM green point");
  194589. png_crc_finish(png_ptr, 8);
  194590. return;
  194591. }
  194592. int_x_green = (png_fixed_point)uint_x;
  194593. int_y_green = (png_fixed_point)uint_y;
  194594. png_crc_read(png_ptr, buf, 4);
  194595. uint_x = png_get_uint_32(buf);
  194596. png_crc_read(png_ptr, buf, 4);
  194597. uint_y = png_get_uint_32(buf);
  194598. if (uint_x + uint_y > 100000L)
  194599. {
  194600. png_warning(png_ptr, "Invalid cHRM blue point");
  194601. png_crc_finish(png_ptr, 0);
  194602. return;
  194603. }
  194604. int_x_blue = (png_fixed_point)uint_x;
  194605. int_y_blue = (png_fixed_point)uint_y;
  194606. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194607. white_x = (float)int_x_white / (float)100000.0;
  194608. white_y = (float)int_y_white / (float)100000.0;
  194609. red_x = (float)int_x_red / (float)100000.0;
  194610. red_y = (float)int_y_red / (float)100000.0;
  194611. green_x = (float)int_x_green / (float)100000.0;
  194612. green_y = (float)int_y_green / (float)100000.0;
  194613. blue_x = (float)int_x_blue / (float)100000.0;
  194614. blue_y = (float)int_y_blue / (float)100000.0;
  194615. #endif
  194616. #if defined(PNG_READ_sRGB_SUPPORTED)
  194617. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194618. {
  194619. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194620. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194621. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194622. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194623. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194624. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194625. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194626. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194627. {
  194628. png_warning(png_ptr,
  194629. "Ignoring incorrect cHRM value when sRGB is also present");
  194630. #ifndef PNG_NO_CONSOLE_IO
  194631. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194632. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194633. white_x, white_y, red_x, red_y);
  194634. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194635. green_x, green_y, blue_x, blue_y);
  194636. #else
  194637. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194638. int_x_white, int_y_white, int_x_red, int_y_red);
  194639. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194640. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194641. #endif
  194642. #endif /* PNG_NO_CONSOLE_IO */
  194643. }
  194644. png_crc_finish(png_ptr, 0);
  194645. return;
  194646. }
  194647. #endif /* PNG_READ_sRGB_SUPPORTED */
  194648. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194649. png_set_cHRM(png_ptr, info_ptr,
  194650. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194651. #endif
  194652. #ifdef PNG_FIXED_POINT_SUPPORTED
  194653. png_set_cHRM_fixed(png_ptr, info_ptr,
  194654. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194655. int_y_green, int_x_blue, int_y_blue);
  194656. #endif
  194657. if (png_crc_finish(png_ptr, 0))
  194658. return;
  194659. }
  194660. #endif
  194661. #if defined(PNG_READ_sRGB_SUPPORTED)
  194662. void /* PRIVATE */
  194663. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194664. {
  194665. int intent;
  194666. png_byte buf[1];
  194667. png_debug(1, "in png_handle_sRGB\n");
  194668. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194669. png_error(png_ptr, "Missing IHDR before sRGB");
  194670. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194671. {
  194672. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194673. png_crc_finish(png_ptr, length);
  194674. return;
  194675. }
  194676. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194677. /* Should be an error, but we can cope with it */
  194678. png_warning(png_ptr, "Out of place sRGB chunk");
  194679. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194680. {
  194681. png_warning(png_ptr, "Duplicate sRGB chunk");
  194682. png_crc_finish(png_ptr, length);
  194683. return;
  194684. }
  194685. if (length != 1)
  194686. {
  194687. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194688. png_crc_finish(png_ptr, length);
  194689. return;
  194690. }
  194691. png_crc_read(png_ptr, buf, 1);
  194692. if (png_crc_finish(png_ptr, 0))
  194693. return;
  194694. intent = buf[0];
  194695. /* check for bad intent */
  194696. if (intent >= PNG_sRGB_INTENT_LAST)
  194697. {
  194698. png_warning(png_ptr, "Unknown sRGB intent");
  194699. return;
  194700. }
  194701. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194702. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194703. {
  194704. png_fixed_point igamma;
  194705. #ifdef PNG_FIXED_POINT_SUPPORTED
  194706. igamma=info_ptr->int_gamma;
  194707. #else
  194708. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194709. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194710. # endif
  194711. #endif
  194712. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194713. {
  194714. png_warning(png_ptr,
  194715. "Ignoring incorrect gAMA value when sRGB is also present");
  194716. #ifndef PNG_NO_CONSOLE_IO
  194717. # ifdef PNG_FIXED_POINT_SUPPORTED
  194718. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194719. # else
  194720. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194721. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194722. # endif
  194723. # endif
  194724. #endif
  194725. }
  194726. }
  194727. #endif /* PNG_READ_gAMA_SUPPORTED */
  194728. #ifdef PNG_READ_cHRM_SUPPORTED
  194729. #ifdef PNG_FIXED_POINT_SUPPORTED
  194730. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194731. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194732. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194733. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194734. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194735. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194736. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194737. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194738. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194739. {
  194740. png_warning(png_ptr,
  194741. "Ignoring incorrect cHRM value when sRGB is also present");
  194742. }
  194743. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194744. #endif /* PNG_READ_cHRM_SUPPORTED */
  194745. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194746. }
  194747. #endif /* PNG_READ_sRGB_SUPPORTED */
  194748. #if defined(PNG_READ_iCCP_SUPPORTED)
  194749. void /* PRIVATE */
  194750. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194751. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194752. {
  194753. png_charp chunkdata;
  194754. png_byte compression_type;
  194755. png_bytep pC;
  194756. png_charp profile;
  194757. png_uint_32 skip = 0;
  194758. png_uint_32 profile_size, profile_length;
  194759. png_size_t slength, prefix_length, data_length;
  194760. png_debug(1, "in png_handle_iCCP\n");
  194761. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194762. png_error(png_ptr, "Missing IHDR before iCCP");
  194763. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194764. {
  194765. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194766. png_crc_finish(png_ptr, length);
  194767. return;
  194768. }
  194769. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194770. /* Should be an error, but we can cope with it */
  194771. png_warning(png_ptr, "Out of place iCCP chunk");
  194772. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194773. {
  194774. png_warning(png_ptr, "Duplicate iCCP chunk");
  194775. png_crc_finish(png_ptr, length);
  194776. return;
  194777. }
  194778. #ifdef PNG_MAX_MALLOC_64K
  194779. if (length > (png_uint_32)65535L)
  194780. {
  194781. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194782. skip = length - (png_uint_32)65535L;
  194783. length = (png_uint_32)65535L;
  194784. }
  194785. #endif
  194786. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194787. slength = (png_size_t)length;
  194788. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194789. if (png_crc_finish(png_ptr, skip))
  194790. {
  194791. png_free(png_ptr, chunkdata);
  194792. return;
  194793. }
  194794. chunkdata[slength] = 0x00;
  194795. for (profile = chunkdata; *profile; profile++)
  194796. /* empty loop to find end of name */ ;
  194797. ++profile;
  194798. /* there should be at least one zero (the compression type byte)
  194799. following the separator, and we should be on it */
  194800. if ( profile >= chunkdata + slength - 1)
  194801. {
  194802. png_free(png_ptr, chunkdata);
  194803. png_warning(png_ptr, "Malformed iCCP chunk");
  194804. return;
  194805. }
  194806. /* compression_type should always be zero */
  194807. compression_type = *profile++;
  194808. if (compression_type)
  194809. {
  194810. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194811. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194812. wrote nonzero) */
  194813. }
  194814. prefix_length = profile - chunkdata;
  194815. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194816. slength, prefix_length, &data_length);
  194817. profile_length = data_length - prefix_length;
  194818. if ( prefix_length > data_length || profile_length < 4)
  194819. {
  194820. png_free(png_ptr, chunkdata);
  194821. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194822. return;
  194823. }
  194824. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194825. pC = (png_bytep)(chunkdata+prefix_length);
  194826. profile_size = ((*(pC ))<<24) |
  194827. ((*(pC+1))<<16) |
  194828. ((*(pC+2))<< 8) |
  194829. ((*(pC+3)) );
  194830. if(profile_size < profile_length)
  194831. profile_length = profile_size;
  194832. if(profile_size > profile_length)
  194833. {
  194834. png_free(png_ptr, chunkdata);
  194835. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194836. return;
  194837. }
  194838. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194839. chunkdata + prefix_length, profile_length);
  194840. png_free(png_ptr, chunkdata);
  194841. }
  194842. #endif /* PNG_READ_iCCP_SUPPORTED */
  194843. #if defined(PNG_READ_sPLT_SUPPORTED)
  194844. void /* PRIVATE */
  194845. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194846. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194847. {
  194848. png_bytep chunkdata;
  194849. png_bytep entry_start;
  194850. png_sPLT_t new_palette;
  194851. #ifdef PNG_NO_POINTER_INDEXING
  194852. png_sPLT_entryp pp;
  194853. #endif
  194854. int data_length, entry_size, i;
  194855. png_uint_32 skip = 0;
  194856. png_size_t slength;
  194857. png_debug(1, "in png_handle_sPLT\n");
  194858. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194859. png_error(png_ptr, "Missing IHDR before sPLT");
  194860. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194861. {
  194862. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194863. png_crc_finish(png_ptr, length);
  194864. return;
  194865. }
  194866. #ifdef PNG_MAX_MALLOC_64K
  194867. if (length > (png_uint_32)65535L)
  194868. {
  194869. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194870. skip = length - (png_uint_32)65535L;
  194871. length = (png_uint_32)65535L;
  194872. }
  194873. #endif
  194874. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194875. slength = (png_size_t)length;
  194876. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194877. if (png_crc_finish(png_ptr, skip))
  194878. {
  194879. png_free(png_ptr, chunkdata);
  194880. return;
  194881. }
  194882. chunkdata[slength] = 0x00;
  194883. for (entry_start = chunkdata; *entry_start; entry_start++)
  194884. /* empty loop to find end of name */ ;
  194885. ++entry_start;
  194886. /* a sample depth should follow the separator, and we should be on it */
  194887. if (entry_start > chunkdata + slength - 2)
  194888. {
  194889. png_free(png_ptr, chunkdata);
  194890. png_warning(png_ptr, "malformed sPLT chunk");
  194891. return;
  194892. }
  194893. new_palette.depth = *entry_start++;
  194894. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194895. data_length = (slength - (entry_start - chunkdata));
  194896. /* integrity-check the data length */
  194897. if (data_length % entry_size)
  194898. {
  194899. png_free(png_ptr, chunkdata);
  194900. png_warning(png_ptr, "sPLT chunk has bad length");
  194901. return;
  194902. }
  194903. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194904. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194905. png_sizeof(png_sPLT_entry)))
  194906. {
  194907. png_warning(png_ptr, "sPLT chunk too long");
  194908. return;
  194909. }
  194910. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194911. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194912. if (new_palette.entries == NULL)
  194913. {
  194914. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194915. return;
  194916. }
  194917. #ifndef PNG_NO_POINTER_INDEXING
  194918. for (i = 0; i < new_palette.nentries; i++)
  194919. {
  194920. png_sPLT_entryp pp = new_palette.entries + i;
  194921. if (new_palette.depth == 8)
  194922. {
  194923. pp->red = *entry_start++;
  194924. pp->green = *entry_start++;
  194925. pp->blue = *entry_start++;
  194926. pp->alpha = *entry_start++;
  194927. }
  194928. else
  194929. {
  194930. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194931. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194932. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194933. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194934. }
  194935. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194936. }
  194937. #else
  194938. pp = new_palette.entries;
  194939. for (i = 0; i < new_palette.nentries; i++)
  194940. {
  194941. if (new_palette.depth == 8)
  194942. {
  194943. pp[i].red = *entry_start++;
  194944. pp[i].green = *entry_start++;
  194945. pp[i].blue = *entry_start++;
  194946. pp[i].alpha = *entry_start++;
  194947. }
  194948. else
  194949. {
  194950. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194951. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194952. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194953. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194954. }
  194955. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194956. }
  194957. #endif
  194958. /* discard all chunk data except the name and stash that */
  194959. new_palette.name = (png_charp)chunkdata;
  194960. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194961. png_free(png_ptr, chunkdata);
  194962. png_free(png_ptr, new_palette.entries);
  194963. }
  194964. #endif /* PNG_READ_sPLT_SUPPORTED */
  194965. #if defined(PNG_READ_tRNS_SUPPORTED)
  194966. void /* PRIVATE */
  194967. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194968. {
  194969. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194970. int bit_mask;
  194971. png_debug(1, "in png_handle_tRNS\n");
  194972. /* For non-indexed color, mask off any bits in the tRNS value that
  194973. * exceed the bit depth. Some creators were writing extra bits there.
  194974. * This is not needed for indexed color. */
  194975. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194976. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194977. png_error(png_ptr, "Missing IHDR before tRNS");
  194978. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194979. {
  194980. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194981. png_crc_finish(png_ptr, length);
  194982. return;
  194983. }
  194984. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194985. {
  194986. png_warning(png_ptr, "Duplicate tRNS chunk");
  194987. png_crc_finish(png_ptr, length);
  194988. return;
  194989. }
  194990. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194991. {
  194992. png_byte buf[2];
  194993. if (length != 2)
  194994. {
  194995. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194996. png_crc_finish(png_ptr, length);
  194997. return;
  194998. }
  194999. png_crc_read(png_ptr, buf, 2);
  195000. png_ptr->num_trans = 1;
  195001. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195002. }
  195003. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195004. {
  195005. png_byte buf[6];
  195006. if (length != 6)
  195007. {
  195008. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195009. png_crc_finish(png_ptr, length);
  195010. return;
  195011. }
  195012. png_crc_read(png_ptr, buf, (png_size_t)length);
  195013. png_ptr->num_trans = 1;
  195014. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195015. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195016. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195017. }
  195018. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195019. {
  195020. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195021. {
  195022. /* Should be an error, but we can cope with it. */
  195023. png_warning(png_ptr, "Missing PLTE before tRNS");
  195024. }
  195025. if (length > (png_uint_32)png_ptr->num_palette ||
  195026. length > PNG_MAX_PALETTE_LENGTH)
  195027. {
  195028. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195029. png_crc_finish(png_ptr, length);
  195030. return;
  195031. }
  195032. if (length == 0)
  195033. {
  195034. png_warning(png_ptr, "Zero length tRNS chunk");
  195035. png_crc_finish(png_ptr, length);
  195036. return;
  195037. }
  195038. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195039. png_ptr->num_trans = (png_uint_16)length;
  195040. }
  195041. else
  195042. {
  195043. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195044. png_crc_finish(png_ptr, length);
  195045. return;
  195046. }
  195047. if (png_crc_finish(png_ptr, 0))
  195048. {
  195049. png_ptr->num_trans = 0;
  195050. return;
  195051. }
  195052. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195053. &(png_ptr->trans_values));
  195054. }
  195055. #endif
  195056. #if defined(PNG_READ_bKGD_SUPPORTED)
  195057. void /* PRIVATE */
  195058. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195059. {
  195060. png_size_t truelen;
  195061. png_byte buf[6];
  195062. png_debug(1, "in png_handle_bKGD\n");
  195063. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195064. png_error(png_ptr, "Missing IHDR before bKGD");
  195065. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195066. {
  195067. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195068. png_crc_finish(png_ptr, length);
  195069. return;
  195070. }
  195071. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195072. !(png_ptr->mode & PNG_HAVE_PLTE))
  195073. {
  195074. png_warning(png_ptr, "Missing PLTE before bKGD");
  195075. png_crc_finish(png_ptr, length);
  195076. return;
  195077. }
  195078. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195079. {
  195080. png_warning(png_ptr, "Duplicate bKGD chunk");
  195081. png_crc_finish(png_ptr, length);
  195082. return;
  195083. }
  195084. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195085. truelen = 1;
  195086. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195087. truelen = 6;
  195088. else
  195089. truelen = 2;
  195090. if (length != truelen)
  195091. {
  195092. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195093. png_crc_finish(png_ptr, length);
  195094. return;
  195095. }
  195096. png_crc_read(png_ptr, buf, truelen);
  195097. if (png_crc_finish(png_ptr, 0))
  195098. return;
  195099. /* We convert the index value into RGB components so that we can allow
  195100. * arbitrary RGB values for background when we have transparency, and
  195101. * so it is easy to determine the RGB values of the background color
  195102. * from the info_ptr struct. */
  195103. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195104. {
  195105. png_ptr->background.index = buf[0];
  195106. if(info_ptr->num_palette)
  195107. {
  195108. if(buf[0] > info_ptr->num_palette)
  195109. {
  195110. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195111. return;
  195112. }
  195113. png_ptr->background.red =
  195114. (png_uint_16)png_ptr->palette[buf[0]].red;
  195115. png_ptr->background.green =
  195116. (png_uint_16)png_ptr->palette[buf[0]].green;
  195117. png_ptr->background.blue =
  195118. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195119. }
  195120. }
  195121. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195122. {
  195123. png_ptr->background.red =
  195124. png_ptr->background.green =
  195125. png_ptr->background.blue =
  195126. png_ptr->background.gray = png_get_uint_16(buf);
  195127. }
  195128. else
  195129. {
  195130. png_ptr->background.red = png_get_uint_16(buf);
  195131. png_ptr->background.green = png_get_uint_16(buf + 2);
  195132. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195133. }
  195134. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195135. }
  195136. #endif
  195137. #if defined(PNG_READ_hIST_SUPPORTED)
  195138. void /* PRIVATE */
  195139. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195140. {
  195141. unsigned int num, i;
  195142. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195143. png_debug(1, "in png_handle_hIST\n");
  195144. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195145. png_error(png_ptr, "Missing IHDR before hIST");
  195146. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195147. {
  195148. png_warning(png_ptr, "Invalid hIST after IDAT");
  195149. png_crc_finish(png_ptr, length);
  195150. return;
  195151. }
  195152. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195153. {
  195154. png_warning(png_ptr, "Missing PLTE before hIST");
  195155. png_crc_finish(png_ptr, length);
  195156. return;
  195157. }
  195158. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195159. {
  195160. png_warning(png_ptr, "Duplicate hIST chunk");
  195161. png_crc_finish(png_ptr, length);
  195162. return;
  195163. }
  195164. num = length / 2 ;
  195165. if (num != (unsigned int) png_ptr->num_palette || num >
  195166. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195167. {
  195168. png_warning(png_ptr, "Incorrect hIST chunk length");
  195169. png_crc_finish(png_ptr, length);
  195170. return;
  195171. }
  195172. for (i = 0; i < num; i++)
  195173. {
  195174. png_byte buf[2];
  195175. png_crc_read(png_ptr, buf, 2);
  195176. readbuf[i] = png_get_uint_16(buf);
  195177. }
  195178. if (png_crc_finish(png_ptr, 0))
  195179. return;
  195180. png_set_hIST(png_ptr, info_ptr, readbuf);
  195181. }
  195182. #endif
  195183. #if defined(PNG_READ_pHYs_SUPPORTED)
  195184. void /* PRIVATE */
  195185. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195186. {
  195187. png_byte buf[9];
  195188. png_uint_32 res_x, res_y;
  195189. int unit_type;
  195190. png_debug(1, "in png_handle_pHYs\n");
  195191. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195192. png_error(png_ptr, "Missing IHDR before pHYs");
  195193. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195194. {
  195195. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195196. png_crc_finish(png_ptr, length);
  195197. return;
  195198. }
  195199. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195200. {
  195201. png_warning(png_ptr, "Duplicate pHYs chunk");
  195202. png_crc_finish(png_ptr, length);
  195203. return;
  195204. }
  195205. if (length != 9)
  195206. {
  195207. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195208. png_crc_finish(png_ptr, length);
  195209. return;
  195210. }
  195211. png_crc_read(png_ptr, buf, 9);
  195212. if (png_crc_finish(png_ptr, 0))
  195213. return;
  195214. res_x = png_get_uint_32(buf);
  195215. res_y = png_get_uint_32(buf + 4);
  195216. unit_type = buf[8];
  195217. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195218. }
  195219. #endif
  195220. #if defined(PNG_READ_oFFs_SUPPORTED)
  195221. void /* PRIVATE */
  195222. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195223. {
  195224. png_byte buf[9];
  195225. png_int_32 offset_x, offset_y;
  195226. int unit_type;
  195227. png_debug(1, "in png_handle_oFFs\n");
  195228. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195229. png_error(png_ptr, "Missing IHDR before oFFs");
  195230. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195231. {
  195232. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195233. png_crc_finish(png_ptr, length);
  195234. return;
  195235. }
  195236. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195237. {
  195238. png_warning(png_ptr, "Duplicate oFFs chunk");
  195239. png_crc_finish(png_ptr, length);
  195240. return;
  195241. }
  195242. if (length != 9)
  195243. {
  195244. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195245. png_crc_finish(png_ptr, length);
  195246. return;
  195247. }
  195248. png_crc_read(png_ptr, buf, 9);
  195249. if (png_crc_finish(png_ptr, 0))
  195250. return;
  195251. offset_x = png_get_int_32(buf);
  195252. offset_y = png_get_int_32(buf + 4);
  195253. unit_type = buf[8];
  195254. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195255. }
  195256. #endif
  195257. #if defined(PNG_READ_pCAL_SUPPORTED)
  195258. /* read the pCAL chunk (described in the PNG Extensions document) */
  195259. void /* PRIVATE */
  195260. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195261. {
  195262. png_charp purpose;
  195263. png_int_32 X0, X1;
  195264. png_byte type, nparams;
  195265. png_charp buf, units, endptr;
  195266. png_charpp params;
  195267. png_size_t slength;
  195268. int i;
  195269. png_debug(1, "in png_handle_pCAL\n");
  195270. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195271. png_error(png_ptr, "Missing IHDR before pCAL");
  195272. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195273. {
  195274. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195275. png_crc_finish(png_ptr, length);
  195276. return;
  195277. }
  195278. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195279. {
  195280. png_warning(png_ptr, "Duplicate pCAL chunk");
  195281. png_crc_finish(png_ptr, length);
  195282. return;
  195283. }
  195284. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195285. length + 1);
  195286. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195287. if (purpose == NULL)
  195288. {
  195289. png_warning(png_ptr, "No memory for pCAL purpose.");
  195290. return;
  195291. }
  195292. slength = (png_size_t)length;
  195293. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195294. if (png_crc_finish(png_ptr, 0))
  195295. {
  195296. png_free(png_ptr, purpose);
  195297. return;
  195298. }
  195299. purpose[slength] = 0x00; /* null terminate the last string */
  195300. png_debug(3, "Finding end of pCAL purpose string\n");
  195301. for (buf = purpose; *buf; buf++)
  195302. /* empty loop */ ;
  195303. endptr = purpose + slength;
  195304. /* We need to have at least 12 bytes after the purpose string
  195305. in order to get the parameter information. */
  195306. if (endptr <= buf + 12)
  195307. {
  195308. png_warning(png_ptr, "Invalid pCAL data");
  195309. png_free(png_ptr, purpose);
  195310. return;
  195311. }
  195312. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195313. X0 = png_get_int_32((png_bytep)buf+1);
  195314. X1 = png_get_int_32((png_bytep)buf+5);
  195315. type = buf[9];
  195316. nparams = buf[10];
  195317. units = buf + 11;
  195318. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195319. /* Check that we have the right number of parameters for known
  195320. equation types. */
  195321. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195322. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195323. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195324. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195325. {
  195326. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195327. png_free(png_ptr, purpose);
  195328. return;
  195329. }
  195330. else if (type >= PNG_EQUATION_LAST)
  195331. {
  195332. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195333. }
  195334. for (buf = units; *buf; buf++)
  195335. /* Empty loop to move past the units string. */ ;
  195336. png_debug(3, "Allocating pCAL parameters array\n");
  195337. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195338. *png_sizeof(png_charp))) ;
  195339. if (params == NULL)
  195340. {
  195341. png_free(png_ptr, purpose);
  195342. png_warning(png_ptr, "No memory for pCAL params.");
  195343. return;
  195344. }
  195345. /* Get pointers to the start of each parameter string. */
  195346. for (i = 0; i < (int)nparams; i++)
  195347. {
  195348. buf++; /* Skip the null string terminator from previous parameter. */
  195349. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195350. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195351. /* Empty loop to move past each parameter string */ ;
  195352. /* Make sure we haven't run out of data yet */
  195353. if (buf > endptr)
  195354. {
  195355. png_warning(png_ptr, "Invalid pCAL data");
  195356. png_free(png_ptr, purpose);
  195357. png_free(png_ptr, params);
  195358. return;
  195359. }
  195360. }
  195361. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195362. units, params);
  195363. png_free(png_ptr, purpose);
  195364. png_free(png_ptr, params);
  195365. }
  195366. #endif
  195367. #if defined(PNG_READ_sCAL_SUPPORTED)
  195368. /* read the sCAL chunk */
  195369. void /* PRIVATE */
  195370. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195371. {
  195372. png_charp buffer, ep;
  195373. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195374. double width, height;
  195375. png_charp vp;
  195376. #else
  195377. #ifdef PNG_FIXED_POINT_SUPPORTED
  195378. png_charp swidth, sheight;
  195379. #endif
  195380. #endif
  195381. png_size_t slength;
  195382. png_debug(1, "in png_handle_sCAL\n");
  195383. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195384. png_error(png_ptr, "Missing IHDR before sCAL");
  195385. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195386. {
  195387. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195388. png_crc_finish(png_ptr, length);
  195389. return;
  195390. }
  195391. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195392. {
  195393. png_warning(png_ptr, "Duplicate sCAL chunk");
  195394. png_crc_finish(png_ptr, length);
  195395. return;
  195396. }
  195397. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195398. length + 1);
  195399. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195400. if (buffer == NULL)
  195401. {
  195402. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195403. return;
  195404. }
  195405. slength = (png_size_t)length;
  195406. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195407. if (png_crc_finish(png_ptr, 0))
  195408. {
  195409. png_free(png_ptr, buffer);
  195410. return;
  195411. }
  195412. buffer[slength] = 0x00; /* null terminate the last string */
  195413. ep = buffer + 1; /* skip unit byte */
  195414. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195415. width = png_strtod(png_ptr, ep, &vp);
  195416. if (*vp)
  195417. {
  195418. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195419. return;
  195420. }
  195421. #else
  195422. #ifdef PNG_FIXED_POINT_SUPPORTED
  195423. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195424. if (swidth == NULL)
  195425. {
  195426. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195427. return;
  195428. }
  195429. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195430. #endif
  195431. #endif
  195432. for (ep = buffer; *ep; ep++)
  195433. /* empty loop */ ;
  195434. ep++;
  195435. if (buffer + slength < ep)
  195436. {
  195437. png_warning(png_ptr, "Truncated sCAL chunk");
  195438. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195439. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195440. png_free(png_ptr, swidth);
  195441. #endif
  195442. png_free(png_ptr, buffer);
  195443. return;
  195444. }
  195445. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195446. height = png_strtod(png_ptr, ep, &vp);
  195447. if (*vp)
  195448. {
  195449. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195450. return;
  195451. }
  195452. #else
  195453. #ifdef PNG_FIXED_POINT_SUPPORTED
  195454. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195455. if (swidth == NULL)
  195456. {
  195457. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195458. return;
  195459. }
  195460. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195461. #endif
  195462. #endif
  195463. if (buffer + slength < ep
  195464. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195465. || width <= 0. || height <= 0.
  195466. #endif
  195467. )
  195468. {
  195469. png_warning(png_ptr, "Invalid sCAL data");
  195470. png_free(png_ptr, buffer);
  195471. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195472. png_free(png_ptr, swidth);
  195473. png_free(png_ptr, sheight);
  195474. #endif
  195475. return;
  195476. }
  195477. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195478. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195479. #else
  195480. #ifdef PNG_FIXED_POINT_SUPPORTED
  195481. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195482. #endif
  195483. #endif
  195484. png_free(png_ptr, buffer);
  195485. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195486. png_free(png_ptr, swidth);
  195487. png_free(png_ptr, sheight);
  195488. #endif
  195489. }
  195490. #endif
  195491. #if defined(PNG_READ_tIME_SUPPORTED)
  195492. void /* PRIVATE */
  195493. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195494. {
  195495. png_byte buf[7];
  195496. png_time mod_time;
  195497. png_debug(1, "in png_handle_tIME\n");
  195498. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195499. png_error(png_ptr, "Out of place tIME chunk");
  195500. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195501. {
  195502. png_warning(png_ptr, "Duplicate tIME chunk");
  195503. png_crc_finish(png_ptr, length);
  195504. return;
  195505. }
  195506. if (png_ptr->mode & PNG_HAVE_IDAT)
  195507. png_ptr->mode |= PNG_AFTER_IDAT;
  195508. if (length != 7)
  195509. {
  195510. png_warning(png_ptr, "Incorrect tIME chunk length");
  195511. png_crc_finish(png_ptr, length);
  195512. return;
  195513. }
  195514. png_crc_read(png_ptr, buf, 7);
  195515. if (png_crc_finish(png_ptr, 0))
  195516. return;
  195517. mod_time.second = buf[6];
  195518. mod_time.minute = buf[5];
  195519. mod_time.hour = buf[4];
  195520. mod_time.day = buf[3];
  195521. mod_time.month = buf[2];
  195522. mod_time.year = png_get_uint_16(buf);
  195523. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195524. }
  195525. #endif
  195526. #if defined(PNG_READ_tEXt_SUPPORTED)
  195527. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195528. void /* PRIVATE */
  195529. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195530. {
  195531. png_textp text_ptr;
  195532. png_charp key;
  195533. png_charp text;
  195534. png_uint_32 skip = 0;
  195535. png_size_t slength;
  195536. int ret;
  195537. png_debug(1, "in png_handle_tEXt\n");
  195538. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195539. png_error(png_ptr, "Missing IHDR before tEXt");
  195540. if (png_ptr->mode & PNG_HAVE_IDAT)
  195541. png_ptr->mode |= PNG_AFTER_IDAT;
  195542. #ifdef PNG_MAX_MALLOC_64K
  195543. if (length > (png_uint_32)65535L)
  195544. {
  195545. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195546. skip = length - (png_uint_32)65535L;
  195547. length = (png_uint_32)65535L;
  195548. }
  195549. #endif
  195550. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195551. if (key == NULL)
  195552. {
  195553. png_warning(png_ptr, "No memory to process text chunk.");
  195554. return;
  195555. }
  195556. slength = (png_size_t)length;
  195557. png_crc_read(png_ptr, (png_bytep)key, slength);
  195558. if (png_crc_finish(png_ptr, skip))
  195559. {
  195560. png_free(png_ptr, key);
  195561. return;
  195562. }
  195563. key[slength] = 0x00;
  195564. for (text = key; *text; text++)
  195565. /* empty loop to find end of key */ ;
  195566. if (text != key + slength)
  195567. text++;
  195568. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195569. (png_uint_32)png_sizeof(png_text));
  195570. if (text_ptr == NULL)
  195571. {
  195572. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195573. png_free(png_ptr, key);
  195574. return;
  195575. }
  195576. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195577. text_ptr->key = key;
  195578. #ifdef PNG_iTXt_SUPPORTED
  195579. text_ptr->lang = NULL;
  195580. text_ptr->lang_key = NULL;
  195581. text_ptr->itxt_length = 0;
  195582. #endif
  195583. text_ptr->text = text;
  195584. text_ptr->text_length = png_strlen(text);
  195585. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195586. png_free(png_ptr, key);
  195587. png_free(png_ptr, text_ptr);
  195588. if (ret)
  195589. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195590. }
  195591. #endif
  195592. #if defined(PNG_READ_zTXt_SUPPORTED)
  195593. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195594. void /* PRIVATE */
  195595. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195596. {
  195597. png_textp text_ptr;
  195598. png_charp chunkdata;
  195599. png_charp text;
  195600. int comp_type;
  195601. int ret;
  195602. png_size_t slength, prefix_len, data_len;
  195603. png_debug(1, "in png_handle_zTXt\n");
  195604. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195605. png_error(png_ptr, "Missing IHDR before zTXt");
  195606. if (png_ptr->mode & PNG_HAVE_IDAT)
  195607. png_ptr->mode |= PNG_AFTER_IDAT;
  195608. #ifdef PNG_MAX_MALLOC_64K
  195609. /* We will no doubt have problems with chunks even half this size, but
  195610. there is no hard and fast rule to tell us where to stop. */
  195611. if (length > (png_uint_32)65535L)
  195612. {
  195613. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195614. png_crc_finish(png_ptr, length);
  195615. return;
  195616. }
  195617. #endif
  195618. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195619. if (chunkdata == NULL)
  195620. {
  195621. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195622. return;
  195623. }
  195624. slength = (png_size_t)length;
  195625. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195626. if (png_crc_finish(png_ptr, 0))
  195627. {
  195628. png_free(png_ptr, chunkdata);
  195629. return;
  195630. }
  195631. chunkdata[slength] = 0x00;
  195632. for (text = chunkdata; *text; text++)
  195633. /* empty loop */ ;
  195634. /* zTXt must have some text after the chunkdataword */
  195635. if (text >= chunkdata + slength - 2)
  195636. {
  195637. png_warning(png_ptr, "Truncated zTXt chunk");
  195638. png_free(png_ptr, chunkdata);
  195639. return;
  195640. }
  195641. else
  195642. {
  195643. comp_type = *(++text);
  195644. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195645. {
  195646. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195647. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195648. }
  195649. text++; /* skip the compression_method byte */
  195650. }
  195651. prefix_len = text - chunkdata;
  195652. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195653. (png_size_t)length, prefix_len, &data_len);
  195654. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195655. (png_uint_32)png_sizeof(png_text));
  195656. if (text_ptr == NULL)
  195657. {
  195658. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195659. png_free(png_ptr, chunkdata);
  195660. return;
  195661. }
  195662. text_ptr->compression = comp_type;
  195663. text_ptr->key = chunkdata;
  195664. #ifdef PNG_iTXt_SUPPORTED
  195665. text_ptr->lang = NULL;
  195666. text_ptr->lang_key = NULL;
  195667. text_ptr->itxt_length = 0;
  195668. #endif
  195669. text_ptr->text = chunkdata + prefix_len;
  195670. text_ptr->text_length = data_len;
  195671. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195672. png_free(png_ptr, text_ptr);
  195673. png_free(png_ptr, chunkdata);
  195674. if (ret)
  195675. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195676. }
  195677. #endif
  195678. #if defined(PNG_READ_iTXt_SUPPORTED)
  195679. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195680. void /* PRIVATE */
  195681. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195682. {
  195683. png_textp text_ptr;
  195684. png_charp chunkdata;
  195685. png_charp key, lang, text, lang_key;
  195686. int comp_flag;
  195687. int comp_type = 0;
  195688. int ret;
  195689. png_size_t slength, prefix_len, data_len;
  195690. png_debug(1, "in png_handle_iTXt\n");
  195691. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195692. png_error(png_ptr, "Missing IHDR before iTXt");
  195693. if (png_ptr->mode & PNG_HAVE_IDAT)
  195694. png_ptr->mode |= PNG_AFTER_IDAT;
  195695. #ifdef PNG_MAX_MALLOC_64K
  195696. /* We will no doubt have problems with chunks even half this size, but
  195697. there is no hard and fast rule to tell us where to stop. */
  195698. if (length > (png_uint_32)65535L)
  195699. {
  195700. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195701. png_crc_finish(png_ptr, length);
  195702. return;
  195703. }
  195704. #endif
  195705. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195706. if (chunkdata == NULL)
  195707. {
  195708. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195709. return;
  195710. }
  195711. slength = (png_size_t)length;
  195712. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195713. if (png_crc_finish(png_ptr, 0))
  195714. {
  195715. png_free(png_ptr, chunkdata);
  195716. return;
  195717. }
  195718. chunkdata[slength] = 0x00;
  195719. for (lang = chunkdata; *lang; lang++)
  195720. /* empty loop */ ;
  195721. lang++; /* skip NUL separator */
  195722. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195723. translated keyword (possibly empty), and possibly some text after the
  195724. keyword */
  195725. if (lang >= chunkdata + slength - 3)
  195726. {
  195727. png_warning(png_ptr, "Truncated iTXt chunk");
  195728. png_free(png_ptr, chunkdata);
  195729. return;
  195730. }
  195731. else
  195732. {
  195733. comp_flag = *lang++;
  195734. comp_type = *lang++;
  195735. }
  195736. for (lang_key = lang; *lang_key; lang_key++)
  195737. /* empty loop */ ;
  195738. lang_key++; /* skip NUL separator */
  195739. if (lang_key >= chunkdata + slength)
  195740. {
  195741. png_warning(png_ptr, "Truncated iTXt chunk");
  195742. png_free(png_ptr, chunkdata);
  195743. return;
  195744. }
  195745. for (text = lang_key; *text; text++)
  195746. /* empty loop */ ;
  195747. text++; /* skip NUL separator */
  195748. if (text >= chunkdata + slength)
  195749. {
  195750. png_warning(png_ptr, "Malformed iTXt chunk");
  195751. png_free(png_ptr, chunkdata);
  195752. return;
  195753. }
  195754. prefix_len = text - chunkdata;
  195755. key=chunkdata;
  195756. if (comp_flag)
  195757. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195758. (size_t)length, prefix_len, &data_len);
  195759. else
  195760. data_len=png_strlen(chunkdata + prefix_len);
  195761. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195762. (png_uint_32)png_sizeof(png_text));
  195763. if (text_ptr == NULL)
  195764. {
  195765. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195766. png_free(png_ptr, chunkdata);
  195767. return;
  195768. }
  195769. text_ptr->compression = (int)comp_flag + 1;
  195770. text_ptr->lang_key = chunkdata+(lang_key-key);
  195771. text_ptr->lang = chunkdata+(lang-key);
  195772. text_ptr->itxt_length = data_len;
  195773. text_ptr->text_length = 0;
  195774. text_ptr->key = chunkdata;
  195775. text_ptr->text = chunkdata + prefix_len;
  195776. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195777. png_free(png_ptr, text_ptr);
  195778. png_free(png_ptr, chunkdata);
  195779. if (ret)
  195780. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195781. }
  195782. #endif
  195783. /* This function is called when we haven't found a handler for a
  195784. chunk. If there isn't a problem with the chunk itself (ie bad
  195785. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195786. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195787. case it will be saved away to be written out later. */
  195788. void /* PRIVATE */
  195789. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195790. {
  195791. png_uint_32 skip = 0;
  195792. png_debug(1, "in png_handle_unknown\n");
  195793. if (png_ptr->mode & PNG_HAVE_IDAT)
  195794. {
  195795. #ifdef PNG_USE_LOCAL_ARRAYS
  195796. PNG_CONST PNG_IDAT;
  195797. #endif
  195798. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195799. png_ptr->mode |= PNG_AFTER_IDAT;
  195800. }
  195801. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195802. if (!(png_ptr->chunk_name[0] & 0x20))
  195803. {
  195804. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195805. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195806. PNG_HANDLE_CHUNK_ALWAYS
  195807. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195808. && png_ptr->read_user_chunk_fn == NULL
  195809. #endif
  195810. )
  195811. #endif
  195812. png_chunk_error(png_ptr, "unknown critical chunk");
  195813. }
  195814. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195815. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195816. (png_ptr->read_user_chunk_fn != NULL))
  195817. {
  195818. #ifdef PNG_MAX_MALLOC_64K
  195819. if (length > (png_uint_32)65535L)
  195820. {
  195821. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195822. skip = length - (png_uint_32)65535L;
  195823. length = (png_uint_32)65535L;
  195824. }
  195825. #endif
  195826. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195827. (png_charp)png_ptr->chunk_name, 5);
  195828. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195829. png_ptr->unknown_chunk.size = (png_size_t)length;
  195830. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195831. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195832. if(png_ptr->read_user_chunk_fn != NULL)
  195833. {
  195834. /* callback to user unknown chunk handler */
  195835. int ret;
  195836. ret = (*(png_ptr->read_user_chunk_fn))
  195837. (png_ptr, &png_ptr->unknown_chunk);
  195838. if (ret < 0)
  195839. png_chunk_error(png_ptr, "error in user chunk");
  195840. if (ret == 0)
  195841. {
  195842. if (!(png_ptr->chunk_name[0] & 0x20))
  195843. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195844. PNG_HANDLE_CHUNK_ALWAYS)
  195845. png_chunk_error(png_ptr, "unknown critical chunk");
  195846. png_set_unknown_chunks(png_ptr, info_ptr,
  195847. &png_ptr->unknown_chunk, 1);
  195848. }
  195849. }
  195850. #else
  195851. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195852. #endif
  195853. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195854. png_ptr->unknown_chunk.data = NULL;
  195855. }
  195856. else
  195857. #endif
  195858. skip = length;
  195859. png_crc_finish(png_ptr, skip);
  195860. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195861. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195862. #endif
  195863. }
  195864. /* This function is called to verify that a chunk name is valid.
  195865. This function can't have the "critical chunk check" incorporated
  195866. into it, since in the future we will need to be able to call user
  195867. functions to handle unknown critical chunks after we check that
  195868. the chunk name itself is valid. */
  195869. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195870. void /* PRIVATE */
  195871. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195872. {
  195873. png_debug(1, "in png_check_chunk_name\n");
  195874. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195875. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195876. {
  195877. png_chunk_error(png_ptr, "invalid chunk type");
  195878. }
  195879. }
  195880. /* Combines the row recently read in with the existing pixels in the
  195881. row. This routine takes care of alpha and transparency if requested.
  195882. This routine also handles the two methods of progressive display
  195883. of interlaced images, depending on the mask value.
  195884. The mask value describes which pixels are to be combined with
  195885. the row. The pattern always repeats every 8 pixels, so just 8
  195886. bits are needed. A one indicates the pixel is to be combined,
  195887. a zero indicates the pixel is to be skipped. This is in addition
  195888. to any alpha or transparency value associated with the pixel. If
  195889. you want all pixels to be combined, pass 0xff (255) in mask. */
  195890. void /* PRIVATE */
  195891. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195892. {
  195893. png_debug(1,"in png_combine_row\n");
  195894. if (mask == 0xff)
  195895. {
  195896. png_memcpy(row, png_ptr->row_buf + 1,
  195897. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195898. }
  195899. else
  195900. {
  195901. switch (png_ptr->row_info.pixel_depth)
  195902. {
  195903. case 1:
  195904. {
  195905. png_bytep sp = png_ptr->row_buf + 1;
  195906. png_bytep dp = row;
  195907. int s_inc, s_start, s_end;
  195908. int m = 0x80;
  195909. int shift;
  195910. png_uint_32 i;
  195911. png_uint_32 row_width = png_ptr->width;
  195912. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195913. if (png_ptr->transformations & PNG_PACKSWAP)
  195914. {
  195915. s_start = 0;
  195916. s_end = 7;
  195917. s_inc = 1;
  195918. }
  195919. else
  195920. #endif
  195921. {
  195922. s_start = 7;
  195923. s_end = 0;
  195924. s_inc = -1;
  195925. }
  195926. shift = s_start;
  195927. for (i = 0; i < row_width; i++)
  195928. {
  195929. if (m & mask)
  195930. {
  195931. int value;
  195932. value = (*sp >> shift) & 0x01;
  195933. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195934. *dp |= (png_byte)(value << shift);
  195935. }
  195936. if (shift == s_end)
  195937. {
  195938. shift = s_start;
  195939. sp++;
  195940. dp++;
  195941. }
  195942. else
  195943. shift += s_inc;
  195944. if (m == 1)
  195945. m = 0x80;
  195946. else
  195947. m >>= 1;
  195948. }
  195949. break;
  195950. }
  195951. case 2:
  195952. {
  195953. png_bytep sp = png_ptr->row_buf + 1;
  195954. png_bytep dp = row;
  195955. int s_start, s_end, s_inc;
  195956. int m = 0x80;
  195957. int shift;
  195958. png_uint_32 i;
  195959. png_uint_32 row_width = png_ptr->width;
  195960. int value;
  195961. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195962. if (png_ptr->transformations & PNG_PACKSWAP)
  195963. {
  195964. s_start = 0;
  195965. s_end = 6;
  195966. s_inc = 2;
  195967. }
  195968. else
  195969. #endif
  195970. {
  195971. s_start = 6;
  195972. s_end = 0;
  195973. s_inc = -2;
  195974. }
  195975. shift = s_start;
  195976. for (i = 0; i < row_width; i++)
  195977. {
  195978. if (m & mask)
  195979. {
  195980. value = (*sp >> shift) & 0x03;
  195981. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195982. *dp |= (png_byte)(value << shift);
  195983. }
  195984. if (shift == s_end)
  195985. {
  195986. shift = s_start;
  195987. sp++;
  195988. dp++;
  195989. }
  195990. else
  195991. shift += s_inc;
  195992. if (m == 1)
  195993. m = 0x80;
  195994. else
  195995. m >>= 1;
  195996. }
  195997. break;
  195998. }
  195999. case 4:
  196000. {
  196001. png_bytep sp = png_ptr->row_buf + 1;
  196002. png_bytep dp = row;
  196003. int s_start, s_end, s_inc;
  196004. int m = 0x80;
  196005. int shift;
  196006. png_uint_32 i;
  196007. png_uint_32 row_width = png_ptr->width;
  196008. int value;
  196009. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196010. if (png_ptr->transformations & PNG_PACKSWAP)
  196011. {
  196012. s_start = 0;
  196013. s_end = 4;
  196014. s_inc = 4;
  196015. }
  196016. else
  196017. #endif
  196018. {
  196019. s_start = 4;
  196020. s_end = 0;
  196021. s_inc = -4;
  196022. }
  196023. shift = s_start;
  196024. for (i = 0; i < row_width; i++)
  196025. {
  196026. if (m & mask)
  196027. {
  196028. value = (*sp >> shift) & 0xf;
  196029. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196030. *dp |= (png_byte)(value << shift);
  196031. }
  196032. if (shift == s_end)
  196033. {
  196034. shift = s_start;
  196035. sp++;
  196036. dp++;
  196037. }
  196038. else
  196039. shift += s_inc;
  196040. if (m == 1)
  196041. m = 0x80;
  196042. else
  196043. m >>= 1;
  196044. }
  196045. break;
  196046. }
  196047. default:
  196048. {
  196049. png_bytep sp = png_ptr->row_buf + 1;
  196050. png_bytep dp = row;
  196051. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196052. png_uint_32 i;
  196053. png_uint_32 row_width = png_ptr->width;
  196054. png_byte m = 0x80;
  196055. for (i = 0; i < row_width; i++)
  196056. {
  196057. if (m & mask)
  196058. {
  196059. png_memcpy(dp, sp, pixel_bytes);
  196060. }
  196061. sp += pixel_bytes;
  196062. dp += pixel_bytes;
  196063. if (m == 1)
  196064. m = 0x80;
  196065. else
  196066. m >>= 1;
  196067. }
  196068. break;
  196069. }
  196070. }
  196071. }
  196072. }
  196073. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196074. /* OLD pre-1.0.9 interface:
  196075. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196076. png_uint_32 transformations)
  196077. */
  196078. void /* PRIVATE */
  196079. png_do_read_interlace(png_structp png_ptr)
  196080. {
  196081. png_row_infop row_info = &(png_ptr->row_info);
  196082. png_bytep row = png_ptr->row_buf + 1;
  196083. int pass = png_ptr->pass;
  196084. png_uint_32 transformations = png_ptr->transformations;
  196085. #ifdef PNG_USE_LOCAL_ARRAYS
  196086. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196087. /* offset to next interlace block */
  196088. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196089. #endif
  196090. png_debug(1,"in png_do_read_interlace\n");
  196091. if (row != NULL && row_info != NULL)
  196092. {
  196093. png_uint_32 final_width;
  196094. final_width = row_info->width * png_pass_inc[pass];
  196095. switch (row_info->pixel_depth)
  196096. {
  196097. case 1:
  196098. {
  196099. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196100. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196101. int sshift, dshift;
  196102. int s_start, s_end, s_inc;
  196103. int jstop = png_pass_inc[pass];
  196104. png_byte v;
  196105. png_uint_32 i;
  196106. int j;
  196107. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196108. if (transformations & PNG_PACKSWAP)
  196109. {
  196110. sshift = (int)((row_info->width + 7) & 0x07);
  196111. dshift = (int)((final_width + 7) & 0x07);
  196112. s_start = 7;
  196113. s_end = 0;
  196114. s_inc = -1;
  196115. }
  196116. else
  196117. #endif
  196118. {
  196119. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196120. dshift = 7 - (int)((final_width + 7) & 0x07);
  196121. s_start = 0;
  196122. s_end = 7;
  196123. s_inc = 1;
  196124. }
  196125. for (i = 0; i < row_info->width; i++)
  196126. {
  196127. v = (png_byte)((*sp >> sshift) & 0x01);
  196128. for (j = 0; j < jstop; j++)
  196129. {
  196130. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196131. *dp |= (png_byte)(v << dshift);
  196132. if (dshift == s_end)
  196133. {
  196134. dshift = s_start;
  196135. dp--;
  196136. }
  196137. else
  196138. dshift += s_inc;
  196139. }
  196140. if (sshift == s_end)
  196141. {
  196142. sshift = s_start;
  196143. sp--;
  196144. }
  196145. else
  196146. sshift += s_inc;
  196147. }
  196148. break;
  196149. }
  196150. case 2:
  196151. {
  196152. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196153. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196154. int sshift, dshift;
  196155. int s_start, s_end, s_inc;
  196156. int jstop = png_pass_inc[pass];
  196157. png_uint_32 i;
  196158. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196159. if (transformations & PNG_PACKSWAP)
  196160. {
  196161. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196162. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196163. s_start = 6;
  196164. s_end = 0;
  196165. s_inc = -2;
  196166. }
  196167. else
  196168. #endif
  196169. {
  196170. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196171. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196172. s_start = 0;
  196173. s_end = 6;
  196174. s_inc = 2;
  196175. }
  196176. for (i = 0; i < row_info->width; i++)
  196177. {
  196178. png_byte v;
  196179. int j;
  196180. v = (png_byte)((*sp >> sshift) & 0x03);
  196181. for (j = 0; j < jstop; j++)
  196182. {
  196183. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196184. *dp |= (png_byte)(v << dshift);
  196185. if (dshift == s_end)
  196186. {
  196187. dshift = s_start;
  196188. dp--;
  196189. }
  196190. else
  196191. dshift += s_inc;
  196192. }
  196193. if (sshift == s_end)
  196194. {
  196195. sshift = s_start;
  196196. sp--;
  196197. }
  196198. else
  196199. sshift += s_inc;
  196200. }
  196201. break;
  196202. }
  196203. case 4:
  196204. {
  196205. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196206. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196207. int sshift, dshift;
  196208. int s_start, s_end, s_inc;
  196209. png_uint_32 i;
  196210. int jstop = png_pass_inc[pass];
  196211. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196212. if (transformations & PNG_PACKSWAP)
  196213. {
  196214. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196215. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196216. s_start = 4;
  196217. s_end = 0;
  196218. s_inc = -4;
  196219. }
  196220. else
  196221. #endif
  196222. {
  196223. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196224. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196225. s_start = 0;
  196226. s_end = 4;
  196227. s_inc = 4;
  196228. }
  196229. for (i = 0; i < row_info->width; i++)
  196230. {
  196231. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196232. int j;
  196233. for (j = 0; j < jstop; j++)
  196234. {
  196235. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196236. *dp |= (png_byte)(v << dshift);
  196237. if (dshift == s_end)
  196238. {
  196239. dshift = s_start;
  196240. dp--;
  196241. }
  196242. else
  196243. dshift += s_inc;
  196244. }
  196245. if (sshift == s_end)
  196246. {
  196247. sshift = s_start;
  196248. sp--;
  196249. }
  196250. else
  196251. sshift += s_inc;
  196252. }
  196253. break;
  196254. }
  196255. default:
  196256. {
  196257. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196258. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196259. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196260. int jstop = png_pass_inc[pass];
  196261. png_uint_32 i;
  196262. for (i = 0; i < row_info->width; i++)
  196263. {
  196264. png_byte v[8];
  196265. int j;
  196266. png_memcpy(v, sp, pixel_bytes);
  196267. for (j = 0; j < jstop; j++)
  196268. {
  196269. png_memcpy(dp, v, pixel_bytes);
  196270. dp -= pixel_bytes;
  196271. }
  196272. sp -= pixel_bytes;
  196273. }
  196274. break;
  196275. }
  196276. }
  196277. row_info->width = final_width;
  196278. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196279. }
  196280. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196281. transformations = transformations; /* silence compiler warning */
  196282. #endif
  196283. }
  196284. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196285. void /* PRIVATE */
  196286. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196287. png_bytep prev_row, int filter)
  196288. {
  196289. png_debug(1, "in png_read_filter_row\n");
  196290. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196291. switch (filter)
  196292. {
  196293. case PNG_FILTER_VALUE_NONE:
  196294. break;
  196295. case PNG_FILTER_VALUE_SUB:
  196296. {
  196297. png_uint_32 i;
  196298. png_uint_32 istop = row_info->rowbytes;
  196299. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196300. png_bytep rp = row + bpp;
  196301. png_bytep lp = row;
  196302. for (i = bpp; i < istop; i++)
  196303. {
  196304. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196305. rp++;
  196306. }
  196307. break;
  196308. }
  196309. case PNG_FILTER_VALUE_UP:
  196310. {
  196311. png_uint_32 i;
  196312. png_uint_32 istop = row_info->rowbytes;
  196313. png_bytep rp = row;
  196314. png_bytep pp = prev_row;
  196315. for (i = 0; i < istop; i++)
  196316. {
  196317. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196318. rp++;
  196319. }
  196320. break;
  196321. }
  196322. case PNG_FILTER_VALUE_AVG:
  196323. {
  196324. png_uint_32 i;
  196325. png_bytep rp = row;
  196326. png_bytep pp = prev_row;
  196327. png_bytep lp = row;
  196328. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196329. png_uint_32 istop = row_info->rowbytes - bpp;
  196330. for (i = 0; i < bpp; i++)
  196331. {
  196332. *rp = (png_byte)(((int)(*rp) +
  196333. ((int)(*pp++) / 2 )) & 0xff);
  196334. rp++;
  196335. }
  196336. for (i = 0; i < istop; i++)
  196337. {
  196338. *rp = (png_byte)(((int)(*rp) +
  196339. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196340. rp++;
  196341. }
  196342. break;
  196343. }
  196344. case PNG_FILTER_VALUE_PAETH:
  196345. {
  196346. png_uint_32 i;
  196347. png_bytep rp = row;
  196348. png_bytep pp = prev_row;
  196349. png_bytep lp = row;
  196350. png_bytep cp = prev_row;
  196351. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196352. png_uint_32 istop=row_info->rowbytes - bpp;
  196353. for (i = 0; i < bpp; i++)
  196354. {
  196355. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196356. rp++;
  196357. }
  196358. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196359. {
  196360. int a, b, c, pa, pb, pc, p;
  196361. a = *lp++;
  196362. b = *pp++;
  196363. c = *cp++;
  196364. p = b - c;
  196365. pc = a - c;
  196366. #ifdef PNG_USE_ABS
  196367. pa = abs(p);
  196368. pb = abs(pc);
  196369. pc = abs(p + pc);
  196370. #else
  196371. pa = p < 0 ? -p : p;
  196372. pb = pc < 0 ? -pc : pc;
  196373. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196374. #endif
  196375. /*
  196376. if (pa <= pb && pa <= pc)
  196377. p = a;
  196378. else if (pb <= pc)
  196379. p = b;
  196380. else
  196381. p = c;
  196382. */
  196383. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196384. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196385. rp++;
  196386. }
  196387. break;
  196388. }
  196389. default:
  196390. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196391. *row=0;
  196392. break;
  196393. }
  196394. }
  196395. void /* PRIVATE */
  196396. png_read_finish_row(png_structp png_ptr)
  196397. {
  196398. #ifdef PNG_USE_LOCAL_ARRAYS
  196399. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196400. /* start of interlace block */
  196401. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196402. /* offset to next interlace block */
  196403. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196404. /* start of interlace block in the y direction */
  196405. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196406. /* offset to next interlace block in the y direction */
  196407. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196408. #endif
  196409. png_debug(1, "in png_read_finish_row\n");
  196410. png_ptr->row_number++;
  196411. if (png_ptr->row_number < png_ptr->num_rows)
  196412. return;
  196413. if (png_ptr->interlaced)
  196414. {
  196415. png_ptr->row_number = 0;
  196416. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196417. png_ptr->rowbytes + 1);
  196418. do
  196419. {
  196420. png_ptr->pass++;
  196421. if (png_ptr->pass >= 7)
  196422. break;
  196423. png_ptr->iwidth = (png_ptr->width +
  196424. png_pass_inc[png_ptr->pass] - 1 -
  196425. png_pass_start[png_ptr->pass]) /
  196426. png_pass_inc[png_ptr->pass];
  196427. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196428. png_ptr->iwidth) + 1;
  196429. if (!(png_ptr->transformations & PNG_INTERLACE))
  196430. {
  196431. png_ptr->num_rows = (png_ptr->height +
  196432. png_pass_yinc[png_ptr->pass] - 1 -
  196433. png_pass_ystart[png_ptr->pass]) /
  196434. png_pass_yinc[png_ptr->pass];
  196435. if (!(png_ptr->num_rows))
  196436. continue;
  196437. }
  196438. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196439. break;
  196440. } while (png_ptr->iwidth == 0);
  196441. if (png_ptr->pass < 7)
  196442. return;
  196443. }
  196444. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196445. {
  196446. #ifdef PNG_USE_LOCAL_ARRAYS
  196447. PNG_CONST PNG_IDAT;
  196448. #endif
  196449. char extra;
  196450. int ret;
  196451. png_ptr->zstream.next_out = (Bytef *)&extra;
  196452. png_ptr->zstream.avail_out = (uInt)1;
  196453. for(;;)
  196454. {
  196455. if (!(png_ptr->zstream.avail_in))
  196456. {
  196457. while (!png_ptr->idat_size)
  196458. {
  196459. png_byte chunk_length[4];
  196460. png_crc_finish(png_ptr, 0);
  196461. png_read_data(png_ptr, chunk_length, 4);
  196462. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196463. png_reset_crc(png_ptr);
  196464. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196465. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196466. png_error(png_ptr, "Not enough image data");
  196467. }
  196468. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196469. png_ptr->zstream.next_in = png_ptr->zbuf;
  196470. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196471. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196472. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196473. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196474. }
  196475. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196476. if (ret == Z_STREAM_END)
  196477. {
  196478. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196479. png_ptr->idat_size)
  196480. png_warning(png_ptr, "Extra compressed data");
  196481. png_ptr->mode |= PNG_AFTER_IDAT;
  196482. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196483. break;
  196484. }
  196485. if (ret != Z_OK)
  196486. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196487. "Decompression Error");
  196488. if (!(png_ptr->zstream.avail_out))
  196489. {
  196490. png_warning(png_ptr, "Extra compressed data.");
  196491. png_ptr->mode |= PNG_AFTER_IDAT;
  196492. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196493. break;
  196494. }
  196495. }
  196496. png_ptr->zstream.avail_out = 0;
  196497. }
  196498. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196499. png_warning(png_ptr, "Extra compression data");
  196500. inflateReset(&png_ptr->zstream);
  196501. png_ptr->mode |= PNG_AFTER_IDAT;
  196502. }
  196503. void /* PRIVATE */
  196504. png_read_start_row(png_structp png_ptr)
  196505. {
  196506. #ifdef PNG_USE_LOCAL_ARRAYS
  196507. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196508. /* start of interlace block */
  196509. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196510. /* offset to next interlace block */
  196511. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196512. /* start of interlace block in the y direction */
  196513. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196514. /* offset to next interlace block in the y direction */
  196515. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196516. #endif
  196517. int max_pixel_depth;
  196518. png_uint_32 row_bytes;
  196519. png_debug(1, "in png_read_start_row\n");
  196520. png_ptr->zstream.avail_in = 0;
  196521. png_init_read_transformations(png_ptr);
  196522. if (png_ptr->interlaced)
  196523. {
  196524. if (!(png_ptr->transformations & PNG_INTERLACE))
  196525. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196526. png_pass_ystart[0]) / png_pass_yinc[0];
  196527. else
  196528. png_ptr->num_rows = png_ptr->height;
  196529. png_ptr->iwidth = (png_ptr->width +
  196530. png_pass_inc[png_ptr->pass] - 1 -
  196531. png_pass_start[png_ptr->pass]) /
  196532. png_pass_inc[png_ptr->pass];
  196533. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196534. png_ptr->irowbytes = (png_size_t)row_bytes;
  196535. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196536. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196537. }
  196538. else
  196539. {
  196540. png_ptr->num_rows = png_ptr->height;
  196541. png_ptr->iwidth = png_ptr->width;
  196542. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196543. }
  196544. max_pixel_depth = png_ptr->pixel_depth;
  196545. #if defined(PNG_READ_PACK_SUPPORTED)
  196546. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196547. max_pixel_depth = 8;
  196548. #endif
  196549. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196550. if (png_ptr->transformations & PNG_EXPAND)
  196551. {
  196552. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196553. {
  196554. if (png_ptr->num_trans)
  196555. max_pixel_depth = 32;
  196556. else
  196557. max_pixel_depth = 24;
  196558. }
  196559. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196560. {
  196561. if (max_pixel_depth < 8)
  196562. max_pixel_depth = 8;
  196563. if (png_ptr->num_trans)
  196564. max_pixel_depth *= 2;
  196565. }
  196566. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196567. {
  196568. if (png_ptr->num_trans)
  196569. {
  196570. max_pixel_depth *= 4;
  196571. max_pixel_depth /= 3;
  196572. }
  196573. }
  196574. }
  196575. #endif
  196576. #if defined(PNG_READ_FILLER_SUPPORTED)
  196577. if (png_ptr->transformations & (PNG_FILLER))
  196578. {
  196579. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196580. max_pixel_depth = 32;
  196581. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196582. {
  196583. if (max_pixel_depth <= 8)
  196584. max_pixel_depth = 16;
  196585. else
  196586. max_pixel_depth = 32;
  196587. }
  196588. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196589. {
  196590. if (max_pixel_depth <= 32)
  196591. max_pixel_depth = 32;
  196592. else
  196593. max_pixel_depth = 64;
  196594. }
  196595. }
  196596. #endif
  196597. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196598. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196599. {
  196600. if (
  196601. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196602. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196603. #endif
  196604. #if defined(PNG_READ_FILLER_SUPPORTED)
  196605. (png_ptr->transformations & (PNG_FILLER)) ||
  196606. #endif
  196607. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196608. {
  196609. if (max_pixel_depth <= 16)
  196610. max_pixel_depth = 32;
  196611. else
  196612. max_pixel_depth = 64;
  196613. }
  196614. else
  196615. {
  196616. if (max_pixel_depth <= 8)
  196617. {
  196618. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196619. max_pixel_depth = 32;
  196620. else
  196621. max_pixel_depth = 24;
  196622. }
  196623. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196624. max_pixel_depth = 64;
  196625. else
  196626. max_pixel_depth = 48;
  196627. }
  196628. }
  196629. #endif
  196630. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196631. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196632. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196633. {
  196634. int user_pixel_depth=png_ptr->user_transform_depth*
  196635. png_ptr->user_transform_channels;
  196636. if(user_pixel_depth > max_pixel_depth)
  196637. max_pixel_depth=user_pixel_depth;
  196638. }
  196639. #endif
  196640. /* align the width on the next larger 8 pixels. Mainly used
  196641. for interlacing */
  196642. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196643. /* calculate the maximum bytes needed, adding a byte and a pixel
  196644. for safety's sake */
  196645. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196646. 1 + ((max_pixel_depth + 7) >> 3);
  196647. #ifdef PNG_MAX_MALLOC_64K
  196648. if (row_bytes > (png_uint_32)65536L)
  196649. png_error(png_ptr, "This image requires a row greater than 64KB");
  196650. #endif
  196651. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196652. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196653. #ifdef PNG_MAX_MALLOC_64K
  196654. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196655. png_error(png_ptr, "This image requires a row greater than 64KB");
  196656. #endif
  196657. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196658. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196659. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196660. png_ptr->rowbytes + 1));
  196661. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196662. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196663. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196664. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196665. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196666. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196667. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196668. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196669. }
  196670. #endif /* PNG_READ_SUPPORTED */
  196671. /*** End of inlined file: pngrutil.c ***/
  196672. /*** Start of inlined file: pngset.c ***/
  196673. /* pngset.c - storage of image information into info struct
  196674. *
  196675. * Last changed in libpng 1.2.21 [October 4, 2007]
  196676. * For conditions of distribution and use, see copyright notice in png.h
  196677. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196678. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196679. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196680. *
  196681. * The functions here are used during reads to store data from the file
  196682. * into the info struct, and during writes to store application data
  196683. * into the info struct for writing into the file. This abstracts the
  196684. * info struct and allows us to change the structure in the future.
  196685. */
  196686. #define PNG_INTERNAL
  196687. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196688. #if defined(PNG_bKGD_SUPPORTED)
  196689. void PNGAPI
  196690. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196691. {
  196692. png_debug1(1, "in %s storage function\n", "bKGD");
  196693. if (png_ptr == NULL || info_ptr == NULL)
  196694. return;
  196695. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196696. info_ptr->valid |= PNG_INFO_bKGD;
  196697. }
  196698. #endif
  196699. #if defined(PNG_cHRM_SUPPORTED)
  196700. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196701. void PNGAPI
  196702. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196703. double white_x, double white_y, double red_x, double red_y,
  196704. double green_x, double green_y, double blue_x, double blue_y)
  196705. {
  196706. png_debug1(1, "in %s storage function\n", "cHRM");
  196707. if (png_ptr == NULL || info_ptr == NULL)
  196708. return;
  196709. if (white_x < 0.0 || white_y < 0.0 ||
  196710. red_x < 0.0 || red_y < 0.0 ||
  196711. green_x < 0.0 || green_y < 0.0 ||
  196712. blue_x < 0.0 || blue_y < 0.0)
  196713. {
  196714. png_warning(png_ptr,
  196715. "Ignoring attempt to set negative chromaticity value");
  196716. return;
  196717. }
  196718. if (white_x > 21474.83 || white_y > 21474.83 ||
  196719. red_x > 21474.83 || red_y > 21474.83 ||
  196720. green_x > 21474.83 || green_y > 21474.83 ||
  196721. blue_x > 21474.83 || blue_y > 21474.83)
  196722. {
  196723. png_warning(png_ptr,
  196724. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196725. return;
  196726. }
  196727. info_ptr->x_white = (float)white_x;
  196728. info_ptr->y_white = (float)white_y;
  196729. info_ptr->x_red = (float)red_x;
  196730. info_ptr->y_red = (float)red_y;
  196731. info_ptr->x_green = (float)green_x;
  196732. info_ptr->y_green = (float)green_y;
  196733. info_ptr->x_blue = (float)blue_x;
  196734. info_ptr->y_blue = (float)blue_y;
  196735. #ifdef PNG_FIXED_POINT_SUPPORTED
  196736. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196737. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196738. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196739. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196740. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196741. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196742. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196743. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196744. #endif
  196745. info_ptr->valid |= PNG_INFO_cHRM;
  196746. }
  196747. #endif
  196748. #ifdef PNG_FIXED_POINT_SUPPORTED
  196749. void PNGAPI
  196750. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196751. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196752. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196753. png_fixed_point blue_x, png_fixed_point blue_y)
  196754. {
  196755. png_debug1(1, "in %s storage function\n", "cHRM");
  196756. if (png_ptr == NULL || info_ptr == NULL)
  196757. return;
  196758. if (white_x < 0 || white_y < 0 ||
  196759. red_x < 0 || red_y < 0 ||
  196760. green_x < 0 || green_y < 0 ||
  196761. blue_x < 0 || blue_y < 0)
  196762. {
  196763. png_warning(png_ptr,
  196764. "Ignoring attempt to set negative chromaticity value");
  196765. return;
  196766. }
  196767. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196768. if (white_x > (double) PNG_UINT_31_MAX ||
  196769. white_y > (double) PNG_UINT_31_MAX ||
  196770. red_x > (double) PNG_UINT_31_MAX ||
  196771. red_y > (double) PNG_UINT_31_MAX ||
  196772. green_x > (double) PNG_UINT_31_MAX ||
  196773. green_y > (double) PNG_UINT_31_MAX ||
  196774. blue_x > (double) PNG_UINT_31_MAX ||
  196775. blue_y > (double) PNG_UINT_31_MAX)
  196776. #else
  196777. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196778. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196779. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196780. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196781. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196782. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196783. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196784. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196785. #endif
  196786. {
  196787. png_warning(png_ptr,
  196788. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196789. return;
  196790. }
  196791. info_ptr->int_x_white = white_x;
  196792. info_ptr->int_y_white = white_y;
  196793. info_ptr->int_x_red = red_x;
  196794. info_ptr->int_y_red = red_y;
  196795. info_ptr->int_x_green = green_x;
  196796. info_ptr->int_y_green = green_y;
  196797. info_ptr->int_x_blue = blue_x;
  196798. info_ptr->int_y_blue = blue_y;
  196799. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196800. info_ptr->x_white = (float)(white_x/100000.);
  196801. info_ptr->y_white = (float)(white_y/100000.);
  196802. info_ptr->x_red = (float)( red_x/100000.);
  196803. info_ptr->y_red = (float)( red_y/100000.);
  196804. info_ptr->x_green = (float)(green_x/100000.);
  196805. info_ptr->y_green = (float)(green_y/100000.);
  196806. info_ptr->x_blue = (float)( blue_x/100000.);
  196807. info_ptr->y_blue = (float)( blue_y/100000.);
  196808. #endif
  196809. info_ptr->valid |= PNG_INFO_cHRM;
  196810. }
  196811. #endif
  196812. #endif
  196813. #if defined(PNG_gAMA_SUPPORTED)
  196814. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196815. void PNGAPI
  196816. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196817. {
  196818. double gamma;
  196819. png_debug1(1, "in %s storage function\n", "gAMA");
  196820. if (png_ptr == NULL || info_ptr == NULL)
  196821. return;
  196822. /* Check for overflow */
  196823. if (file_gamma > 21474.83)
  196824. {
  196825. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196826. gamma=21474.83;
  196827. }
  196828. else
  196829. gamma=file_gamma;
  196830. info_ptr->gamma = (float)gamma;
  196831. #ifdef PNG_FIXED_POINT_SUPPORTED
  196832. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196833. #endif
  196834. info_ptr->valid |= PNG_INFO_gAMA;
  196835. if(gamma == 0.0)
  196836. png_warning(png_ptr, "Setting gamma=0");
  196837. }
  196838. #endif
  196839. void PNGAPI
  196840. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196841. int_gamma)
  196842. {
  196843. png_fixed_point gamma;
  196844. png_debug1(1, "in %s storage function\n", "gAMA");
  196845. if (png_ptr == NULL || info_ptr == NULL)
  196846. return;
  196847. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196848. {
  196849. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196850. gamma=PNG_UINT_31_MAX;
  196851. }
  196852. else
  196853. {
  196854. if (int_gamma < 0)
  196855. {
  196856. png_warning(png_ptr, "Setting negative gamma to zero");
  196857. gamma=0;
  196858. }
  196859. else
  196860. gamma=int_gamma;
  196861. }
  196862. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196863. info_ptr->gamma = (float)(gamma/100000.);
  196864. #endif
  196865. #ifdef PNG_FIXED_POINT_SUPPORTED
  196866. info_ptr->int_gamma = gamma;
  196867. #endif
  196868. info_ptr->valid |= PNG_INFO_gAMA;
  196869. if(gamma == 0)
  196870. png_warning(png_ptr, "Setting gamma=0");
  196871. }
  196872. #endif
  196873. #if defined(PNG_hIST_SUPPORTED)
  196874. void PNGAPI
  196875. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196876. {
  196877. int i;
  196878. png_debug1(1, "in %s storage function\n", "hIST");
  196879. if (png_ptr == NULL || info_ptr == NULL)
  196880. return;
  196881. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196882. > PNG_MAX_PALETTE_LENGTH)
  196883. {
  196884. png_warning(png_ptr,
  196885. "Invalid palette size, hIST allocation skipped.");
  196886. return;
  196887. }
  196888. #ifdef PNG_FREE_ME_SUPPORTED
  196889. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196890. #endif
  196891. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196892. 1.2.1 */
  196893. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196894. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196895. if (png_ptr->hist == NULL)
  196896. {
  196897. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196898. return;
  196899. }
  196900. for (i = 0; i < info_ptr->num_palette; i++)
  196901. png_ptr->hist[i] = hist[i];
  196902. info_ptr->hist = png_ptr->hist;
  196903. info_ptr->valid |= PNG_INFO_hIST;
  196904. #ifdef PNG_FREE_ME_SUPPORTED
  196905. info_ptr->free_me |= PNG_FREE_HIST;
  196906. #else
  196907. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196908. #endif
  196909. }
  196910. #endif
  196911. void PNGAPI
  196912. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196913. png_uint_32 width, png_uint_32 height, int bit_depth,
  196914. int color_type, int interlace_type, int compression_type,
  196915. int filter_type)
  196916. {
  196917. png_debug1(1, "in %s storage function\n", "IHDR");
  196918. if (png_ptr == NULL || info_ptr == NULL)
  196919. return;
  196920. /* check for width and height valid values */
  196921. if (width == 0 || height == 0)
  196922. png_error(png_ptr, "Image width or height is zero in IHDR");
  196923. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196924. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196925. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196926. #else
  196927. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196928. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196929. #endif
  196930. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196931. png_error(png_ptr, "Invalid image size in IHDR");
  196932. if ( width > (PNG_UINT_32_MAX
  196933. >> 3) /* 8-byte RGBA pixels */
  196934. - 64 /* bigrowbuf hack */
  196935. - 1 /* filter byte */
  196936. - 7*8 /* rounding of width to multiple of 8 pixels */
  196937. - 8) /* extra max_pixel_depth pad */
  196938. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196939. /* check other values */
  196940. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196941. bit_depth != 8 && bit_depth != 16)
  196942. png_error(png_ptr, "Invalid bit depth in IHDR");
  196943. if (color_type < 0 || color_type == 1 ||
  196944. color_type == 5 || color_type > 6)
  196945. png_error(png_ptr, "Invalid color type in IHDR");
  196946. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196947. ((color_type == PNG_COLOR_TYPE_RGB ||
  196948. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196949. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196950. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196951. if (interlace_type >= PNG_INTERLACE_LAST)
  196952. png_error(png_ptr, "Unknown interlace method in IHDR");
  196953. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196954. png_error(png_ptr, "Unknown compression method in IHDR");
  196955. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196956. /* Accept filter_method 64 (intrapixel differencing) only if
  196957. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196958. * 2. Libpng did not read a PNG signature (this filter_method is only
  196959. * used in PNG datastreams that are embedded in MNG datastreams) and
  196960. * 3. The application called png_permit_mng_features with a mask that
  196961. * included PNG_FLAG_MNG_FILTER_64 and
  196962. * 4. The filter_method is 64 and
  196963. * 5. The color_type is RGB or RGBA
  196964. */
  196965. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196966. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196967. if(filter_type != PNG_FILTER_TYPE_BASE)
  196968. {
  196969. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196970. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196971. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196972. (color_type == PNG_COLOR_TYPE_RGB ||
  196973. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196974. png_error(png_ptr, "Unknown filter method in IHDR");
  196975. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196976. png_warning(png_ptr, "Invalid filter method in IHDR");
  196977. }
  196978. #else
  196979. if(filter_type != PNG_FILTER_TYPE_BASE)
  196980. png_error(png_ptr, "Unknown filter method in IHDR");
  196981. #endif
  196982. info_ptr->width = width;
  196983. info_ptr->height = height;
  196984. info_ptr->bit_depth = (png_byte)bit_depth;
  196985. info_ptr->color_type =(png_byte) color_type;
  196986. info_ptr->compression_type = (png_byte)compression_type;
  196987. info_ptr->filter_type = (png_byte)filter_type;
  196988. info_ptr->interlace_type = (png_byte)interlace_type;
  196989. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196990. info_ptr->channels = 1;
  196991. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196992. info_ptr->channels = 3;
  196993. else
  196994. info_ptr->channels = 1;
  196995. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196996. info_ptr->channels++;
  196997. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196998. /* check for potential overflow */
  196999. if (width > (PNG_UINT_32_MAX
  197000. >> 3) /* 8-byte RGBA pixels */
  197001. - 64 /* bigrowbuf hack */
  197002. - 1 /* filter byte */
  197003. - 7*8 /* rounding of width to multiple of 8 pixels */
  197004. - 8) /* extra max_pixel_depth pad */
  197005. info_ptr->rowbytes = (png_size_t)0;
  197006. else
  197007. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197008. }
  197009. #if defined(PNG_oFFs_SUPPORTED)
  197010. void PNGAPI
  197011. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197012. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197013. {
  197014. png_debug1(1, "in %s storage function\n", "oFFs");
  197015. if (png_ptr == NULL || info_ptr == NULL)
  197016. return;
  197017. info_ptr->x_offset = offset_x;
  197018. info_ptr->y_offset = offset_y;
  197019. info_ptr->offset_unit_type = (png_byte)unit_type;
  197020. info_ptr->valid |= PNG_INFO_oFFs;
  197021. }
  197022. #endif
  197023. #if defined(PNG_pCAL_SUPPORTED)
  197024. void PNGAPI
  197025. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197026. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197027. png_charp units, png_charpp params)
  197028. {
  197029. png_uint_32 length;
  197030. int i;
  197031. png_debug1(1, "in %s storage function\n", "pCAL");
  197032. if (png_ptr == NULL || info_ptr == NULL)
  197033. return;
  197034. length = png_strlen(purpose) + 1;
  197035. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197036. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197037. if (info_ptr->pcal_purpose == NULL)
  197038. {
  197039. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197040. return;
  197041. }
  197042. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197043. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197044. info_ptr->pcal_X0 = X0;
  197045. info_ptr->pcal_X1 = X1;
  197046. info_ptr->pcal_type = (png_byte)type;
  197047. info_ptr->pcal_nparams = (png_byte)nparams;
  197048. length = png_strlen(units) + 1;
  197049. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197050. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197051. if (info_ptr->pcal_units == NULL)
  197052. {
  197053. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197054. return;
  197055. }
  197056. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197057. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197058. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197059. if (info_ptr->pcal_params == NULL)
  197060. {
  197061. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197062. return;
  197063. }
  197064. info_ptr->pcal_params[nparams] = NULL;
  197065. for (i = 0; i < nparams; i++)
  197066. {
  197067. length = png_strlen(params[i]) + 1;
  197068. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197069. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197070. if (info_ptr->pcal_params[i] == NULL)
  197071. {
  197072. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197073. return;
  197074. }
  197075. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197076. }
  197077. info_ptr->valid |= PNG_INFO_pCAL;
  197078. #ifdef PNG_FREE_ME_SUPPORTED
  197079. info_ptr->free_me |= PNG_FREE_PCAL;
  197080. #endif
  197081. }
  197082. #endif
  197083. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197084. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197085. void PNGAPI
  197086. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197087. int unit, double width, double height)
  197088. {
  197089. png_debug1(1, "in %s storage function\n", "sCAL");
  197090. if (png_ptr == NULL || info_ptr == NULL)
  197091. return;
  197092. info_ptr->scal_unit = (png_byte)unit;
  197093. info_ptr->scal_pixel_width = width;
  197094. info_ptr->scal_pixel_height = height;
  197095. info_ptr->valid |= PNG_INFO_sCAL;
  197096. }
  197097. #else
  197098. #ifdef PNG_FIXED_POINT_SUPPORTED
  197099. void PNGAPI
  197100. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197101. int unit, png_charp swidth, png_charp sheight)
  197102. {
  197103. png_uint_32 length;
  197104. png_debug1(1, "in %s storage function\n", "sCAL");
  197105. if (png_ptr == NULL || info_ptr == NULL)
  197106. return;
  197107. info_ptr->scal_unit = (png_byte)unit;
  197108. length = png_strlen(swidth) + 1;
  197109. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197110. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197111. if (info_ptr->scal_s_width == NULL)
  197112. {
  197113. png_warning(png_ptr,
  197114. "Memory allocation failed while processing sCAL.");
  197115. }
  197116. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197117. length = png_strlen(sheight) + 1;
  197118. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197119. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197120. if (info_ptr->scal_s_height == NULL)
  197121. {
  197122. png_free (png_ptr, info_ptr->scal_s_width);
  197123. png_warning(png_ptr,
  197124. "Memory allocation failed while processing sCAL.");
  197125. }
  197126. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197127. info_ptr->valid |= PNG_INFO_sCAL;
  197128. #ifdef PNG_FREE_ME_SUPPORTED
  197129. info_ptr->free_me |= PNG_FREE_SCAL;
  197130. #endif
  197131. }
  197132. #endif
  197133. #endif
  197134. #endif
  197135. #if defined(PNG_pHYs_SUPPORTED)
  197136. void PNGAPI
  197137. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197138. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197139. {
  197140. png_debug1(1, "in %s storage function\n", "pHYs");
  197141. if (png_ptr == NULL || info_ptr == NULL)
  197142. return;
  197143. info_ptr->x_pixels_per_unit = res_x;
  197144. info_ptr->y_pixels_per_unit = res_y;
  197145. info_ptr->phys_unit_type = (png_byte)unit_type;
  197146. info_ptr->valid |= PNG_INFO_pHYs;
  197147. }
  197148. #endif
  197149. void PNGAPI
  197150. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197151. png_colorp palette, int num_palette)
  197152. {
  197153. png_debug1(1, "in %s storage function\n", "PLTE");
  197154. if (png_ptr == NULL || info_ptr == NULL)
  197155. return;
  197156. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197157. {
  197158. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197159. png_error(png_ptr, "Invalid palette length");
  197160. else
  197161. {
  197162. png_warning(png_ptr, "Invalid palette length");
  197163. return;
  197164. }
  197165. }
  197166. /*
  197167. * It may not actually be necessary to set png_ptr->palette here;
  197168. * we do it for backward compatibility with the way the png_handle_tRNS
  197169. * function used to do the allocation.
  197170. */
  197171. #ifdef PNG_FREE_ME_SUPPORTED
  197172. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197173. #endif
  197174. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197175. of num_palette entries,
  197176. in case of an invalid PNG file that has too-large sample values. */
  197177. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197178. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197179. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197180. png_sizeof(png_color));
  197181. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197182. info_ptr->palette = png_ptr->palette;
  197183. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197184. #ifdef PNG_FREE_ME_SUPPORTED
  197185. info_ptr->free_me |= PNG_FREE_PLTE;
  197186. #else
  197187. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197188. #endif
  197189. info_ptr->valid |= PNG_INFO_PLTE;
  197190. }
  197191. #if defined(PNG_sBIT_SUPPORTED)
  197192. void PNGAPI
  197193. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197194. png_color_8p sig_bit)
  197195. {
  197196. png_debug1(1, "in %s storage function\n", "sBIT");
  197197. if (png_ptr == NULL || info_ptr == NULL)
  197198. return;
  197199. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197200. info_ptr->valid |= PNG_INFO_sBIT;
  197201. }
  197202. #endif
  197203. #if defined(PNG_sRGB_SUPPORTED)
  197204. void PNGAPI
  197205. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197206. {
  197207. png_debug1(1, "in %s storage function\n", "sRGB");
  197208. if (png_ptr == NULL || info_ptr == NULL)
  197209. return;
  197210. info_ptr->srgb_intent = (png_byte)intent;
  197211. info_ptr->valid |= PNG_INFO_sRGB;
  197212. }
  197213. void PNGAPI
  197214. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197215. int intent)
  197216. {
  197217. #if defined(PNG_gAMA_SUPPORTED)
  197218. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197219. float file_gamma;
  197220. #endif
  197221. #ifdef PNG_FIXED_POINT_SUPPORTED
  197222. png_fixed_point int_file_gamma;
  197223. #endif
  197224. #endif
  197225. #if defined(PNG_cHRM_SUPPORTED)
  197226. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197227. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197228. #endif
  197229. #ifdef PNG_FIXED_POINT_SUPPORTED
  197230. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197231. int_green_y, int_blue_x, int_blue_y;
  197232. #endif
  197233. #endif
  197234. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197235. if (png_ptr == NULL || info_ptr == NULL)
  197236. return;
  197237. png_set_sRGB(png_ptr, info_ptr, intent);
  197238. #if defined(PNG_gAMA_SUPPORTED)
  197239. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197240. file_gamma = (float).45455;
  197241. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197242. #endif
  197243. #ifdef PNG_FIXED_POINT_SUPPORTED
  197244. int_file_gamma = 45455L;
  197245. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197246. #endif
  197247. #endif
  197248. #if defined(PNG_cHRM_SUPPORTED)
  197249. #ifdef PNG_FIXED_POINT_SUPPORTED
  197250. int_white_x = 31270L;
  197251. int_white_y = 32900L;
  197252. int_red_x = 64000L;
  197253. int_red_y = 33000L;
  197254. int_green_x = 30000L;
  197255. int_green_y = 60000L;
  197256. int_blue_x = 15000L;
  197257. int_blue_y = 6000L;
  197258. png_set_cHRM_fixed(png_ptr, info_ptr,
  197259. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197260. int_blue_x, int_blue_y);
  197261. #endif
  197262. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197263. white_x = (float).3127;
  197264. white_y = (float).3290;
  197265. red_x = (float).64;
  197266. red_y = (float).33;
  197267. green_x = (float).30;
  197268. green_y = (float).60;
  197269. blue_x = (float).15;
  197270. blue_y = (float).06;
  197271. png_set_cHRM(png_ptr, info_ptr,
  197272. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197273. #endif
  197274. #endif
  197275. }
  197276. #endif
  197277. #if defined(PNG_iCCP_SUPPORTED)
  197278. void PNGAPI
  197279. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197280. png_charp name, int compression_type,
  197281. png_charp profile, png_uint_32 proflen)
  197282. {
  197283. png_charp new_iccp_name;
  197284. png_charp new_iccp_profile;
  197285. png_debug1(1, "in %s storage function\n", "iCCP");
  197286. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197287. return;
  197288. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197289. if (new_iccp_name == NULL)
  197290. {
  197291. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197292. return;
  197293. }
  197294. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197295. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197296. if (new_iccp_profile == NULL)
  197297. {
  197298. png_free (png_ptr, new_iccp_name);
  197299. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197300. return;
  197301. }
  197302. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197303. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197304. info_ptr->iccp_proflen = proflen;
  197305. info_ptr->iccp_name = new_iccp_name;
  197306. info_ptr->iccp_profile = new_iccp_profile;
  197307. /* Compression is always zero but is here so the API and info structure
  197308. * does not have to change if we introduce multiple compression types */
  197309. info_ptr->iccp_compression = (png_byte)compression_type;
  197310. #ifdef PNG_FREE_ME_SUPPORTED
  197311. info_ptr->free_me |= PNG_FREE_ICCP;
  197312. #endif
  197313. info_ptr->valid |= PNG_INFO_iCCP;
  197314. }
  197315. #endif
  197316. #if defined(PNG_TEXT_SUPPORTED)
  197317. void PNGAPI
  197318. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197319. int num_text)
  197320. {
  197321. int ret;
  197322. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197323. if (ret)
  197324. png_error(png_ptr, "Insufficient memory to store text");
  197325. }
  197326. int /* PRIVATE */
  197327. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197328. int num_text)
  197329. {
  197330. int i;
  197331. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197332. "text" : (png_const_charp)png_ptr->chunk_name));
  197333. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197334. return(0);
  197335. /* Make sure we have enough space in the "text" array in info_struct
  197336. * to hold all of the incoming text_ptr objects.
  197337. */
  197338. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197339. {
  197340. if (info_ptr->text != NULL)
  197341. {
  197342. png_textp old_text;
  197343. int old_max;
  197344. old_max = info_ptr->max_text;
  197345. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197346. old_text = info_ptr->text;
  197347. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197348. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197349. if (info_ptr->text == NULL)
  197350. {
  197351. png_free(png_ptr, old_text);
  197352. return(1);
  197353. }
  197354. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197355. png_sizeof(png_text)));
  197356. png_free(png_ptr, old_text);
  197357. }
  197358. else
  197359. {
  197360. info_ptr->max_text = num_text + 8;
  197361. info_ptr->num_text = 0;
  197362. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197363. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197364. if (info_ptr->text == NULL)
  197365. return(1);
  197366. #ifdef PNG_FREE_ME_SUPPORTED
  197367. info_ptr->free_me |= PNG_FREE_TEXT;
  197368. #endif
  197369. }
  197370. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197371. info_ptr->max_text);
  197372. }
  197373. for (i = 0; i < num_text; i++)
  197374. {
  197375. png_size_t text_length,key_len;
  197376. png_size_t lang_len,lang_key_len;
  197377. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197378. if (text_ptr[i].key == NULL)
  197379. continue;
  197380. key_len = png_strlen(text_ptr[i].key);
  197381. if(text_ptr[i].compression <= 0)
  197382. {
  197383. lang_len = 0;
  197384. lang_key_len = 0;
  197385. }
  197386. else
  197387. #ifdef PNG_iTXt_SUPPORTED
  197388. {
  197389. /* set iTXt data */
  197390. if (text_ptr[i].lang != NULL)
  197391. lang_len = png_strlen(text_ptr[i].lang);
  197392. else
  197393. lang_len = 0;
  197394. if (text_ptr[i].lang_key != NULL)
  197395. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197396. else
  197397. lang_key_len = 0;
  197398. }
  197399. #else
  197400. {
  197401. png_warning(png_ptr, "iTXt chunk not supported.");
  197402. continue;
  197403. }
  197404. #endif
  197405. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197406. {
  197407. text_length = 0;
  197408. #ifdef PNG_iTXt_SUPPORTED
  197409. if(text_ptr[i].compression > 0)
  197410. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197411. else
  197412. #endif
  197413. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197414. }
  197415. else
  197416. {
  197417. text_length = png_strlen(text_ptr[i].text);
  197418. textp->compression = text_ptr[i].compression;
  197419. }
  197420. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197421. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197422. if (textp->key == NULL)
  197423. return(1);
  197424. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197425. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197426. (int)textp->key);
  197427. png_memcpy(textp->key, text_ptr[i].key,
  197428. (png_size_t)(key_len));
  197429. *(textp->key+key_len) = '\0';
  197430. #ifdef PNG_iTXt_SUPPORTED
  197431. if (text_ptr[i].compression > 0)
  197432. {
  197433. textp->lang=textp->key + key_len + 1;
  197434. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197435. *(textp->lang+lang_len) = '\0';
  197436. textp->lang_key=textp->lang + lang_len + 1;
  197437. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197438. *(textp->lang_key+lang_key_len) = '\0';
  197439. textp->text=textp->lang_key + lang_key_len + 1;
  197440. }
  197441. else
  197442. #endif
  197443. {
  197444. #ifdef PNG_iTXt_SUPPORTED
  197445. textp->lang=NULL;
  197446. textp->lang_key=NULL;
  197447. #endif
  197448. textp->text=textp->key + key_len + 1;
  197449. }
  197450. if(text_length)
  197451. png_memcpy(textp->text, text_ptr[i].text,
  197452. (png_size_t)(text_length));
  197453. *(textp->text+text_length) = '\0';
  197454. #ifdef PNG_iTXt_SUPPORTED
  197455. if(textp->compression > 0)
  197456. {
  197457. textp->text_length = 0;
  197458. textp->itxt_length = text_length;
  197459. }
  197460. else
  197461. #endif
  197462. {
  197463. textp->text_length = text_length;
  197464. #ifdef PNG_iTXt_SUPPORTED
  197465. textp->itxt_length = 0;
  197466. #endif
  197467. }
  197468. info_ptr->num_text++;
  197469. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197470. }
  197471. return(0);
  197472. }
  197473. #endif
  197474. #if defined(PNG_tIME_SUPPORTED)
  197475. void PNGAPI
  197476. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197477. {
  197478. png_debug1(1, "in %s storage function\n", "tIME");
  197479. if (png_ptr == NULL || info_ptr == NULL ||
  197480. (png_ptr->mode & PNG_WROTE_tIME))
  197481. return;
  197482. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197483. info_ptr->valid |= PNG_INFO_tIME;
  197484. }
  197485. #endif
  197486. #if defined(PNG_tRNS_SUPPORTED)
  197487. void PNGAPI
  197488. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197489. png_bytep trans, int num_trans, png_color_16p trans_values)
  197490. {
  197491. png_debug1(1, "in %s storage function\n", "tRNS");
  197492. if (png_ptr == NULL || info_ptr == NULL)
  197493. return;
  197494. if (trans != NULL)
  197495. {
  197496. /*
  197497. * It may not actually be necessary to set png_ptr->trans here;
  197498. * we do it for backward compatibility with the way the png_handle_tRNS
  197499. * function used to do the allocation.
  197500. */
  197501. #ifdef PNG_FREE_ME_SUPPORTED
  197502. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197503. #endif
  197504. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197505. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197506. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197507. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197508. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197509. #ifdef PNG_FREE_ME_SUPPORTED
  197510. info_ptr->free_me |= PNG_FREE_TRNS;
  197511. #else
  197512. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197513. #endif
  197514. }
  197515. if (trans_values != NULL)
  197516. {
  197517. png_memcpy(&(info_ptr->trans_values), trans_values,
  197518. png_sizeof(png_color_16));
  197519. if (num_trans == 0)
  197520. num_trans = 1;
  197521. }
  197522. info_ptr->num_trans = (png_uint_16)num_trans;
  197523. info_ptr->valid |= PNG_INFO_tRNS;
  197524. }
  197525. #endif
  197526. #if defined(PNG_sPLT_SUPPORTED)
  197527. void PNGAPI
  197528. png_set_sPLT(png_structp png_ptr,
  197529. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197530. {
  197531. png_sPLT_tp np;
  197532. int i;
  197533. if (png_ptr == NULL || info_ptr == NULL)
  197534. return;
  197535. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197536. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197537. if (np == NULL)
  197538. {
  197539. png_warning(png_ptr, "No memory for sPLT palettes.");
  197540. return;
  197541. }
  197542. png_memcpy(np, info_ptr->splt_palettes,
  197543. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197544. png_free(png_ptr, info_ptr->splt_palettes);
  197545. info_ptr->splt_palettes=NULL;
  197546. for (i = 0; i < nentries; i++)
  197547. {
  197548. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197549. png_sPLT_tp from = entries + i;
  197550. to->name = (png_charp)png_malloc_warn(png_ptr,
  197551. png_strlen(from->name) + 1);
  197552. if (to->name == NULL)
  197553. {
  197554. png_warning(png_ptr,
  197555. "Out of memory while processing sPLT chunk");
  197556. }
  197557. /* TODO: use png_malloc_warn */
  197558. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197559. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197560. from->nentries * png_sizeof(png_sPLT_entry));
  197561. /* TODO: use png_malloc_warn */
  197562. png_memcpy(to->entries, from->entries,
  197563. from->nentries * png_sizeof(png_sPLT_entry));
  197564. if (to->entries == NULL)
  197565. {
  197566. png_warning(png_ptr,
  197567. "Out of memory while processing sPLT chunk");
  197568. png_free(png_ptr,to->name);
  197569. to->name = NULL;
  197570. }
  197571. to->nentries = from->nentries;
  197572. to->depth = from->depth;
  197573. }
  197574. info_ptr->splt_palettes = np;
  197575. info_ptr->splt_palettes_num += nentries;
  197576. info_ptr->valid |= PNG_INFO_sPLT;
  197577. #ifdef PNG_FREE_ME_SUPPORTED
  197578. info_ptr->free_me |= PNG_FREE_SPLT;
  197579. #endif
  197580. }
  197581. #endif /* PNG_sPLT_SUPPORTED */
  197582. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197583. void PNGAPI
  197584. png_set_unknown_chunks(png_structp png_ptr,
  197585. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197586. {
  197587. png_unknown_chunkp np;
  197588. int i;
  197589. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197590. return;
  197591. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197592. (info_ptr->unknown_chunks_num + num_unknowns) *
  197593. png_sizeof(png_unknown_chunk));
  197594. if (np == NULL)
  197595. {
  197596. png_warning(png_ptr,
  197597. "Out of memory while processing unknown chunk.");
  197598. return;
  197599. }
  197600. png_memcpy(np, info_ptr->unknown_chunks,
  197601. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197602. png_free(png_ptr, info_ptr->unknown_chunks);
  197603. info_ptr->unknown_chunks=NULL;
  197604. for (i = 0; i < num_unknowns; i++)
  197605. {
  197606. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197607. png_unknown_chunkp from = unknowns + i;
  197608. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197609. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197610. if (to->data == NULL)
  197611. {
  197612. png_warning(png_ptr,
  197613. "Out of memory while processing unknown chunk.");
  197614. }
  197615. else
  197616. {
  197617. png_memcpy(to->data, from->data, from->size);
  197618. to->size = from->size;
  197619. /* note our location in the read or write sequence */
  197620. to->location = (png_byte)(png_ptr->mode & 0xff);
  197621. }
  197622. }
  197623. info_ptr->unknown_chunks = np;
  197624. info_ptr->unknown_chunks_num += num_unknowns;
  197625. #ifdef PNG_FREE_ME_SUPPORTED
  197626. info_ptr->free_me |= PNG_FREE_UNKN;
  197627. #endif
  197628. }
  197629. void PNGAPI
  197630. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197631. int chunk, int location)
  197632. {
  197633. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197634. (int)info_ptr->unknown_chunks_num)
  197635. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197636. }
  197637. #endif
  197638. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197639. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197640. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197641. void PNGAPI
  197642. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197643. {
  197644. /* This function is deprecated in favor of png_permit_mng_features()
  197645. and will be removed from libpng-1.3.0 */
  197646. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197647. if (png_ptr == NULL)
  197648. return;
  197649. png_ptr->mng_features_permitted = (png_byte)
  197650. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197651. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197652. }
  197653. #endif
  197654. #endif
  197655. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197656. png_uint_32 PNGAPI
  197657. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197658. {
  197659. png_debug(1, "in png_permit_mng_features\n");
  197660. if (png_ptr == NULL)
  197661. return (png_uint_32)0;
  197662. png_ptr->mng_features_permitted =
  197663. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197664. return (png_uint_32)png_ptr->mng_features_permitted;
  197665. }
  197666. #endif
  197667. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197668. void PNGAPI
  197669. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197670. chunk_list, int num_chunks)
  197671. {
  197672. png_bytep new_list, p;
  197673. int i, old_num_chunks;
  197674. if (png_ptr == NULL)
  197675. return;
  197676. if (num_chunks == 0)
  197677. {
  197678. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197679. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197680. else
  197681. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197682. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197683. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197684. else
  197685. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197686. return;
  197687. }
  197688. if (chunk_list == NULL)
  197689. return;
  197690. old_num_chunks=png_ptr->num_chunk_list;
  197691. new_list=(png_bytep)png_malloc(png_ptr,
  197692. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197693. if(png_ptr->chunk_list != NULL)
  197694. {
  197695. png_memcpy(new_list, png_ptr->chunk_list,
  197696. (png_size_t)(5*old_num_chunks));
  197697. png_free(png_ptr, png_ptr->chunk_list);
  197698. png_ptr->chunk_list=NULL;
  197699. }
  197700. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197701. (png_size_t)(5*num_chunks));
  197702. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197703. *p=(png_byte)keep;
  197704. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197705. png_ptr->chunk_list=new_list;
  197706. #ifdef PNG_FREE_ME_SUPPORTED
  197707. png_ptr->free_me |= PNG_FREE_LIST;
  197708. #endif
  197709. }
  197710. #endif
  197711. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197712. void PNGAPI
  197713. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197714. png_user_chunk_ptr read_user_chunk_fn)
  197715. {
  197716. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197717. if (png_ptr == NULL)
  197718. return;
  197719. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197720. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197721. }
  197722. #endif
  197723. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197724. void PNGAPI
  197725. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197726. {
  197727. png_debug1(1, "in %s storage function\n", "rows");
  197728. if (png_ptr == NULL || info_ptr == NULL)
  197729. return;
  197730. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197731. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197732. info_ptr->row_pointers = row_pointers;
  197733. if(row_pointers)
  197734. info_ptr->valid |= PNG_INFO_IDAT;
  197735. }
  197736. #endif
  197737. #ifdef PNG_WRITE_SUPPORTED
  197738. void PNGAPI
  197739. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197740. {
  197741. if (png_ptr == NULL)
  197742. return;
  197743. if(png_ptr->zbuf)
  197744. png_free(png_ptr, png_ptr->zbuf);
  197745. png_ptr->zbuf_size = (png_size_t)size;
  197746. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197747. png_ptr->zstream.next_out = png_ptr->zbuf;
  197748. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197749. }
  197750. #endif
  197751. void PNGAPI
  197752. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197753. {
  197754. if (png_ptr && info_ptr)
  197755. info_ptr->valid &= ~(mask);
  197756. }
  197757. #ifndef PNG_1_0_X
  197758. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197759. /* function was added to libpng 1.2.0 and should always exist by default */
  197760. void PNGAPI
  197761. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197762. {
  197763. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197764. if (png_ptr != NULL)
  197765. png_ptr->asm_flags = 0;
  197766. }
  197767. /* this function was added to libpng 1.2.0 */
  197768. void PNGAPI
  197769. png_set_mmx_thresholds (png_structp png_ptr,
  197770. png_byte,
  197771. png_uint_32)
  197772. {
  197773. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197774. if (png_ptr == NULL)
  197775. return;
  197776. }
  197777. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197778. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197779. /* this function was added to libpng 1.2.6 */
  197780. void PNGAPI
  197781. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197782. png_uint_32 user_height_max)
  197783. {
  197784. /* Images with dimensions larger than these limits will be
  197785. * rejected by png_set_IHDR(). To accept any PNG datastream
  197786. * regardless of dimensions, set both limits to 0x7ffffffL.
  197787. */
  197788. if(png_ptr == NULL) return;
  197789. png_ptr->user_width_max = user_width_max;
  197790. png_ptr->user_height_max = user_height_max;
  197791. }
  197792. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197793. #endif /* ?PNG_1_0_X */
  197794. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197795. /*** End of inlined file: pngset.c ***/
  197796. /*** Start of inlined file: pngtrans.c ***/
  197797. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197798. *
  197799. * Last changed in libpng 1.2.17 May 15, 2007
  197800. * For conditions of distribution and use, see copyright notice in png.h
  197801. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197802. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197803. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197804. */
  197805. #define PNG_INTERNAL
  197806. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197807. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197808. /* turn on BGR-to-RGB mapping */
  197809. void PNGAPI
  197810. png_set_bgr(png_structp png_ptr)
  197811. {
  197812. png_debug(1, "in png_set_bgr\n");
  197813. if(png_ptr == NULL) return;
  197814. png_ptr->transformations |= PNG_BGR;
  197815. }
  197816. #endif
  197817. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197818. /* turn on 16 bit byte swapping */
  197819. void PNGAPI
  197820. png_set_swap(png_structp png_ptr)
  197821. {
  197822. png_debug(1, "in png_set_swap\n");
  197823. if(png_ptr == NULL) return;
  197824. if (png_ptr->bit_depth == 16)
  197825. png_ptr->transformations |= PNG_SWAP_BYTES;
  197826. }
  197827. #endif
  197828. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197829. /* turn on pixel packing */
  197830. void PNGAPI
  197831. png_set_packing(png_structp png_ptr)
  197832. {
  197833. png_debug(1, "in png_set_packing\n");
  197834. if(png_ptr == NULL) return;
  197835. if (png_ptr->bit_depth < 8)
  197836. {
  197837. png_ptr->transformations |= PNG_PACK;
  197838. png_ptr->usr_bit_depth = 8;
  197839. }
  197840. }
  197841. #endif
  197842. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197843. /* turn on packed pixel swapping */
  197844. void PNGAPI
  197845. png_set_packswap(png_structp png_ptr)
  197846. {
  197847. png_debug(1, "in png_set_packswap\n");
  197848. if(png_ptr == NULL) return;
  197849. if (png_ptr->bit_depth < 8)
  197850. png_ptr->transformations |= PNG_PACKSWAP;
  197851. }
  197852. #endif
  197853. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197854. void PNGAPI
  197855. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197856. {
  197857. png_debug(1, "in png_set_shift\n");
  197858. if(png_ptr == NULL) return;
  197859. png_ptr->transformations |= PNG_SHIFT;
  197860. png_ptr->shift = *true_bits;
  197861. }
  197862. #endif
  197863. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197864. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197865. int PNGAPI
  197866. png_set_interlace_handling(png_structp png_ptr)
  197867. {
  197868. png_debug(1, "in png_set_interlace handling\n");
  197869. if (png_ptr && png_ptr->interlaced)
  197870. {
  197871. png_ptr->transformations |= PNG_INTERLACE;
  197872. return (7);
  197873. }
  197874. return (1);
  197875. }
  197876. #endif
  197877. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197878. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197879. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197880. * for 48-bit input data, as well as to avoid problems with some compilers
  197881. * that don't like bytes as parameters.
  197882. */
  197883. void PNGAPI
  197884. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197885. {
  197886. png_debug(1, "in png_set_filler\n");
  197887. if(png_ptr == NULL) return;
  197888. png_ptr->transformations |= PNG_FILLER;
  197889. png_ptr->filler = (png_byte)filler;
  197890. if (filler_loc == PNG_FILLER_AFTER)
  197891. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197892. else
  197893. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197894. /* This should probably go in the "do_read_filler" routine.
  197895. * I attempted to do that in libpng-1.0.1a but that caused problems
  197896. * so I restored it in libpng-1.0.2a
  197897. */
  197898. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197899. {
  197900. png_ptr->usr_channels = 4;
  197901. }
  197902. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197903. * a less-than-8-bit grayscale to GA? */
  197904. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197905. {
  197906. png_ptr->usr_channels = 2;
  197907. }
  197908. }
  197909. #if !defined(PNG_1_0_X)
  197910. /* Added to libpng-1.2.7 */
  197911. void PNGAPI
  197912. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197913. {
  197914. png_debug(1, "in png_set_add_alpha\n");
  197915. if(png_ptr == NULL) return;
  197916. png_set_filler(png_ptr, filler, filler_loc);
  197917. png_ptr->transformations |= PNG_ADD_ALPHA;
  197918. }
  197919. #endif
  197920. #endif
  197921. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197922. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197923. void PNGAPI
  197924. png_set_swap_alpha(png_structp png_ptr)
  197925. {
  197926. png_debug(1, "in png_set_swap_alpha\n");
  197927. if(png_ptr == NULL) return;
  197928. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197929. }
  197930. #endif
  197931. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197932. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197933. void PNGAPI
  197934. png_set_invert_alpha(png_structp png_ptr)
  197935. {
  197936. png_debug(1, "in png_set_invert_alpha\n");
  197937. if(png_ptr == NULL) return;
  197938. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197939. }
  197940. #endif
  197941. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197942. void PNGAPI
  197943. png_set_invert_mono(png_structp png_ptr)
  197944. {
  197945. png_debug(1, "in png_set_invert_mono\n");
  197946. if(png_ptr == NULL) return;
  197947. png_ptr->transformations |= PNG_INVERT_MONO;
  197948. }
  197949. /* invert monochrome grayscale data */
  197950. void /* PRIVATE */
  197951. png_do_invert(png_row_infop row_info, png_bytep row)
  197952. {
  197953. png_debug(1, "in png_do_invert\n");
  197954. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197955. * if (row_info->bit_depth == 1 &&
  197956. */
  197957. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197958. if (row == NULL || row_info == NULL)
  197959. return;
  197960. #endif
  197961. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197962. {
  197963. png_bytep rp = row;
  197964. png_uint_32 i;
  197965. png_uint_32 istop = row_info->rowbytes;
  197966. for (i = 0; i < istop; i++)
  197967. {
  197968. *rp = (png_byte)(~(*rp));
  197969. rp++;
  197970. }
  197971. }
  197972. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197973. row_info->bit_depth == 8)
  197974. {
  197975. png_bytep rp = row;
  197976. png_uint_32 i;
  197977. png_uint_32 istop = row_info->rowbytes;
  197978. for (i = 0; i < istop; i+=2)
  197979. {
  197980. *rp = (png_byte)(~(*rp));
  197981. rp+=2;
  197982. }
  197983. }
  197984. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197985. row_info->bit_depth == 16)
  197986. {
  197987. png_bytep rp = row;
  197988. png_uint_32 i;
  197989. png_uint_32 istop = row_info->rowbytes;
  197990. for (i = 0; i < istop; i+=4)
  197991. {
  197992. *rp = (png_byte)(~(*rp));
  197993. *(rp+1) = (png_byte)(~(*(rp+1)));
  197994. rp+=4;
  197995. }
  197996. }
  197997. }
  197998. #endif
  197999. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198000. /* swaps byte order on 16 bit depth images */
  198001. void /* PRIVATE */
  198002. png_do_swap(png_row_infop row_info, png_bytep row)
  198003. {
  198004. png_debug(1, "in png_do_swap\n");
  198005. if (
  198006. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198007. row != NULL && row_info != NULL &&
  198008. #endif
  198009. row_info->bit_depth == 16)
  198010. {
  198011. png_bytep rp = row;
  198012. png_uint_32 i;
  198013. png_uint_32 istop= row_info->width * row_info->channels;
  198014. for (i = 0; i < istop; i++, rp += 2)
  198015. {
  198016. png_byte t = *rp;
  198017. *rp = *(rp + 1);
  198018. *(rp + 1) = t;
  198019. }
  198020. }
  198021. }
  198022. #endif
  198023. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198024. static PNG_CONST png_byte onebppswaptable[256] = {
  198025. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198026. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198027. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198028. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198029. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198030. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198031. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198032. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198033. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198034. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198035. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198036. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198037. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198038. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198039. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198040. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198041. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198042. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198043. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198044. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198045. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198046. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198047. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198048. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198049. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198050. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198051. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198052. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198053. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198054. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198055. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198056. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198057. };
  198058. static PNG_CONST png_byte twobppswaptable[256] = {
  198059. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198060. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198061. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198062. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198063. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198064. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198065. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198066. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198067. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198068. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198069. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198070. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198071. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198072. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198073. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198074. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198075. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198076. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198077. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198078. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198079. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198080. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198081. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198082. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198083. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198084. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198085. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198086. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198087. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198088. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198089. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198090. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198091. };
  198092. static PNG_CONST png_byte fourbppswaptable[256] = {
  198093. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198094. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198095. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198096. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198097. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198098. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198099. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198100. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198101. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198102. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198103. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198104. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198105. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198106. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198107. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198108. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198109. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198110. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198111. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198112. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198113. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198114. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198115. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198116. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198117. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198118. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198119. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198120. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198121. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198122. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198123. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198124. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198125. };
  198126. /* swaps pixel packing order within bytes */
  198127. void /* PRIVATE */
  198128. png_do_packswap(png_row_infop row_info, png_bytep row)
  198129. {
  198130. png_debug(1, "in png_do_packswap\n");
  198131. if (
  198132. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198133. row != NULL && row_info != NULL &&
  198134. #endif
  198135. row_info->bit_depth < 8)
  198136. {
  198137. png_bytep rp, end, table;
  198138. end = row + row_info->rowbytes;
  198139. if (row_info->bit_depth == 1)
  198140. table = (png_bytep)onebppswaptable;
  198141. else if (row_info->bit_depth == 2)
  198142. table = (png_bytep)twobppswaptable;
  198143. else if (row_info->bit_depth == 4)
  198144. table = (png_bytep)fourbppswaptable;
  198145. else
  198146. return;
  198147. for (rp = row; rp < end; rp++)
  198148. *rp = table[*rp];
  198149. }
  198150. }
  198151. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198152. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198153. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198154. /* remove filler or alpha byte(s) */
  198155. void /* PRIVATE */
  198156. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198157. {
  198158. png_debug(1, "in png_do_strip_filler\n");
  198159. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198160. if (row != NULL && row_info != NULL)
  198161. #endif
  198162. {
  198163. png_bytep sp=row;
  198164. png_bytep dp=row;
  198165. png_uint_32 row_width=row_info->width;
  198166. png_uint_32 i;
  198167. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198168. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198169. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198170. row_info->channels == 4)
  198171. {
  198172. if (row_info->bit_depth == 8)
  198173. {
  198174. /* This converts from RGBX or RGBA to RGB */
  198175. if (flags & PNG_FLAG_FILLER_AFTER)
  198176. {
  198177. dp+=3; sp+=4;
  198178. for (i = 1; i < row_width; i++)
  198179. {
  198180. *dp++ = *sp++;
  198181. *dp++ = *sp++;
  198182. *dp++ = *sp++;
  198183. sp++;
  198184. }
  198185. }
  198186. /* This converts from XRGB or ARGB to RGB */
  198187. else
  198188. {
  198189. for (i = 0; i < row_width; i++)
  198190. {
  198191. sp++;
  198192. *dp++ = *sp++;
  198193. *dp++ = *sp++;
  198194. *dp++ = *sp++;
  198195. }
  198196. }
  198197. row_info->pixel_depth = 24;
  198198. row_info->rowbytes = row_width * 3;
  198199. }
  198200. else /* if (row_info->bit_depth == 16) */
  198201. {
  198202. if (flags & PNG_FLAG_FILLER_AFTER)
  198203. {
  198204. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198205. sp += 8; dp += 6;
  198206. for (i = 1; i < row_width; i++)
  198207. {
  198208. /* This could be (although png_memcpy is probably slower):
  198209. png_memcpy(dp, sp, 6);
  198210. sp += 8;
  198211. dp += 6;
  198212. */
  198213. *dp++ = *sp++;
  198214. *dp++ = *sp++;
  198215. *dp++ = *sp++;
  198216. *dp++ = *sp++;
  198217. *dp++ = *sp++;
  198218. *dp++ = *sp++;
  198219. sp += 2;
  198220. }
  198221. }
  198222. else
  198223. {
  198224. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198225. for (i = 0; i < row_width; i++)
  198226. {
  198227. /* This could be (although png_memcpy is probably slower):
  198228. png_memcpy(dp, sp, 6);
  198229. sp += 8;
  198230. dp += 6;
  198231. */
  198232. sp+=2;
  198233. *dp++ = *sp++;
  198234. *dp++ = *sp++;
  198235. *dp++ = *sp++;
  198236. *dp++ = *sp++;
  198237. *dp++ = *sp++;
  198238. *dp++ = *sp++;
  198239. }
  198240. }
  198241. row_info->pixel_depth = 48;
  198242. row_info->rowbytes = row_width * 6;
  198243. }
  198244. row_info->channels = 3;
  198245. }
  198246. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198247. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198248. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198249. row_info->channels == 2)
  198250. {
  198251. if (row_info->bit_depth == 8)
  198252. {
  198253. /* This converts from GX or GA to G */
  198254. if (flags & PNG_FLAG_FILLER_AFTER)
  198255. {
  198256. for (i = 0; i < row_width; i++)
  198257. {
  198258. *dp++ = *sp++;
  198259. sp++;
  198260. }
  198261. }
  198262. /* This converts from XG or AG to G */
  198263. else
  198264. {
  198265. for (i = 0; i < row_width; i++)
  198266. {
  198267. sp++;
  198268. *dp++ = *sp++;
  198269. }
  198270. }
  198271. row_info->pixel_depth = 8;
  198272. row_info->rowbytes = row_width;
  198273. }
  198274. else /* if (row_info->bit_depth == 16) */
  198275. {
  198276. if (flags & PNG_FLAG_FILLER_AFTER)
  198277. {
  198278. /* This converts from GGXX or GGAA to GG */
  198279. sp += 4; dp += 2;
  198280. for (i = 1; i < row_width; i++)
  198281. {
  198282. *dp++ = *sp++;
  198283. *dp++ = *sp++;
  198284. sp += 2;
  198285. }
  198286. }
  198287. else
  198288. {
  198289. /* This converts from XXGG or AAGG to GG */
  198290. for (i = 0; i < row_width; i++)
  198291. {
  198292. sp += 2;
  198293. *dp++ = *sp++;
  198294. *dp++ = *sp++;
  198295. }
  198296. }
  198297. row_info->pixel_depth = 16;
  198298. row_info->rowbytes = row_width * 2;
  198299. }
  198300. row_info->channels = 1;
  198301. }
  198302. if (flags & PNG_FLAG_STRIP_ALPHA)
  198303. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198304. }
  198305. }
  198306. #endif
  198307. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198308. /* swaps red and blue bytes within a pixel */
  198309. void /* PRIVATE */
  198310. png_do_bgr(png_row_infop row_info, png_bytep row)
  198311. {
  198312. png_debug(1, "in png_do_bgr\n");
  198313. if (
  198314. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198315. row != NULL && row_info != NULL &&
  198316. #endif
  198317. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198318. {
  198319. png_uint_32 row_width = row_info->width;
  198320. if (row_info->bit_depth == 8)
  198321. {
  198322. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198323. {
  198324. png_bytep rp;
  198325. png_uint_32 i;
  198326. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198327. {
  198328. png_byte save = *rp;
  198329. *rp = *(rp + 2);
  198330. *(rp + 2) = save;
  198331. }
  198332. }
  198333. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198334. {
  198335. png_bytep rp;
  198336. png_uint_32 i;
  198337. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198338. {
  198339. png_byte save = *rp;
  198340. *rp = *(rp + 2);
  198341. *(rp + 2) = save;
  198342. }
  198343. }
  198344. }
  198345. else if (row_info->bit_depth == 16)
  198346. {
  198347. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198348. {
  198349. png_bytep rp;
  198350. png_uint_32 i;
  198351. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198352. {
  198353. png_byte save = *rp;
  198354. *rp = *(rp + 4);
  198355. *(rp + 4) = save;
  198356. save = *(rp + 1);
  198357. *(rp + 1) = *(rp + 5);
  198358. *(rp + 5) = save;
  198359. }
  198360. }
  198361. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198362. {
  198363. png_bytep rp;
  198364. png_uint_32 i;
  198365. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198366. {
  198367. png_byte save = *rp;
  198368. *rp = *(rp + 4);
  198369. *(rp + 4) = save;
  198370. save = *(rp + 1);
  198371. *(rp + 1) = *(rp + 5);
  198372. *(rp + 5) = save;
  198373. }
  198374. }
  198375. }
  198376. }
  198377. }
  198378. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198379. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198380. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198381. defined(PNG_LEGACY_SUPPORTED)
  198382. void PNGAPI
  198383. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198384. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198385. {
  198386. png_debug(1, "in png_set_user_transform_info\n");
  198387. if(png_ptr == NULL) return;
  198388. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198389. png_ptr->user_transform_ptr = user_transform_ptr;
  198390. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198391. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198392. #else
  198393. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198394. png_warning(png_ptr,
  198395. "This version of libpng does not support user transform info");
  198396. #endif
  198397. }
  198398. #endif
  198399. /* This function returns a pointer to the user_transform_ptr associated with
  198400. * the user transform functions. The application should free any memory
  198401. * associated with this pointer before png_write_destroy and png_read_destroy
  198402. * are called.
  198403. */
  198404. png_voidp PNGAPI
  198405. png_get_user_transform_ptr(png_structp png_ptr)
  198406. {
  198407. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198408. if (png_ptr == NULL) return (NULL);
  198409. return ((png_voidp)png_ptr->user_transform_ptr);
  198410. #else
  198411. return (NULL);
  198412. #endif
  198413. }
  198414. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198415. /*** End of inlined file: pngtrans.c ***/
  198416. /*** Start of inlined file: pngwio.c ***/
  198417. /* pngwio.c - functions for data output
  198418. *
  198419. * Last changed in libpng 1.2.13 November 13, 2006
  198420. * For conditions of distribution and use, see copyright notice in png.h
  198421. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198422. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198423. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198424. *
  198425. * This file provides a location for all output. Users who need
  198426. * special handling are expected to write functions that have the same
  198427. * arguments as these and perform similar functions, but that possibly
  198428. * use different output methods. Note that you shouldn't change these
  198429. * functions, but rather write replacement functions and then change
  198430. * them at run time with png_set_write_fn(...).
  198431. */
  198432. #define PNG_INTERNAL
  198433. #ifdef PNG_WRITE_SUPPORTED
  198434. /* Write the data to whatever output you are using. The default routine
  198435. writes to a file pointer. Note that this routine sometimes gets called
  198436. with very small lengths, so you should implement some kind of simple
  198437. buffering if you are using unbuffered writes. This should never be asked
  198438. to write more than 64K on a 16 bit machine. */
  198439. void /* PRIVATE */
  198440. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198441. {
  198442. if (png_ptr->write_data_fn != NULL )
  198443. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198444. else
  198445. png_error(png_ptr, "Call to NULL write function");
  198446. }
  198447. #if !defined(PNG_NO_STDIO)
  198448. /* This is the function that does the actual writing of data. If you are
  198449. not writing to a standard C stream, you should create a replacement
  198450. write_data function and use it at run time with png_set_write_fn(), rather
  198451. than changing the library. */
  198452. #ifndef USE_FAR_KEYWORD
  198453. void PNGAPI
  198454. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198455. {
  198456. png_uint_32 check;
  198457. if(png_ptr == NULL) return;
  198458. #if defined(_WIN32_WCE)
  198459. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198460. check = 0;
  198461. #else
  198462. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198463. #endif
  198464. if (check != length)
  198465. png_error(png_ptr, "Write Error");
  198466. }
  198467. #else
  198468. /* this is the model-independent version. Since the standard I/O library
  198469. can't handle far buffers in the medium and small models, we have to copy
  198470. the data.
  198471. */
  198472. #define NEAR_BUF_SIZE 1024
  198473. #define MIN(a,b) (a <= b ? a : b)
  198474. void PNGAPI
  198475. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198476. {
  198477. png_uint_32 check;
  198478. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198479. png_FILE_p io_ptr;
  198480. if(png_ptr == NULL) return;
  198481. /* Check if data really is near. If so, use usual code. */
  198482. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198483. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198484. if ((png_bytep)near_data == data)
  198485. {
  198486. #if defined(_WIN32_WCE)
  198487. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198488. check = 0;
  198489. #else
  198490. check = fwrite(near_data, 1, length, io_ptr);
  198491. #endif
  198492. }
  198493. else
  198494. {
  198495. png_byte buf[NEAR_BUF_SIZE];
  198496. png_size_t written, remaining, err;
  198497. check = 0;
  198498. remaining = length;
  198499. do
  198500. {
  198501. written = MIN(NEAR_BUF_SIZE, remaining);
  198502. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198503. #if defined(_WIN32_WCE)
  198504. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198505. err = 0;
  198506. #else
  198507. err = fwrite(buf, 1, written, io_ptr);
  198508. #endif
  198509. if (err != written)
  198510. break;
  198511. else
  198512. check += err;
  198513. data += written;
  198514. remaining -= written;
  198515. }
  198516. while (remaining != 0);
  198517. }
  198518. if (check != length)
  198519. png_error(png_ptr, "Write Error");
  198520. }
  198521. #endif
  198522. #endif
  198523. /* This function is called to output any data pending writing (normally
  198524. to disk). After png_flush is called, there should be no data pending
  198525. writing in any buffers. */
  198526. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198527. void /* PRIVATE */
  198528. png_flush(png_structp png_ptr)
  198529. {
  198530. if (png_ptr->output_flush_fn != NULL)
  198531. (*(png_ptr->output_flush_fn))(png_ptr);
  198532. }
  198533. #if !defined(PNG_NO_STDIO)
  198534. void PNGAPI
  198535. png_default_flush(png_structp png_ptr)
  198536. {
  198537. #if !defined(_WIN32_WCE)
  198538. png_FILE_p io_ptr;
  198539. #endif
  198540. if(png_ptr == NULL) return;
  198541. #if !defined(_WIN32_WCE)
  198542. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198543. if (io_ptr != NULL)
  198544. fflush(io_ptr);
  198545. #endif
  198546. }
  198547. #endif
  198548. #endif
  198549. /* This function allows the application to supply new output functions for
  198550. libpng if standard C streams aren't being used.
  198551. This function takes as its arguments:
  198552. png_ptr - pointer to a png output data structure
  198553. io_ptr - pointer to user supplied structure containing info about
  198554. the output functions. May be NULL.
  198555. write_data_fn - pointer to a new output function that takes as its
  198556. arguments a pointer to a png_struct, a pointer to
  198557. data to be written, and a 32-bit unsigned int that is
  198558. the number of bytes to be written. The new write
  198559. function should call png_error(png_ptr, "Error msg")
  198560. to exit and output any fatal error messages.
  198561. flush_data_fn - pointer to a new flush function that takes as its
  198562. arguments a pointer to a png_struct. After a call to
  198563. the flush function, there should be no data in any buffers
  198564. or pending transmission. If the output method doesn't do
  198565. any buffering of ouput, a function prototype must still be
  198566. supplied although it doesn't have to do anything. If
  198567. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198568. time, output_flush_fn will be ignored, although it must be
  198569. supplied for compatibility. */
  198570. void PNGAPI
  198571. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198572. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198573. {
  198574. if(png_ptr == NULL) return;
  198575. png_ptr->io_ptr = io_ptr;
  198576. #if !defined(PNG_NO_STDIO)
  198577. if (write_data_fn != NULL)
  198578. png_ptr->write_data_fn = write_data_fn;
  198579. else
  198580. png_ptr->write_data_fn = png_default_write_data;
  198581. #else
  198582. png_ptr->write_data_fn = write_data_fn;
  198583. #endif
  198584. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198585. #if !defined(PNG_NO_STDIO)
  198586. if (output_flush_fn != NULL)
  198587. png_ptr->output_flush_fn = output_flush_fn;
  198588. else
  198589. png_ptr->output_flush_fn = png_default_flush;
  198590. #else
  198591. png_ptr->output_flush_fn = output_flush_fn;
  198592. #endif
  198593. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198594. /* It is an error to read while writing a png file */
  198595. if (png_ptr->read_data_fn != NULL)
  198596. {
  198597. png_ptr->read_data_fn = NULL;
  198598. png_warning(png_ptr,
  198599. "Attempted to set both read_data_fn and write_data_fn in");
  198600. png_warning(png_ptr,
  198601. "the same structure. Resetting read_data_fn to NULL.");
  198602. }
  198603. }
  198604. #if defined(USE_FAR_KEYWORD)
  198605. #if defined(_MSC_VER)
  198606. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198607. {
  198608. void *near_ptr;
  198609. void FAR *far_ptr;
  198610. FP_OFF(near_ptr) = FP_OFF(ptr);
  198611. far_ptr = (void FAR *)near_ptr;
  198612. if(check != 0)
  198613. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198614. png_error(png_ptr,"segment lost in conversion");
  198615. return(near_ptr);
  198616. }
  198617. # else
  198618. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198619. {
  198620. void *near_ptr;
  198621. void FAR *far_ptr;
  198622. near_ptr = (void FAR *)ptr;
  198623. far_ptr = (void FAR *)near_ptr;
  198624. if(check != 0)
  198625. if(far_ptr != ptr)
  198626. png_error(png_ptr,"segment lost in conversion");
  198627. return(near_ptr);
  198628. }
  198629. # endif
  198630. # endif
  198631. #endif /* PNG_WRITE_SUPPORTED */
  198632. /*** End of inlined file: pngwio.c ***/
  198633. /*** Start of inlined file: pngwrite.c ***/
  198634. /* pngwrite.c - general routines to write a PNG file
  198635. *
  198636. * Last changed in libpng 1.2.15 January 5, 2007
  198637. * For conditions of distribution and use, see copyright notice in png.h
  198638. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198639. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198640. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198641. */
  198642. /* get internal access to png.h */
  198643. #define PNG_INTERNAL
  198644. #ifdef PNG_WRITE_SUPPORTED
  198645. /* Writes all the PNG information. This is the suggested way to use the
  198646. * library. If you have a new chunk to add, make a function to write it,
  198647. * and put it in the correct location here. If you want the chunk written
  198648. * after the image data, put it in png_write_end(). I strongly encourage
  198649. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198650. * the chunk, as that will keep the code from breaking if you want to just
  198651. * write a plain PNG file. If you have long comments, I suggest writing
  198652. * them in png_write_end(), and compressing them.
  198653. */
  198654. void PNGAPI
  198655. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198656. {
  198657. png_debug(1, "in png_write_info_before_PLTE\n");
  198658. if (png_ptr == NULL || info_ptr == NULL)
  198659. return;
  198660. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198661. {
  198662. png_write_sig(png_ptr); /* write PNG signature */
  198663. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198664. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198665. {
  198666. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198667. png_ptr->mng_features_permitted=0;
  198668. }
  198669. #endif
  198670. /* write IHDR information. */
  198671. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198672. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198673. info_ptr->filter_type,
  198674. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198675. info_ptr->interlace_type);
  198676. #else
  198677. 0);
  198678. #endif
  198679. /* the rest of these check to see if the valid field has the appropriate
  198680. flag set, and if it does, writes the chunk. */
  198681. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198682. if (info_ptr->valid & PNG_INFO_gAMA)
  198683. {
  198684. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198685. png_write_gAMA(png_ptr, info_ptr->gamma);
  198686. #else
  198687. #ifdef PNG_FIXED_POINT_SUPPORTED
  198688. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198689. # endif
  198690. #endif
  198691. }
  198692. #endif
  198693. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198694. if (info_ptr->valid & PNG_INFO_sRGB)
  198695. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198696. #endif
  198697. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198698. if (info_ptr->valid & PNG_INFO_iCCP)
  198699. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198700. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198701. #endif
  198702. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198703. if (info_ptr->valid & PNG_INFO_sBIT)
  198704. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198705. #endif
  198706. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198707. if (info_ptr->valid & PNG_INFO_cHRM)
  198708. {
  198709. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198710. png_write_cHRM(png_ptr,
  198711. info_ptr->x_white, info_ptr->y_white,
  198712. info_ptr->x_red, info_ptr->y_red,
  198713. info_ptr->x_green, info_ptr->y_green,
  198714. info_ptr->x_blue, info_ptr->y_blue);
  198715. #else
  198716. # ifdef PNG_FIXED_POINT_SUPPORTED
  198717. png_write_cHRM_fixed(png_ptr,
  198718. info_ptr->int_x_white, info_ptr->int_y_white,
  198719. info_ptr->int_x_red, info_ptr->int_y_red,
  198720. info_ptr->int_x_green, info_ptr->int_y_green,
  198721. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198722. # endif
  198723. #endif
  198724. }
  198725. #endif
  198726. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198727. if (info_ptr->unknown_chunks_num)
  198728. {
  198729. png_unknown_chunk *up;
  198730. png_debug(5, "writing extra chunks\n");
  198731. for (up = info_ptr->unknown_chunks;
  198732. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198733. up++)
  198734. {
  198735. int keep=png_handle_as_unknown(png_ptr, up->name);
  198736. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198737. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198738. !(up->location & PNG_HAVE_IDAT) &&
  198739. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198740. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198741. {
  198742. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198743. }
  198744. }
  198745. }
  198746. #endif
  198747. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198748. }
  198749. }
  198750. void PNGAPI
  198751. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198752. {
  198753. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198754. int i;
  198755. #endif
  198756. png_debug(1, "in png_write_info\n");
  198757. if (png_ptr == NULL || info_ptr == NULL)
  198758. return;
  198759. png_write_info_before_PLTE(png_ptr, info_ptr);
  198760. if (info_ptr->valid & PNG_INFO_PLTE)
  198761. png_write_PLTE(png_ptr, info_ptr->palette,
  198762. (png_uint_32)info_ptr->num_palette);
  198763. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198764. png_error(png_ptr, "Valid palette required for paletted images");
  198765. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198766. if (info_ptr->valid & PNG_INFO_tRNS)
  198767. {
  198768. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198769. /* invert the alpha channel (in tRNS) */
  198770. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198771. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198772. {
  198773. int j;
  198774. for (j=0; j<(int)info_ptr->num_trans; j++)
  198775. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198776. }
  198777. #endif
  198778. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198779. info_ptr->num_trans, info_ptr->color_type);
  198780. }
  198781. #endif
  198782. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198783. if (info_ptr->valid & PNG_INFO_bKGD)
  198784. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198785. #endif
  198786. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198787. if (info_ptr->valid & PNG_INFO_hIST)
  198788. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198789. #endif
  198790. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198791. if (info_ptr->valid & PNG_INFO_oFFs)
  198792. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198793. info_ptr->offset_unit_type);
  198794. #endif
  198795. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198796. if (info_ptr->valid & PNG_INFO_pCAL)
  198797. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198798. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198799. info_ptr->pcal_units, info_ptr->pcal_params);
  198800. #endif
  198801. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198802. if (info_ptr->valid & PNG_INFO_sCAL)
  198803. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198804. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198805. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198806. #else
  198807. #ifdef PNG_FIXED_POINT_SUPPORTED
  198808. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198809. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198810. #else
  198811. png_warning(png_ptr,
  198812. "png_write_sCAL not supported; sCAL chunk not written.");
  198813. #endif
  198814. #endif
  198815. #endif
  198816. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198817. if (info_ptr->valid & PNG_INFO_pHYs)
  198818. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198819. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198820. #endif
  198821. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198822. if (info_ptr->valid & PNG_INFO_tIME)
  198823. {
  198824. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198825. png_ptr->mode |= PNG_WROTE_tIME;
  198826. }
  198827. #endif
  198828. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198829. if (info_ptr->valid & PNG_INFO_sPLT)
  198830. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198831. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198832. #endif
  198833. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198834. /* Check to see if we need to write text chunks */
  198835. for (i = 0; i < info_ptr->num_text; i++)
  198836. {
  198837. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198838. info_ptr->text[i].compression);
  198839. /* an internationalized chunk? */
  198840. if (info_ptr->text[i].compression > 0)
  198841. {
  198842. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198843. /* write international chunk */
  198844. png_write_iTXt(png_ptr,
  198845. info_ptr->text[i].compression,
  198846. info_ptr->text[i].key,
  198847. info_ptr->text[i].lang,
  198848. info_ptr->text[i].lang_key,
  198849. info_ptr->text[i].text);
  198850. #else
  198851. png_warning(png_ptr, "Unable to write international text");
  198852. #endif
  198853. /* Mark this chunk as written */
  198854. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198855. }
  198856. /* If we want a compressed text chunk */
  198857. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198858. {
  198859. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198860. /* write compressed chunk */
  198861. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198862. info_ptr->text[i].text, 0,
  198863. info_ptr->text[i].compression);
  198864. #else
  198865. png_warning(png_ptr, "Unable to write compressed text");
  198866. #endif
  198867. /* Mark this chunk as written */
  198868. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198869. }
  198870. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198871. {
  198872. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198873. /* write uncompressed chunk */
  198874. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198875. info_ptr->text[i].text,
  198876. 0);
  198877. #else
  198878. png_warning(png_ptr, "Unable to write uncompressed text");
  198879. #endif
  198880. /* Mark this chunk as written */
  198881. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198882. }
  198883. }
  198884. #endif
  198885. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198886. if (info_ptr->unknown_chunks_num)
  198887. {
  198888. png_unknown_chunk *up;
  198889. png_debug(5, "writing extra chunks\n");
  198890. for (up = info_ptr->unknown_chunks;
  198891. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198892. up++)
  198893. {
  198894. int keep=png_handle_as_unknown(png_ptr, up->name);
  198895. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198896. up->location && (up->location & PNG_HAVE_PLTE) &&
  198897. !(up->location & PNG_HAVE_IDAT) &&
  198898. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198899. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198900. {
  198901. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198902. }
  198903. }
  198904. }
  198905. #endif
  198906. }
  198907. /* Writes the end of the PNG file. If you don't want to write comments or
  198908. * time information, you can pass NULL for info. If you already wrote these
  198909. * in png_write_info(), do not write them again here. If you have long
  198910. * comments, I suggest writing them here, and compressing them.
  198911. */
  198912. void PNGAPI
  198913. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198914. {
  198915. png_debug(1, "in png_write_end\n");
  198916. if (png_ptr == NULL)
  198917. return;
  198918. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198919. png_error(png_ptr, "No IDATs written into file");
  198920. /* see if user wants us to write information chunks */
  198921. if (info_ptr != NULL)
  198922. {
  198923. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198924. int i; /* local index variable */
  198925. #endif
  198926. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198927. /* check to see if user has supplied a time chunk */
  198928. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198929. !(png_ptr->mode & PNG_WROTE_tIME))
  198930. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198931. #endif
  198932. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198933. /* loop through comment chunks */
  198934. for (i = 0; i < info_ptr->num_text; i++)
  198935. {
  198936. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198937. info_ptr->text[i].compression);
  198938. /* an internationalized chunk? */
  198939. if (info_ptr->text[i].compression > 0)
  198940. {
  198941. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198942. /* write international chunk */
  198943. png_write_iTXt(png_ptr,
  198944. info_ptr->text[i].compression,
  198945. info_ptr->text[i].key,
  198946. info_ptr->text[i].lang,
  198947. info_ptr->text[i].lang_key,
  198948. info_ptr->text[i].text);
  198949. #else
  198950. png_warning(png_ptr, "Unable to write international text");
  198951. #endif
  198952. /* Mark this chunk as written */
  198953. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198954. }
  198955. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198956. {
  198957. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198958. /* write compressed chunk */
  198959. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198960. info_ptr->text[i].text, 0,
  198961. info_ptr->text[i].compression);
  198962. #else
  198963. png_warning(png_ptr, "Unable to write compressed text");
  198964. #endif
  198965. /* Mark this chunk as written */
  198966. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198967. }
  198968. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198969. {
  198970. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198971. /* write uncompressed chunk */
  198972. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198973. info_ptr->text[i].text, 0);
  198974. #else
  198975. png_warning(png_ptr, "Unable to write uncompressed text");
  198976. #endif
  198977. /* Mark this chunk as written */
  198978. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198979. }
  198980. }
  198981. #endif
  198982. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198983. if (info_ptr->unknown_chunks_num)
  198984. {
  198985. png_unknown_chunk *up;
  198986. png_debug(5, "writing extra chunks\n");
  198987. for (up = info_ptr->unknown_chunks;
  198988. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198989. up++)
  198990. {
  198991. int keep=png_handle_as_unknown(png_ptr, up->name);
  198992. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198993. up->location && (up->location & PNG_AFTER_IDAT) &&
  198994. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198995. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198996. {
  198997. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198998. }
  198999. }
  199000. }
  199001. #endif
  199002. }
  199003. png_ptr->mode |= PNG_AFTER_IDAT;
  199004. /* write end of PNG file */
  199005. png_write_IEND(png_ptr);
  199006. }
  199007. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199008. #if !defined(_WIN32_WCE)
  199009. /* "time.h" functions are not supported on WindowsCE */
  199010. void PNGAPI
  199011. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199012. {
  199013. png_debug(1, "in png_convert_from_struct_tm\n");
  199014. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199015. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199016. ptime->day = (png_byte)ttime->tm_mday;
  199017. ptime->hour = (png_byte)ttime->tm_hour;
  199018. ptime->minute = (png_byte)ttime->tm_min;
  199019. ptime->second = (png_byte)ttime->tm_sec;
  199020. }
  199021. void PNGAPI
  199022. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199023. {
  199024. struct tm *tbuf;
  199025. png_debug(1, "in png_convert_from_time_t\n");
  199026. tbuf = gmtime(&ttime);
  199027. png_convert_from_struct_tm(ptime, tbuf);
  199028. }
  199029. #endif
  199030. #endif
  199031. /* Initialize png_ptr structure, and allocate any memory needed */
  199032. png_structp PNGAPI
  199033. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199034. png_error_ptr error_fn, png_error_ptr warn_fn)
  199035. {
  199036. #ifdef PNG_USER_MEM_SUPPORTED
  199037. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199038. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199039. }
  199040. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199041. png_structp PNGAPI
  199042. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199043. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199044. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199045. {
  199046. #endif /* PNG_USER_MEM_SUPPORTED */
  199047. png_structp png_ptr;
  199048. #ifdef PNG_SETJMP_SUPPORTED
  199049. #ifdef USE_FAR_KEYWORD
  199050. jmp_buf jmpbuf;
  199051. #endif
  199052. #endif
  199053. int i;
  199054. png_debug(1, "in png_create_write_struct\n");
  199055. #ifdef PNG_USER_MEM_SUPPORTED
  199056. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199057. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199058. #else
  199059. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199060. #endif /* PNG_USER_MEM_SUPPORTED */
  199061. if (png_ptr == NULL)
  199062. return (NULL);
  199063. /* added at libpng-1.2.6 */
  199064. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199065. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199066. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199067. #endif
  199068. #ifdef PNG_SETJMP_SUPPORTED
  199069. #ifdef USE_FAR_KEYWORD
  199070. if (setjmp(jmpbuf))
  199071. #else
  199072. if (setjmp(png_ptr->jmpbuf))
  199073. #endif
  199074. {
  199075. png_free(png_ptr, png_ptr->zbuf);
  199076. png_ptr->zbuf=NULL;
  199077. png_destroy_struct(png_ptr);
  199078. return (NULL);
  199079. }
  199080. #ifdef USE_FAR_KEYWORD
  199081. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199082. #endif
  199083. #endif
  199084. #ifdef PNG_USER_MEM_SUPPORTED
  199085. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199086. #endif /* PNG_USER_MEM_SUPPORTED */
  199087. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199088. i=0;
  199089. do
  199090. {
  199091. if(user_png_ver[i] != png_libpng_ver[i])
  199092. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199093. } while (png_libpng_ver[i++]);
  199094. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199095. {
  199096. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199097. * we must recompile any applications that use any older library version.
  199098. * For versions after libpng 1.0, we will be compatible, so we need
  199099. * only check the first digit.
  199100. */
  199101. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199102. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199103. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199104. {
  199105. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199106. char msg[80];
  199107. if (user_png_ver)
  199108. {
  199109. png_snprintf(msg, 80,
  199110. "Application was compiled with png.h from libpng-%.20s",
  199111. user_png_ver);
  199112. png_warning(png_ptr, msg);
  199113. }
  199114. png_snprintf(msg, 80,
  199115. "Application is running with png.c from libpng-%.20s",
  199116. png_libpng_ver);
  199117. png_warning(png_ptr, msg);
  199118. #endif
  199119. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199120. png_ptr->flags=0;
  199121. #endif
  199122. png_error(png_ptr,
  199123. "Incompatible libpng version in application and library");
  199124. }
  199125. }
  199126. /* initialize zbuf - compression buffer */
  199127. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199128. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199129. (png_uint_32)png_ptr->zbuf_size);
  199130. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199131. png_flush_ptr_NULL);
  199132. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199133. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199134. 1, png_doublep_NULL, png_doublep_NULL);
  199135. #endif
  199136. #ifdef PNG_SETJMP_SUPPORTED
  199137. /* Applications that neglect to set up their own setjmp() and then encounter
  199138. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199139. abort instead of returning. */
  199140. #ifdef USE_FAR_KEYWORD
  199141. if (setjmp(jmpbuf))
  199142. PNG_ABORT();
  199143. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199144. #else
  199145. if (setjmp(png_ptr->jmpbuf))
  199146. PNG_ABORT();
  199147. #endif
  199148. #endif
  199149. return (png_ptr);
  199150. }
  199151. /* Initialize png_ptr structure, and allocate any memory needed */
  199152. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199153. /* Deprecated. */
  199154. #undef png_write_init
  199155. void PNGAPI
  199156. png_write_init(png_structp png_ptr)
  199157. {
  199158. /* We only come here via pre-1.0.7-compiled applications */
  199159. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199160. }
  199161. void PNGAPI
  199162. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199163. png_size_t png_struct_size, png_size_t png_info_size)
  199164. {
  199165. /* We only come here via pre-1.0.12-compiled applications */
  199166. if(png_ptr == NULL) return;
  199167. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199168. if(png_sizeof(png_struct) > png_struct_size ||
  199169. png_sizeof(png_info) > png_info_size)
  199170. {
  199171. char msg[80];
  199172. png_ptr->warning_fn=NULL;
  199173. if (user_png_ver)
  199174. {
  199175. png_snprintf(msg, 80,
  199176. "Application was compiled with png.h from libpng-%.20s",
  199177. user_png_ver);
  199178. png_warning(png_ptr, msg);
  199179. }
  199180. png_snprintf(msg, 80,
  199181. "Application is running with png.c from libpng-%.20s",
  199182. png_libpng_ver);
  199183. png_warning(png_ptr, msg);
  199184. }
  199185. #endif
  199186. if(png_sizeof(png_struct) > png_struct_size)
  199187. {
  199188. png_ptr->error_fn=NULL;
  199189. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199190. png_ptr->flags=0;
  199191. #endif
  199192. png_error(png_ptr,
  199193. "The png struct allocated by the application for writing is too small.");
  199194. }
  199195. if(png_sizeof(png_info) > png_info_size)
  199196. {
  199197. png_ptr->error_fn=NULL;
  199198. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199199. png_ptr->flags=0;
  199200. #endif
  199201. png_error(png_ptr,
  199202. "The info struct allocated by the application for writing is too small.");
  199203. }
  199204. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199205. }
  199206. #endif /* PNG_1_0_X || PNG_1_2_X */
  199207. void PNGAPI
  199208. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199209. png_size_t png_struct_size)
  199210. {
  199211. png_structp png_ptr=*ptr_ptr;
  199212. #ifdef PNG_SETJMP_SUPPORTED
  199213. jmp_buf tmp_jmp; /* to save current jump buffer */
  199214. #endif
  199215. int i = 0;
  199216. if (png_ptr == NULL)
  199217. return;
  199218. do
  199219. {
  199220. if (user_png_ver[i] != png_libpng_ver[i])
  199221. {
  199222. #ifdef PNG_LEGACY_SUPPORTED
  199223. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199224. #else
  199225. png_ptr->warning_fn=NULL;
  199226. png_warning(png_ptr,
  199227. "Application uses deprecated png_write_init() and should be recompiled.");
  199228. break;
  199229. #endif
  199230. }
  199231. } while (png_libpng_ver[i++]);
  199232. png_debug(1, "in png_write_init_3\n");
  199233. #ifdef PNG_SETJMP_SUPPORTED
  199234. /* save jump buffer and error functions */
  199235. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199236. #endif
  199237. if (png_sizeof(png_struct) > png_struct_size)
  199238. {
  199239. png_destroy_struct(png_ptr);
  199240. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199241. *ptr_ptr = png_ptr;
  199242. }
  199243. /* reset all variables to 0 */
  199244. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199245. /* added at libpng-1.2.6 */
  199246. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199247. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199248. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199249. #endif
  199250. #ifdef PNG_SETJMP_SUPPORTED
  199251. /* restore jump buffer */
  199252. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199253. #endif
  199254. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199255. png_flush_ptr_NULL);
  199256. /* initialize zbuf - compression buffer */
  199257. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199258. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199259. (png_uint_32)png_ptr->zbuf_size);
  199260. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199261. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199262. 1, png_doublep_NULL, png_doublep_NULL);
  199263. #endif
  199264. }
  199265. /* Write a few rows of image data. If the image is interlaced,
  199266. * either you will have to write the 7 sub images, or, if you
  199267. * have called png_set_interlace_handling(), you will have to
  199268. * "write" the image seven times.
  199269. */
  199270. void PNGAPI
  199271. png_write_rows(png_structp png_ptr, png_bytepp row,
  199272. png_uint_32 num_rows)
  199273. {
  199274. png_uint_32 i; /* row counter */
  199275. png_bytepp rp; /* row pointer */
  199276. png_debug(1, "in png_write_rows\n");
  199277. if (png_ptr == NULL)
  199278. return;
  199279. /* loop through the rows */
  199280. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199281. {
  199282. png_write_row(png_ptr, *rp);
  199283. }
  199284. }
  199285. /* Write the image. You only need to call this function once, even
  199286. * if you are writing an interlaced image.
  199287. */
  199288. void PNGAPI
  199289. png_write_image(png_structp png_ptr, png_bytepp image)
  199290. {
  199291. png_uint_32 i; /* row index */
  199292. int pass, num_pass; /* pass variables */
  199293. png_bytepp rp; /* points to current row */
  199294. if (png_ptr == NULL)
  199295. return;
  199296. png_debug(1, "in png_write_image\n");
  199297. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199298. /* intialize interlace handling. If image is not interlaced,
  199299. this will set pass to 1 */
  199300. num_pass = png_set_interlace_handling(png_ptr);
  199301. #else
  199302. num_pass = 1;
  199303. #endif
  199304. /* loop through passes */
  199305. for (pass = 0; pass < num_pass; pass++)
  199306. {
  199307. /* loop through image */
  199308. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199309. {
  199310. png_write_row(png_ptr, *rp);
  199311. }
  199312. }
  199313. }
  199314. /* called by user to write a row of image data */
  199315. void PNGAPI
  199316. png_write_row(png_structp png_ptr, png_bytep row)
  199317. {
  199318. if (png_ptr == NULL)
  199319. return;
  199320. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199321. png_ptr->row_number, png_ptr->pass);
  199322. /* initialize transformations and other stuff if first time */
  199323. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199324. {
  199325. /* make sure we wrote the header info */
  199326. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199327. png_error(png_ptr,
  199328. "png_write_info was never called before png_write_row.");
  199329. /* check for transforms that have been set but were defined out */
  199330. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199331. if (png_ptr->transformations & PNG_INVERT_MONO)
  199332. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199333. #endif
  199334. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199335. if (png_ptr->transformations & PNG_FILLER)
  199336. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199337. #endif
  199338. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199339. if (png_ptr->transformations & PNG_PACKSWAP)
  199340. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199341. #endif
  199342. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199343. if (png_ptr->transformations & PNG_PACK)
  199344. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199345. #endif
  199346. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199347. if (png_ptr->transformations & PNG_SHIFT)
  199348. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199349. #endif
  199350. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199351. if (png_ptr->transformations & PNG_BGR)
  199352. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199353. #endif
  199354. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199355. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199356. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199357. #endif
  199358. png_write_start_row(png_ptr);
  199359. }
  199360. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199361. /* if interlaced and not interested in row, return */
  199362. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199363. {
  199364. switch (png_ptr->pass)
  199365. {
  199366. case 0:
  199367. if (png_ptr->row_number & 0x07)
  199368. {
  199369. png_write_finish_row(png_ptr);
  199370. return;
  199371. }
  199372. break;
  199373. case 1:
  199374. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199375. {
  199376. png_write_finish_row(png_ptr);
  199377. return;
  199378. }
  199379. break;
  199380. case 2:
  199381. if ((png_ptr->row_number & 0x07) != 4)
  199382. {
  199383. png_write_finish_row(png_ptr);
  199384. return;
  199385. }
  199386. break;
  199387. case 3:
  199388. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199389. {
  199390. png_write_finish_row(png_ptr);
  199391. return;
  199392. }
  199393. break;
  199394. case 4:
  199395. if ((png_ptr->row_number & 0x03) != 2)
  199396. {
  199397. png_write_finish_row(png_ptr);
  199398. return;
  199399. }
  199400. break;
  199401. case 5:
  199402. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199403. {
  199404. png_write_finish_row(png_ptr);
  199405. return;
  199406. }
  199407. break;
  199408. case 6:
  199409. if (!(png_ptr->row_number & 0x01))
  199410. {
  199411. png_write_finish_row(png_ptr);
  199412. return;
  199413. }
  199414. break;
  199415. }
  199416. }
  199417. #endif
  199418. /* set up row info for transformations */
  199419. png_ptr->row_info.color_type = png_ptr->color_type;
  199420. png_ptr->row_info.width = png_ptr->usr_width;
  199421. png_ptr->row_info.channels = png_ptr->usr_channels;
  199422. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199423. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199424. png_ptr->row_info.channels);
  199425. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199426. png_ptr->row_info.width);
  199427. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199428. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199429. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199430. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199431. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199432. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199433. /* Copy user's row into buffer, leaving room for filter byte. */
  199434. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199435. png_ptr->row_info.rowbytes);
  199436. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199437. /* handle interlacing */
  199438. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199439. (png_ptr->transformations & PNG_INTERLACE))
  199440. {
  199441. png_do_write_interlace(&(png_ptr->row_info),
  199442. png_ptr->row_buf + 1, png_ptr->pass);
  199443. /* this should always get caught above, but still ... */
  199444. if (!(png_ptr->row_info.width))
  199445. {
  199446. png_write_finish_row(png_ptr);
  199447. return;
  199448. }
  199449. }
  199450. #endif
  199451. /* handle other transformations */
  199452. if (png_ptr->transformations)
  199453. png_do_write_transformations(png_ptr);
  199454. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199455. /* Write filter_method 64 (intrapixel differencing) only if
  199456. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199457. * 2. Libpng did not write a PNG signature (this filter_method is only
  199458. * used in PNG datastreams that are embedded in MNG datastreams) and
  199459. * 3. The application called png_permit_mng_features with a mask that
  199460. * included PNG_FLAG_MNG_FILTER_64 and
  199461. * 4. The filter_method is 64 and
  199462. * 5. The color_type is RGB or RGBA
  199463. */
  199464. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199465. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199466. {
  199467. /* Intrapixel differencing */
  199468. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199469. }
  199470. #endif
  199471. /* Find a filter if necessary, filter the row and write it out. */
  199472. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199473. if (png_ptr->write_row_fn != NULL)
  199474. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199475. }
  199476. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199477. /* Set the automatic flush interval or 0 to turn flushing off */
  199478. void PNGAPI
  199479. png_set_flush(png_structp png_ptr, int nrows)
  199480. {
  199481. png_debug(1, "in png_set_flush\n");
  199482. if (png_ptr == NULL)
  199483. return;
  199484. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199485. }
  199486. /* flush the current output buffers now */
  199487. void PNGAPI
  199488. png_write_flush(png_structp png_ptr)
  199489. {
  199490. int wrote_IDAT;
  199491. png_debug(1, "in png_write_flush\n");
  199492. if (png_ptr == NULL)
  199493. return;
  199494. /* We have already written out all of the data */
  199495. if (png_ptr->row_number >= png_ptr->num_rows)
  199496. return;
  199497. do
  199498. {
  199499. int ret;
  199500. /* compress the data */
  199501. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199502. wrote_IDAT = 0;
  199503. /* check for compression errors */
  199504. if (ret != Z_OK)
  199505. {
  199506. if (png_ptr->zstream.msg != NULL)
  199507. png_error(png_ptr, png_ptr->zstream.msg);
  199508. else
  199509. png_error(png_ptr, "zlib error");
  199510. }
  199511. if (!(png_ptr->zstream.avail_out))
  199512. {
  199513. /* write the IDAT and reset the zlib output buffer */
  199514. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199515. png_ptr->zbuf_size);
  199516. png_ptr->zstream.next_out = png_ptr->zbuf;
  199517. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199518. wrote_IDAT = 1;
  199519. }
  199520. } while(wrote_IDAT == 1);
  199521. /* If there is any data left to be output, write it into a new IDAT */
  199522. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199523. {
  199524. /* write the IDAT and reset the zlib output buffer */
  199525. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199526. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199527. png_ptr->zstream.next_out = png_ptr->zbuf;
  199528. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199529. }
  199530. png_ptr->flush_rows = 0;
  199531. png_flush(png_ptr);
  199532. }
  199533. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199534. /* free all memory used by the write */
  199535. void PNGAPI
  199536. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199537. {
  199538. png_structp png_ptr = NULL;
  199539. png_infop info_ptr = NULL;
  199540. #ifdef PNG_USER_MEM_SUPPORTED
  199541. png_free_ptr free_fn = NULL;
  199542. png_voidp mem_ptr = NULL;
  199543. #endif
  199544. png_debug(1, "in png_destroy_write_struct\n");
  199545. if (png_ptr_ptr != NULL)
  199546. {
  199547. png_ptr = *png_ptr_ptr;
  199548. #ifdef PNG_USER_MEM_SUPPORTED
  199549. free_fn = png_ptr->free_fn;
  199550. mem_ptr = png_ptr->mem_ptr;
  199551. #endif
  199552. }
  199553. if (info_ptr_ptr != NULL)
  199554. info_ptr = *info_ptr_ptr;
  199555. if (info_ptr != NULL)
  199556. {
  199557. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199558. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199559. if (png_ptr->num_chunk_list)
  199560. {
  199561. png_free(png_ptr, png_ptr->chunk_list);
  199562. png_ptr->chunk_list=NULL;
  199563. png_ptr->num_chunk_list=0;
  199564. }
  199565. #endif
  199566. #ifdef PNG_USER_MEM_SUPPORTED
  199567. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199568. (png_voidp)mem_ptr);
  199569. #else
  199570. png_destroy_struct((png_voidp)info_ptr);
  199571. #endif
  199572. *info_ptr_ptr = NULL;
  199573. }
  199574. if (png_ptr != NULL)
  199575. {
  199576. png_write_destroy(png_ptr);
  199577. #ifdef PNG_USER_MEM_SUPPORTED
  199578. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199579. (png_voidp)mem_ptr);
  199580. #else
  199581. png_destroy_struct((png_voidp)png_ptr);
  199582. #endif
  199583. *png_ptr_ptr = NULL;
  199584. }
  199585. }
  199586. /* Free any memory used in png_ptr struct (old method) */
  199587. void /* PRIVATE */
  199588. png_write_destroy(png_structp png_ptr)
  199589. {
  199590. #ifdef PNG_SETJMP_SUPPORTED
  199591. jmp_buf tmp_jmp; /* save jump buffer */
  199592. #endif
  199593. png_error_ptr error_fn;
  199594. png_error_ptr warning_fn;
  199595. png_voidp error_ptr;
  199596. #ifdef PNG_USER_MEM_SUPPORTED
  199597. png_free_ptr free_fn;
  199598. #endif
  199599. png_debug(1, "in png_write_destroy\n");
  199600. /* free any memory zlib uses */
  199601. deflateEnd(&png_ptr->zstream);
  199602. /* free our memory. png_free checks NULL for us. */
  199603. png_free(png_ptr, png_ptr->zbuf);
  199604. png_free(png_ptr, png_ptr->row_buf);
  199605. png_free(png_ptr, png_ptr->prev_row);
  199606. png_free(png_ptr, png_ptr->sub_row);
  199607. png_free(png_ptr, png_ptr->up_row);
  199608. png_free(png_ptr, png_ptr->avg_row);
  199609. png_free(png_ptr, png_ptr->paeth_row);
  199610. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199611. png_free(png_ptr, png_ptr->time_buffer);
  199612. #endif
  199613. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199614. png_free(png_ptr, png_ptr->prev_filters);
  199615. png_free(png_ptr, png_ptr->filter_weights);
  199616. png_free(png_ptr, png_ptr->inv_filter_weights);
  199617. png_free(png_ptr, png_ptr->filter_costs);
  199618. png_free(png_ptr, png_ptr->inv_filter_costs);
  199619. #endif
  199620. #ifdef PNG_SETJMP_SUPPORTED
  199621. /* reset structure */
  199622. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199623. #endif
  199624. error_fn = png_ptr->error_fn;
  199625. warning_fn = png_ptr->warning_fn;
  199626. error_ptr = png_ptr->error_ptr;
  199627. #ifdef PNG_USER_MEM_SUPPORTED
  199628. free_fn = png_ptr->free_fn;
  199629. #endif
  199630. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199631. png_ptr->error_fn = error_fn;
  199632. png_ptr->warning_fn = warning_fn;
  199633. png_ptr->error_ptr = error_ptr;
  199634. #ifdef PNG_USER_MEM_SUPPORTED
  199635. png_ptr->free_fn = free_fn;
  199636. #endif
  199637. #ifdef PNG_SETJMP_SUPPORTED
  199638. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199639. #endif
  199640. }
  199641. /* Allow the application to select one or more row filters to use. */
  199642. void PNGAPI
  199643. png_set_filter(png_structp png_ptr, int method, int filters)
  199644. {
  199645. png_debug(1, "in png_set_filter\n");
  199646. if (png_ptr == NULL)
  199647. return;
  199648. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199649. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199650. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199651. method = PNG_FILTER_TYPE_BASE;
  199652. #endif
  199653. if (method == PNG_FILTER_TYPE_BASE)
  199654. {
  199655. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199656. {
  199657. #ifndef PNG_NO_WRITE_FILTER
  199658. case 5:
  199659. case 6:
  199660. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199661. #endif /* PNG_NO_WRITE_FILTER */
  199662. case PNG_FILTER_VALUE_NONE:
  199663. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199664. #ifndef PNG_NO_WRITE_FILTER
  199665. case PNG_FILTER_VALUE_SUB:
  199666. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199667. case PNG_FILTER_VALUE_UP:
  199668. png_ptr->do_filter=PNG_FILTER_UP; break;
  199669. case PNG_FILTER_VALUE_AVG:
  199670. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199671. case PNG_FILTER_VALUE_PAETH:
  199672. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199673. default: png_ptr->do_filter = (png_byte)filters; break;
  199674. #else
  199675. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199676. #endif /* PNG_NO_WRITE_FILTER */
  199677. }
  199678. /* If we have allocated the row_buf, this means we have already started
  199679. * with the image and we should have allocated all of the filter buffers
  199680. * that have been selected. If prev_row isn't already allocated, then
  199681. * it is too late to start using the filters that need it, since we
  199682. * will be missing the data in the previous row. If an application
  199683. * wants to start and stop using particular filters during compression,
  199684. * it should start out with all of the filters, and then add and
  199685. * remove them after the start of compression.
  199686. */
  199687. if (png_ptr->row_buf != NULL)
  199688. {
  199689. #ifndef PNG_NO_WRITE_FILTER
  199690. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199691. {
  199692. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199693. (png_ptr->rowbytes + 1));
  199694. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199695. }
  199696. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199697. {
  199698. if (png_ptr->prev_row == NULL)
  199699. {
  199700. png_warning(png_ptr, "Can't add Up filter after starting");
  199701. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199702. }
  199703. else
  199704. {
  199705. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199706. (png_ptr->rowbytes + 1));
  199707. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199708. }
  199709. }
  199710. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199711. {
  199712. if (png_ptr->prev_row == NULL)
  199713. {
  199714. png_warning(png_ptr, "Can't add Average filter after starting");
  199715. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199716. }
  199717. else
  199718. {
  199719. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199720. (png_ptr->rowbytes + 1));
  199721. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199722. }
  199723. }
  199724. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199725. png_ptr->paeth_row == NULL)
  199726. {
  199727. if (png_ptr->prev_row == NULL)
  199728. {
  199729. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199730. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199731. }
  199732. else
  199733. {
  199734. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199735. (png_ptr->rowbytes + 1));
  199736. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199737. }
  199738. }
  199739. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199740. #endif /* PNG_NO_WRITE_FILTER */
  199741. png_ptr->do_filter = PNG_FILTER_NONE;
  199742. }
  199743. }
  199744. else
  199745. png_error(png_ptr, "Unknown custom filter method");
  199746. }
  199747. /* This allows us to influence the way in which libpng chooses the "best"
  199748. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199749. * differences metric is relatively fast and effective, there is some
  199750. * question as to whether it can be improved upon by trying to keep the
  199751. * filtered data going to zlib more consistent, hopefully resulting in
  199752. * better compression.
  199753. */
  199754. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199755. void PNGAPI
  199756. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199757. int num_weights, png_doublep filter_weights,
  199758. png_doublep filter_costs)
  199759. {
  199760. int i;
  199761. png_debug(1, "in png_set_filter_heuristics\n");
  199762. if (png_ptr == NULL)
  199763. return;
  199764. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199765. {
  199766. png_warning(png_ptr, "Unknown filter heuristic method");
  199767. return;
  199768. }
  199769. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199770. {
  199771. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199772. }
  199773. if (num_weights < 0 || filter_weights == NULL ||
  199774. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199775. {
  199776. num_weights = 0;
  199777. }
  199778. png_ptr->num_prev_filters = (png_byte)num_weights;
  199779. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199780. if (num_weights > 0)
  199781. {
  199782. if (png_ptr->prev_filters == NULL)
  199783. {
  199784. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199785. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199786. /* To make sure that the weighting starts out fairly */
  199787. for (i = 0; i < num_weights; i++)
  199788. {
  199789. png_ptr->prev_filters[i] = 255;
  199790. }
  199791. }
  199792. if (png_ptr->filter_weights == NULL)
  199793. {
  199794. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199795. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199796. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199797. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199798. for (i = 0; i < num_weights; i++)
  199799. {
  199800. png_ptr->inv_filter_weights[i] =
  199801. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199802. }
  199803. }
  199804. for (i = 0; i < num_weights; i++)
  199805. {
  199806. if (filter_weights[i] < 0.0)
  199807. {
  199808. png_ptr->inv_filter_weights[i] =
  199809. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199810. }
  199811. else
  199812. {
  199813. png_ptr->inv_filter_weights[i] =
  199814. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199815. png_ptr->filter_weights[i] =
  199816. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199817. }
  199818. }
  199819. }
  199820. /* If, in the future, there are other filter methods, this would
  199821. * need to be based on png_ptr->filter.
  199822. */
  199823. if (png_ptr->filter_costs == NULL)
  199824. {
  199825. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199826. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199827. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199828. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199829. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199830. {
  199831. png_ptr->inv_filter_costs[i] =
  199832. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199833. }
  199834. }
  199835. /* Here is where we set the relative costs of the different filters. We
  199836. * should take the desired compression level into account when setting
  199837. * the costs, so that Paeth, for instance, has a high relative cost at low
  199838. * compression levels, while it has a lower relative cost at higher
  199839. * compression settings. The filter types are in order of increasing
  199840. * relative cost, so it would be possible to do this with an algorithm.
  199841. */
  199842. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199843. {
  199844. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199845. {
  199846. png_ptr->inv_filter_costs[i] =
  199847. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199848. }
  199849. else if (filter_costs[i] >= 1.0)
  199850. {
  199851. png_ptr->inv_filter_costs[i] =
  199852. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199853. png_ptr->filter_costs[i] =
  199854. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199855. }
  199856. }
  199857. }
  199858. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199859. void PNGAPI
  199860. png_set_compression_level(png_structp png_ptr, int level)
  199861. {
  199862. png_debug(1, "in png_set_compression_level\n");
  199863. if (png_ptr == NULL)
  199864. return;
  199865. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199866. png_ptr->zlib_level = level;
  199867. }
  199868. void PNGAPI
  199869. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199870. {
  199871. png_debug(1, "in png_set_compression_mem_level\n");
  199872. if (png_ptr == NULL)
  199873. return;
  199874. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199875. png_ptr->zlib_mem_level = mem_level;
  199876. }
  199877. void PNGAPI
  199878. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199879. {
  199880. png_debug(1, "in png_set_compression_strategy\n");
  199881. if (png_ptr == NULL)
  199882. return;
  199883. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199884. png_ptr->zlib_strategy = strategy;
  199885. }
  199886. void PNGAPI
  199887. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199888. {
  199889. if (png_ptr == NULL)
  199890. return;
  199891. if (window_bits > 15)
  199892. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199893. else if (window_bits < 8)
  199894. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199895. #ifndef WBITS_8_OK
  199896. /* avoid libpng bug with 256-byte windows */
  199897. if (window_bits == 8)
  199898. {
  199899. png_warning(png_ptr, "Compression window is being reset to 512");
  199900. window_bits=9;
  199901. }
  199902. #endif
  199903. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199904. png_ptr->zlib_window_bits = window_bits;
  199905. }
  199906. void PNGAPI
  199907. png_set_compression_method(png_structp png_ptr, int method)
  199908. {
  199909. png_debug(1, "in png_set_compression_method\n");
  199910. if (png_ptr == NULL)
  199911. return;
  199912. if (method != 8)
  199913. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199914. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199915. png_ptr->zlib_method = method;
  199916. }
  199917. void PNGAPI
  199918. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199919. {
  199920. if (png_ptr == NULL)
  199921. return;
  199922. png_ptr->write_row_fn = write_row_fn;
  199923. }
  199924. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199925. void PNGAPI
  199926. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199927. write_user_transform_fn)
  199928. {
  199929. png_debug(1, "in png_set_write_user_transform_fn\n");
  199930. if (png_ptr == NULL)
  199931. return;
  199932. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199933. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199934. }
  199935. #endif
  199936. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199937. void PNGAPI
  199938. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199939. int transforms, voidp params)
  199940. {
  199941. if (png_ptr == NULL || info_ptr == NULL)
  199942. return;
  199943. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199944. /* invert the alpha channel from opacity to transparency */
  199945. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199946. png_set_invert_alpha(png_ptr);
  199947. #endif
  199948. /* Write the file header information. */
  199949. png_write_info(png_ptr, info_ptr);
  199950. /* ------ these transformations don't touch the info structure ------- */
  199951. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199952. /* invert monochrome pixels */
  199953. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199954. png_set_invert_mono(png_ptr);
  199955. #endif
  199956. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199957. /* Shift the pixels up to a legal bit depth and fill in
  199958. * as appropriate to correctly scale the image.
  199959. */
  199960. if ((transforms & PNG_TRANSFORM_SHIFT)
  199961. && (info_ptr->valid & PNG_INFO_sBIT))
  199962. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199963. #endif
  199964. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199965. /* pack pixels into bytes */
  199966. if (transforms & PNG_TRANSFORM_PACKING)
  199967. png_set_packing(png_ptr);
  199968. #endif
  199969. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199970. /* swap location of alpha bytes from ARGB to RGBA */
  199971. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199972. png_set_swap_alpha(png_ptr);
  199973. #endif
  199974. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199975. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199976. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199977. */
  199978. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199979. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199980. #endif
  199981. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199982. /* flip BGR pixels to RGB */
  199983. if (transforms & PNG_TRANSFORM_BGR)
  199984. png_set_bgr(png_ptr);
  199985. #endif
  199986. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199987. /* swap bytes of 16-bit files to most significant byte first */
  199988. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199989. png_set_swap(png_ptr);
  199990. #endif
  199991. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199992. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199993. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199994. png_set_packswap(png_ptr);
  199995. #endif
  199996. /* ----------------------- end of transformations ------------------- */
  199997. /* write the bits */
  199998. if (info_ptr->valid & PNG_INFO_IDAT)
  199999. png_write_image(png_ptr, info_ptr->row_pointers);
  200000. /* It is REQUIRED to call this to finish writing the rest of the file */
  200001. png_write_end(png_ptr, info_ptr);
  200002. transforms = transforms; /* quiet compiler warnings */
  200003. params = params;
  200004. }
  200005. #endif
  200006. #endif /* PNG_WRITE_SUPPORTED */
  200007. /*** End of inlined file: pngwrite.c ***/
  200008. /*** Start of inlined file: pngwtran.c ***/
  200009. /* pngwtran.c - transforms the data in a row for PNG writers
  200010. *
  200011. * Last changed in libpng 1.2.9 April 14, 2006
  200012. * For conditions of distribution and use, see copyright notice in png.h
  200013. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200014. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200015. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200016. */
  200017. #define PNG_INTERNAL
  200018. #ifdef PNG_WRITE_SUPPORTED
  200019. /* Transform the data according to the user's wishes. The order of
  200020. * transformations is significant.
  200021. */
  200022. void /* PRIVATE */
  200023. png_do_write_transformations(png_structp png_ptr)
  200024. {
  200025. png_debug(1, "in png_do_write_transformations\n");
  200026. if (png_ptr == NULL)
  200027. return;
  200028. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200029. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200030. if(png_ptr->write_user_transform_fn != NULL)
  200031. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200032. (png_ptr, /* png_ptr */
  200033. &(png_ptr->row_info), /* row_info: */
  200034. /* png_uint_32 width; width of row */
  200035. /* png_uint_32 rowbytes; number of bytes in row */
  200036. /* png_byte color_type; color type of pixels */
  200037. /* png_byte bit_depth; bit depth of samples */
  200038. /* png_byte channels; number of channels (1-4) */
  200039. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200040. png_ptr->row_buf + 1); /* start of pixel data for row */
  200041. #endif
  200042. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200043. if (png_ptr->transformations & PNG_FILLER)
  200044. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200045. png_ptr->flags);
  200046. #endif
  200047. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200048. if (png_ptr->transformations & PNG_PACKSWAP)
  200049. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200050. #endif
  200051. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200052. if (png_ptr->transformations & PNG_PACK)
  200053. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200054. (png_uint_32)png_ptr->bit_depth);
  200055. #endif
  200056. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200057. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200058. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200059. #endif
  200060. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200061. if (png_ptr->transformations & PNG_SHIFT)
  200062. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200063. &(png_ptr->shift));
  200064. #endif
  200065. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200066. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200067. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200068. #endif
  200069. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200070. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200071. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200072. #endif
  200073. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200074. if (png_ptr->transformations & PNG_BGR)
  200075. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200076. #endif
  200077. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200078. if (png_ptr->transformations & PNG_INVERT_MONO)
  200079. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200080. #endif
  200081. }
  200082. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200083. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200084. * row_info bit depth should be 8 (one pixel per byte). The channels
  200085. * should be 1 (this only happens on grayscale and paletted images).
  200086. */
  200087. void /* PRIVATE */
  200088. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200089. {
  200090. png_debug(1, "in png_do_pack\n");
  200091. if (row_info->bit_depth == 8 &&
  200092. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200093. row != NULL && row_info != NULL &&
  200094. #endif
  200095. row_info->channels == 1)
  200096. {
  200097. switch ((int)bit_depth)
  200098. {
  200099. case 1:
  200100. {
  200101. png_bytep sp, dp;
  200102. int mask, v;
  200103. png_uint_32 i;
  200104. png_uint_32 row_width = row_info->width;
  200105. sp = row;
  200106. dp = row;
  200107. mask = 0x80;
  200108. v = 0;
  200109. for (i = 0; i < row_width; i++)
  200110. {
  200111. if (*sp != 0)
  200112. v |= mask;
  200113. sp++;
  200114. if (mask > 1)
  200115. mask >>= 1;
  200116. else
  200117. {
  200118. mask = 0x80;
  200119. *dp = (png_byte)v;
  200120. dp++;
  200121. v = 0;
  200122. }
  200123. }
  200124. if (mask != 0x80)
  200125. *dp = (png_byte)v;
  200126. break;
  200127. }
  200128. case 2:
  200129. {
  200130. png_bytep sp, dp;
  200131. int shift, v;
  200132. png_uint_32 i;
  200133. png_uint_32 row_width = row_info->width;
  200134. sp = row;
  200135. dp = row;
  200136. shift = 6;
  200137. v = 0;
  200138. for (i = 0; i < row_width; i++)
  200139. {
  200140. png_byte value;
  200141. value = (png_byte)(*sp & 0x03);
  200142. v |= (value << shift);
  200143. if (shift == 0)
  200144. {
  200145. shift = 6;
  200146. *dp = (png_byte)v;
  200147. dp++;
  200148. v = 0;
  200149. }
  200150. else
  200151. shift -= 2;
  200152. sp++;
  200153. }
  200154. if (shift != 6)
  200155. *dp = (png_byte)v;
  200156. break;
  200157. }
  200158. case 4:
  200159. {
  200160. png_bytep sp, dp;
  200161. int shift, v;
  200162. png_uint_32 i;
  200163. png_uint_32 row_width = row_info->width;
  200164. sp = row;
  200165. dp = row;
  200166. shift = 4;
  200167. v = 0;
  200168. for (i = 0; i < row_width; i++)
  200169. {
  200170. png_byte value;
  200171. value = (png_byte)(*sp & 0x0f);
  200172. v |= (value << shift);
  200173. if (shift == 0)
  200174. {
  200175. shift = 4;
  200176. *dp = (png_byte)v;
  200177. dp++;
  200178. v = 0;
  200179. }
  200180. else
  200181. shift -= 4;
  200182. sp++;
  200183. }
  200184. if (shift != 4)
  200185. *dp = (png_byte)v;
  200186. break;
  200187. }
  200188. }
  200189. row_info->bit_depth = (png_byte)bit_depth;
  200190. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200191. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200192. row_info->width);
  200193. }
  200194. }
  200195. #endif
  200196. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200197. /* Shift pixel values to take advantage of whole range. Pass the
  200198. * true number of bits in bit_depth. The row should be packed
  200199. * according to row_info->bit_depth. Thus, if you had a row of
  200200. * bit depth 4, but the pixels only had values from 0 to 7, you
  200201. * would pass 3 as bit_depth, and this routine would translate the
  200202. * data to 0 to 15.
  200203. */
  200204. void /* PRIVATE */
  200205. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200206. {
  200207. png_debug(1, "in png_do_shift\n");
  200208. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200209. if (row != NULL && row_info != NULL &&
  200210. #else
  200211. if (
  200212. #endif
  200213. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200214. {
  200215. int shift_start[4], shift_dec[4];
  200216. int channels = 0;
  200217. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200218. {
  200219. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200220. shift_dec[channels] = bit_depth->red;
  200221. channels++;
  200222. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200223. shift_dec[channels] = bit_depth->green;
  200224. channels++;
  200225. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200226. shift_dec[channels] = bit_depth->blue;
  200227. channels++;
  200228. }
  200229. else
  200230. {
  200231. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200232. shift_dec[channels] = bit_depth->gray;
  200233. channels++;
  200234. }
  200235. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200236. {
  200237. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200238. shift_dec[channels] = bit_depth->alpha;
  200239. channels++;
  200240. }
  200241. /* with low row depths, could only be grayscale, so one channel */
  200242. if (row_info->bit_depth < 8)
  200243. {
  200244. png_bytep bp = row;
  200245. png_uint_32 i;
  200246. png_byte mask;
  200247. png_uint_32 row_bytes = row_info->rowbytes;
  200248. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200249. mask = 0x55;
  200250. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200251. mask = 0x11;
  200252. else
  200253. mask = 0xff;
  200254. for (i = 0; i < row_bytes; i++, bp++)
  200255. {
  200256. png_uint_16 v;
  200257. int j;
  200258. v = *bp;
  200259. *bp = 0;
  200260. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200261. {
  200262. if (j > 0)
  200263. *bp |= (png_byte)((v << j) & 0xff);
  200264. else
  200265. *bp |= (png_byte)((v >> (-j)) & mask);
  200266. }
  200267. }
  200268. }
  200269. else if (row_info->bit_depth == 8)
  200270. {
  200271. png_bytep bp = row;
  200272. png_uint_32 i;
  200273. png_uint_32 istop = channels * row_info->width;
  200274. for (i = 0; i < istop; i++, bp++)
  200275. {
  200276. png_uint_16 v;
  200277. int j;
  200278. int c = (int)(i%channels);
  200279. v = *bp;
  200280. *bp = 0;
  200281. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200282. {
  200283. if (j > 0)
  200284. *bp |= (png_byte)((v << j) & 0xff);
  200285. else
  200286. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200287. }
  200288. }
  200289. }
  200290. else
  200291. {
  200292. png_bytep bp;
  200293. png_uint_32 i;
  200294. png_uint_32 istop = channels * row_info->width;
  200295. for (bp = row, i = 0; i < istop; i++)
  200296. {
  200297. int c = (int)(i%channels);
  200298. png_uint_16 value, v;
  200299. int j;
  200300. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200301. value = 0;
  200302. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200303. {
  200304. if (j > 0)
  200305. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200306. else
  200307. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200308. }
  200309. *bp++ = (png_byte)(value >> 8);
  200310. *bp++ = (png_byte)(value & 0xff);
  200311. }
  200312. }
  200313. }
  200314. }
  200315. #endif
  200316. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200317. void /* PRIVATE */
  200318. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200319. {
  200320. png_debug(1, "in png_do_write_swap_alpha\n");
  200321. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200322. if (row != NULL && row_info != NULL)
  200323. #endif
  200324. {
  200325. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200326. {
  200327. /* This converts from ARGB to RGBA */
  200328. if (row_info->bit_depth == 8)
  200329. {
  200330. png_bytep sp, dp;
  200331. png_uint_32 i;
  200332. png_uint_32 row_width = row_info->width;
  200333. for (i = 0, sp = dp = row; i < row_width; i++)
  200334. {
  200335. png_byte save = *(sp++);
  200336. *(dp++) = *(sp++);
  200337. *(dp++) = *(sp++);
  200338. *(dp++) = *(sp++);
  200339. *(dp++) = save;
  200340. }
  200341. }
  200342. /* This converts from AARRGGBB to RRGGBBAA */
  200343. else
  200344. {
  200345. png_bytep sp, dp;
  200346. png_uint_32 i;
  200347. png_uint_32 row_width = row_info->width;
  200348. for (i = 0, sp = dp = row; i < row_width; i++)
  200349. {
  200350. png_byte save[2];
  200351. save[0] = *(sp++);
  200352. save[1] = *(sp++);
  200353. *(dp++) = *(sp++);
  200354. *(dp++) = *(sp++);
  200355. *(dp++) = *(sp++);
  200356. *(dp++) = *(sp++);
  200357. *(dp++) = *(sp++);
  200358. *(dp++) = *(sp++);
  200359. *(dp++) = save[0];
  200360. *(dp++) = save[1];
  200361. }
  200362. }
  200363. }
  200364. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200365. {
  200366. /* This converts from AG to GA */
  200367. if (row_info->bit_depth == 8)
  200368. {
  200369. png_bytep sp, dp;
  200370. png_uint_32 i;
  200371. png_uint_32 row_width = row_info->width;
  200372. for (i = 0, sp = dp = row; i < row_width; i++)
  200373. {
  200374. png_byte save = *(sp++);
  200375. *(dp++) = *(sp++);
  200376. *(dp++) = save;
  200377. }
  200378. }
  200379. /* This converts from AAGG to GGAA */
  200380. else
  200381. {
  200382. png_bytep sp, dp;
  200383. png_uint_32 i;
  200384. png_uint_32 row_width = row_info->width;
  200385. for (i = 0, sp = dp = row; i < row_width; i++)
  200386. {
  200387. png_byte save[2];
  200388. save[0] = *(sp++);
  200389. save[1] = *(sp++);
  200390. *(dp++) = *(sp++);
  200391. *(dp++) = *(sp++);
  200392. *(dp++) = save[0];
  200393. *(dp++) = save[1];
  200394. }
  200395. }
  200396. }
  200397. }
  200398. }
  200399. #endif
  200400. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200401. void /* PRIVATE */
  200402. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200403. {
  200404. png_debug(1, "in png_do_write_invert_alpha\n");
  200405. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200406. if (row != NULL && row_info != NULL)
  200407. #endif
  200408. {
  200409. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200410. {
  200411. /* This inverts the alpha channel in RGBA */
  200412. if (row_info->bit_depth == 8)
  200413. {
  200414. png_bytep sp, dp;
  200415. png_uint_32 i;
  200416. png_uint_32 row_width = row_info->width;
  200417. for (i = 0, sp = dp = row; i < row_width; i++)
  200418. {
  200419. /* does nothing
  200420. *(dp++) = *(sp++);
  200421. *(dp++) = *(sp++);
  200422. *(dp++) = *(sp++);
  200423. */
  200424. sp+=3; dp = sp;
  200425. *(dp++) = (png_byte)(255 - *(sp++));
  200426. }
  200427. }
  200428. /* This inverts the alpha channel in RRGGBBAA */
  200429. else
  200430. {
  200431. png_bytep sp, dp;
  200432. png_uint_32 i;
  200433. png_uint_32 row_width = row_info->width;
  200434. for (i = 0, sp = dp = row; i < row_width; i++)
  200435. {
  200436. /* does nothing
  200437. *(dp++) = *(sp++);
  200438. *(dp++) = *(sp++);
  200439. *(dp++) = *(sp++);
  200440. *(dp++) = *(sp++);
  200441. *(dp++) = *(sp++);
  200442. *(dp++) = *(sp++);
  200443. */
  200444. sp+=6; dp = sp;
  200445. *(dp++) = (png_byte)(255 - *(sp++));
  200446. *(dp++) = (png_byte)(255 - *(sp++));
  200447. }
  200448. }
  200449. }
  200450. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200451. {
  200452. /* This inverts the alpha channel in GA */
  200453. if (row_info->bit_depth == 8)
  200454. {
  200455. png_bytep sp, dp;
  200456. png_uint_32 i;
  200457. png_uint_32 row_width = row_info->width;
  200458. for (i = 0, sp = dp = row; i < row_width; i++)
  200459. {
  200460. *(dp++) = *(sp++);
  200461. *(dp++) = (png_byte)(255 - *(sp++));
  200462. }
  200463. }
  200464. /* This inverts the alpha channel in GGAA */
  200465. else
  200466. {
  200467. png_bytep sp, dp;
  200468. png_uint_32 i;
  200469. png_uint_32 row_width = row_info->width;
  200470. for (i = 0, sp = dp = row; i < row_width; i++)
  200471. {
  200472. /* does nothing
  200473. *(dp++) = *(sp++);
  200474. *(dp++) = *(sp++);
  200475. */
  200476. sp+=2; dp = sp;
  200477. *(dp++) = (png_byte)(255 - *(sp++));
  200478. *(dp++) = (png_byte)(255 - *(sp++));
  200479. }
  200480. }
  200481. }
  200482. }
  200483. }
  200484. #endif
  200485. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200486. /* undoes intrapixel differencing */
  200487. void /* PRIVATE */
  200488. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200489. {
  200490. png_debug(1, "in png_do_write_intrapixel\n");
  200491. if (
  200492. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200493. row != NULL && row_info != NULL &&
  200494. #endif
  200495. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200496. {
  200497. int bytes_per_pixel;
  200498. png_uint_32 row_width = row_info->width;
  200499. if (row_info->bit_depth == 8)
  200500. {
  200501. png_bytep rp;
  200502. png_uint_32 i;
  200503. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200504. bytes_per_pixel = 3;
  200505. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200506. bytes_per_pixel = 4;
  200507. else
  200508. return;
  200509. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200510. {
  200511. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200512. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200513. }
  200514. }
  200515. else if (row_info->bit_depth == 16)
  200516. {
  200517. png_bytep rp;
  200518. png_uint_32 i;
  200519. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200520. bytes_per_pixel = 6;
  200521. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200522. bytes_per_pixel = 8;
  200523. else
  200524. return;
  200525. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200526. {
  200527. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200528. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200529. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200530. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200531. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200532. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200533. *(rp+1) = (png_byte)(red & 0xff);
  200534. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200535. *(rp+5) = (png_byte)(blue & 0xff);
  200536. }
  200537. }
  200538. }
  200539. }
  200540. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200541. #endif /* PNG_WRITE_SUPPORTED */
  200542. /*** End of inlined file: pngwtran.c ***/
  200543. /*** Start of inlined file: pngwutil.c ***/
  200544. /* pngwutil.c - utilities to write a PNG file
  200545. *
  200546. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200547. * For conditions of distribution and use, see copyright notice in png.h
  200548. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200549. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200550. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200551. */
  200552. #define PNG_INTERNAL
  200553. #ifdef PNG_WRITE_SUPPORTED
  200554. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200555. * with unsigned numbers for convenience, although one supported
  200556. * ancillary chunk uses signed (two's complement) numbers.
  200557. */
  200558. void PNGAPI
  200559. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200560. {
  200561. buf[0] = (png_byte)((i >> 24) & 0xff);
  200562. buf[1] = (png_byte)((i >> 16) & 0xff);
  200563. buf[2] = (png_byte)((i >> 8) & 0xff);
  200564. buf[3] = (png_byte)(i & 0xff);
  200565. }
  200566. /* The png_save_int_32 function assumes integers are stored in two's
  200567. * complement format. If this isn't the case, then this routine needs to
  200568. * be modified to write data in two's complement format.
  200569. */
  200570. void PNGAPI
  200571. png_save_int_32(png_bytep buf, png_int_32 i)
  200572. {
  200573. buf[0] = (png_byte)((i >> 24) & 0xff);
  200574. buf[1] = (png_byte)((i >> 16) & 0xff);
  200575. buf[2] = (png_byte)((i >> 8) & 0xff);
  200576. buf[3] = (png_byte)(i & 0xff);
  200577. }
  200578. /* Place a 16-bit number into a buffer in PNG byte order.
  200579. * The parameter is declared unsigned int, not png_uint_16,
  200580. * just to avoid potential problems on pre-ANSI C compilers.
  200581. */
  200582. void PNGAPI
  200583. png_save_uint_16(png_bytep buf, unsigned int i)
  200584. {
  200585. buf[0] = (png_byte)((i >> 8) & 0xff);
  200586. buf[1] = (png_byte)(i & 0xff);
  200587. }
  200588. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200589. * representing the chunk name. The array must be at least 4 bytes in
  200590. * length, and does not need to be null terminated. To be safe, pass the
  200591. * pre-defined chunk names here, and if you need a new one, define it
  200592. * where the others are defined. The length is the length of the data.
  200593. * All the data must be present. If that is not possible, use the
  200594. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200595. * functions instead.
  200596. */
  200597. void PNGAPI
  200598. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200599. png_bytep data, png_size_t length)
  200600. {
  200601. if(png_ptr == NULL) return;
  200602. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200603. png_write_chunk_data(png_ptr, data, length);
  200604. png_write_chunk_end(png_ptr);
  200605. }
  200606. /* Write the start of a PNG chunk. The type is the chunk type.
  200607. * The total_length is the sum of the lengths of all the data you will be
  200608. * passing in png_write_chunk_data().
  200609. */
  200610. void PNGAPI
  200611. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200612. png_uint_32 length)
  200613. {
  200614. png_byte buf[4];
  200615. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200616. if(png_ptr == NULL) return;
  200617. /* write the length */
  200618. png_save_uint_32(buf, length);
  200619. png_write_data(png_ptr, buf, (png_size_t)4);
  200620. /* write the chunk name */
  200621. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200622. /* reset the crc and run it over the chunk name */
  200623. png_reset_crc(png_ptr);
  200624. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200625. }
  200626. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200627. * Note that multiple calls to this function are allowed, and that the
  200628. * sum of the lengths from these calls *must* add up to the total_length
  200629. * given to png_write_chunk_start().
  200630. */
  200631. void PNGAPI
  200632. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200633. {
  200634. /* write the data, and run the CRC over it */
  200635. if(png_ptr == NULL) return;
  200636. if (data != NULL && length > 0)
  200637. {
  200638. png_calculate_crc(png_ptr, data, length);
  200639. png_write_data(png_ptr, data, length);
  200640. }
  200641. }
  200642. /* Finish a chunk started with png_write_chunk_start(). */
  200643. void PNGAPI
  200644. png_write_chunk_end(png_structp png_ptr)
  200645. {
  200646. png_byte buf[4];
  200647. if(png_ptr == NULL) return;
  200648. /* write the crc */
  200649. png_save_uint_32(buf, png_ptr->crc);
  200650. png_write_data(png_ptr, buf, (png_size_t)4);
  200651. }
  200652. /* Simple function to write the signature. If we have already written
  200653. * the magic bytes of the signature, or more likely, the PNG stream is
  200654. * being embedded into another stream and doesn't need its own signature,
  200655. * we should call png_set_sig_bytes() to tell libpng how many of the
  200656. * bytes have already been written.
  200657. */
  200658. void /* PRIVATE */
  200659. png_write_sig(png_structp png_ptr)
  200660. {
  200661. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200662. /* write the rest of the 8 byte signature */
  200663. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200664. (png_size_t)8 - png_ptr->sig_bytes);
  200665. if(png_ptr->sig_bytes < 3)
  200666. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200667. }
  200668. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200669. /*
  200670. * This pair of functions encapsulates the operation of (a) compressing a
  200671. * text string, and (b) issuing it later as a series of chunk data writes.
  200672. * The compression_state structure is shared context for these functions
  200673. * set up by the caller in order to make the whole mess thread-safe.
  200674. */
  200675. typedef struct
  200676. {
  200677. char *input; /* the uncompressed input data */
  200678. int input_len; /* its length */
  200679. int num_output_ptr; /* number of output pointers used */
  200680. int max_output_ptr; /* size of output_ptr */
  200681. png_charpp output_ptr; /* array of pointers to output */
  200682. } compression_state;
  200683. /* compress given text into storage in the png_ptr structure */
  200684. static int /* PRIVATE */
  200685. png_text_compress(png_structp png_ptr,
  200686. png_charp text, png_size_t text_len, int compression,
  200687. compression_state *comp)
  200688. {
  200689. int ret;
  200690. comp->num_output_ptr = 0;
  200691. comp->max_output_ptr = 0;
  200692. comp->output_ptr = NULL;
  200693. comp->input = NULL;
  200694. comp->input_len = 0;
  200695. /* we may just want to pass the text right through */
  200696. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200697. {
  200698. comp->input = text;
  200699. comp->input_len = text_len;
  200700. return((int)text_len);
  200701. }
  200702. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200703. {
  200704. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200705. char msg[50];
  200706. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200707. png_warning(png_ptr, msg);
  200708. #else
  200709. png_warning(png_ptr, "Unknown compression type");
  200710. #endif
  200711. }
  200712. /* We can't write the chunk until we find out how much data we have,
  200713. * which means we need to run the compressor first and save the
  200714. * output. This shouldn't be a problem, as the vast majority of
  200715. * comments should be reasonable, but we will set up an array of
  200716. * malloc'd pointers to be sure.
  200717. *
  200718. * If we knew the application was well behaved, we could simplify this
  200719. * greatly by assuming we can always malloc an output buffer large
  200720. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200721. * and malloc this directly. The only time this would be a bad idea is
  200722. * if we can't malloc more than 64K and we have 64K of random input
  200723. * data, or if the input string is incredibly large (although this
  200724. * wouldn't cause a failure, just a slowdown due to swapping).
  200725. */
  200726. /* set up the compression buffers */
  200727. png_ptr->zstream.avail_in = (uInt)text_len;
  200728. png_ptr->zstream.next_in = (Bytef *)text;
  200729. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200730. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200731. /* this is the same compression loop as in png_write_row() */
  200732. do
  200733. {
  200734. /* compress the data */
  200735. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200736. if (ret != Z_OK)
  200737. {
  200738. /* error */
  200739. if (png_ptr->zstream.msg != NULL)
  200740. png_error(png_ptr, png_ptr->zstream.msg);
  200741. else
  200742. png_error(png_ptr, "zlib error");
  200743. }
  200744. /* check to see if we need more room */
  200745. if (!(png_ptr->zstream.avail_out))
  200746. {
  200747. /* make sure the output array has room */
  200748. if (comp->num_output_ptr >= comp->max_output_ptr)
  200749. {
  200750. int old_max;
  200751. old_max = comp->max_output_ptr;
  200752. comp->max_output_ptr = comp->num_output_ptr + 4;
  200753. if (comp->output_ptr != NULL)
  200754. {
  200755. png_charpp old_ptr;
  200756. old_ptr = comp->output_ptr;
  200757. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200758. (png_uint_32)(comp->max_output_ptr *
  200759. png_sizeof (png_charpp)));
  200760. png_memcpy(comp->output_ptr, old_ptr, old_max
  200761. * png_sizeof (png_charp));
  200762. png_free(png_ptr, old_ptr);
  200763. }
  200764. else
  200765. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200766. (png_uint_32)(comp->max_output_ptr *
  200767. png_sizeof (png_charp)));
  200768. }
  200769. /* save the data */
  200770. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200771. (png_uint_32)png_ptr->zbuf_size);
  200772. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200773. png_ptr->zbuf_size);
  200774. comp->num_output_ptr++;
  200775. /* and reset the buffer */
  200776. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200777. png_ptr->zstream.next_out = png_ptr->zbuf;
  200778. }
  200779. /* continue until we don't have any more to compress */
  200780. } while (png_ptr->zstream.avail_in);
  200781. /* finish the compression */
  200782. do
  200783. {
  200784. /* tell zlib we are finished */
  200785. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200786. if (ret == Z_OK)
  200787. {
  200788. /* check to see if we need more room */
  200789. if (!(png_ptr->zstream.avail_out))
  200790. {
  200791. /* check to make sure our output array has room */
  200792. if (comp->num_output_ptr >= comp->max_output_ptr)
  200793. {
  200794. int old_max;
  200795. old_max = comp->max_output_ptr;
  200796. comp->max_output_ptr = comp->num_output_ptr + 4;
  200797. if (comp->output_ptr != NULL)
  200798. {
  200799. png_charpp old_ptr;
  200800. old_ptr = comp->output_ptr;
  200801. /* This could be optimized to realloc() */
  200802. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200803. (png_uint_32)(comp->max_output_ptr *
  200804. png_sizeof (png_charpp)));
  200805. png_memcpy(comp->output_ptr, old_ptr,
  200806. old_max * png_sizeof (png_charp));
  200807. png_free(png_ptr, old_ptr);
  200808. }
  200809. else
  200810. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200811. (png_uint_32)(comp->max_output_ptr *
  200812. png_sizeof (png_charp)));
  200813. }
  200814. /* save off the data */
  200815. comp->output_ptr[comp->num_output_ptr] =
  200816. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200817. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200818. png_ptr->zbuf_size);
  200819. comp->num_output_ptr++;
  200820. /* and reset the buffer pointers */
  200821. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200822. png_ptr->zstream.next_out = png_ptr->zbuf;
  200823. }
  200824. }
  200825. else if (ret != Z_STREAM_END)
  200826. {
  200827. /* we got an error */
  200828. if (png_ptr->zstream.msg != NULL)
  200829. png_error(png_ptr, png_ptr->zstream.msg);
  200830. else
  200831. png_error(png_ptr, "zlib error");
  200832. }
  200833. } while (ret != Z_STREAM_END);
  200834. /* text length is number of buffers plus last buffer */
  200835. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200836. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200837. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200838. return((int)text_len);
  200839. }
  200840. /* ship the compressed text out via chunk writes */
  200841. static void /* PRIVATE */
  200842. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200843. {
  200844. int i;
  200845. /* handle the no-compression case */
  200846. if (comp->input)
  200847. {
  200848. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200849. (png_size_t)comp->input_len);
  200850. return;
  200851. }
  200852. /* write saved output buffers, if any */
  200853. for (i = 0; i < comp->num_output_ptr; i++)
  200854. {
  200855. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200856. png_ptr->zbuf_size);
  200857. png_free(png_ptr, comp->output_ptr[i]);
  200858. comp->output_ptr[i]=NULL;
  200859. }
  200860. if (comp->max_output_ptr != 0)
  200861. png_free(png_ptr, comp->output_ptr);
  200862. comp->output_ptr=NULL;
  200863. /* write anything left in zbuf */
  200864. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200865. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200866. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200867. /* reset zlib for another zTXt/iTXt or image data */
  200868. deflateReset(&png_ptr->zstream);
  200869. png_ptr->zstream.data_type = Z_BINARY;
  200870. }
  200871. #endif
  200872. /* Write the IHDR chunk, and update the png_struct with the necessary
  200873. * information. Note that the rest of this code depends upon this
  200874. * information being correct.
  200875. */
  200876. void /* PRIVATE */
  200877. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200878. int bit_depth, int color_type, int compression_type, int filter_type,
  200879. int interlace_type)
  200880. {
  200881. #ifdef PNG_USE_LOCAL_ARRAYS
  200882. PNG_IHDR;
  200883. #endif
  200884. png_byte buf[13]; /* buffer to store the IHDR info */
  200885. png_debug(1, "in png_write_IHDR\n");
  200886. /* Check that we have valid input data from the application info */
  200887. switch (color_type)
  200888. {
  200889. case PNG_COLOR_TYPE_GRAY:
  200890. switch (bit_depth)
  200891. {
  200892. case 1:
  200893. case 2:
  200894. case 4:
  200895. case 8:
  200896. case 16: png_ptr->channels = 1; break;
  200897. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200898. }
  200899. break;
  200900. case PNG_COLOR_TYPE_RGB:
  200901. if (bit_depth != 8 && bit_depth != 16)
  200902. png_error(png_ptr, "Invalid bit depth for RGB image");
  200903. png_ptr->channels = 3;
  200904. break;
  200905. case PNG_COLOR_TYPE_PALETTE:
  200906. switch (bit_depth)
  200907. {
  200908. case 1:
  200909. case 2:
  200910. case 4:
  200911. case 8: png_ptr->channels = 1; break;
  200912. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200913. }
  200914. break;
  200915. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200916. if (bit_depth != 8 && bit_depth != 16)
  200917. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200918. png_ptr->channels = 2;
  200919. break;
  200920. case PNG_COLOR_TYPE_RGB_ALPHA:
  200921. if (bit_depth != 8 && bit_depth != 16)
  200922. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200923. png_ptr->channels = 4;
  200924. break;
  200925. default:
  200926. png_error(png_ptr, "Invalid image color type specified");
  200927. }
  200928. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200929. {
  200930. png_warning(png_ptr, "Invalid compression type specified");
  200931. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200932. }
  200933. /* Write filter_method 64 (intrapixel differencing) only if
  200934. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200935. * 2. Libpng did not write a PNG signature (this filter_method is only
  200936. * used in PNG datastreams that are embedded in MNG datastreams) and
  200937. * 3. The application called png_permit_mng_features with a mask that
  200938. * included PNG_FLAG_MNG_FILTER_64 and
  200939. * 4. The filter_method is 64 and
  200940. * 5. The color_type is RGB or RGBA
  200941. */
  200942. if (
  200943. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200944. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200945. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200946. (color_type == PNG_COLOR_TYPE_RGB ||
  200947. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200948. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200949. #endif
  200950. filter_type != PNG_FILTER_TYPE_BASE)
  200951. {
  200952. png_warning(png_ptr, "Invalid filter type specified");
  200953. filter_type = PNG_FILTER_TYPE_BASE;
  200954. }
  200955. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200956. if (interlace_type != PNG_INTERLACE_NONE &&
  200957. interlace_type != PNG_INTERLACE_ADAM7)
  200958. {
  200959. png_warning(png_ptr, "Invalid interlace type specified");
  200960. interlace_type = PNG_INTERLACE_ADAM7;
  200961. }
  200962. #else
  200963. interlace_type=PNG_INTERLACE_NONE;
  200964. #endif
  200965. /* save off the relevent information */
  200966. png_ptr->bit_depth = (png_byte)bit_depth;
  200967. png_ptr->color_type = (png_byte)color_type;
  200968. png_ptr->interlaced = (png_byte)interlace_type;
  200969. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200970. png_ptr->filter_type = (png_byte)filter_type;
  200971. #endif
  200972. png_ptr->compression_type = (png_byte)compression_type;
  200973. png_ptr->width = width;
  200974. png_ptr->height = height;
  200975. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200976. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200977. /* set the usr info, so any transformations can modify it */
  200978. png_ptr->usr_width = png_ptr->width;
  200979. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200980. png_ptr->usr_channels = png_ptr->channels;
  200981. /* pack the header information into the buffer */
  200982. png_save_uint_32(buf, width);
  200983. png_save_uint_32(buf + 4, height);
  200984. buf[8] = (png_byte)bit_depth;
  200985. buf[9] = (png_byte)color_type;
  200986. buf[10] = (png_byte)compression_type;
  200987. buf[11] = (png_byte)filter_type;
  200988. buf[12] = (png_byte)interlace_type;
  200989. /* write the chunk */
  200990. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200991. /* initialize zlib with PNG info */
  200992. png_ptr->zstream.zalloc = png_zalloc;
  200993. png_ptr->zstream.zfree = png_zfree;
  200994. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200995. if (!(png_ptr->do_filter))
  200996. {
  200997. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200998. png_ptr->bit_depth < 8)
  200999. png_ptr->do_filter = PNG_FILTER_NONE;
  201000. else
  201001. png_ptr->do_filter = PNG_ALL_FILTERS;
  201002. }
  201003. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201004. {
  201005. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201006. png_ptr->zlib_strategy = Z_FILTERED;
  201007. else
  201008. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201009. }
  201010. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201011. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201012. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201013. png_ptr->zlib_mem_level = 8;
  201014. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201015. png_ptr->zlib_window_bits = 15;
  201016. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201017. png_ptr->zlib_method = 8;
  201018. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201019. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201020. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201021. png_error(png_ptr, "zlib failed to initialize compressor");
  201022. png_ptr->zstream.next_out = png_ptr->zbuf;
  201023. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201024. /* libpng is not interested in zstream.data_type */
  201025. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201026. png_ptr->zstream.data_type = Z_BINARY;
  201027. png_ptr->mode = PNG_HAVE_IHDR;
  201028. }
  201029. /* write the palette. We are careful not to trust png_color to be in the
  201030. * correct order for PNG, so people can redefine it to any convenient
  201031. * structure.
  201032. */
  201033. void /* PRIVATE */
  201034. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201035. {
  201036. #ifdef PNG_USE_LOCAL_ARRAYS
  201037. PNG_PLTE;
  201038. #endif
  201039. png_uint_32 i;
  201040. png_colorp pal_ptr;
  201041. png_byte buf[3];
  201042. png_debug(1, "in png_write_PLTE\n");
  201043. if ((
  201044. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201045. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201046. #endif
  201047. num_pal == 0) || num_pal > 256)
  201048. {
  201049. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201050. {
  201051. png_error(png_ptr, "Invalid number of colors in palette");
  201052. }
  201053. else
  201054. {
  201055. png_warning(png_ptr, "Invalid number of colors in palette");
  201056. return;
  201057. }
  201058. }
  201059. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201060. {
  201061. png_warning(png_ptr,
  201062. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201063. return;
  201064. }
  201065. png_ptr->num_palette = (png_uint_16)num_pal;
  201066. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201067. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201068. #ifndef PNG_NO_POINTER_INDEXING
  201069. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201070. {
  201071. buf[0] = pal_ptr->red;
  201072. buf[1] = pal_ptr->green;
  201073. buf[2] = pal_ptr->blue;
  201074. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201075. }
  201076. #else
  201077. /* This is a little slower but some buggy compilers need to do this instead */
  201078. pal_ptr=palette;
  201079. for (i = 0; i < num_pal; i++)
  201080. {
  201081. buf[0] = pal_ptr[i].red;
  201082. buf[1] = pal_ptr[i].green;
  201083. buf[2] = pal_ptr[i].blue;
  201084. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201085. }
  201086. #endif
  201087. png_write_chunk_end(png_ptr);
  201088. png_ptr->mode |= PNG_HAVE_PLTE;
  201089. }
  201090. /* write an IDAT chunk */
  201091. void /* PRIVATE */
  201092. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201093. {
  201094. #ifdef PNG_USE_LOCAL_ARRAYS
  201095. PNG_IDAT;
  201096. #endif
  201097. png_debug(1, "in png_write_IDAT\n");
  201098. /* Optimize the CMF field in the zlib stream. */
  201099. /* This hack of the zlib stream is compliant to the stream specification. */
  201100. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201101. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201102. {
  201103. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201104. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201105. {
  201106. /* Avoid memory underflows and multiplication overflows. */
  201107. /* The conditions below are practically always satisfied;
  201108. however, they still must be checked. */
  201109. if (length >= 2 &&
  201110. png_ptr->height < 16384 && png_ptr->width < 16384)
  201111. {
  201112. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201113. ((png_ptr->width *
  201114. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201115. unsigned int z_cinfo = z_cmf >> 4;
  201116. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201117. while (uncompressed_idat_size <= half_z_window_size &&
  201118. half_z_window_size >= 256)
  201119. {
  201120. z_cinfo--;
  201121. half_z_window_size >>= 1;
  201122. }
  201123. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201124. if (data[0] != (png_byte)z_cmf)
  201125. {
  201126. data[0] = (png_byte)z_cmf;
  201127. data[1] &= 0xe0;
  201128. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201129. }
  201130. }
  201131. }
  201132. else
  201133. png_error(png_ptr,
  201134. "Invalid zlib compression method or flags in IDAT");
  201135. }
  201136. png_write_chunk(png_ptr, png_IDAT, data, length);
  201137. png_ptr->mode |= PNG_HAVE_IDAT;
  201138. }
  201139. /* write an IEND chunk */
  201140. void /* PRIVATE */
  201141. png_write_IEND(png_structp png_ptr)
  201142. {
  201143. #ifdef PNG_USE_LOCAL_ARRAYS
  201144. PNG_IEND;
  201145. #endif
  201146. png_debug(1, "in png_write_IEND\n");
  201147. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201148. (png_size_t)0);
  201149. png_ptr->mode |= PNG_HAVE_IEND;
  201150. }
  201151. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201152. /* write a gAMA chunk */
  201153. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201154. void /* PRIVATE */
  201155. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201156. {
  201157. #ifdef PNG_USE_LOCAL_ARRAYS
  201158. PNG_gAMA;
  201159. #endif
  201160. png_uint_32 igamma;
  201161. png_byte buf[4];
  201162. png_debug(1, "in png_write_gAMA\n");
  201163. /* file_gamma is saved in 1/100,000ths */
  201164. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201165. png_save_uint_32(buf, igamma);
  201166. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201167. }
  201168. #endif
  201169. #ifdef PNG_FIXED_POINT_SUPPORTED
  201170. void /* PRIVATE */
  201171. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201172. {
  201173. #ifdef PNG_USE_LOCAL_ARRAYS
  201174. PNG_gAMA;
  201175. #endif
  201176. png_byte buf[4];
  201177. png_debug(1, "in png_write_gAMA\n");
  201178. /* file_gamma is saved in 1/100,000ths */
  201179. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201180. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201181. }
  201182. #endif
  201183. #endif
  201184. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201185. /* write a sRGB chunk */
  201186. void /* PRIVATE */
  201187. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201188. {
  201189. #ifdef PNG_USE_LOCAL_ARRAYS
  201190. PNG_sRGB;
  201191. #endif
  201192. png_byte buf[1];
  201193. png_debug(1, "in png_write_sRGB\n");
  201194. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201195. png_warning(png_ptr,
  201196. "Invalid sRGB rendering intent specified");
  201197. buf[0]=(png_byte)srgb_intent;
  201198. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201199. }
  201200. #endif
  201201. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201202. /* write an iCCP chunk */
  201203. void /* PRIVATE */
  201204. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201205. png_charp profile, int profile_len)
  201206. {
  201207. #ifdef PNG_USE_LOCAL_ARRAYS
  201208. PNG_iCCP;
  201209. #endif
  201210. png_size_t name_len;
  201211. png_charp new_name;
  201212. compression_state comp;
  201213. int embedded_profile_len = 0;
  201214. png_debug(1, "in png_write_iCCP\n");
  201215. comp.num_output_ptr = 0;
  201216. comp.max_output_ptr = 0;
  201217. comp.output_ptr = NULL;
  201218. comp.input = NULL;
  201219. comp.input_len = 0;
  201220. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201221. &new_name)) == 0)
  201222. {
  201223. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201224. return;
  201225. }
  201226. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201227. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201228. if (profile == NULL)
  201229. profile_len = 0;
  201230. if (profile_len > 3)
  201231. embedded_profile_len =
  201232. ((*( (png_bytep)profile ))<<24) |
  201233. ((*( (png_bytep)profile+1))<<16) |
  201234. ((*( (png_bytep)profile+2))<< 8) |
  201235. ((*( (png_bytep)profile+3)) );
  201236. if (profile_len < embedded_profile_len)
  201237. {
  201238. png_warning(png_ptr,
  201239. "Embedded profile length too large in iCCP chunk");
  201240. return;
  201241. }
  201242. if (profile_len > embedded_profile_len)
  201243. {
  201244. png_warning(png_ptr,
  201245. "Truncating profile to actual length in iCCP chunk");
  201246. profile_len = embedded_profile_len;
  201247. }
  201248. if (profile_len)
  201249. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201250. PNG_COMPRESSION_TYPE_BASE, &comp);
  201251. /* make sure we include the NULL after the name and the compression type */
  201252. png_write_chunk_start(png_ptr, png_iCCP,
  201253. (png_uint_32)name_len+profile_len+2);
  201254. new_name[name_len+1]=0x00;
  201255. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201256. if (profile_len)
  201257. png_write_compressed_data_out(png_ptr, &comp);
  201258. png_write_chunk_end(png_ptr);
  201259. png_free(png_ptr, new_name);
  201260. }
  201261. #endif
  201262. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201263. /* write a sPLT chunk */
  201264. void /* PRIVATE */
  201265. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201266. {
  201267. #ifdef PNG_USE_LOCAL_ARRAYS
  201268. PNG_sPLT;
  201269. #endif
  201270. png_size_t name_len;
  201271. png_charp new_name;
  201272. png_byte entrybuf[10];
  201273. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201274. int palette_size = entry_size * spalette->nentries;
  201275. png_sPLT_entryp ep;
  201276. #ifdef PNG_NO_POINTER_INDEXING
  201277. int i;
  201278. #endif
  201279. png_debug(1, "in png_write_sPLT\n");
  201280. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201281. spalette->name, &new_name))==0)
  201282. {
  201283. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201284. return;
  201285. }
  201286. /* make sure we include the NULL after the name */
  201287. png_write_chunk_start(png_ptr, png_sPLT,
  201288. (png_uint_32)(name_len + 2 + palette_size));
  201289. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201290. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201291. /* loop through each palette entry, writing appropriately */
  201292. #ifndef PNG_NO_POINTER_INDEXING
  201293. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201294. {
  201295. if (spalette->depth == 8)
  201296. {
  201297. entrybuf[0] = (png_byte)ep->red;
  201298. entrybuf[1] = (png_byte)ep->green;
  201299. entrybuf[2] = (png_byte)ep->blue;
  201300. entrybuf[3] = (png_byte)ep->alpha;
  201301. png_save_uint_16(entrybuf + 4, ep->frequency);
  201302. }
  201303. else
  201304. {
  201305. png_save_uint_16(entrybuf + 0, ep->red);
  201306. png_save_uint_16(entrybuf + 2, ep->green);
  201307. png_save_uint_16(entrybuf + 4, ep->blue);
  201308. png_save_uint_16(entrybuf + 6, ep->alpha);
  201309. png_save_uint_16(entrybuf + 8, ep->frequency);
  201310. }
  201311. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201312. }
  201313. #else
  201314. ep=spalette->entries;
  201315. for (i=0; i>spalette->nentries; i++)
  201316. {
  201317. if (spalette->depth == 8)
  201318. {
  201319. entrybuf[0] = (png_byte)ep[i].red;
  201320. entrybuf[1] = (png_byte)ep[i].green;
  201321. entrybuf[2] = (png_byte)ep[i].blue;
  201322. entrybuf[3] = (png_byte)ep[i].alpha;
  201323. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201324. }
  201325. else
  201326. {
  201327. png_save_uint_16(entrybuf + 0, ep[i].red);
  201328. png_save_uint_16(entrybuf + 2, ep[i].green);
  201329. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201330. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201331. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201332. }
  201333. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201334. }
  201335. #endif
  201336. png_write_chunk_end(png_ptr);
  201337. png_free(png_ptr, new_name);
  201338. }
  201339. #endif
  201340. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201341. /* write the sBIT chunk */
  201342. void /* PRIVATE */
  201343. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201344. {
  201345. #ifdef PNG_USE_LOCAL_ARRAYS
  201346. PNG_sBIT;
  201347. #endif
  201348. png_byte buf[4];
  201349. png_size_t size;
  201350. png_debug(1, "in png_write_sBIT\n");
  201351. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201352. if (color_type & PNG_COLOR_MASK_COLOR)
  201353. {
  201354. png_byte maxbits;
  201355. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201356. png_ptr->usr_bit_depth);
  201357. if (sbit->red == 0 || sbit->red > maxbits ||
  201358. sbit->green == 0 || sbit->green > maxbits ||
  201359. sbit->blue == 0 || sbit->blue > maxbits)
  201360. {
  201361. png_warning(png_ptr, "Invalid sBIT depth specified");
  201362. return;
  201363. }
  201364. buf[0] = sbit->red;
  201365. buf[1] = sbit->green;
  201366. buf[2] = sbit->blue;
  201367. size = 3;
  201368. }
  201369. else
  201370. {
  201371. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201372. {
  201373. png_warning(png_ptr, "Invalid sBIT depth specified");
  201374. return;
  201375. }
  201376. buf[0] = sbit->gray;
  201377. size = 1;
  201378. }
  201379. if (color_type & PNG_COLOR_MASK_ALPHA)
  201380. {
  201381. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201382. {
  201383. png_warning(png_ptr, "Invalid sBIT depth specified");
  201384. return;
  201385. }
  201386. buf[size++] = sbit->alpha;
  201387. }
  201388. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201389. }
  201390. #endif
  201391. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201392. /* write the cHRM chunk */
  201393. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201394. void /* PRIVATE */
  201395. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201396. double red_x, double red_y, double green_x, double green_y,
  201397. double blue_x, double blue_y)
  201398. {
  201399. #ifdef PNG_USE_LOCAL_ARRAYS
  201400. PNG_cHRM;
  201401. #endif
  201402. png_byte buf[32];
  201403. png_uint_32 itemp;
  201404. png_debug(1, "in png_write_cHRM\n");
  201405. /* each value is saved in 1/100,000ths */
  201406. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201407. white_x + white_y > 1.0)
  201408. {
  201409. png_warning(png_ptr, "Invalid cHRM white point specified");
  201410. #if !defined(PNG_NO_CONSOLE_IO)
  201411. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201412. #endif
  201413. return;
  201414. }
  201415. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201416. png_save_uint_32(buf, itemp);
  201417. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201418. png_save_uint_32(buf + 4, itemp);
  201419. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201420. {
  201421. png_warning(png_ptr, "Invalid cHRM red point specified");
  201422. return;
  201423. }
  201424. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201425. png_save_uint_32(buf + 8, itemp);
  201426. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201427. png_save_uint_32(buf + 12, itemp);
  201428. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201429. {
  201430. png_warning(png_ptr, "Invalid cHRM green point specified");
  201431. return;
  201432. }
  201433. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201434. png_save_uint_32(buf + 16, itemp);
  201435. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201436. png_save_uint_32(buf + 20, itemp);
  201437. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201438. {
  201439. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201440. return;
  201441. }
  201442. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201443. png_save_uint_32(buf + 24, itemp);
  201444. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201445. png_save_uint_32(buf + 28, itemp);
  201446. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201447. }
  201448. #endif
  201449. #ifdef PNG_FIXED_POINT_SUPPORTED
  201450. void /* PRIVATE */
  201451. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201452. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201453. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201454. png_fixed_point blue_y)
  201455. {
  201456. #ifdef PNG_USE_LOCAL_ARRAYS
  201457. PNG_cHRM;
  201458. #endif
  201459. png_byte buf[32];
  201460. png_debug(1, "in png_write_cHRM\n");
  201461. /* each value is saved in 1/100,000ths */
  201462. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201463. {
  201464. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201465. #if !defined(PNG_NO_CONSOLE_IO)
  201466. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201467. #endif
  201468. return;
  201469. }
  201470. png_save_uint_32(buf, (png_uint_32)white_x);
  201471. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201472. if (red_x + red_y > 100000L)
  201473. {
  201474. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201475. return;
  201476. }
  201477. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201478. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201479. if (green_x + green_y > 100000L)
  201480. {
  201481. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201482. return;
  201483. }
  201484. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201485. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201486. if (blue_x + blue_y > 100000L)
  201487. {
  201488. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201489. return;
  201490. }
  201491. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201492. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201493. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201494. }
  201495. #endif
  201496. #endif
  201497. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201498. /* write the tRNS chunk */
  201499. void /* PRIVATE */
  201500. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201501. int num_trans, int color_type)
  201502. {
  201503. #ifdef PNG_USE_LOCAL_ARRAYS
  201504. PNG_tRNS;
  201505. #endif
  201506. png_byte buf[6];
  201507. png_debug(1, "in png_write_tRNS\n");
  201508. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201509. {
  201510. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201511. {
  201512. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201513. return;
  201514. }
  201515. /* write the chunk out as it is */
  201516. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201517. }
  201518. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201519. {
  201520. /* one 16 bit value */
  201521. if(tran->gray >= (1 << png_ptr->bit_depth))
  201522. {
  201523. png_warning(png_ptr,
  201524. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201525. return;
  201526. }
  201527. png_save_uint_16(buf, tran->gray);
  201528. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201529. }
  201530. else if (color_type == PNG_COLOR_TYPE_RGB)
  201531. {
  201532. /* three 16 bit values */
  201533. png_save_uint_16(buf, tran->red);
  201534. png_save_uint_16(buf + 2, tran->green);
  201535. png_save_uint_16(buf + 4, tran->blue);
  201536. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201537. {
  201538. png_warning(png_ptr,
  201539. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201540. return;
  201541. }
  201542. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201543. }
  201544. else
  201545. {
  201546. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201547. }
  201548. }
  201549. #endif
  201550. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201551. /* write the background chunk */
  201552. void /* PRIVATE */
  201553. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201554. {
  201555. #ifdef PNG_USE_LOCAL_ARRAYS
  201556. PNG_bKGD;
  201557. #endif
  201558. png_byte buf[6];
  201559. png_debug(1, "in png_write_bKGD\n");
  201560. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201561. {
  201562. if (
  201563. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201564. (png_ptr->num_palette ||
  201565. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201566. #endif
  201567. back->index > png_ptr->num_palette)
  201568. {
  201569. png_warning(png_ptr, "Invalid background palette index");
  201570. return;
  201571. }
  201572. buf[0] = back->index;
  201573. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201574. }
  201575. else if (color_type & PNG_COLOR_MASK_COLOR)
  201576. {
  201577. png_save_uint_16(buf, back->red);
  201578. png_save_uint_16(buf + 2, back->green);
  201579. png_save_uint_16(buf + 4, back->blue);
  201580. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201581. {
  201582. png_warning(png_ptr,
  201583. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201584. return;
  201585. }
  201586. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201587. }
  201588. else
  201589. {
  201590. if(back->gray >= (1 << png_ptr->bit_depth))
  201591. {
  201592. png_warning(png_ptr,
  201593. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201594. return;
  201595. }
  201596. png_save_uint_16(buf, back->gray);
  201597. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201598. }
  201599. }
  201600. #endif
  201601. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201602. /* write the histogram */
  201603. void /* PRIVATE */
  201604. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201605. {
  201606. #ifdef PNG_USE_LOCAL_ARRAYS
  201607. PNG_hIST;
  201608. #endif
  201609. int i;
  201610. png_byte buf[3];
  201611. png_debug(1, "in png_write_hIST\n");
  201612. if (num_hist > (int)png_ptr->num_palette)
  201613. {
  201614. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201615. png_ptr->num_palette);
  201616. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201617. return;
  201618. }
  201619. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201620. for (i = 0; i < num_hist; i++)
  201621. {
  201622. png_save_uint_16(buf, hist[i]);
  201623. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201624. }
  201625. png_write_chunk_end(png_ptr);
  201626. }
  201627. #endif
  201628. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201629. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201630. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201631. * and if invalid, correct the keyword rather than discarding the entire
  201632. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201633. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201634. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201635. *
  201636. * The new_key is allocated to hold the corrected keyword and must be freed
  201637. * by the calling routine. This avoids problems with trying to write to
  201638. * static keywords without having to have duplicate copies of the strings.
  201639. */
  201640. png_size_t /* PRIVATE */
  201641. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201642. {
  201643. png_size_t key_len;
  201644. png_charp kp, dp;
  201645. int kflag;
  201646. int kwarn=0;
  201647. png_debug(1, "in png_check_keyword\n");
  201648. *new_key = NULL;
  201649. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201650. {
  201651. png_warning(png_ptr, "zero length keyword");
  201652. return ((png_size_t)0);
  201653. }
  201654. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201655. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201656. if (*new_key == NULL)
  201657. {
  201658. png_warning(png_ptr, "Out of memory while procesing keyword");
  201659. return ((png_size_t)0);
  201660. }
  201661. /* Replace non-printing characters with a blank and print a warning */
  201662. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201663. {
  201664. if ((png_byte)*kp < 0x20 ||
  201665. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201666. {
  201667. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201668. char msg[40];
  201669. png_snprintf(msg, 40,
  201670. "invalid keyword character 0x%02X", (png_byte)*kp);
  201671. png_warning(png_ptr, msg);
  201672. #else
  201673. png_warning(png_ptr, "invalid character in keyword");
  201674. #endif
  201675. *dp = ' ';
  201676. }
  201677. else
  201678. {
  201679. *dp = *kp;
  201680. }
  201681. }
  201682. *dp = '\0';
  201683. /* Remove any trailing white space. */
  201684. kp = *new_key + key_len - 1;
  201685. if (*kp == ' ')
  201686. {
  201687. png_warning(png_ptr, "trailing spaces removed from keyword");
  201688. while (*kp == ' ')
  201689. {
  201690. *(kp--) = '\0';
  201691. key_len--;
  201692. }
  201693. }
  201694. /* Remove any leading white space. */
  201695. kp = *new_key;
  201696. if (*kp == ' ')
  201697. {
  201698. png_warning(png_ptr, "leading spaces removed from keyword");
  201699. while (*kp == ' ')
  201700. {
  201701. kp++;
  201702. key_len--;
  201703. }
  201704. }
  201705. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201706. /* Remove multiple internal spaces. */
  201707. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201708. {
  201709. if (*kp == ' ' && kflag == 0)
  201710. {
  201711. *(dp++) = *kp;
  201712. kflag = 1;
  201713. }
  201714. else if (*kp == ' ')
  201715. {
  201716. key_len--;
  201717. kwarn=1;
  201718. }
  201719. else
  201720. {
  201721. *(dp++) = *kp;
  201722. kflag = 0;
  201723. }
  201724. }
  201725. *dp = '\0';
  201726. if(kwarn)
  201727. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201728. if (key_len == 0)
  201729. {
  201730. png_free(png_ptr, *new_key);
  201731. *new_key=NULL;
  201732. png_warning(png_ptr, "Zero length keyword");
  201733. }
  201734. if (key_len > 79)
  201735. {
  201736. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201737. new_key[79] = '\0';
  201738. key_len = 79;
  201739. }
  201740. return (key_len);
  201741. }
  201742. #endif
  201743. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201744. /* write a tEXt chunk */
  201745. void /* PRIVATE */
  201746. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201747. png_size_t text_len)
  201748. {
  201749. #ifdef PNG_USE_LOCAL_ARRAYS
  201750. PNG_tEXt;
  201751. #endif
  201752. png_size_t key_len;
  201753. png_charp new_key;
  201754. png_debug(1, "in png_write_tEXt\n");
  201755. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201756. {
  201757. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201758. return;
  201759. }
  201760. if (text == NULL || *text == '\0')
  201761. text_len = 0;
  201762. else
  201763. text_len = png_strlen(text);
  201764. /* make sure we include the 0 after the key */
  201765. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201766. /*
  201767. * We leave it to the application to meet PNG-1.0 requirements on the
  201768. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201769. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201770. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201771. */
  201772. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201773. if (text_len)
  201774. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201775. png_write_chunk_end(png_ptr);
  201776. png_free(png_ptr, new_key);
  201777. }
  201778. #endif
  201779. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201780. /* write a compressed text chunk */
  201781. void /* PRIVATE */
  201782. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201783. png_size_t text_len, int compression)
  201784. {
  201785. #ifdef PNG_USE_LOCAL_ARRAYS
  201786. PNG_zTXt;
  201787. #endif
  201788. png_size_t key_len;
  201789. char buf[1];
  201790. png_charp new_key;
  201791. compression_state comp;
  201792. png_debug(1, "in png_write_zTXt\n");
  201793. comp.num_output_ptr = 0;
  201794. comp.max_output_ptr = 0;
  201795. comp.output_ptr = NULL;
  201796. comp.input = NULL;
  201797. comp.input_len = 0;
  201798. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201799. {
  201800. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201801. return;
  201802. }
  201803. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201804. {
  201805. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201806. png_free(png_ptr, new_key);
  201807. return;
  201808. }
  201809. text_len = png_strlen(text);
  201810. /* compute the compressed data; do it now for the length */
  201811. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201812. &comp);
  201813. /* write start of chunk */
  201814. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201815. (key_len+text_len+2));
  201816. /* write key */
  201817. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201818. png_free(png_ptr, new_key);
  201819. buf[0] = (png_byte)compression;
  201820. /* write compression */
  201821. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201822. /* write the compressed data */
  201823. png_write_compressed_data_out(png_ptr, &comp);
  201824. /* close the chunk */
  201825. png_write_chunk_end(png_ptr);
  201826. }
  201827. #endif
  201828. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201829. /* write an iTXt chunk */
  201830. void /* PRIVATE */
  201831. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201832. png_charp lang, png_charp lang_key, png_charp text)
  201833. {
  201834. #ifdef PNG_USE_LOCAL_ARRAYS
  201835. PNG_iTXt;
  201836. #endif
  201837. png_size_t lang_len, key_len, lang_key_len, text_len;
  201838. png_charp new_lang, new_key;
  201839. png_byte cbuf[2];
  201840. compression_state comp;
  201841. png_debug(1, "in png_write_iTXt\n");
  201842. comp.num_output_ptr = 0;
  201843. comp.max_output_ptr = 0;
  201844. comp.output_ptr = NULL;
  201845. comp.input = NULL;
  201846. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201847. {
  201848. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201849. return;
  201850. }
  201851. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201852. {
  201853. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201854. new_lang = NULL;
  201855. lang_len = 0;
  201856. }
  201857. if (lang_key == NULL)
  201858. lang_key_len = 0;
  201859. else
  201860. lang_key_len = png_strlen(lang_key);
  201861. if (text == NULL)
  201862. text_len = 0;
  201863. else
  201864. text_len = png_strlen(text);
  201865. /* compute the compressed data; do it now for the length */
  201866. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201867. &comp);
  201868. /* make sure we include the compression flag, the compression byte,
  201869. * and the NULs after the key, lang, and lang_key parts */
  201870. png_write_chunk_start(png_ptr, png_iTXt,
  201871. (png_uint_32)(
  201872. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201873. + key_len
  201874. + lang_len
  201875. + lang_key_len
  201876. + text_len));
  201877. /*
  201878. * We leave it to the application to meet PNG-1.0 requirements on the
  201879. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201880. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201881. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201882. */
  201883. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201884. /* set the compression flag */
  201885. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201886. compression == PNG_TEXT_COMPRESSION_NONE)
  201887. cbuf[0] = 0;
  201888. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201889. cbuf[0] = 1;
  201890. /* set the compression method */
  201891. cbuf[1] = 0;
  201892. png_write_chunk_data(png_ptr, cbuf, 2);
  201893. cbuf[0] = 0;
  201894. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201895. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201896. png_write_compressed_data_out(png_ptr, &comp);
  201897. png_write_chunk_end(png_ptr);
  201898. png_free(png_ptr, new_key);
  201899. if (new_lang)
  201900. png_free(png_ptr, new_lang);
  201901. }
  201902. #endif
  201903. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201904. /* write the oFFs chunk */
  201905. void /* PRIVATE */
  201906. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201907. int unit_type)
  201908. {
  201909. #ifdef PNG_USE_LOCAL_ARRAYS
  201910. PNG_oFFs;
  201911. #endif
  201912. png_byte buf[9];
  201913. png_debug(1, "in png_write_oFFs\n");
  201914. if (unit_type >= PNG_OFFSET_LAST)
  201915. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201916. png_save_int_32(buf, x_offset);
  201917. png_save_int_32(buf + 4, y_offset);
  201918. buf[8] = (png_byte)unit_type;
  201919. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201920. }
  201921. #endif
  201922. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201923. /* write the pCAL chunk (described in the PNG extensions document) */
  201924. void /* PRIVATE */
  201925. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201926. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201927. {
  201928. #ifdef PNG_USE_LOCAL_ARRAYS
  201929. PNG_pCAL;
  201930. #endif
  201931. png_size_t purpose_len, units_len, total_len;
  201932. png_uint_32p params_len;
  201933. png_byte buf[10];
  201934. png_charp new_purpose;
  201935. int i;
  201936. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201937. if (type >= PNG_EQUATION_LAST)
  201938. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201939. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201940. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201941. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201942. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201943. total_len = purpose_len + units_len + 10;
  201944. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201945. *png_sizeof(png_uint_32)));
  201946. /* Find the length of each parameter, making sure we don't count the
  201947. null terminator for the last parameter. */
  201948. for (i = 0; i < nparams; i++)
  201949. {
  201950. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201951. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201952. total_len += (png_size_t)params_len[i];
  201953. }
  201954. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201955. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201956. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201957. png_save_int_32(buf, X0);
  201958. png_save_int_32(buf + 4, X1);
  201959. buf[8] = (png_byte)type;
  201960. buf[9] = (png_byte)nparams;
  201961. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201962. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201963. png_free(png_ptr, new_purpose);
  201964. for (i = 0; i < nparams; i++)
  201965. {
  201966. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201967. (png_size_t)params_len[i]);
  201968. }
  201969. png_free(png_ptr, params_len);
  201970. png_write_chunk_end(png_ptr);
  201971. }
  201972. #endif
  201973. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201974. /* write the sCAL chunk */
  201975. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201976. void /* PRIVATE */
  201977. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201978. {
  201979. #ifdef PNG_USE_LOCAL_ARRAYS
  201980. PNG_sCAL;
  201981. #endif
  201982. char buf[64];
  201983. png_size_t total_len;
  201984. png_debug(1, "in png_write_sCAL\n");
  201985. buf[0] = (char)unit;
  201986. #if defined(_WIN32_WCE)
  201987. /* sprintf() function is not supported on WindowsCE */
  201988. {
  201989. wchar_t wc_buf[32];
  201990. size_t wc_len;
  201991. swprintf(wc_buf, TEXT("%12.12e"), width);
  201992. wc_len = wcslen(wc_buf);
  201993. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201994. total_len = wc_len + 2;
  201995. swprintf(wc_buf, TEXT("%12.12e"), height);
  201996. wc_len = wcslen(wc_buf);
  201997. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201998. NULL, NULL);
  201999. total_len += wc_len;
  202000. }
  202001. #else
  202002. png_snprintf(buf + 1, 63, "%12.12e", width);
  202003. total_len = 1 + png_strlen(buf + 1) + 1;
  202004. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202005. total_len += png_strlen(buf + total_len);
  202006. #endif
  202007. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202008. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202009. }
  202010. #else
  202011. #ifdef PNG_FIXED_POINT_SUPPORTED
  202012. void /* PRIVATE */
  202013. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202014. png_charp height)
  202015. {
  202016. #ifdef PNG_USE_LOCAL_ARRAYS
  202017. PNG_sCAL;
  202018. #endif
  202019. png_byte buf[64];
  202020. png_size_t wlen, hlen, total_len;
  202021. png_debug(1, "in png_write_sCAL_s\n");
  202022. wlen = png_strlen(width);
  202023. hlen = png_strlen(height);
  202024. total_len = wlen + hlen + 2;
  202025. if (total_len > 64)
  202026. {
  202027. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202028. return;
  202029. }
  202030. buf[0] = (png_byte)unit;
  202031. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202032. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202033. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202034. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202035. }
  202036. #endif
  202037. #endif
  202038. #endif
  202039. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202040. /* write the pHYs chunk */
  202041. void /* PRIVATE */
  202042. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202043. png_uint_32 y_pixels_per_unit,
  202044. int unit_type)
  202045. {
  202046. #ifdef PNG_USE_LOCAL_ARRAYS
  202047. PNG_pHYs;
  202048. #endif
  202049. png_byte buf[9];
  202050. png_debug(1, "in png_write_pHYs\n");
  202051. if (unit_type >= PNG_RESOLUTION_LAST)
  202052. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202053. png_save_uint_32(buf, x_pixels_per_unit);
  202054. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202055. buf[8] = (png_byte)unit_type;
  202056. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202057. }
  202058. #endif
  202059. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202060. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202061. * or png_convert_from_time_t(), or fill in the structure yourself.
  202062. */
  202063. void /* PRIVATE */
  202064. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202065. {
  202066. #ifdef PNG_USE_LOCAL_ARRAYS
  202067. PNG_tIME;
  202068. #endif
  202069. png_byte buf[7];
  202070. png_debug(1, "in png_write_tIME\n");
  202071. if (mod_time->month > 12 || mod_time->month < 1 ||
  202072. mod_time->day > 31 || mod_time->day < 1 ||
  202073. mod_time->hour > 23 || mod_time->second > 60)
  202074. {
  202075. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202076. return;
  202077. }
  202078. png_save_uint_16(buf, mod_time->year);
  202079. buf[2] = mod_time->month;
  202080. buf[3] = mod_time->day;
  202081. buf[4] = mod_time->hour;
  202082. buf[5] = mod_time->minute;
  202083. buf[6] = mod_time->second;
  202084. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202085. }
  202086. #endif
  202087. /* initializes the row writing capability of libpng */
  202088. void /* PRIVATE */
  202089. png_write_start_row(png_structp png_ptr)
  202090. {
  202091. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202092. #ifdef PNG_USE_LOCAL_ARRAYS
  202093. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202094. /* start of interlace block */
  202095. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202096. /* offset to next interlace block */
  202097. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202098. /* start of interlace block in the y direction */
  202099. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202100. /* offset to next interlace block in the y direction */
  202101. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202102. #endif
  202103. #endif
  202104. png_size_t buf_size;
  202105. png_debug(1, "in png_write_start_row\n");
  202106. buf_size = (png_size_t)(PNG_ROWBYTES(
  202107. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202108. /* set up row buffer */
  202109. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202110. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202111. #ifndef PNG_NO_WRITE_FILTERING
  202112. /* set up filtering buffer, if using this filter */
  202113. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202114. {
  202115. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202116. (png_ptr->rowbytes + 1));
  202117. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202118. }
  202119. /* We only need to keep the previous row if we are using one of these. */
  202120. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202121. {
  202122. /* set up previous row buffer */
  202123. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202124. png_memset(png_ptr->prev_row, 0, buf_size);
  202125. if (png_ptr->do_filter & PNG_FILTER_UP)
  202126. {
  202127. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202128. (png_ptr->rowbytes + 1));
  202129. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202130. }
  202131. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202132. {
  202133. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202134. (png_ptr->rowbytes + 1));
  202135. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202136. }
  202137. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202138. {
  202139. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202140. (png_ptr->rowbytes + 1));
  202141. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202142. }
  202143. #endif /* PNG_NO_WRITE_FILTERING */
  202144. }
  202145. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202146. /* if interlaced, we need to set up width and height of pass */
  202147. if (png_ptr->interlaced)
  202148. {
  202149. if (!(png_ptr->transformations & PNG_INTERLACE))
  202150. {
  202151. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202152. png_pass_ystart[0]) / png_pass_yinc[0];
  202153. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202154. png_pass_start[0]) / png_pass_inc[0];
  202155. }
  202156. else
  202157. {
  202158. png_ptr->num_rows = png_ptr->height;
  202159. png_ptr->usr_width = png_ptr->width;
  202160. }
  202161. }
  202162. else
  202163. #endif
  202164. {
  202165. png_ptr->num_rows = png_ptr->height;
  202166. png_ptr->usr_width = png_ptr->width;
  202167. }
  202168. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202169. png_ptr->zstream.next_out = png_ptr->zbuf;
  202170. }
  202171. /* Internal use only. Called when finished processing a row of data. */
  202172. void /* PRIVATE */
  202173. png_write_finish_row(png_structp png_ptr)
  202174. {
  202175. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202176. #ifdef PNG_USE_LOCAL_ARRAYS
  202177. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202178. /* start of interlace block */
  202179. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202180. /* offset to next interlace block */
  202181. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202182. /* start of interlace block in the y direction */
  202183. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202184. /* offset to next interlace block in the y direction */
  202185. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202186. #endif
  202187. #endif
  202188. int ret;
  202189. png_debug(1, "in png_write_finish_row\n");
  202190. /* next row */
  202191. png_ptr->row_number++;
  202192. /* see if we are done */
  202193. if (png_ptr->row_number < png_ptr->num_rows)
  202194. return;
  202195. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202196. /* if interlaced, go to next pass */
  202197. if (png_ptr->interlaced)
  202198. {
  202199. png_ptr->row_number = 0;
  202200. if (png_ptr->transformations & PNG_INTERLACE)
  202201. {
  202202. png_ptr->pass++;
  202203. }
  202204. else
  202205. {
  202206. /* loop until we find a non-zero width or height pass */
  202207. do
  202208. {
  202209. png_ptr->pass++;
  202210. if (png_ptr->pass >= 7)
  202211. break;
  202212. png_ptr->usr_width = (png_ptr->width +
  202213. png_pass_inc[png_ptr->pass] - 1 -
  202214. png_pass_start[png_ptr->pass]) /
  202215. png_pass_inc[png_ptr->pass];
  202216. png_ptr->num_rows = (png_ptr->height +
  202217. png_pass_yinc[png_ptr->pass] - 1 -
  202218. png_pass_ystart[png_ptr->pass]) /
  202219. png_pass_yinc[png_ptr->pass];
  202220. if (png_ptr->transformations & PNG_INTERLACE)
  202221. break;
  202222. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202223. }
  202224. /* reset the row above the image for the next pass */
  202225. if (png_ptr->pass < 7)
  202226. {
  202227. if (png_ptr->prev_row != NULL)
  202228. png_memset(png_ptr->prev_row, 0,
  202229. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202230. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202231. return;
  202232. }
  202233. }
  202234. #endif
  202235. /* if we get here, we've just written the last row, so we need
  202236. to flush the compressor */
  202237. do
  202238. {
  202239. /* tell the compressor we are done */
  202240. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202241. /* check for an error */
  202242. if (ret == Z_OK)
  202243. {
  202244. /* check to see if we need more room */
  202245. if (!(png_ptr->zstream.avail_out))
  202246. {
  202247. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202248. png_ptr->zstream.next_out = png_ptr->zbuf;
  202249. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202250. }
  202251. }
  202252. else if (ret != Z_STREAM_END)
  202253. {
  202254. if (png_ptr->zstream.msg != NULL)
  202255. png_error(png_ptr, png_ptr->zstream.msg);
  202256. else
  202257. png_error(png_ptr, "zlib error");
  202258. }
  202259. } while (ret != Z_STREAM_END);
  202260. /* write any extra space */
  202261. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202262. {
  202263. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202264. png_ptr->zstream.avail_out);
  202265. }
  202266. deflateReset(&png_ptr->zstream);
  202267. png_ptr->zstream.data_type = Z_BINARY;
  202268. }
  202269. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202270. /* Pick out the correct pixels for the interlace pass.
  202271. * The basic idea here is to go through the row with a source
  202272. * pointer and a destination pointer (sp and dp), and copy the
  202273. * correct pixels for the pass. As the row gets compacted,
  202274. * sp will always be >= dp, so we should never overwrite anything.
  202275. * See the default: case for the easiest code to understand.
  202276. */
  202277. void /* PRIVATE */
  202278. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202279. {
  202280. #ifdef PNG_USE_LOCAL_ARRAYS
  202281. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202282. /* start of interlace block */
  202283. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202284. /* offset to next interlace block */
  202285. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202286. #endif
  202287. png_debug(1, "in png_do_write_interlace\n");
  202288. /* we don't have to do anything on the last pass (6) */
  202289. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202290. if (row != NULL && row_info != NULL && pass < 6)
  202291. #else
  202292. if (pass < 6)
  202293. #endif
  202294. {
  202295. /* each pixel depth is handled separately */
  202296. switch (row_info->pixel_depth)
  202297. {
  202298. case 1:
  202299. {
  202300. png_bytep sp;
  202301. png_bytep dp;
  202302. int shift;
  202303. int d;
  202304. int value;
  202305. png_uint_32 i;
  202306. png_uint_32 row_width = row_info->width;
  202307. dp = row;
  202308. d = 0;
  202309. shift = 7;
  202310. for (i = png_pass_start[pass]; i < row_width;
  202311. i += png_pass_inc[pass])
  202312. {
  202313. sp = row + (png_size_t)(i >> 3);
  202314. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202315. d |= (value << shift);
  202316. if (shift == 0)
  202317. {
  202318. shift = 7;
  202319. *dp++ = (png_byte)d;
  202320. d = 0;
  202321. }
  202322. else
  202323. shift--;
  202324. }
  202325. if (shift != 7)
  202326. *dp = (png_byte)d;
  202327. break;
  202328. }
  202329. case 2:
  202330. {
  202331. png_bytep sp;
  202332. png_bytep dp;
  202333. int shift;
  202334. int d;
  202335. int value;
  202336. png_uint_32 i;
  202337. png_uint_32 row_width = row_info->width;
  202338. dp = row;
  202339. shift = 6;
  202340. d = 0;
  202341. for (i = png_pass_start[pass]; i < row_width;
  202342. i += png_pass_inc[pass])
  202343. {
  202344. sp = row + (png_size_t)(i >> 2);
  202345. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202346. d |= (value << shift);
  202347. if (shift == 0)
  202348. {
  202349. shift = 6;
  202350. *dp++ = (png_byte)d;
  202351. d = 0;
  202352. }
  202353. else
  202354. shift -= 2;
  202355. }
  202356. if (shift != 6)
  202357. *dp = (png_byte)d;
  202358. break;
  202359. }
  202360. case 4:
  202361. {
  202362. png_bytep sp;
  202363. png_bytep dp;
  202364. int shift;
  202365. int d;
  202366. int value;
  202367. png_uint_32 i;
  202368. png_uint_32 row_width = row_info->width;
  202369. dp = row;
  202370. shift = 4;
  202371. d = 0;
  202372. for (i = png_pass_start[pass]; i < row_width;
  202373. i += png_pass_inc[pass])
  202374. {
  202375. sp = row + (png_size_t)(i >> 1);
  202376. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202377. d |= (value << shift);
  202378. if (shift == 0)
  202379. {
  202380. shift = 4;
  202381. *dp++ = (png_byte)d;
  202382. d = 0;
  202383. }
  202384. else
  202385. shift -= 4;
  202386. }
  202387. if (shift != 4)
  202388. *dp = (png_byte)d;
  202389. break;
  202390. }
  202391. default:
  202392. {
  202393. png_bytep sp;
  202394. png_bytep dp;
  202395. png_uint_32 i;
  202396. png_uint_32 row_width = row_info->width;
  202397. png_size_t pixel_bytes;
  202398. /* start at the beginning */
  202399. dp = row;
  202400. /* find out how many bytes each pixel takes up */
  202401. pixel_bytes = (row_info->pixel_depth >> 3);
  202402. /* loop through the row, only looking at the pixels that
  202403. matter */
  202404. for (i = png_pass_start[pass]; i < row_width;
  202405. i += png_pass_inc[pass])
  202406. {
  202407. /* find out where the original pixel is */
  202408. sp = row + (png_size_t)i * pixel_bytes;
  202409. /* move the pixel */
  202410. if (dp != sp)
  202411. png_memcpy(dp, sp, pixel_bytes);
  202412. /* next pixel */
  202413. dp += pixel_bytes;
  202414. }
  202415. break;
  202416. }
  202417. }
  202418. /* set new row width */
  202419. row_info->width = (row_info->width +
  202420. png_pass_inc[pass] - 1 -
  202421. png_pass_start[pass]) /
  202422. png_pass_inc[pass];
  202423. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202424. row_info->width);
  202425. }
  202426. }
  202427. #endif
  202428. /* This filters the row, chooses which filter to use, if it has not already
  202429. * been specified by the application, and then writes the row out with the
  202430. * chosen filter.
  202431. */
  202432. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202433. #define PNG_HISHIFT 10
  202434. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202435. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202436. void /* PRIVATE */
  202437. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202438. {
  202439. png_bytep best_row;
  202440. #ifndef PNG_NO_WRITE_FILTER
  202441. png_bytep prev_row, row_buf;
  202442. png_uint_32 mins, bpp;
  202443. png_byte filter_to_do = png_ptr->do_filter;
  202444. png_uint_32 row_bytes = row_info->rowbytes;
  202445. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202446. int num_p_filters = (int)png_ptr->num_prev_filters;
  202447. #endif
  202448. png_debug(1, "in png_write_find_filter\n");
  202449. /* find out how many bytes offset each pixel is */
  202450. bpp = (row_info->pixel_depth + 7) >> 3;
  202451. prev_row = png_ptr->prev_row;
  202452. #endif
  202453. best_row = png_ptr->row_buf;
  202454. #ifndef PNG_NO_WRITE_FILTER
  202455. row_buf = best_row;
  202456. mins = PNG_MAXSUM;
  202457. /* The prediction method we use is to find which method provides the
  202458. * smallest value when summing the absolute values of the distances
  202459. * from zero, using anything >= 128 as negative numbers. This is known
  202460. * as the "minimum sum of absolute differences" heuristic. Other
  202461. * heuristics are the "weighted minimum sum of absolute differences"
  202462. * (experimental and can in theory improve compression), and the "zlib
  202463. * predictive" method (not implemented yet), which does test compressions
  202464. * of lines using different filter methods, and then chooses the
  202465. * (series of) filter(s) that give minimum compressed data size (VERY
  202466. * computationally expensive).
  202467. *
  202468. * GRR 980525: consider also
  202469. * (1) minimum sum of absolute differences from running average (i.e.,
  202470. * keep running sum of non-absolute differences & count of bytes)
  202471. * [track dispersion, too? restart average if dispersion too large?]
  202472. * (1b) minimum sum of absolute differences from sliding average, probably
  202473. * with window size <= deflate window (usually 32K)
  202474. * (2) minimum sum of squared differences from zero or running average
  202475. * (i.e., ~ root-mean-square approach)
  202476. */
  202477. /* We don't need to test the 'no filter' case if this is the only filter
  202478. * that has been chosen, as it doesn't actually do anything to the data.
  202479. */
  202480. if ((filter_to_do & PNG_FILTER_NONE) &&
  202481. filter_to_do != PNG_FILTER_NONE)
  202482. {
  202483. png_bytep rp;
  202484. png_uint_32 sum = 0;
  202485. png_uint_32 i;
  202486. int v;
  202487. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202488. {
  202489. v = *rp;
  202490. sum += (v < 128) ? v : 256 - v;
  202491. }
  202492. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202493. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202494. {
  202495. png_uint_32 sumhi, sumlo;
  202496. int j;
  202497. sumlo = sum & PNG_LOMASK;
  202498. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202499. /* Reduce the sum if we match any of the previous rows */
  202500. for (j = 0; j < num_p_filters; j++)
  202501. {
  202502. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202503. {
  202504. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202505. PNG_WEIGHT_SHIFT;
  202506. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202507. PNG_WEIGHT_SHIFT;
  202508. }
  202509. }
  202510. /* Factor in the cost of this filter (this is here for completeness,
  202511. * but it makes no sense to have a "cost" for the NONE filter, as
  202512. * it has the minimum possible computational cost - none).
  202513. */
  202514. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202515. PNG_COST_SHIFT;
  202516. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202517. PNG_COST_SHIFT;
  202518. if (sumhi > PNG_HIMASK)
  202519. sum = PNG_MAXSUM;
  202520. else
  202521. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202522. }
  202523. #endif
  202524. mins = sum;
  202525. }
  202526. /* sub filter */
  202527. if (filter_to_do == PNG_FILTER_SUB)
  202528. /* it's the only filter so no testing is needed */
  202529. {
  202530. png_bytep rp, lp, dp;
  202531. png_uint_32 i;
  202532. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202533. i++, rp++, dp++)
  202534. {
  202535. *dp = *rp;
  202536. }
  202537. for (lp = row_buf + 1; i < row_bytes;
  202538. i++, rp++, lp++, dp++)
  202539. {
  202540. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202541. }
  202542. best_row = png_ptr->sub_row;
  202543. }
  202544. else if (filter_to_do & PNG_FILTER_SUB)
  202545. {
  202546. png_bytep rp, dp, lp;
  202547. png_uint_32 sum = 0, lmins = mins;
  202548. png_uint_32 i;
  202549. int v;
  202550. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202551. /* We temporarily increase the "minimum sum" by the factor we
  202552. * would reduce the sum of this filter, so that we can do the
  202553. * early exit comparison without scaling the sum each time.
  202554. */
  202555. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202556. {
  202557. int j;
  202558. png_uint_32 lmhi, lmlo;
  202559. lmlo = lmins & PNG_LOMASK;
  202560. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202561. for (j = 0; j < num_p_filters; j++)
  202562. {
  202563. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202564. {
  202565. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202566. PNG_WEIGHT_SHIFT;
  202567. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202568. PNG_WEIGHT_SHIFT;
  202569. }
  202570. }
  202571. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202572. PNG_COST_SHIFT;
  202573. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202574. PNG_COST_SHIFT;
  202575. if (lmhi > PNG_HIMASK)
  202576. lmins = PNG_MAXSUM;
  202577. else
  202578. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202579. }
  202580. #endif
  202581. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202582. i++, rp++, dp++)
  202583. {
  202584. v = *dp = *rp;
  202585. sum += (v < 128) ? v : 256 - v;
  202586. }
  202587. for (lp = row_buf + 1; i < row_bytes;
  202588. i++, rp++, lp++, dp++)
  202589. {
  202590. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202591. sum += (v < 128) ? v : 256 - v;
  202592. if (sum > lmins) /* We are already worse, don't continue. */
  202593. break;
  202594. }
  202595. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202596. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202597. {
  202598. int j;
  202599. png_uint_32 sumhi, sumlo;
  202600. sumlo = sum & PNG_LOMASK;
  202601. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202602. for (j = 0; j < num_p_filters; j++)
  202603. {
  202604. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202605. {
  202606. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202607. PNG_WEIGHT_SHIFT;
  202608. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202609. PNG_WEIGHT_SHIFT;
  202610. }
  202611. }
  202612. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202613. PNG_COST_SHIFT;
  202614. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202615. PNG_COST_SHIFT;
  202616. if (sumhi > PNG_HIMASK)
  202617. sum = PNG_MAXSUM;
  202618. else
  202619. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202620. }
  202621. #endif
  202622. if (sum < mins)
  202623. {
  202624. mins = sum;
  202625. best_row = png_ptr->sub_row;
  202626. }
  202627. }
  202628. /* up filter */
  202629. if (filter_to_do == PNG_FILTER_UP)
  202630. {
  202631. png_bytep rp, dp, pp;
  202632. png_uint_32 i;
  202633. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202634. pp = prev_row + 1; i < row_bytes;
  202635. i++, rp++, pp++, dp++)
  202636. {
  202637. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202638. }
  202639. best_row = png_ptr->up_row;
  202640. }
  202641. else if (filter_to_do & PNG_FILTER_UP)
  202642. {
  202643. png_bytep rp, dp, pp;
  202644. png_uint_32 sum = 0, lmins = mins;
  202645. png_uint_32 i;
  202646. int v;
  202647. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202648. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202649. {
  202650. int j;
  202651. png_uint_32 lmhi, lmlo;
  202652. lmlo = lmins & PNG_LOMASK;
  202653. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202654. for (j = 0; j < num_p_filters; j++)
  202655. {
  202656. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202657. {
  202658. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202659. PNG_WEIGHT_SHIFT;
  202660. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202661. PNG_WEIGHT_SHIFT;
  202662. }
  202663. }
  202664. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202665. PNG_COST_SHIFT;
  202666. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202667. PNG_COST_SHIFT;
  202668. if (lmhi > PNG_HIMASK)
  202669. lmins = PNG_MAXSUM;
  202670. else
  202671. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202672. }
  202673. #endif
  202674. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202675. pp = prev_row + 1; i < row_bytes; i++)
  202676. {
  202677. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202678. sum += (v < 128) ? v : 256 - v;
  202679. if (sum > lmins) /* We are already worse, don't continue. */
  202680. break;
  202681. }
  202682. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202683. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202684. {
  202685. int j;
  202686. png_uint_32 sumhi, sumlo;
  202687. sumlo = sum & PNG_LOMASK;
  202688. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202689. for (j = 0; j < num_p_filters; j++)
  202690. {
  202691. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202692. {
  202693. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202694. PNG_WEIGHT_SHIFT;
  202695. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202696. PNG_WEIGHT_SHIFT;
  202697. }
  202698. }
  202699. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202700. PNG_COST_SHIFT;
  202701. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202702. PNG_COST_SHIFT;
  202703. if (sumhi > PNG_HIMASK)
  202704. sum = PNG_MAXSUM;
  202705. else
  202706. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202707. }
  202708. #endif
  202709. if (sum < mins)
  202710. {
  202711. mins = sum;
  202712. best_row = png_ptr->up_row;
  202713. }
  202714. }
  202715. /* avg filter */
  202716. if (filter_to_do == PNG_FILTER_AVG)
  202717. {
  202718. png_bytep rp, dp, pp, lp;
  202719. png_uint_32 i;
  202720. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202721. pp = prev_row + 1; i < bpp; i++)
  202722. {
  202723. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202724. }
  202725. for (lp = row_buf + 1; i < row_bytes; i++)
  202726. {
  202727. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202728. & 0xff);
  202729. }
  202730. best_row = png_ptr->avg_row;
  202731. }
  202732. else if (filter_to_do & PNG_FILTER_AVG)
  202733. {
  202734. png_bytep rp, dp, pp, lp;
  202735. png_uint_32 sum = 0, lmins = mins;
  202736. png_uint_32 i;
  202737. int v;
  202738. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202739. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202740. {
  202741. int j;
  202742. png_uint_32 lmhi, lmlo;
  202743. lmlo = lmins & PNG_LOMASK;
  202744. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202745. for (j = 0; j < num_p_filters; j++)
  202746. {
  202747. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202748. {
  202749. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202750. PNG_WEIGHT_SHIFT;
  202751. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202752. PNG_WEIGHT_SHIFT;
  202753. }
  202754. }
  202755. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202756. PNG_COST_SHIFT;
  202757. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202758. PNG_COST_SHIFT;
  202759. if (lmhi > PNG_HIMASK)
  202760. lmins = PNG_MAXSUM;
  202761. else
  202762. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202763. }
  202764. #endif
  202765. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202766. pp = prev_row + 1; i < bpp; i++)
  202767. {
  202768. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202769. sum += (v < 128) ? v : 256 - v;
  202770. }
  202771. for (lp = row_buf + 1; i < row_bytes; i++)
  202772. {
  202773. v = *dp++ =
  202774. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202775. sum += (v < 128) ? v : 256 - v;
  202776. if (sum > lmins) /* We are already worse, don't continue. */
  202777. break;
  202778. }
  202779. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202780. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202781. {
  202782. int j;
  202783. png_uint_32 sumhi, sumlo;
  202784. sumlo = sum & PNG_LOMASK;
  202785. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202786. for (j = 0; j < num_p_filters; j++)
  202787. {
  202788. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202789. {
  202790. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202791. PNG_WEIGHT_SHIFT;
  202792. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202793. PNG_WEIGHT_SHIFT;
  202794. }
  202795. }
  202796. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202797. PNG_COST_SHIFT;
  202798. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202799. PNG_COST_SHIFT;
  202800. if (sumhi > PNG_HIMASK)
  202801. sum = PNG_MAXSUM;
  202802. else
  202803. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202804. }
  202805. #endif
  202806. if (sum < mins)
  202807. {
  202808. mins = sum;
  202809. best_row = png_ptr->avg_row;
  202810. }
  202811. }
  202812. /* Paeth filter */
  202813. if (filter_to_do == PNG_FILTER_PAETH)
  202814. {
  202815. png_bytep rp, dp, pp, cp, lp;
  202816. png_uint_32 i;
  202817. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202818. pp = prev_row + 1; i < bpp; i++)
  202819. {
  202820. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202821. }
  202822. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202823. {
  202824. int a, b, c, pa, pb, pc, p;
  202825. b = *pp++;
  202826. c = *cp++;
  202827. a = *lp++;
  202828. p = b - c;
  202829. pc = a - c;
  202830. #ifdef PNG_USE_ABS
  202831. pa = abs(p);
  202832. pb = abs(pc);
  202833. pc = abs(p + pc);
  202834. #else
  202835. pa = p < 0 ? -p : p;
  202836. pb = pc < 0 ? -pc : pc;
  202837. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202838. #endif
  202839. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202840. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202841. }
  202842. best_row = png_ptr->paeth_row;
  202843. }
  202844. else if (filter_to_do & PNG_FILTER_PAETH)
  202845. {
  202846. png_bytep rp, dp, pp, cp, lp;
  202847. png_uint_32 sum = 0, lmins = mins;
  202848. png_uint_32 i;
  202849. int v;
  202850. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202851. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202852. {
  202853. int j;
  202854. png_uint_32 lmhi, lmlo;
  202855. lmlo = lmins & PNG_LOMASK;
  202856. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202857. for (j = 0; j < num_p_filters; j++)
  202858. {
  202859. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202860. {
  202861. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202862. PNG_WEIGHT_SHIFT;
  202863. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202864. PNG_WEIGHT_SHIFT;
  202865. }
  202866. }
  202867. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202868. PNG_COST_SHIFT;
  202869. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202870. PNG_COST_SHIFT;
  202871. if (lmhi > PNG_HIMASK)
  202872. lmins = PNG_MAXSUM;
  202873. else
  202874. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202875. }
  202876. #endif
  202877. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202878. pp = prev_row + 1; i < bpp; i++)
  202879. {
  202880. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202881. sum += (v < 128) ? v : 256 - v;
  202882. }
  202883. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202884. {
  202885. int a, b, c, pa, pb, pc, p;
  202886. b = *pp++;
  202887. c = *cp++;
  202888. a = *lp++;
  202889. #ifndef PNG_SLOW_PAETH
  202890. p = b - c;
  202891. pc = a - c;
  202892. #ifdef PNG_USE_ABS
  202893. pa = abs(p);
  202894. pb = abs(pc);
  202895. pc = abs(p + pc);
  202896. #else
  202897. pa = p < 0 ? -p : p;
  202898. pb = pc < 0 ? -pc : pc;
  202899. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202900. #endif
  202901. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202902. #else /* PNG_SLOW_PAETH */
  202903. p = a + b - c;
  202904. pa = abs(p - a);
  202905. pb = abs(p - b);
  202906. pc = abs(p - c);
  202907. if (pa <= pb && pa <= pc)
  202908. p = a;
  202909. else if (pb <= pc)
  202910. p = b;
  202911. else
  202912. p = c;
  202913. #endif /* PNG_SLOW_PAETH */
  202914. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202915. sum += (v < 128) ? v : 256 - v;
  202916. if (sum > lmins) /* We are already worse, don't continue. */
  202917. break;
  202918. }
  202919. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202920. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202921. {
  202922. int j;
  202923. png_uint_32 sumhi, sumlo;
  202924. sumlo = sum & PNG_LOMASK;
  202925. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202926. for (j = 0; j < num_p_filters; j++)
  202927. {
  202928. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202929. {
  202930. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202931. PNG_WEIGHT_SHIFT;
  202932. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202933. PNG_WEIGHT_SHIFT;
  202934. }
  202935. }
  202936. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202937. PNG_COST_SHIFT;
  202938. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202939. PNG_COST_SHIFT;
  202940. if (sumhi > PNG_HIMASK)
  202941. sum = PNG_MAXSUM;
  202942. else
  202943. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202944. }
  202945. #endif
  202946. if (sum < mins)
  202947. {
  202948. best_row = png_ptr->paeth_row;
  202949. }
  202950. }
  202951. #endif /* PNG_NO_WRITE_FILTER */
  202952. /* Do the actual writing of the filtered row data from the chosen filter. */
  202953. png_write_filtered_row(png_ptr, best_row);
  202954. #ifndef PNG_NO_WRITE_FILTER
  202955. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202956. /* Save the type of filter we picked this time for future calculations */
  202957. if (png_ptr->num_prev_filters > 0)
  202958. {
  202959. int j;
  202960. for (j = 1; j < num_p_filters; j++)
  202961. {
  202962. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202963. }
  202964. png_ptr->prev_filters[j] = best_row[0];
  202965. }
  202966. #endif
  202967. #endif /* PNG_NO_WRITE_FILTER */
  202968. }
  202969. /* Do the actual writing of a previously filtered row. */
  202970. void /* PRIVATE */
  202971. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202972. {
  202973. png_debug(1, "in png_write_filtered_row\n");
  202974. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202975. /* set up the zlib input buffer */
  202976. png_ptr->zstream.next_in = filtered_row;
  202977. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202978. /* repeat until we have compressed all the data */
  202979. do
  202980. {
  202981. int ret; /* return of zlib */
  202982. /* compress the data */
  202983. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202984. /* check for compression errors */
  202985. if (ret != Z_OK)
  202986. {
  202987. if (png_ptr->zstream.msg != NULL)
  202988. png_error(png_ptr, png_ptr->zstream.msg);
  202989. else
  202990. png_error(png_ptr, "zlib error");
  202991. }
  202992. /* see if it is time to write another IDAT */
  202993. if (!(png_ptr->zstream.avail_out))
  202994. {
  202995. /* write the IDAT and reset the zlib output buffer */
  202996. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202997. png_ptr->zstream.next_out = png_ptr->zbuf;
  202998. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202999. }
  203000. /* repeat until all data has been compressed */
  203001. } while (png_ptr->zstream.avail_in);
  203002. /* swap the current and previous rows */
  203003. if (png_ptr->prev_row != NULL)
  203004. {
  203005. png_bytep tptr;
  203006. tptr = png_ptr->prev_row;
  203007. png_ptr->prev_row = png_ptr->row_buf;
  203008. png_ptr->row_buf = tptr;
  203009. }
  203010. /* finish row - updates counters and flushes zlib if last row */
  203011. png_write_finish_row(png_ptr);
  203012. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203013. png_ptr->flush_rows++;
  203014. if (png_ptr->flush_dist > 0 &&
  203015. png_ptr->flush_rows >= png_ptr->flush_dist)
  203016. {
  203017. png_write_flush(png_ptr);
  203018. }
  203019. #endif
  203020. }
  203021. #endif /* PNG_WRITE_SUPPORTED */
  203022. /*** End of inlined file: pngwutil.c ***/
  203023. #else
  203024. extern "C"
  203025. {
  203026. #include <png.h>
  203027. #include <pngconf.h>
  203028. }
  203029. #endif
  203030. }
  203031. #undef max
  203032. #undef min
  203033. #if JUCE_MSVC
  203034. #pragma warning (pop)
  203035. #endif
  203036. BEGIN_JUCE_NAMESPACE
  203037. using ::calloc;
  203038. using ::malloc;
  203039. using ::free;
  203040. namespace PNGHelpers
  203041. {
  203042. using namespace pnglibNamespace;
  203043. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203044. {
  203045. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203046. }
  203047. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203048. {
  203049. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203050. }
  203051. struct PNGErrorStruct {};
  203052. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203053. {
  203054. throw PNGErrorStruct();
  203055. }
  203056. }
  203057. PNGImageFormat::PNGImageFormat() {}
  203058. PNGImageFormat::~PNGImageFormat() {}
  203059. const String PNGImageFormat::getFormatName()
  203060. {
  203061. return "PNG";
  203062. }
  203063. bool PNGImageFormat::canUnderstand (InputStream& in)
  203064. {
  203065. const int bytesNeeded = 4;
  203066. char header [bytesNeeded];
  203067. return in.read (header, bytesNeeded) == bytesNeeded
  203068. && header[1] == 'P'
  203069. && header[2] == 'N'
  203070. && header[3] == 'G';
  203071. }
  203072. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203073. const Image juce_loadWithCoreImage (InputStream& input);
  203074. #endif
  203075. const Image PNGImageFormat::decodeImage (InputStream& in)
  203076. {
  203077. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203078. return juce_loadWithCoreImage (in);
  203079. #else
  203080. using namespace pnglibNamespace;
  203081. Image image;
  203082. png_structp pngReadStruct;
  203083. png_infop pngInfoStruct;
  203084. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203085. if (pngReadStruct != 0)
  203086. {
  203087. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203088. if (pngInfoStruct == 0)
  203089. {
  203090. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203091. return Image::null;
  203092. }
  203093. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203094. // read the header..
  203095. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203096. png_uint_32 width, height;
  203097. int bitDepth, colorType, interlaceType;
  203098. png_read_info (pngReadStruct, pngInfoStruct);
  203099. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203100. &width, &height,
  203101. &bitDepth, &colorType,
  203102. &interlaceType, 0, 0);
  203103. if (bitDepth == 16)
  203104. png_set_strip_16 (pngReadStruct);
  203105. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203106. png_set_expand (pngReadStruct);
  203107. if (bitDepth < 8)
  203108. png_set_expand (pngReadStruct);
  203109. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203110. png_set_expand (pngReadStruct);
  203111. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203112. png_set_gray_to_rgb (pngReadStruct);
  203113. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203114. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203115. || pngInfoStruct->num_trans > 0;
  203116. // Load the image into a temp buffer in the pnglib format..
  203117. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203118. {
  203119. HeapBlock <png_bytep> rows (height);
  203120. for (int y = (int) height; --y >= 0;)
  203121. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203122. png_read_image (pngReadStruct, rows);
  203123. png_read_end (pngReadStruct, pngInfoStruct);
  203124. }
  203125. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203126. // now convert the data to a juce image format..
  203127. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203128. (int) width, (int) height, hasAlphaChan);
  203129. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203130. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203131. const Image::BitmapData destData (image, true);
  203132. uint8* srcRow = tempBuffer;
  203133. uint8* destRow = destData.data;
  203134. for (int y = 0; y < (int) height; ++y)
  203135. {
  203136. const uint8* src = srcRow;
  203137. srcRow += (width << 2);
  203138. uint8* dest = destRow;
  203139. destRow += destData.lineStride;
  203140. if (hasAlphaChan)
  203141. {
  203142. for (int i = (int) width; --i >= 0;)
  203143. {
  203144. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203145. ((PixelARGB*) dest)->premultiply();
  203146. dest += destData.pixelStride;
  203147. src += 4;
  203148. }
  203149. }
  203150. else
  203151. {
  203152. for (int i = (int) width; --i >= 0;)
  203153. {
  203154. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203155. dest += destData.pixelStride;
  203156. src += 4;
  203157. }
  203158. }
  203159. }
  203160. }
  203161. return image;
  203162. #endif
  203163. }
  203164. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203165. {
  203166. using namespace pnglibNamespace;
  203167. const int width = image.getWidth();
  203168. const int height = image.getHeight();
  203169. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203170. if (pngWriteStruct == 0)
  203171. return false;
  203172. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203173. if (pngInfoStruct == 0)
  203174. {
  203175. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203176. return false;
  203177. }
  203178. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203179. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203180. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203181. : PNG_COLOR_TYPE_RGB,
  203182. PNG_INTERLACE_NONE,
  203183. PNG_COMPRESSION_TYPE_BASE,
  203184. PNG_FILTER_TYPE_BASE);
  203185. HeapBlock <uint8> rowData (width * 4);
  203186. png_color_8 sig_bit;
  203187. sig_bit.red = 8;
  203188. sig_bit.green = 8;
  203189. sig_bit.blue = 8;
  203190. sig_bit.alpha = 8;
  203191. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203192. png_write_info (pngWriteStruct, pngInfoStruct);
  203193. png_set_shift (pngWriteStruct, &sig_bit);
  203194. png_set_packing (pngWriteStruct);
  203195. const Image::BitmapData srcData (image, false);
  203196. for (int y = 0; y < height; ++y)
  203197. {
  203198. uint8* dst = rowData;
  203199. const uint8* src = srcData.getLinePointer (y);
  203200. if (image.hasAlphaChannel())
  203201. {
  203202. for (int i = width; --i >= 0;)
  203203. {
  203204. PixelARGB p (*(const PixelARGB*) src);
  203205. p.unpremultiply();
  203206. *dst++ = p.getRed();
  203207. *dst++ = p.getGreen();
  203208. *dst++ = p.getBlue();
  203209. *dst++ = p.getAlpha();
  203210. src += srcData.pixelStride;
  203211. }
  203212. }
  203213. else
  203214. {
  203215. for (int i = width; --i >= 0;)
  203216. {
  203217. *dst++ = ((const PixelRGB*) src)->getRed();
  203218. *dst++ = ((const PixelRGB*) src)->getGreen();
  203219. *dst++ = ((const PixelRGB*) src)->getBlue();
  203220. src += srcData.pixelStride;
  203221. }
  203222. }
  203223. png_bytep rowPtr = rowData;
  203224. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203225. }
  203226. png_write_end (pngWriteStruct, pngInfoStruct);
  203227. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203228. out.flush();
  203229. return true;
  203230. }
  203231. END_JUCE_NAMESPACE
  203232. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203233. #endif
  203234. //==============================================================================
  203235. #if JUCE_BUILD_NATIVE
  203236. // Non-public headers that are needed by more than one platform must be included
  203237. // before the platform-specific sections..
  203238. BEGIN_JUCE_NAMESPACE
  203239. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203240. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203241. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203242. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203243. /**
  203244. Helper class that takes chunks of incoming midi bytes, packages them into
  203245. messages, and dispatches them to a midi callback.
  203246. */
  203247. class MidiDataConcatenator
  203248. {
  203249. public:
  203250. MidiDataConcatenator (const int initialBufferSize)
  203251. : pendingData (initialBufferSize),
  203252. pendingBytes (0), pendingDataTime (0)
  203253. {
  203254. }
  203255. void reset()
  203256. {
  203257. pendingBytes = 0;
  203258. pendingDataTime = 0;
  203259. }
  203260. void pushMidiData (const void* data, int numBytes, double time,
  203261. MidiInput* input, MidiInputCallback& callback)
  203262. {
  203263. const uint8* d = static_cast <const uint8*> (data);
  203264. while (numBytes > 0)
  203265. {
  203266. if (pendingBytes > 0 || d[0] == 0xf0)
  203267. {
  203268. processSysex (d, numBytes, time, input, callback);
  203269. }
  203270. else
  203271. {
  203272. int used = 0;
  203273. const MidiMessage m (d, numBytes, used, 0, time);
  203274. if (used <= 0)
  203275. break; // malformed message..
  203276. callback.handleIncomingMidiMessage (input, m);
  203277. numBytes -= used;
  203278. d += used;
  203279. }
  203280. }
  203281. }
  203282. private:
  203283. void processSysex (const uint8*& d, int& numBytes, double time,
  203284. MidiInput* input, MidiInputCallback& callback)
  203285. {
  203286. if (*d == 0xf0)
  203287. {
  203288. pendingBytes = 0;
  203289. pendingDataTime = time;
  203290. }
  203291. pendingData.ensureSize (pendingBytes + numBytes, false);
  203292. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203293. uint8* dest = totalMessage + pendingBytes;
  203294. do
  203295. {
  203296. if (pendingBytes > 0 && *d >= 0x80)
  203297. {
  203298. if (*d >= 0xfa || *d == 0xf8)
  203299. {
  203300. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203301. ++d;
  203302. --numBytes;
  203303. }
  203304. else
  203305. {
  203306. if (*d == 0xf7)
  203307. {
  203308. *dest++ = *d++;
  203309. pendingBytes++;
  203310. --numBytes;
  203311. }
  203312. break;
  203313. }
  203314. }
  203315. else
  203316. {
  203317. *dest++ = *d++;
  203318. pendingBytes++;
  203319. --numBytes;
  203320. }
  203321. }
  203322. while (numBytes > 0);
  203323. if (pendingBytes > 0)
  203324. {
  203325. if (totalMessage [pendingBytes - 1] == 0xf7)
  203326. {
  203327. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203328. pendingBytes = 0;
  203329. }
  203330. else
  203331. {
  203332. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203333. }
  203334. }
  203335. }
  203336. MemoryBlock pendingData;
  203337. int pendingBytes;
  203338. double pendingDataTime;
  203339. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203340. };
  203341. #endif
  203342. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203343. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203344. END_JUCE_NAMESPACE
  203345. #if JUCE_WINDOWS
  203346. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203347. /*
  203348. This file wraps together all the win32-specific code, so that
  203349. we can include all the native headers just once, and compile all our
  203350. platform-specific stuff in one big lump, keeping it out of the way of
  203351. the rest of the codebase.
  203352. */
  203353. #if JUCE_WINDOWS
  203354. #undef JUCE_BUILD_NATIVE
  203355. #define JUCE_BUILD_NATIVE 1
  203356. BEGIN_JUCE_NAMESPACE
  203357. #define JUCE_INCLUDED_FILE 1
  203358. // Now include the actual code files..
  203359. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203360. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203361. // compiled on its own).
  203362. #if JUCE_INCLUDED_FILE
  203363. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203364. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203365. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203366. #ifndef DOXYGEN
  203367. // use with DynamicLibraryLoader to simplify importing functions
  203368. //
  203369. // functionName: function to import
  203370. // localFunctionName: name you want to use to actually call it (must be different)
  203371. // returnType: the return type
  203372. // object: the DynamicLibraryLoader to use
  203373. // params: list of params (bracketed)
  203374. //
  203375. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203376. typedef returnType (WINAPI *type##localFunctionName) params; \
  203377. type##localFunctionName localFunctionName \
  203378. = (type##localFunctionName)object.findProcAddress (#functionName);
  203379. // loads and unloads a DLL automatically
  203380. class JUCE_API DynamicLibraryLoader
  203381. {
  203382. public:
  203383. DynamicLibraryLoader (const String& name = String::empty);
  203384. ~DynamicLibraryLoader();
  203385. bool load (const String& libraryName);
  203386. void* findProcAddress (const String& functionName);
  203387. private:
  203388. void* libHandle;
  203389. };
  203390. #endif
  203391. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203392. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203393. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203394. : libHandle (0)
  203395. {
  203396. load (name);
  203397. }
  203398. DynamicLibraryLoader::~DynamicLibraryLoader()
  203399. {
  203400. load (String::empty);
  203401. }
  203402. bool DynamicLibraryLoader::load (const String& name)
  203403. {
  203404. FreeLibrary ((HMODULE) libHandle);
  203405. libHandle = name.isNotEmpty() ? LoadLibrary (name) : 0;
  203406. return libHandle != 0;
  203407. }
  203408. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203409. {
  203410. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203411. }
  203412. #endif
  203413. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203414. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203415. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203416. // compiled on its own).
  203417. #if JUCE_INCLUDED_FILE
  203418. void Logger::outputDebugString (const String& text)
  203419. {
  203420. OutputDebugString (text + "\n");
  203421. }
  203422. static int64 hiResTicksPerSecond;
  203423. static double hiResTicksScaleFactor;
  203424. #if JUCE_USE_INTRINSICS
  203425. // CPU info functions using intrinsics...
  203426. #pragma intrinsic (__cpuid)
  203427. #pragma intrinsic (__rdtsc)
  203428. const String SystemStats::getCpuVendor()
  203429. {
  203430. int info [4];
  203431. __cpuid (info, 0);
  203432. char v [12];
  203433. memcpy (v, info + 1, 4);
  203434. memcpy (v + 4, info + 3, 4);
  203435. memcpy (v + 8, info + 2, 4);
  203436. return String (v, 12);
  203437. }
  203438. #else
  203439. // CPU info functions using old fashioned inline asm...
  203440. static void juce_getCpuVendor (char* const v)
  203441. {
  203442. int vendor[4];
  203443. zeromem (vendor, 16);
  203444. #ifdef JUCE_64BIT
  203445. #else
  203446. #ifndef __MINGW32__
  203447. __try
  203448. #endif
  203449. {
  203450. #if JUCE_GCC
  203451. unsigned int dummy = 0;
  203452. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203453. #else
  203454. __asm
  203455. {
  203456. mov eax, 0
  203457. cpuid
  203458. mov [vendor], ebx
  203459. mov [vendor + 4], edx
  203460. mov [vendor + 8], ecx
  203461. }
  203462. #endif
  203463. }
  203464. #ifndef __MINGW32__
  203465. __except (EXCEPTION_EXECUTE_HANDLER)
  203466. {
  203467. *v = 0;
  203468. }
  203469. #endif
  203470. #endif
  203471. memcpy (v, vendor, 16);
  203472. }
  203473. const String SystemStats::getCpuVendor()
  203474. {
  203475. char v [16];
  203476. juce_getCpuVendor (v);
  203477. return String (v, 16);
  203478. }
  203479. #endif
  203480. void SystemStats::initialiseStats()
  203481. {
  203482. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203483. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203484. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203485. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203486. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203487. #else
  203488. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203489. #endif
  203490. {
  203491. SYSTEM_INFO systemInfo;
  203492. GetSystemInfo (&systemInfo);
  203493. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203494. }
  203495. LARGE_INTEGER f;
  203496. QueryPerformanceFrequency (&f);
  203497. hiResTicksPerSecond = f.QuadPart;
  203498. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203499. String s (SystemStats::getJUCEVersion());
  203500. const MMRESULT res = timeBeginPeriod (1);
  203501. (void) res;
  203502. jassert (res == TIMERR_NOERROR);
  203503. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203504. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203505. #endif
  203506. }
  203507. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203508. {
  203509. OSVERSIONINFO info;
  203510. info.dwOSVersionInfoSize = sizeof (info);
  203511. GetVersionEx (&info);
  203512. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203513. {
  203514. switch (info.dwMajorVersion)
  203515. {
  203516. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203517. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203518. default: jassertfalse; break; // !! not a supported OS!
  203519. }
  203520. }
  203521. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203522. {
  203523. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203524. return Win98;
  203525. }
  203526. return UnknownOS;
  203527. }
  203528. const String SystemStats::getOperatingSystemName()
  203529. {
  203530. const char* name = "Unknown OS";
  203531. switch (getOperatingSystemType())
  203532. {
  203533. case Windows7: name = "Windows 7"; break;
  203534. case WinVista: name = "Windows Vista"; break;
  203535. case WinXP: name = "Windows XP"; break;
  203536. case Win2000: name = "Windows 2000"; break;
  203537. case Win98: name = "Windows 98"; break;
  203538. default: jassertfalse; break; // !! new type of OS?
  203539. }
  203540. return name;
  203541. }
  203542. bool SystemStats::isOperatingSystem64Bit()
  203543. {
  203544. #ifdef _WIN64
  203545. return true;
  203546. #else
  203547. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203548. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203549. BOOL isWow64 = FALSE;
  203550. return (fnIsWow64Process != 0)
  203551. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203552. && (isWow64 != FALSE);
  203553. #endif
  203554. }
  203555. int SystemStats::getMemorySizeInMegabytes()
  203556. {
  203557. MEMORYSTATUSEX mem;
  203558. mem.dwLength = sizeof (mem);
  203559. GlobalMemoryStatusEx (&mem);
  203560. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203561. }
  203562. uint32 juce_millisecondsSinceStartup() throw()
  203563. {
  203564. return (uint32) timeGetTime();
  203565. }
  203566. int64 Time::getHighResolutionTicks() throw()
  203567. {
  203568. LARGE_INTEGER ticks;
  203569. QueryPerformanceCounter (&ticks);
  203570. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203571. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203572. // fix for a very obscure PCI hardware bug that can make the counter
  203573. // sometimes jump forwards by a few seconds..
  203574. static int64 hiResTicksOffset = 0;
  203575. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203576. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203577. hiResTicksOffset = newOffset;
  203578. return ticks.QuadPart + hiResTicksOffset;
  203579. }
  203580. double Time::getMillisecondCounterHiRes() throw()
  203581. {
  203582. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203583. }
  203584. int64 Time::getHighResolutionTicksPerSecond() throw()
  203585. {
  203586. return hiResTicksPerSecond;
  203587. }
  203588. static int64 juce_getClockCycleCounter() throw()
  203589. {
  203590. #if JUCE_USE_INTRINSICS
  203591. // MS intrinsics version...
  203592. return __rdtsc();
  203593. #elif JUCE_GCC
  203594. // GNU inline asm version...
  203595. unsigned int hi = 0, lo = 0;
  203596. __asm__ __volatile__ (
  203597. "xor %%eax, %%eax \n\
  203598. xor %%edx, %%edx \n\
  203599. rdtsc \n\
  203600. movl %%eax, %[lo] \n\
  203601. movl %%edx, %[hi]"
  203602. :
  203603. : [hi] "m" (hi),
  203604. [lo] "m" (lo)
  203605. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203606. return (int64) ((((uint64) hi) << 32) | lo);
  203607. #else
  203608. // MSVC inline asm version...
  203609. unsigned int hi = 0, lo = 0;
  203610. __asm
  203611. {
  203612. xor eax, eax
  203613. xor edx, edx
  203614. rdtsc
  203615. mov lo, eax
  203616. mov hi, edx
  203617. }
  203618. return (int64) ((((uint64) hi) << 32) | lo);
  203619. #endif
  203620. }
  203621. int SystemStats::getCpuSpeedInMegaherz()
  203622. {
  203623. const int64 cycles = juce_getClockCycleCounter();
  203624. const uint32 millis = Time::getMillisecondCounter();
  203625. int lastResult = 0;
  203626. for (;;)
  203627. {
  203628. int n = 1000000;
  203629. while (--n > 0) {}
  203630. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203631. const int64 cyclesNow = juce_getClockCycleCounter();
  203632. if (millisElapsed > 80)
  203633. {
  203634. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203635. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203636. return newResult;
  203637. lastResult = newResult;
  203638. }
  203639. }
  203640. }
  203641. bool Time::setSystemTimeToThisTime() const
  203642. {
  203643. SYSTEMTIME st;
  203644. st.wDayOfWeek = 0;
  203645. st.wYear = (WORD) getYear();
  203646. st.wMonth = (WORD) (getMonth() + 1);
  203647. st.wDay = (WORD) getDayOfMonth();
  203648. st.wHour = (WORD) getHours();
  203649. st.wMinute = (WORD) getMinutes();
  203650. st.wSecond = (WORD) getSeconds();
  203651. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203652. // do this twice because of daylight saving conversion problems - the
  203653. // first one sets it up, the second one kicks it in.
  203654. return SetLocalTime (&st) != 0
  203655. && SetLocalTime (&st) != 0;
  203656. }
  203657. int SystemStats::getPageSize()
  203658. {
  203659. SYSTEM_INFO systemInfo;
  203660. GetSystemInfo (&systemInfo);
  203661. return systemInfo.dwPageSize;
  203662. }
  203663. const String SystemStats::getLogonName()
  203664. {
  203665. TCHAR text [256];
  203666. DWORD len = numElementsInArray (text) - 2;
  203667. zerostruct (text);
  203668. GetUserName (text, &len);
  203669. return String (text, len);
  203670. }
  203671. const String SystemStats::getFullUserName()
  203672. {
  203673. return getLogonName();
  203674. }
  203675. #endif
  203676. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203677. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203678. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203679. // compiled on its own).
  203680. #if JUCE_INCLUDED_FILE
  203681. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203682. extern HWND juce_messageWindowHandle;
  203683. #endif
  203684. #if ! JUCE_USE_INTRINSICS
  203685. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203686. // older ones we have to actually call the ops as win32 functions..
  203687. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203688. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203689. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203690. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203691. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203692. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203693. {
  203694. jassertfalse; // This operation isn't available in old MS compiler versions!
  203695. __int64 oldValue = *value;
  203696. if (oldValue == valueToCompare)
  203697. *value = newValue;
  203698. return oldValue;
  203699. }
  203700. #endif
  203701. CriticalSection::CriticalSection() throw()
  203702. {
  203703. // (just to check the MS haven't changed this structure and broken things...)
  203704. #if JUCE_VC7_OR_EARLIER
  203705. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203706. #else
  203707. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203708. #endif
  203709. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203710. }
  203711. CriticalSection::~CriticalSection() throw()
  203712. {
  203713. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203714. }
  203715. void CriticalSection::enter() const throw()
  203716. {
  203717. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203718. }
  203719. bool CriticalSection::tryEnter() const throw()
  203720. {
  203721. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203722. }
  203723. void CriticalSection::exit() const throw()
  203724. {
  203725. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203726. }
  203727. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203728. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203729. {
  203730. }
  203731. WaitableEvent::~WaitableEvent() throw()
  203732. {
  203733. CloseHandle (internal);
  203734. }
  203735. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203736. {
  203737. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203738. }
  203739. void WaitableEvent::signal() const throw()
  203740. {
  203741. SetEvent (internal);
  203742. }
  203743. void WaitableEvent::reset() const throw()
  203744. {
  203745. ResetEvent (internal);
  203746. }
  203747. void JUCE_API juce_threadEntryPoint (void*);
  203748. static unsigned int __stdcall threadEntryProc (void* userData)
  203749. {
  203750. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203751. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203752. GetCurrentThreadId(), TRUE);
  203753. #endif
  203754. juce_threadEntryPoint (userData);
  203755. _endthreadex (0);
  203756. return 0;
  203757. }
  203758. void Thread::launchThread()
  203759. {
  203760. unsigned int newThreadId;
  203761. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  203762. threadId_ = (ThreadID) newThreadId;
  203763. }
  203764. void Thread::closeThreadHandle()
  203765. {
  203766. CloseHandle ((HANDLE) threadHandle_);
  203767. threadId_ = 0;
  203768. threadHandle_ = 0;
  203769. }
  203770. void Thread::killThread()
  203771. {
  203772. if (threadHandle_ != 0)
  203773. {
  203774. #if JUCE_DEBUG
  203775. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203776. #endif
  203777. TerminateThread (threadHandle_, 0);
  203778. }
  203779. }
  203780. void Thread::setCurrentThreadName (const String& name)
  203781. {
  203782. #if JUCE_DEBUG && JUCE_MSVC
  203783. struct
  203784. {
  203785. DWORD dwType;
  203786. LPCSTR szName;
  203787. DWORD dwThreadID;
  203788. DWORD dwFlags;
  203789. } info;
  203790. info.dwType = 0x1000;
  203791. info.szName = name.toCString();
  203792. info.dwThreadID = GetCurrentThreadId();
  203793. info.dwFlags = 0;
  203794. __try
  203795. {
  203796. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203797. }
  203798. __except (EXCEPTION_CONTINUE_EXECUTION)
  203799. {}
  203800. #else
  203801. (void) name;
  203802. #endif
  203803. }
  203804. Thread::ThreadID Thread::getCurrentThreadId()
  203805. {
  203806. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203807. }
  203808. bool Thread::setThreadPriority (void* handle, int priority)
  203809. {
  203810. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203811. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203812. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203813. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203814. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203815. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203816. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203817. if (handle == 0)
  203818. handle = GetCurrentThread();
  203819. return SetThreadPriority (handle, pri) != FALSE;
  203820. }
  203821. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203822. {
  203823. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203824. }
  203825. struct SleepEvent
  203826. {
  203827. SleepEvent()
  203828. : handle (CreateEvent (0, 0, 0,
  203829. #if JUCE_DEBUG
  203830. _T("Juce Sleep Event")))
  203831. #else
  203832. 0))
  203833. #endif
  203834. {
  203835. }
  203836. HANDLE handle;
  203837. };
  203838. static SleepEvent sleepEvent;
  203839. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203840. {
  203841. if (millisecs >= 10)
  203842. {
  203843. Sleep (millisecs);
  203844. }
  203845. else
  203846. {
  203847. // unlike Sleep() this is guaranteed to return to the current thread after
  203848. // the time expires, so we'll use this for short waits, which are more likely
  203849. // to need to be accurate
  203850. WaitForSingleObject (sleepEvent.handle, millisecs);
  203851. }
  203852. }
  203853. void Thread::yield()
  203854. {
  203855. Sleep (0);
  203856. }
  203857. static int lastProcessPriority = -1;
  203858. // called by WindowDriver because Windows does wierd things to process priority
  203859. // when you swap apps, and this forces an update when the app is brought to the front.
  203860. void juce_repeatLastProcessPriority()
  203861. {
  203862. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203863. {
  203864. DWORD p;
  203865. switch (lastProcessPriority)
  203866. {
  203867. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203868. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203869. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203870. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203871. default: jassertfalse; return; // bad priority value
  203872. }
  203873. SetPriorityClass (GetCurrentProcess(), p);
  203874. }
  203875. }
  203876. void Process::setPriority (ProcessPriority prior)
  203877. {
  203878. if (lastProcessPriority != (int) prior)
  203879. {
  203880. lastProcessPriority = (int) prior;
  203881. juce_repeatLastProcessPriority();
  203882. }
  203883. }
  203884. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  203885. {
  203886. return IsDebuggerPresent() != FALSE;
  203887. }
  203888. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203889. {
  203890. return juce_isRunningUnderDebugger();
  203891. }
  203892. void Process::raisePrivilege()
  203893. {
  203894. jassertfalse; // xxx not implemented
  203895. }
  203896. void Process::lowerPrivilege()
  203897. {
  203898. jassertfalse; // xxx not implemented
  203899. }
  203900. void Process::terminate()
  203901. {
  203902. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203903. _CrtDumpMemoryLeaks();
  203904. #endif
  203905. // bullet in the head in case there's a problem shutting down..
  203906. ExitProcess (0);
  203907. }
  203908. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203909. {
  203910. void* result = 0;
  203911. JUCE_TRY
  203912. {
  203913. result = LoadLibrary (name);
  203914. }
  203915. JUCE_CATCH_ALL
  203916. return result;
  203917. }
  203918. void PlatformUtilities::freeDynamicLibrary (void* h)
  203919. {
  203920. JUCE_TRY
  203921. {
  203922. if (h != 0)
  203923. FreeLibrary ((HMODULE) h);
  203924. }
  203925. JUCE_CATCH_ALL
  203926. }
  203927. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203928. {
  203929. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  203930. }
  203931. class InterProcessLock::Pimpl
  203932. {
  203933. public:
  203934. Pimpl (const String& name, const int timeOutMillisecs)
  203935. : handle (0), refCount (1)
  203936. {
  203937. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203938. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203939. {
  203940. if (timeOutMillisecs == 0)
  203941. {
  203942. close();
  203943. return;
  203944. }
  203945. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203946. {
  203947. case WAIT_OBJECT_0:
  203948. case WAIT_ABANDONED:
  203949. break;
  203950. case WAIT_TIMEOUT:
  203951. default:
  203952. close();
  203953. break;
  203954. }
  203955. }
  203956. }
  203957. ~Pimpl()
  203958. {
  203959. close();
  203960. }
  203961. void close()
  203962. {
  203963. if (handle != 0)
  203964. {
  203965. ReleaseMutex (handle);
  203966. CloseHandle (handle);
  203967. handle = 0;
  203968. }
  203969. }
  203970. HANDLE handle;
  203971. int refCount;
  203972. };
  203973. InterProcessLock::InterProcessLock (const String& name_)
  203974. : name (name_)
  203975. {
  203976. }
  203977. InterProcessLock::~InterProcessLock()
  203978. {
  203979. }
  203980. bool InterProcessLock::enter (const int timeOutMillisecs)
  203981. {
  203982. const ScopedLock sl (lock);
  203983. if (pimpl == 0)
  203984. {
  203985. pimpl = new Pimpl (name, timeOutMillisecs);
  203986. if (pimpl->handle == 0)
  203987. pimpl = 0;
  203988. }
  203989. else
  203990. {
  203991. pimpl->refCount++;
  203992. }
  203993. return pimpl != 0;
  203994. }
  203995. void InterProcessLock::exit()
  203996. {
  203997. const ScopedLock sl (lock);
  203998. // Trying to release the lock too many times!
  203999. jassert (pimpl != 0);
  204000. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204001. pimpl = 0;
  204002. }
  204003. #endif
  204004. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204005. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204006. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204007. // compiled on its own).
  204008. #if JUCE_INCLUDED_FILE
  204009. #ifndef CSIDL_MYMUSIC
  204010. #define CSIDL_MYMUSIC 0x000d
  204011. #endif
  204012. #ifndef CSIDL_MYVIDEO
  204013. #define CSIDL_MYVIDEO 0x000e
  204014. #endif
  204015. #ifndef INVALID_FILE_ATTRIBUTES
  204016. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204017. #endif
  204018. namespace WindowsFileHelpers
  204019. {
  204020. int64 fileTimeToTime (const FILETIME* const ft)
  204021. {
  204022. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204023. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204024. }
  204025. void timeToFileTime (const int64 time, FILETIME* const ft)
  204026. {
  204027. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204028. }
  204029. const String getDriveFromPath (const String& path)
  204030. {
  204031. if (path.isNotEmpty() && path[1] == ':')
  204032. return path.substring (0, 2) + '\\';
  204033. return path;
  204034. }
  204035. int64 getDiskSpaceInfo (const String& path, const bool total)
  204036. {
  204037. ULARGE_INTEGER spc, tot, totFree;
  204038. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204039. return total ? (int64) tot.QuadPart
  204040. : (int64) spc.QuadPart;
  204041. return 0;
  204042. }
  204043. unsigned int getWindowsDriveType (const String& path)
  204044. {
  204045. return GetDriveType (getDriveFromPath (path));
  204046. }
  204047. const File getSpecialFolderPath (int type)
  204048. {
  204049. WCHAR path [MAX_PATH + 256];
  204050. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204051. return File (String (path));
  204052. return File::nonexistent;
  204053. }
  204054. }
  204055. const juce_wchar File::separator = '\\';
  204056. const String File::separatorString ("\\");
  204057. bool File::exists() const
  204058. {
  204059. return fullPath.isNotEmpty()
  204060. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204061. }
  204062. bool File::existsAsFile() const
  204063. {
  204064. return fullPath.isNotEmpty()
  204065. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204066. }
  204067. bool File::isDirectory() const
  204068. {
  204069. const DWORD attr = GetFileAttributes (fullPath);
  204070. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204071. }
  204072. bool File::hasWriteAccess() const
  204073. {
  204074. if (exists())
  204075. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204076. // on windows, it seems that even read-only directories can still be written into,
  204077. // so checking the parent directory's permissions would return the wrong result..
  204078. return true;
  204079. }
  204080. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204081. {
  204082. DWORD attr = GetFileAttributes (fullPath);
  204083. if (attr == INVALID_FILE_ATTRIBUTES)
  204084. return false;
  204085. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204086. return true;
  204087. if (shouldBeReadOnly)
  204088. attr |= FILE_ATTRIBUTE_READONLY;
  204089. else
  204090. attr &= ~FILE_ATTRIBUTE_READONLY;
  204091. return SetFileAttributes (fullPath, attr) != FALSE;
  204092. }
  204093. bool File::isHidden() const
  204094. {
  204095. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204096. }
  204097. bool File::deleteFile() const
  204098. {
  204099. if (! exists())
  204100. return true;
  204101. else if (isDirectory())
  204102. return RemoveDirectory (fullPath) != 0;
  204103. else
  204104. return DeleteFile (fullPath) != 0;
  204105. }
  204106. bool File::moveToTrash() const
  204107. {
  204108. if (! exists())
  204109. return true;
  204110. SHFILEOPSTRUCT fos;
  204111. zerostruct (fos);
  204112. // The string we pass in must be double null terminated..
  204113. String doubleNullTermPath (getFullPathName() + " ");
  204114. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204115. p [getFullPathName().length()] = 0;
  204116. fos.wFunc = FO_DELETE;
  204117. fos.pFrom = p;
  204118. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204119. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204120. return SHFileOperation (&fos) == 0;
  204121. }
  204122. bool File::copyInternal (const File& dest) const
  204123. {
  204124. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204125. }
  204126. bool File::moveInternal (const File& dest) const
  204127. {
  204128. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204129. }
  204130. void File::createDirectoryInternal (const String& fileName) const
  204131. {
  204132. CreateDirectory (fileName, 0);
  204133. }
  204134. int64 juce_fileSetPosition (void* handle, int64 pos)
  204135. {
  204136. LARGE_INTEGER li;
  204137. li.QuadPart = pos;
  204138. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204139. return li.QuadPart;
  204140. }
  204141. void FileInputStream::openHandle()
  204142. {
  204143. totalSize = file.getSize();
  204144. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204145. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204146. if (h != INVALID_HANDLE_VALUE)
  204147. fileHandle = (void*) h;
  204148. }
  204149. void FileInputStream::closeHandle()
  204150. {
  204151. CloseHandle ((HANDLE) fileHandle);
  204152. }
  204153. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204154. {
  204155. if (fileHandle != 0)
  204156. {
  204157. DWORD actualNum = 0;
  204158. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204159. return (size_t) actualNum;
  204160. }
  204161. return 0;
  204162. }
  204163. void FileOutputStream::openHandle()
  204164. {
  204165. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204166. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204167. if (h != INVALID_HANDLE_VALUE)
  204168. {
  204169. LARGE_INTEGER li;
  204170. li.QuadPart = 0;
  204171. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204172. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204173. {
  204174. fileHandle = (void*) h;
  204175. currentPosition = li.QuadPart;
  204176. }
  204177. }
  204178. }
  204179. void FileOutputStream::closeHandle()
  204180. {
  204181. CloseHandle ((HANDLE) fileHandle);
  204182. }
  204183. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204184. {
  204185. if (fileHandle != 0)
  204186. {
  204187. DWORD actualNum = 0;
  204188. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204189. return (int) actualNum;
  204190. }
  204191. return 0;
  204192. }
  204193. void FileOutputStream::flushInternal()
  204194. {
  204195. if (fileHandle != 0)
  204196. FlushFileBuffers ((HANDLE) fileHandle);
  204197. }
  204198. int64 File::getSize() const
  204199. {
  204200. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204201. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204202. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204203. return 0;
  204204. }
  204205. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204206. {
  204207. using namespace WindowsFileHelpers;
  204208. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204209. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204210. {
  204211. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204212. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204213. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204214. }
  204215. else
  204216. {
  204217. creationTime = accessTime = modificationTime = 0;
  204218. }
  204219. }
  204220. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204221. {
  204222. using namespace WindowsFileHelpers;
  204223. bool ok = false;
  204224. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204225. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204226. if (h != INVALID_HANDLE_VALUE)
  204227. {
  204228. FILETIME m, a, c;
  204229. timeToFileTime (modificationTime, &m);
  204230. timeToFileTime (accessTime, &a);
  204231. timeToFileTime (creationTime, &c);
  204232. ok = SetFileTime (h,
  204233. creationTime > 0 ? &c : 0,
  204234. accessTime > 0 ? &a : 0,
  204235. modificationTime > 0 ? &m : 0) != 0;
  204236. CloseHandle (h);
  204237. }
  204238. return ok;
  204239. }
  204240. void File::findFileSystemRoots (Array<File>& destArray)
  204241. {
  204242. TCHAR buffer [2048];
  204243. buffer[0] = 0;
  204244. buffer[1] = 0;
  204245. GetLogicalDriveStrings (2048, buffer);
  204246. const TCHAR* n = buffer;
  204247. StringArray roots;
  204248. while (*n != 0)
  204249. {
  204250. roots.add (String (n));
  204251. while (*n++ != 0)
  204252. {}
  204253. }
  204254. roots.sort (true);
  204255. for (int i = 0; i < roots.size(); ++i)
  204256. destArray.add (roots [i]);
  204257. }
  204258. const String File::getVolumeLabel() const
  204259. {
  204260. TCHAR dest[64];
  204261. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204262. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204263. dest[0] = 0;
  204264. return dest;
  204265. }
  204266. int File::getVolumeSerialNumber() const
  204267. {
  204268. TCHAR dest[64];
  204269. DWORD serialNum;
  204270. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204271. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204272. return 0;
  204273. return (int) serialNum;
  204274. }
  204275. int64 File::getBytesFreeOnVolume() const
  204276. {
  204277. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204278. }
  204279. int64 File::getVolumeTotalSize() const
  204280. {
  204281. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204282. }
  204283. bool File::isOnCDRomDrive() const
  204284. {
  204285. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204286. }
  204287. bool File::isOnHardDisk() const
  204288. {
  204289. if (fullPath.isEmpty())
  204290. return false;
  204291. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204292. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204293. return n != DRIVE_REMOVABLE;
  204294. else
  204295. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204296. }
  204297. bool File::isOnRemovableDrive() const
  204298. {
  204299. if (fullPath.isEmpty())
  204300. return false;
  204301. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204302. return n == DRIVE_CDROM
  204303. || n == DRIVE_REMOTE
  204304. || n == DRIVE_REMOVABLE
  204305. || n == DRIVE_RAMDISK;
  204306. }
  204307. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204308. {
  204309. int csidlType = 0;
  204310. switch (type)
  204311. {
  204312. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204313. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204314. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204315. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204316. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204317. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204318. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204319. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204320. case tempDirectory:
  204321. {
  204322. WCHAR dest [2048];
  204323. dest[0] = 0;
  204324. GetTempPath (numElementsInArray (dest), dest);
  204325. return File (String (dest));
  204326. }
  204327. case invokedExecutableFile:
  204328. case currentExecutableFile:
  204329. case currentApplicationFile:
  204330. {
  204331. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204332. WCHAR dest [MAX_PATH + 256];
  204333. dest[0] = 0;
  204334. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204335. return File (String (dest));
  204336. }
  204337. case hostApplicationPath:
  204338. {
  204339. WCHAR dest [MAX_PATH + 256];
  204340. dest[0] = 0;
  204341. GetModuleFileName (0, dest, numElementsInArray (dest));
  204342. return File (String (dest));
  204343. }
  204344. default:
  204345. jassertfalse; // unknown type?
  204346. return File::nonexistent;
  204347. }
  204348. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204349. }
  204350. const File File::getCurrentWorkingDirectory()
  204351. {
  204352. WCHAR dest [MAX_PATH + 256];
  204353. dest[0] = 0;
  204354. GetCurrentDirectory (numElementsInArray (dest), dest);
  204355. return File (String (dest));
  204356. }
  204357. bool File::setAsCurrentWorkingDirectory() const
  204358. {
  204359. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204360. }
  204361. const String File::getVersion() const
  204362. {
  204363. String result;
  204364. DWORD handle = 0;
  204365. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204366. HeapBlock<char> buffer;
  204367. buffer.calloc (bufferSize);
  204368. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204369. {
  204370. VS_FIXEDFILEINFO* vffi;
  204371. UINT len = 0;
  204372. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204373. {
  204374. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204375. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204376. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204377. << (int) LOWORD (vffi->dwFileVersionLS);
  204378. }
  204379. }
  204380. return result;
  204381. }
  204382. const File File::getLinkedTarget() const
  204383. {
  204384. File result (*this);
  204385. String p (getFullPathName());
  204386. if (! exists())
  204387. p += ".lnk";
  204388. else if (getFileExtension() != ".lnk")
  204389. return result;
  204390. ComSmartPtr <IShellLink> shellLink;
  204391. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204392. {
  204393. ComSmartPtr <IPersistFile> persistFile;
  204394. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204395. {
  204396. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204397. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204398. {
  204399. WIN32_FIND_DATA winFindData;
  204400. WCHAR resolvedPath [MAX_PATH];
  204401. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204402. result = File (resolvedPath);
  204403. }
  204404. }
  204405. }
  204406. return result;
  204407. }
  204408. class DirectoryIterator::NativeIterator::Pimpl
  204409. {
  204410. public:
  204411. Pimpl (const File& directory, const String& wildCard)
  204412. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204413. handle (INVALID_HANDLE_VALUE)
  204414. {
  204415. }
  204416. ~Pimpl()
  204417. {
  204418. if (handle != INVALID_HANDLE_VALUE)
  204419. FindClose (handle);
  204420. }
  204421. bool next (String& filenameFound,
  204422. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204423. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204424. {
  204425. using namespace WindowsFileHelpers;
  204426. WIN32_FIND_DATA findData;
  204427. if (handle == INVALID_HANDLE_VALUE)
  204428. {
  204429. handle = FindFirstFile (directoryWithWildCard, &findData);
  204430. if (handle == INVALID_HANDLE_VALUE)
  204431. return false;
  204432. }
  204433. else
  204434. {
  204435. if (FindNextFile (handle, &findData) == 0)
  204436. return false;
  204437. }
  204438. filenameFound = findData.cFileName;
  204439. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204440. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204441. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204442. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204443. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204444. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204445. return true;
  204446. }
  204447. private:
  204448. const String directoryWithWildCard;
  204449. HANDLE handle;
  204450. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204451. };
  204452. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204453. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204454. {
  204455. }
  204456. DirectoryIterator::NativeIterator::~NativeIterator()
  204457. {
  204458. }
  204459. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204460. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204461. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204462. {
  204463. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204464. }
  204465. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204466. {
  204467. HINSTANCE hInstance = 0;
  204468. JUCE_TRY
  204469. {
  204470. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204471. }
  204472. JUCE_CATCH_ALL
  204473. return hInstance > (HINSTANCE) 32;
  204474. }
  204475. void File::revealToUser() const
  204476. {
  204477. if (isDirectory())
  204478. startAsProcess();
  204479. else if (getParentDirectory().exists())
  204480. getParentDirectory().startAsProcess();
  204481. }
  204482. class NamedPipeInternal
  204483. {
  204484. public:
  204485. NamedPipeInternal (const String& file, const bool isPipe_)
  204486. : pipeH (0),
  204487. cancelEvent (0),
  204488. connected (false),
  204489. isPipe (isPipe_)
  204490. {
  204491. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204492. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204493. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204494. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204495. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204496. }
  204497. ~NamedPipeInternal()
  204498. {
  204499. disconnectPipe();
  204500. if (pipeH != 0)
  204501. CloseHandle (pipeH);
  204502. CloseHandle (cancelEvent);
  204503. }
  204504. bool connect (const int timeOutMs)
  204505. {
  204506. if (! isPipe)
  204507. return true;
  204508. if (! connected)
  204509. {
  204510. OVERLAPPED over;
  204511. zerostruct (over);
  204512. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204513. if (ConnectNamedPipe (pipeH, &over))
  204514. {
  204515. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204516. }
  204517. else
  204518. {
  204519. const int err = GetLastError();
  204520. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204521. {
  204522. HANDLE handles[] = { over.hEvent, cancelEvent };
  204523. if (WaitForMultipleObjects (2, handles, FALSE,
  204524. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204525. connected = true;
  204526. }
  204527. else if (err == ERROR_PIPE_CONNECTED)
  204528. {
  204529. connected = true;
  204530. }
  204531. }
  204532. CloseHandle (over.hEvent);
  204533. }
  204534. return connected;
  204535. }
  204536. void disconnectPipe()
  204537. {
  204538. if (connected)
  204539. {
  204540. DisconnectNamedPipe (pipeH);
  204541. connected = false;
  204542. }
  204543. }
  204544. HANDLE pipeH;
  204545. HANDLE cancelEvent;
  204546. bool connected, isPipe;
  204547. };
  204548. void NamedPipe::close()
  204549. {
  204550. cancelPendingReads();
  204551. const ScopedLock sl (lock);
  204552. delete static_cast<NamedPipeInternal*> (internal);
  204553. internal = 0;
  204554. }
  204555. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204556. {
  204557. close();
  204558. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204559. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204560. {
  204561. internal = intern.release();
  204562. return true;
  204563. }
  204564. return false;
  204565. }
  204566. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204567. {
  204568. const ScopedLock sl (lock);
  204569. int bytesRead = -1;
  204570. bool waitAgain = true;
  204571. while (waitAgain && internal != 0)
  204572. {
  204573. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204574. waitAgain = false;
  204575. if (! intern->connect (timeOutMilliseconds))
  204576. break;
  204577. if (maxBytesToRead <= 0)
  204578. return 0;
  204579. OVERLAPPED over;
  204580. zerostruct (over);
  204581. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204582. unsigned long numRead;
  204583. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204584. {
  204585. bytesRead = (int) numRead;
  204586. }
  204587. else if (GetLastError() == ERROR_IO_PENDING)
  204588. {
  204589. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204590. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204591. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204592. : INFINITE);
  204593. if (waitResult != WAIT_OBJECT_0)
  204594. {
  204595. // if the operation timed out, let's cancel it...
  204596. CancelIo (intern->pipeH);
  204597. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204598. }
  204599. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204600. {
  204601. bytesRead = (int) numRead;
  204602. }
  204603. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204604. {
  204605. intern->disconnectPipe();
  204606. waitAgain = true;
  204607. }
  204608. }
  204609. else
  204610. {
  204611. waitAgain = internal != 0;
  204612. Sleep (5);
  204613. }
  204614. CloseHandle (over.hEvent);
  204615. }
  204616. return bytesRead;
  204617. }
  204618. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204619. {
  204620. int bytesWritten = -1;
  204621. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204622. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204623. {
  204624. if (numBytesToWrite <= 0)
  204625. return 0;
  204626. OVERLAPPED over;
  204627. zerostruct (over);
  204628. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204629. unsigned long numWritten;
  204630. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204631. {
  204632. bytesWritten = (int) numWritten;
  204633. }
  204634. else if (GetLastError() == ERROR_IO_PENDING)
  204635. {
  204636. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204637. DWORD waitResult;
  204638. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204639. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204640. : INFINITE);
  204641. if (waitResult != WAIT_OBJECT_0)
  204642. {
  204643. CancelIo (intern->pipeH);
  204644. WaitForSingleObject (over.hEvent, INFINITE);
  204645. }
  204646. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204647. {
  204648. bytesWritten = (int) numWritten;
  204649. }
  204650. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204651. {
  204652. intern->disconnectPipe();
  204653. }
  204654. }
  204655. CloseHandle (over.hEvent);
  204656. }
  204657. return bytesWritten;
  204658. }
  204659. void NamedPipe::cancelPendingReads()
  204660. {
  204661. if (internal != 0)
  204662. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204663. }
  204664. #endif
  204665. /*** End of inlined file: juce_win32_Files.cpp ***/
  204666. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204667. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204668. // compiled on its own).
  204669. #if JUCE_INCLUDED_FILE
  204670. #ifndef INTERNET_FLAG_NEED_FILE
  204671. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204672. #endif
  204673. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204674. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204675. #endif
  204676. static HINTERNET sessionHandle = 0;
  204677. #ifndef WORKAROUND_TIMEOUT_BUG
  204678. //#define WORKAROUND_TIMEOUT_BUG 1
  204679. #endif
  204680. #if WORKAROUND_TIMEOUT_BUG
  204681. // Required because of a Microsoft bug in setting a timeout
  204682. class InternetConnectThread : public Thread
  204683. {
  204684. public:
  204685. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204686. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204687. {
  204688. startThread();
  204689. }
  204690. ~InternetConnectThread()
  204691. {
  204692. stopThread (60000);
  204693. }
  204694. void run()
  204695. {
  204696. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204697. uc.nPort, _T(""), _T(""),
  204698. isFtp ? INTERNET_SERVICE_FTP
  204699. : INTERNET_SERVICE_HTTP,
  204700. 0, 0);
  204701. notify();
  204702. }
  204703. private:
  204704. URL_COMPONENTS& uc;
  204705. HINTERNET& connection;
  204706. const bool isFtp;
  204707. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204708. };
  204709. #endif
  204710. class WebInputStream : public InputStream
  204711. {
  204712. public:
  204713. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  204714. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204715. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  204716. : connection (0), request (0),
  204717. address (address_), headers (headers_), postData (postData_), position (0),
  204718. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  204719. {
  204720. createConnection (progressCallback, progressCallbackContext);
  204721. if (responseHeaders != 0 && ! isError())
  204722. {
  204723. DWORD bufferSizeBytes = 4096;
  204724. for (;;)
  204725. {
  204726. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204727. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204728. {
  204729. StringArray headersArray;
  204730. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204731. for (int i = 0; i < headersArray.size(); ++i)
  204732. {
  204733. const String& header = headersArray[i];
  204734. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204735. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204736. const String previousValue ((*responseHeaders) [key]);
  204737. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204738. }
  204739. break;
  204740. }
  204741. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204742. break;
  204743. }
  204744. }
  204745. }
  204746. ~WebInputStream()
  204747. {
  204748. close();
  204749. }
  204750. bool isError() const { return request == 0; }
  204751. bool isExhausted() { return finished; }
  204752. int64 getPosition() { return position; }
  204753. int64 getTotalLength()
  204754. {
  204755. if (! isError())
  204756. {
  204757. DWORD index = 0, result = 0, size = sizeof (result);
  204758. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204759. return (int64) result;
  204760. }
  204761. return -1;
  204762. }
  204763. int read (void* buffer, int bytesToRead)
  204764. {
  204765. DWORD bytesRead = 0;
  204766. if (! (finished || isError()))
  204767. {
  204768. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  204769. position += bytesRead;
  204770. if (bytesRead == 0)
  204771. finished = true;
  204772. }
  204773. return (int) bytesRead;
  204774. }
  204775. bool setPosition (int64 wantedPos)
  204776. {
  204777. if (isError())
  204778. return false;
  204779. if (wantedPos != position)
  204780. {
  204781. finished = false;
  204782. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  204783. if (position == wantedPos)
  204784. return true;
  204785. if (wantedPos < position)
  204786. {
  204787. close();
  204788. position = 0;
  204789. createConnection (0, 0);
  204790. }
  204791. skipNextBytes (wantedPos - position);
  204792. }
  204793. return true;
  204794. }
  204795. private:
  204796. HINTERNET connection, request;
  204797. String address, headers;
  204798. MemoryBlock postData;
  204799. int64 position;
  204800. bool finished;
  204801. const bool isPost;
  204802. int timeOutMs;
  204803. void close()
  204804. {
  204805. if (request != 0)
  204806. {
  204807. InternetCloseHandle (request);
  204808. request = 0;
  204809. }
  204810. if (connection != 0)
  204811. {
  204812. InternetCloseHandle (connection);
  204813. connection = 0;
  204814. }
  204815. }
  204816. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  204817. void* progressCallbackContext)
  204818. {
  204819. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  204820. close();
  204821. if (sessionHandle != 0)
  204822. {
  204823. // break up the url..
  204824. TCHAR file[1024], server[1024];
  204825. URL_COMPONENTS uc;
  204826. zerostruct (uc);
  204827. uc.dwStructSize = sizeof (uc);
  204828. uc.dwUrlPathLength = sizeof (file);
  204829. uc.dwHostNameLength = sizeof (server);
  204830. uc.lpszUrlPath = file;
  204831. uc.lpszHostName = server;
  204832. if (InternetCrackUrl (address, 0, 0, &uc))
  204833. {
  204834. int disable = 1;
  204835. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204836. if (timeOutMs == 0)
  204837. timeOutMs = 30000;
  204838. else if (timeOutMs < 0)
  204839. timeOutMs = -1;
  204840. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204841. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  204842. #if WORKAROUND_TIMEOUT_BUG
  204843. connection = 0;
  204844. {
  204845. InternetConnectThread connectThread (uc, connection, isFtp);
  204846. connectThread.wait (timeOutMs);
  204847. if (connection == 0)
  204848. {
  204849. InternetCloseHandle (sessionHandle);
  204850. sessionHandle = 0;
  204851. }
  204852. }
  204853. #else
  204854. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  204855. _T(""), _T(""),
  204856. isFtp ? INTERNET_SERVICE_FTP
  204857. : INTERNET_SERVICE_HTTP,
  204858. 0, 0);
  204859. #endif
  204860. if (connection != 0)
  204861. {
  204862. if (isFtp)
  204863. {
  204864. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  204865. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  204866. }
  204867. else
  204868. {
  204869. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204870. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204871. if (address.startsWithIgnoreCase ("https:"))
  204872. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204873. // IE7 seems to automatically work out when it's https)
  204874. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  204875. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  204876. if (request != 0)
  204877. {
  204878. INTERNET_BUFFERS buffers;
  204879. zerostruct (buffers);
  204880. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204881. buffers.lpcszHeader = static_cast <LPCTSTR> (headers);
  204882. buffers.dwHeadersLength = headers.length();
  204883. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204884. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204885. {
  204886. int bytesSent = 0;
  204887. for (;;)
  204888. {
  204889. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204890. DWORD bytesDone = 0;
  204891. if (bytesToDo > 0
  204892. && ! InternetWriteFile (request,
  204893. static_cast <const char*> (postData.getData()) + bytesSent,
  204894. bytesToDo, &bytesDone))
  204895. {
  204896. break;
  204897. }
  204898. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204899. {
  204900. if (HttpEndRequest (request, 0, 0, 0))
  204901. return;
  204902. break;
  204903. }
  204904. bytesSent += bytesDone;
  204905. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  204906. break;
  204907. }
  204908. }
  204909. }
  204910. close();
  204911. }
  204912. }
  204913. }
  204914. }
  204915. }
  204916. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  204917. };
  204918. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  204919. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204920. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  204921. {
  204922. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  204923. progressCallback, progressCallbackContext,
  204924. headers, timeOutMs, responseHeaders));
  204925. return wi->isError() ? 0 : wi.release();
  204926. }
  204927. namespace MACAddressHelpers
  204928. {
  204929. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  204930. {
  204931. DynamicLibraryLoader dll ("iphlpapi.dll");
  204932. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204933. if (getAdaptersInfo != 0)
  204934. {
  204935. ULONG len = sizeof (IP_ADAPTER_INFO);
  204936. MemoryBlock mb;
  204937. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204938. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204939. {
  204940. mb.setSize (len);
  204941. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204942. }
  204943. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204944. {
  204945. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  204946. {
  204947. if (adapter->AddressLength >= 6)
  204948. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  204949. }
  204950. }
  204951. }
  204952. }
  204953. void getViaNetBios (Array<MACAddress>& result)
  204954. {
  204955. DynamicLibraryLoader dll ("netapi32.dll");
  204956. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204957. if (NetbiosCall != 0)
  204958. {
  204959. NCB ncb;
  204960. zerostruct (ncb);
  204961. struct ASTAT
  204962. {
  204963. ADAPTER_STATUS adapt;
  204964. NAME_BUFFER NameBuff [30];
  204965. };
  204966. ASTAT astat;
  204967. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204968. LANA_ENUM enums;
  204969. zerostruct (enums);
  204970. ncb.ncb_command = NCBENUM;
  204971. ncb.ncb_buffer = (unsigned char*) &enums;
  204972. ncb.ncb_length = sizeof (LANA_ENUM);
  204973. NetbiosCall (&ncb);
  204974. for (int i = 0; i < enums.length; ++i)
  204975. {
  204976. zerostruct (ncb);
  204977. ncb.ncb_command = NCBRESET;
  204978. ncb.ncb_lana_num = enums.lana[i];
  204979. if (NetbiosCall (&ncb) == 0)
  204980. {
  204981. zerostruct (ncb);
  204982. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204983. ncb.ncb_command = NCBASTAT;
  204984. ncb.ncb_lana_num = enums.lana[i];
  204985. ncb.ncb_buffer = (unsigned char*) &astat;
  204986. ncb.ncb_length = sizeof (ASTAT);
  204987. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  204988. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  204989. }
  204990. }
  204991. }
  204992. }
  204993. }
  204994. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  204995. {
  204996. MACAddressHelpers::getViaGetAdaptersInfo (result);
  204997. MACAddressHelpers::getViaNetBios (result);
  204998. }
  204999. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205000. const String& emailSubject,
  205001. const String& bodyText,
  205002. const StringArray& filesToAttach)
  205003. {
  205004. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205005. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205006. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205007. bool ok = false;
  205008. if (mapiSendMail != 0)
  205009. {
  205010. MapiMessage message;
  205011. zerostruct (message);
  205012. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205013. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205014. MapiRecipDesc recip;
  205015. zerostruct (recip);
  205016. recip.ulRecipClass = MAPI_TO;
  205017. String targetEmailAddress_ (targetEmailAddress);
  205018. if (targetEmailAddress_.isEmpty())
  205019. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205020. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205021. message.nRecipCount = 1;
  205022. message.lpRecips = &recip;
  205023. HeapBlock <MapiFileDesc> files;
  205024. files.calloc (filesToAttach.size());
  205025. message.nFileCount = filesToAttach.size();
  205026. message.lpFiles = files;
  205027. for (int i = 0; i < filesToAttach.size(); ++i)
  205028. {
  205029. files[i].nPosition = (ULONG) -1;
  205030. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205031. }
  205032. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205033. }
  205034. FreeLibrary (h);
  205035. return ok;
  205036. }
  205037. #endif
  205038. /*** End of inlined file: juce_win32_Network.cpp ***/
  205039. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205040. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205041. // compiled on its own).
  205042. #if JUCE_INCLUDED_FILE
  205043. namespace
  205044. {
  205045. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  205046. {
  205047. HKEY rootKey = 0;
  205048. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205049. rootKey = HKEY_CURRENT_USER;
  205050. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205051. rootKey = HKEY_LOCAL_MACHINE;
  205052. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205053. rootKey = HKEY_CLASSES_ROOT;
  205054. if (rootKey != 0)
  205055. {
  205056. name = name.substring (name.indexOfChar ('\\') + 1);
  205057. const int lastSlash = name.lastIndexOfChar ('\\');
  205058. valueName = name.substring (lastSlash + 1);
  205059. name = name.substring (0, lastSlash);
  205060. HKEY key;
  205061. DWORD result;
  205062. if (createForWriting)
  205063. {
  205064. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205065. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205066. return key;
  205067. }
  205068. else
  205069. {
  205070. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205071. return key;
  205072. }
  205073. }
  205074. return 0;
  205075. }
  205076. }
  205077. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205078. const String& defaultValue)
  205079. {
  205080. String valueName, result (defaultValue);
  205081. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205082. if (k != 0)
  205083. {
  205084. WCHAR buffer [2048];
  205085. unsigned long bufferSize = sizeof (buffer);
  205086. DWORD type = REG_SZ;
  205087. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205088. {
  205089. if (type == REG_SZ)
  205090. result = buffer;
  205091. else if (type == REG_DWORD)
  205092. result = String ((int) *(DWORD*) buffer);
  205093. }
  205094. RegCloseKey (k);
  205095. }
  205096. return result;
  205097. }
  205098. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205099. const String& value)
  205100. {
  205101. String valueName;
  205102. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205103. if (k != 0)
  205104. {
  205105. RegSetValueEx (k, valueName, 0, REG_SZ,
  205106. (const BYTE*) (const WCHAR*) value,
  205107. sizeof (WCHAR) * (value.length() + 1));
  205108. RegCloseKey (k);
  205109. }
  205110. }
  205111. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205112. {
  205113. bool exists = false;
  205114. String valueName;
  205115. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205116. if (k != 0)
  205117. {
  205118. unsigned char buffer [2048];
  205119. unsigned long bufferSize = sizeof (buffer);
  205120. DWORD type = 0;
  205121. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205122. exists = true;
  205123. RegCloseKey (k);
  205124. }
  205125. return exists;
  205126. }
  205127. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205128. {
  205129. String valueName;
  205130. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205131. if (k != 0)
  205132. {
  205133. RegDeleteValue (k, valueName);
  205134. RegCloseKey (k);
  205135. }
  205136. }
  205137. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205138. {
  205139. String valueName;
  205140. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205141. if (k != 0)
  205142. {
  205143. RegDeleteKey (k, valueName);
  205144. RegCloseKey (k);
  205145. }
  205146. }
  205147. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205148. const String& symbolicDescription,
  205149. const String& fullDescription,
  205150. const File& targetExecutable,
  205151. int iconResourceNumber)
  205152. {
  205153. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205154. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205155. if (iconResourceNumber != 0)
  205156. setRegistryValue (key + "\\DefaultIcon\\",
  205157. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205158. setRegistryValue (key + "\\", fullDescription);
  205159. setRegistryValue (key + "\\shell\\open\\command\\",
  205160. targetExecutable.getFullPathName() + " %1");
  205161. }
  205162. bool juce_IsRunningInWine()
  205163. {
  205164. HKEY key;
  205165. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205166. {
  205167. RegCloseKey (key);
  205168. return true;
  205169. }
  205170. return false;
  205171. }
  205172. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205173. {
  205174. String s (::GetCommandLineW());
  205175. StringArray tokens;
  205176. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205177. return tokens.joinIntoString (" ", 1);
  205178. }
  205179. static void* currentModuleHandle = 0;
  205180. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205181. {
  205182. if (currentModuleHandle == 0)
  205183. currentModuleHandle = GetModuleHandle (0);
  205184. return currentModuleHandle;
  205185. }
  205186. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205187. {
  205188. currentModuleHandle = newHandle;
  205189. }
  205190. void PlatformUtilities::fpuReset()
  205191. {
  205192. #if JUCE_MSVC
  205193. _clearfp();
  205194. #endif
  205195. }
  205196. void PlatformUtilities::beep()
  205197. {
  205198. MessageBeep (MB_OK);
  205199. }
  205200. #endif
  205201. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205202. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205203. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205204. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205205. // compiled on its own).
  205206. #if JUCE_INCLUDED_FILE
  205207. static const unsigned int specialId = WM_APP + 0x4400;
  205208. static const unsigned int broadcastId = WM_APP + 0x4403;
  205209. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205210. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205211. HWND juce_messageWindowHandle = 0;
  205212. extern long improbableWindowNumber; // defined in windowing.cpp
  205213. #ifndef WM_APPCOMMAND
  205214. #define WM_APPCOMMAND 0x0319
  205215. #endif
  205216. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205217. const UINT message,
  205218. const WPARAM wParam,
  205219. const LPARAM lParam) throw()
  205220. {
  205221. JUCE_TRY
  205222. {
  205223. if (h == juce_messageWindowHandle)
  205224. {
  205225. if (message == specialCallbackId)
  205226. {
  205227. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205228. return (LRESULT) (*func) ((void*) lParam);
  205229. }
  205230. else if (message == specialId)
  205231. {
  205232. // these are trapped early in the dispatch call, but must also be checked
  205233. // here in case there are windows modal dialog boxes doing their own
  205234. // dispatch loop and not calling our version
  205235. Message* const message = reinterpret_cast <Message*> (lParam);
  205236. MessageManager::getInstance()->deliverMessage (message);
  205237. message->decReferenceCount();
  205238. return 0;
  205239. }
  205240. else if (message == broadcastId)
  205241. {
  205242. const ScopedPointer <String> messageString ((String*) lParam);
  205243. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205244. return 0;
  205245. }
  205246. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205247. {
  205248. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205249. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205250. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205251. return 0;
  205252. }
  205253. }
  205254. }
  205255. JUCE_CATCH_EXCEPTION
  205256. return DefWindowProc (h, message, wParam, lParam);
  205257. }
  205258. static bool isEventBlockedByModalComps (MSG& m)
  205259. {
  205260. if (Component::getNumCurrentlyModalComponents() == 0
  205261. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205262. return false;
  205263. switch (m.message)
  205264. {
  205265. case WM_MOUSEMOVE:
  205266. case WM_NCMOUSEMOVE:
  205267. case 0x020A: /* WM_MOUSEWHEEL */
  205268. case 0x020E: /* WM_MOUSEHWHEEL */
  205269. case WM_KEYUP:
  205270. case WM_SYSKEYUP:
  205271. case WM_CHAR:
  205272. case WM_APPCOMMAND:
  205273. case WM_LBUTTONUP:
  205274. case WM_MBUTTONUP:
  205275. case WM_RBUTTONUP:
  205276. case WM_MOUSEACTIVATE:
  205277. case WM_NCMOUSEHOVER:
  205278. case WM_MOUSEHOVER:
  205279. return true;
  205280. case WM_NCLBUTTONDOWN:
  205281. case WM_NCLBUTTONDBLCLK:
  205282. case WM_NCRBUTTONDOWN:
  205283. case WM_NCRBUTTONDBLCLK:
  205284. case WM_NCMBUTTONDOWN:
  205285. case WM_NCMBUTTONDBLCLK:
  205286. case WM_LBUTTONDOWN:
  205287. case WM_LBUTTONDBLCLK:
  205288. case WM_MBUTTONDOWN:
  205289. case WM_MBUTTONDBLCLK:
  205290. case WM_RBUTTONDOWN:
  205291. case WM_RBUTTONDBLCLK:
  205292. case WM_KEYDOWN:
  205293. case WM_SYSKEYDOWN:
  205294. {
  205295. Component* const modal = Component::getCurrentlyModalComponent (0);
  205296. if (modal != 0)
  205297. modal->inputAttemptWhenModal();
  205298. return true;
  205299. }
  205300. default:
  205301. break;
  205302. }
  205303. return false;
  205304. }
  205305. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205306. {
  205307. MSG m;
  205308. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205309. return false;
  205310. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205311. {
  205312. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205313. {
  205314. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205315. MessageManager::getInstance()->deliverMessage (message);
  205316. message->decReferenceCount();
  205317. }
  205318. else if (m.message == WM_QUIT)
  205319. {
  205320. if (JUCEApplication::getInstance() != 0)
  205321. JUCEApplication::getInstance()->systemRequestedQuit();
  205322. }
  205323. else if (! isEventBlockedByModalComps (m))
  205324. {
  205325. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205326. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205327. {
  205328. // if it's someone else's window being clicked on, and the focus is
  205329. // currently on a juce window, pass the kb focus over..
  205330. HWND currentFocus = GetFocus();
  205331. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205332. SetFocus (m.hwnd);
  205333. }
  205334. TranslateMessage (&m);
  205335. DispatchMessage (&m);
  205336. }
  205337. }
  205338. return true;
  205339. }
  205340. bool juce_postMessageToSystemQueue (Message* message)
  205341. {
  205342. message->incReferenceCount();
  205343. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205344. }
  205345. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205346. void* userData)
  205347. {
  205348. if (MessageManager::getInstance()->isThisTheMessageThread())
  205349. {
  205350. return (*callback) (userData);
  205351. }
  205352. else
  205353. {
  205354. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205355. // deadlock because the message manager is blocked from running, and can't
  205356. // call your function..
  205357. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205358. return (void*) SendMessage (juce_messageWindowHandle,
  205359. specialCallbackId,
  205360. (WPARAM) callback,
  205361. (LPARAM) userData);
  205362. }
  205363. }
  205364. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205365. {
  205366. if (hwnd != juce_messageWindowHandle)
  205367. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205368. return TRUE;
  205369. }
  205370. void MessageManager::broadcastMessage (const String& value)
  205371. {
  205372. Array<void*> windows;
  205373. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205374. const String localCopy (value);
  205375. COPYDATASTRUCT data;
  205376. data.dwData = broadcastId;
  205377. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205378. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205379. for (int i = windows.size(); --i >= 0;)
  205380. {
  205381. HWND hwnd = (HWND) windows.getUnchecked(i);
  205382. TCHAR windowName [64]; // no need to read longer strings than this
  205383. GetWindowText (hwnd, windowName, 64);
  205384. windowName [63] = 0;
  205385. if (String (windowName) == messageWindowName)
  205386. {
  205387. DWORD_PTR result;
  205388. SendMessageTimeout (hwnd, WM_COPYDATA,
  205389. (WPARAM) juce_messageWindowHandle,
  205390. (LPARAM) &data,
  205391. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205392. 8000,
  205393. &result);
  205394. }
  205395. }
  205396. }
  205397. static const String getMessageWindowClassName()
  205398. {
  205399. // this name has to be different for each app/dll instance because otherwise
  205400. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205401. // window class).
  205402. static int number = 0;
  205403. if (number == 0)
  205404. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205405. return "JUCEcs_" + String (number);
  205406. }
  205407. void MessageManager::doPlatformSpecificInitialisation()
  205408. {
  205409. OleInitialize (0);
  205410. const String className (getMessageWindowClassName());
  205411. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205412. WNDCLASSEX wc;
  205413. zerostruct (wc);
  205414. wc.cbSize = sizeof (wc);
  205415. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205416. wc.cbWndExtra = 4;
  205417. wc.hInstance = hmod;
  205418. wc.lpszClassName = className;
  205419. RegisterClassEx (&wc);
  205420. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205421. messageWindowName,
  205422. 0, 0, 0, 0, 0, 0, 0,
  205423. hmod, 0);
  205424. }
  205425. void MessageManager::doPlatformSpecificShutdown()
  205426. {
  205427. DestroyWindow (juce_messageWindowHandle);
  205428. UnregisterClass (getMessageWindowClassName(), 0);
  205429. OleUninitialize();
  205430. }
  205431. #endif
  205432. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205433. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205434. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205435. // compiled on its own).
  205436. #if JUCE_INCLUDED_FILE
  205437. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205438. NEWTEXTMETRICEXW*,
  205439. int type,
  205440. LPARAM lParam)
  205441. {
  205442. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205443. {
  205444. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205445. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205446. }
  205447. return 1;
  205448. }
  205449. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205450. NEWTEXTMETRICEXW*,
  205451. int type,
  205452. LPARAM lParam)
  205453. {
  205454. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205455. {
  205456. LOGFONTW lf;
  205457. zerostruct (lf);
  205458. lf.lfWeight = FW_DONTCARE;
  205459. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205460. lf.lfQuality = DEFAULT_QUALITY;
  205461. lf.lfCharSet = DEFAULT_CHARSET;
  205462. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205463. lf.lfPitchAndFamily = FF_DONTCARE;
  205464. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205465. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205466. HDC dc = CreateCompatibleDC (0);
  205467. EnumFontFamiliesEx (dc, &lf,
  205468. (FONTENUMPROCW) &wfontEnum2,
  205469. lParam, 0);
  205470. DeleteDC (dc);
  205471. }
  205472. return 1;
  205473. }
  205474. const StringArray Font::findAllTypefaceNames()
  205475. {
  205476. StringArray results;
  205477. HDC dc = CreateCompatibleDC (0);
  205478. {
  205479. LOGFONTW lf;
  205480. zerostruct (lf);
  205481. lf.lfWeight = FW_DONTCARE;
  205482. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205483. lf.lfQuality = DEFAULT_QUALITY;
  205484. lf.lfCharSet = DEFAULT_CHARSET;
  205485. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205486. lf.lfPitchAndFamily = FF_DONTCARE;
  205487. lf.lfFaceName[0] = 0;
  205488. EnumFontFamiliesEx (dc, &lf,
  205489. (FONTENUMPROCW) &wfontEnum1,
  205490. (LPARAM) &results, 0);
  205491. }
  205492. DeleteDC (dc);
  205493. results.sort (true);
  205494. return results;
  205495. }
  205496. extern bool juce_IsRunningInWine();
  205497. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205498. {
  205499. if (juce_IsRunningInWine())
  205500. {
  205501. // If we're running in Wine, then use fonts that might be available on Linux..
  205502. defaultSans = "Bitstream Vera Sans";
  205503. defaultSerif = "Bitstream Vera Serif";
  205504. defaultFixed = "Bitstream Vera Sans Mono";
  205505. }
  205506. else
  205507. {
  205508. defaultSans = "Verdana";
  205509. defaultSerif = "Times";
  205510. defaultFixed = "Lucida Console";
  205511. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205512. }
  205513. }
  205514. class FontDCHolder : private DeletedAtShutdown
  205515. {
  205516. public:
  205517. FontDCHolder()
  205518. : dc (0), numKPs (0), size (0),
  205519. bold (false), italic (false)
  205520. {
  205521. }
  205522. ~FontDCHolder()
  205523. {
  205524. if (dc != 0)
  205525. {
  205526. DeleteDC (dc);
  205527. DeleteObject (fontH);
  205528. }
  205529. clearSingletonInstance();
  205530. }
  205531. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205532. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205533. {
  205534. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205535. {
  205536. fontName = fontName_;
  205537. bold = bold_;
  205538. italic = italic_;
  205539. size = size_;
  205540. if (dc != 0)
  205541. {
  205542. DeleteDC (dc);
  205543. DeleteObject (fontH);
  205544. kps.free();
  205545. }
  205546. fontH = 0;
  205547. dc = CreateCompatibleDC (0);
  205548. SetMapperFlags (dc, 0);
  205549. SetMapMode (dc, MM_TEXT);
  205550. LOGFONTW lfw;
  205551. zerostruct (lfw);
  205552. lfw.lfCharSet = DEFAULT_CHARSET;
  205553. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205554. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205555. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205556. lfw.lfQuality = PROOF_QUALITY;
  205557. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205558. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205559. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205560. lfw.lfHeight = size > 0 ? size : -256;
  205561. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205562. if (standardSizedFont != 0)
  205563. {
  205564. if (SelectObject (dc, standardSizedFont) != 0)
  205565. {
  205566. fontH = standardSizedFont;
  205567. if (size == 0)
  205568. {
  205569. OUTLINETEXTMETRIC otm;
  205570. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205571. {
  205572. lfw.lfHeight = -(int) otm.otmEMSquare;
  205573. fontH = CreateFontIndirect (&lfw);
  205574. SelectObject (dc, fontH);
  205575. DeleteObject (standardSizedFont);
  205576. }
  205577. }
  205578. }
  205579. else
  205580. {
  205581. jassertfalse;
  205582. }
  205583. }
  205584. else
  205585. {
  205586. jassertfalse;
  205587. }
  205588. }
  205589. return dc;
  205590. }
  205591. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205592. {
  205593. if (kps == 0)
  205594. {
  205595. numKPs = GetKerningPairs (dc, 0, 0);
  205596. kps.calloc (numKPs);
  205597. GetKerningPairs (dc, numKPs, kps);
  205598. }
  205599. numKPs_ = numKPs;
  205600. return kps;
  205601. }
  205602. private:
  205603. HFONT fontH;
  205604. HDC dc;
  205605. String fontName;
  205606. HeapBlock <KERNINGPAIR> kps;
  205607. int numKPs, size;
  205608. bool bold, italic;
  205609. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205610. };
  205611. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205612. class WindowsTypeface : public CustomTypeface
  205613. {
  205614. public:
  205615. WindowsTypeface (const Font& font)
  205616. {
  205617. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205618. font.isBold(), font.isItalic(), 0);
  205619. TEXTMETRIC tm;
  205620. tm.tmAscent = tm.tmHeight = 1;
  205621. tm.tmDefaultChar = 0;
  205622. GetTextMetrics (dc, &tm);
  205623. setCharacteristics (font.getTypefaceName(),
  205624. tm.tmAscent / (float) tm.tmHeight,
  205625. font.isBold(), font.isItalic(),
  205626. tm.tmDefaultChar);
  205627. }
  205628. bool loadGlyphIfPossible (juce_wchar character)
  205629. {
  205630. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205631. GLYPHMETRICS gm;
  205632. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205633. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205634. // gets correctly created later on.
  205635. if (! isFallbackFont)
  205636. {
  205637. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205638. WORD index = 0;
  205639. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205640. && index == 0xffff)
  205641. {
  205642. return false;
  205643. }
  205644. }
  205645. Path glyphPath;
  205646. TEXTMETRIC tm;
  205647. if (! GetTextMetrics (dc, &tm))
  205648. {
  205649. addGlyph (character, glyphPath, 0);
  205650. return true;
  205651. }
  205652. const float height = (float) tm.tmHeight;
  205653. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205654. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205655. &gm, 0, 0, &identityMatrix);
  205656. if (bufSize > 0)
  205657. {
  205658. HeapBlock<char> data (bufSize);
  205659. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205660. bufSize, data, &identityMatrix);
  205661. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205662. const float scaleX = 1.0f / height;
  205663. const float scaleY = -1.0f / height;
  205664. while ((char*) pheader < data + bufSize)
  205665. {
  205666. float x = scaleX * pheader->pfxStart.x.value;
  205667. float y = scaleY * pheader->pfxStart.y.value;
  205668. glyphPath.startNewSubPath (x, y);
  205669. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205670. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205671. while ((const char*) curve < curveEnd)
  205672. {
  205673. if (curve->wType == TT_PRIM_LINE)
  205674. {
  205675. for (int i = 0; i < curve->cpfx; ++i)
  205676. {
  205677. x = scaleX * curve->apfx[i].x.value;
  205678. y = scaleY * curve->apfx[i].y.value;
  205679. glyphPath.lineTo (x, y);
  205680. }
  205681. }
  205682. else if (curve->wType == TT_PRIM_QSPLINE)
  205683. {
  205684. for (int i = 0; i < curve->cpfx - 1; ++i)
  205685. {
  205686. const float x2 = scaleX * curve->apfx[i].x.value;
  205687. const float y2 = scaleY * curve->apfx[i].y.value;
  205688. float x3, y3;
  205689. if (i < curve->cpfx - 2)
  205690. {
  205691. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205692. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205693. }
  205694. else
  205695. {
  205696. x3 = scaleX * curve->apfx[i + 1].x.value;
  205697. y3 = scaleY * curve->apfx[i + 1].y.value;
  205698. }
  205699. glyphPath.quadraticTo (x2, y2, x3, y3);
  205700. x = x3;
  205701. y = y3;
  205702. }
  205703. }
  205704. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205705. }
  205706. pheader = (const TTPOLYGONHEADER*) curve;
  205707. glyphPath.closeSubPath();
  205708. }
  205709. }
  205710. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205711. int numKPs;
  205712. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205713. for (int i = 0; i < numKPs; ++i)
  205714. {
  205715. if (kps[i].wFirst == character)
  205716. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205717. kps[i].iKernAmount / height);
  205718. }
  205719. return true;
  205720. }
  205721. private:
  205722. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  205723. };
  205724. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205725. {
  205726. return new WindowsTypeface (font);
  205727. }
  205728. #endif
  205729. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205730. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205731. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205732. // compiled on its own).
  205733. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205734. class SharedD2DFactory : public DeletedAtShutdown
  205735. {
  205736. public:
  205737. SharedD2DFactory()
  205738. {
  205739. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205740. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205741. if (directWriteFactory != 0)
  205742. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205743. }
  205744. ~SharedD2DFactory()
  205745. {
  205746. clearSingletonInstance();
  205747. }
  205748. juce_DeclareSingleton (SharedD2DFactory, false);
  205749. ComSmartPtr <ID2D1Factory> d2dFactory;
  205750. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205751. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205752. };
  205753. juce_ImplementSingleton (SharedD2DFactory)
  205754. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205755. {
  205756. public:
  205757. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205758. : hwnd (hwnd_),
  205759. currentState (0)
  205760. {
  205761. RECT windowRect;
  205762. GetClientRect (hwnd, &windowRect);
  205763. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205764. bounds.setSize (size.width, size.height);
  205765. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205766. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205767. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205768. // xxx check for error
  205769. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205770. }
  205771. ~Direct2DLowLevelGraphicsContext()
  205772. {
  205773. states.clear();
  205774. }
  205775. void resized()
  205776. {
  205777. RECT windowRect;
  205778. GetClientRect (hwnd, &windowRect);
  205779. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205780. renderingTarget->Resize (size);
  205781. bounds.setSize (size.width, size.height);
  205782. }
  205783. void clear()
  205784. {
  205785. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205786. }
  205787. void start()
  205788. {
  205789. renderingTarget->BeginDraw();
  205790. saveState();
  205791. }
  205792. void end()
  205793. {
  205794. states.clear();
  205795. currentState = 0;
  205796. renderingTarget->EndDraw();
  205797. renderingTarget->CheckWindowState();
  205798. }
  205799. bool isVectorDevice() const { return false; }
  205800. void setOrigin (int x, int y)
  205801. {
  205802. currentState->origin.addXY (x, y);
  205803. }
  205804. void addTransform (const AffineTransform& transform)
  205805. {
  205806. //xxx todo
  205807. jassertfalse;
  205808. }
  205809. float getScaleFactor()
  205810. {
  205811. jassertfalse; //xxx
  205812. return 1.0f;
  205813. }
  205814. bool clipToRectangle (const Rectangle<int>& r)
  205815. {
  205816. currentState->clipToRectangle (r);
  205817. return ! isClipEmpty();
  205818. }
  205819. bool clipToRectangleList (const RectangleList& clipRegion)
  205820. {
  205821. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205822. return ! isClipEmpty();
  205823. }
  205824. void excludeClipRectangle (const Rectangle<int>&)
  205825. {
  205826. //xxx
  205827. }
  205828. void clipToPath (const Path& path, const AffineTransform& transform)
  205829. {
  205830. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205831. }
  205832. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205833. {
  205834. currentState->clipToImage (sourceImage,transform);
  205835. }
  205836. bool clipRegionIntersects (const Rectangle<int>& r)
  205837. {
  205838. const Rectangle<int> r2 (r + currentState->origin);
  205839. return currentState->clipRect.intersects (r2);
  205840. }
  205841. const Rectangle<int> getClipBounds() const
  205842. {
  205843. // xxx could this take into account complex clip regions?
  205844. return currentState->clipRect - currentState->origin;
  205845. }
  205846. bool isClipEmpty() const
  205847. {
  205848. return currentState->clipRect.isEmpty();
  205849. }
  205850. void saveState()
  205851. {
  205852. states.add (new SavedState (*this));
  205853. currentState = states.getLast();
  205854. }
  205855. void restoreState()
  205856. {
  205857. jassert (states.size() > 1) //you should never pop the last state!
  205858. states.removeLast (1);
  205859. currentState = states.getLast();
  205860. }
  205861. void beginTransparencyLayer (float opacity)
  205862. {
  205863. jassertfalse; //xxx todo
  205864. }
  205865. void endTransparencyLayer()
  205866. {
  205867. jassertfalse; //xxx todo
  205868. }
  205869. void setFill (const FillType& fillType)
  205870. {
  205871. currentState->setFill (fillType);
  205872. }
  205873. void setOpacity (float newOpacity)
  205874. {
  205875. currentState->setOpacity (newOpacity);
  205876. }
  205877. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205878. {
  205879. }
  205880. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205881. {
  205882. currentState->createBrush();
  205883. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205884. }
  205885. void fillPath (const Path& p, const AffineTransform& transform)
  205886. {
  205887. currentState->createBrush();
  205888. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205889. if (renderingTarget != 0)
  205890. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205891. }
  205892. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205893. {
  205894. const int x = currentState->origin.getX();
  205895. const int y = currentState->origin.getY();
  205896. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205897. D2D1_SIZE_U size;
  205898. size.width = image.getWidth();
  205899. size.height = image.getHeight();
  205900. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205901. Image img (image.convertedToFormat (Image::ARGB));
  205902. Image::BitmapData bd (img, false);
  205903. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205904. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205905. {
  205906. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205907. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205908. if (tempBitmap != 0)
  205909. renderingTarget->DrawBitmap (tempBitmap);
  205910. }
  205911. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205912. }
  205913. void drawLine (const Line <float>& line)
  205914. {
  205915. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205916. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205917. line.getEnd() + currentState->origin.toFloat());
  205918. currentState->createBrush();
  205919. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205920. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205921. currentState->currentBrush);
  205922. }
  205923. void drawVerticalLine (int x, float top, float bottom)
  205924. {
  205925. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205926. currentState->createBrush();
  205927. x += currentState->origin.getX();
  205928. const int y = currentState->origin.getY();
  205929. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205930. D2D1::Point2F (x, y + bottom),
  205931. currentState->currentBrush);
  205932. }
  205933. void drawHorizontalLine (int y, float left, float right)
  205934. {
  205935. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205936. currentState->createBrush();
  205937. y += currentState->origin.getY();
  205938. const int x = currentState->origin.getX();
  205939. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205940. D2D1::Point2F (x + right, y),
  205941. currentState->currentBrush);
  205942. }
  205943. void setFont (const Font& newFont)
  205944. {
  205945. currentState->setFont (newFont);
  205946. }
  205947. const Font getFont()
  205948. {
  205949. return currentState->font;
  205950. }
  205951. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205952. {
  205953. const float x = currentState->origin.getX();
  205954. const float y = currentState->origin.getY();
  205955. currentState->createBrush();
  205956. currentState->createFont();
  205957. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205958. float hScale = currentState->font.getHorizontalScale();
  205959. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205960. float dpiX = 0, dpiY = 0;
  205961. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205962. UINT32 glyphNum = glyphNumber;
  205963. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205964. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205965. DWRITE_GLYPH_OFFSET offset;
  205966. offset.advanceOffset = 0;
  205967. offset.ascenderOffset = 0;
  205968. float glyphAdvances = 0;
  205969. DWRITE_GLYPH_RUN glyph;
  205970. glyph.fontFace = currentState->currentFontFace;
  205971. glyph.glyphCount = 1;
  205972. glyph.glyphIndices = &glyphNum1;
  205973. glyph.isSideways = FALSE;
  205974. glyph.glyphAdvances = &glyphAdvances;
  205975. glyph.glyphOffsets = &offset;
  205976. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  205977. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  205978. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205979. }
  205980. class SavedState
  205981. {
  205982. public:
  205983. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  205984. : owner (owner_), currentBrush (0),
  205985. fontScaling (1.0f), currentFontFace (0),
  205986. clipsRect (false), shouldClipRect (false),
  205987. clipsRectList (false), shouldClipRectList (false),
  205988. clipsComplex (false), shouldClipComplex (false),
  205989. clipsBitmap (false), shouldClipBitmap (false)
  205990. {
  205991. if (owner.currentState != 0)
  205992. {
  205993. // xxx seems like a very slow way to create one of these, and this is a performance
  205994. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  205995. setFill (owner.currentState->fillType);
  205996. currentBrush = owner.currentState->currentBrush;
  205997. origin = owner.currentState->origin;
  205998. clipRect = owner.currentState->clipRect;
  205999. font = owner.currentState->font;
  206000. currentFontFace = owner.currentState->currentFontFace;
  206001. }
  206002. else
  206003. {
  206004. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206005. clipRect.setSize (size.width, size.height);
  206006. setFill (FillType (Colours::black));
  206007. }
  206008. }
  206009. ~SavedState()
  206010. {
  206011. clearClip();
  206012. clearFont();
  206013. clearFill();
  206014. clearPathClip();
  206015. clearImageClip();
  206016. complexClipLayer = 0;
  206017. bitmapMaskLayer = 0;
  206018. }
  206019. void clearClip()
  206020. {
  206021. popClips();
  206022. shouldClipRect = false;
  206023. }
  206024. void clipToRectangle (const Rectangle<int>& r)
  206025. {
  206026. clearClip();
  206027. clipRect = r + origin;
  206028. shouldClipRect = true;
  206029. pushClips();
  206030. }
  206031. void clearPathClip()
  206032. {
  206033. popClips();
  206034. if (shouldClipComplex)
  206035. {
  206036. complexClipGeometry = 0;
  206037. shouldClipComplex = false;
  206038. }
  206039. }
  206040. void clipToPath (ID2D1Geometry* geometry)
  206041. {
  206042. clearPathClip();
  206043. if (complexClipLayer == 0)
  206044. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206045. complexClipGeometry = geometry;
  206046. shouldClipComplex = true;
  206047. pushClips();
  206048. }
  206049. void clearRectListClip()
  206050. {
  206051. popClips();
  206052. if (shouldClipRectList)
  206053. {
  206054. rectListGeometry = 0;
  206055. shouldClipRectList = false;
  206056. }
  206057. }
  206058. void clipToRectList (ID2D1Geometry* geometry)
  206059. {
  206060. clearRectListClip();
  206061. if (rectListLayer == 0)
  206062. owner.renderingTarget->CreateLayer (&rectListLayer);
  206063. rectListGeometry = geometry;
  206064. shouldClipRectList = true;
  206065. pushClips();
  206066. }
  206067. void clearImageClip()
  206068. {
  206069. popClips();
  206070. if (shouldClipBitmap)
  206071. {
  206072. maskBitmap = 0;
  206073. bitmapMaskBrush = 0;
  206074. shouldClipBitmap = false;
  206075. }
  206076. }
  206077. void clipToImage (const Image& image, const AffineTransform& transform)
  206078. {
  206079. clearImageClip();
  206080. if (bitmapMaskLayer == 0)
  206081. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206082. D2D1_BRUSH_PROPERTIES brushProps;
  206083. brushProps.opacity = 1;
  206084. brushProps.transform = transfromToMatrix (transform);
  206085. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206086. D2D1_SIZE_U size;
  206087. size.width = image.getWidth();
  206088. size.height = image.getHeight();
  206089. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206090. maskImage = image.convertedToFormat (Image::ARGB);
  206091. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206092. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206093. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206094. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206095. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206096. imageMaskLayerParams = D2D1::LayerParameters();
  206097. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206098. shouldClipBitmap = true;
  206099. pushClips();
  206100. }
  206101. void popClips()
  206102. {
  206103. if (clipsBitmap)
  206104. {
  206105. owner.renderingTarget->PopLayer();
  206106. clipsBitmap = false;
  206107. }
  206108. if (clipsComplex)
  206109. {
  206110. owner.renderingTarget->PopLayer();
  206111. clipsComplex = false;
  206112. }
  206113. if (clipsRectList)
  206114. {
  206115. owner.renderingTarget->PopLayer();
  206116. clipsRectList = false;
  206117. }
  206118. if (clipsRect)
  206119. {
  206120. owner.renderingTarget->PopAxisAlignedClip();
  206121. clipsRect = false;
  206122. }
  206123. }
  206124. void pushClips()
  206125. {
  206126. if (shouldClipRect && ! clipsRect)
  206127. {
  206128. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206129. clipsRect = true;
  206130. }
  206131. if (shouldClipRectList && ! clipsRectList)
  206132. {
  206133. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206134. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206135. layerParams.geometricMask = rectListGeometry;
  206136. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206137. clipsRectList = true;
  206138. }
  206139. if (shouldClipComplex && ! clipsComplex)
  206140. {
  206141. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206142. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206143. layerParams.geometricMask = complexClipGeometry;
  206144. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206145. clipsComplex = true;
  206146. }
  206147. if (shouldClipBitmap && ! clipsBitmap)
  206148. {
  206149. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206150. clipsBitmap = true;
  206151. }
  206152. }
  206153. void setFill (const FillType& newFillType)
  206154. {
  206155. if (fillType != newFillType)
  206156. {
  206157. fillType = newFillType;
  206158. clearFill();
  206159. }
  206160. }
  206161. void clearFont()
  206162. {
  206163. currentFontFace = localFontFace = 0;
  206164. }
  206165. void setFont (const Font& newFont)
  206166. {
  206167. if (font != newFont)
  206168. {
  206169. font = newFont;
  206170. clearFont();
  206171. }
  206172. }
  206173. void createFont()
  206174. {
  206175. // xxx The font shouldn't be managed by the graphics context.
  206176. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206177. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206178. // WindowsTypeface class.
  206179. if (currentFontFace == 0)
  206180. {
  206181. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206182. fontScaling = systemType->getAscent();
  206183. BOOL fontFound;
  206184. uint32 fontIndex;
  206185. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206186. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206187. if (! fontFound)
  206188. fontIndex = 0;
  206189. ComSmartPtr <IDWriteFontFamily> fontFam;
  206190. fonts->GetFontFamily (fontIndex, &fontFam);
  206191. ComSmartPtr <IDWriteFont> font;
  206192. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206193. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206194. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206195. font->CreateFontFace (&localFontFace);
  206196. currentFontFace = localFontFace;
  206197. }
  206198. }
  206199. void setOpacity (float newOpacity)
  206200. {
  206201. fillType.setOpacity (newOpacity);
  206202. if (currentBrush != 0)
  206203. currentBrush->SetOpacity (newOpacity);
  206204. }
  206205. void clearFill()
  206206. {
  206207. gradientStops = 0;
  206208. linearGradient = 0;
  206209. radialGradient = 0;
  206210. bitmap = 0;
  206211. bitmapBrush = 0;
  206212. currentBrush = 0;
  206213. }
  206214. void createBrush()
  206215. {
  206216. if (currentBrush == 0)
  206217. {
  206218. const int x = origin.getX();
  206219. const int y = origin.getY();
  206220. if (fillType.isColour())
  206221. {
  206222. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206223. owner.colourBrush->SetColor (colour);
  206224. currentBrush = owner.colourBrush;
  206225. }
  206226. else if (fillType.isTiledImage())
  206227. {
  206228. D2D1_BRUSH_PROPERTIES brushProps;
  206229. brushProps.opacity = fillType.getOpacity();
  206230. brushProps.transform = transfromToMatrix (fillType.transform);
  206231. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206232. image = fillType.image;
  206233. D2D1_SIZE_U size;
  206234. size.width = image.getWidth();
  206235. size.height = image.getHeight();
  206236. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206237. this->image = image.convertedToFormat (Image::ARGB);
  206238. Image::BitmapData bd (this->image, false);
  206239. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206240. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206241. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206242. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206243. currentBrush = bitmapBrush;
  206244. }
  206245. else if (fillType.isGradient())
  206246. {
  206247. gradientStops = 0;
  206248. D2D1_BRUSH_PROPERTIES brushProps;
  206249. brushProps.opacity = fillType.getOpacity();
  206250. brushProps.transform = transfromToMatrix (fillType.transform);
  206251. const int numColors = fillType.gradient->getNumColours();
  206252. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206253. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206254. {
  206255. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206256. stops[i].position = fillType.gradient->getColourPosition(i);
  206257. }
  206258. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206259. if (fillType.gradient->isRadial)
  206260. {
  206261. radialGradient = 0;
  206262. const Point<float>& p1 = fillType.gradient->point1;
  206263. const Point<float>& p2 = fillType.gradient->point2;
  206264. float r = p1.getDistanceFrom (p2);
  206265. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206266. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206267. D2D1::Point2F (0, 0),
  206268. r, r);
  206269. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206270. currentBrush = radialGradient;
  206271. }
  206272. else
  206273. {
  206274. linearGradient = 0;
  206275. const Point<float>& p1 = fillType.gradient->point1;
  206276. const Point<float>& p2 = fillType.gradient->point2;
  206277. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206278. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206279. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206280. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206281. currentBrush = linearGradient;
  206282. }
  206283. }
  206284. }
  206285. }
  206286. //xxx most of these members should probably be private...
  206287. Direct2DLowLevelGraphicsContext& owner;
  206288. Point<int> origin;
  206289. Font font;
  206290. float fontScaling;
  206291. IDWriteFontFace* currentFontFace;
  206292. ComSmartPtr <IDWriteFontFace> localFontFace;
  206293. FillType fillType;
  206294. Image image;
  206295. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206296. Rectangle<int> clipRect;
  206297. bool clipsRect, shouldClipRect;
  206298. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206299. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206300. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206301. bool clipsComplex, shouldClipComplex;
  206302. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206303. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206304. ComSmartPtr <ID2D1Layer> rectListLayer;
  206305. bool clipsRectList, shouldClipRectList;
  206306. Image maskImage;
  206307. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206308. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206309. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206310. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206311. bool clipsBitmap, shouldClipBitmap;
  206312. ID2D1Brush* currentBrush;
  206313. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206314. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206315. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206316. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206317. private:
  206318. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206319. };
  206320. private:
  206321. HWND hwnd;
  206322. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206323. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206324. Rectangle<int> bounds;
  206325. SavedState* currentState;
  206326. OwnedArray<SavedState> states;
  206327. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206328. {
  206329. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206330. }
  206331. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206332. {
  206333. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206334. }
  206335. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206336. {
  206337. transform.transformPoint (x, y);
  206338. return D2D1::Point2F (x, y);
  206339. }
  206340. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206341. {
  206342. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206343. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206344. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206345. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206346. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206347. }
  206348. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206349. {
  206350. ID2D1PathGeometry* p = 0;
  206351. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206352. ComSmartPtr <ID2D1GeometrySink> sink;
  206353. HRESULT hr = p->Open (&sink); // xxx handle error
  206354. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206355. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206356. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206357. hr = sink->Close();
  206358. return p;
  206359. }
  206360. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206361. {
  206362. Path::Iterator it (path);
  206363. while (it.next())
  206364. {
  206365. switch (it.elementType)
  206366. {
  206367. case Path::Iterator::cubicTo:
  206368. {
  206369. D2D1_BEZIER_SEGMENT seg;
  206370. transform.transformPoint (it.x1, it.y1);
  206371. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206372. transform.transformPoint (it.x2, it.y2);
  206373. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206374. transform.transformPoint(it.x3, it.y3);
  206375. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206376. sink->AddBezier (seg);
  206377. break;
  206378. }
  206379. case Path::Iterator::lineTo:
  206380. {
  206381. transform.transformPoint (it.x1, it.y1);
  206382. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206383. break;
  206384. }
  206385. case Path::Iterator::quadraticTo:
  206386. {
  206387. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206388. transform.transformPoint (it.x1, it.y1);
  206389. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206390. transform.transformPoint (it.x2, it.y2);
  206391. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206392. sink->AddQuadraticBezier (seg);
  206393. break;
  206394. }
  206395. case Path::Iterator::closePath:
  206396. {
  206397. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206398. break;
  206399. }
  206400. case Path::Iterator::startNewSubPath:
  206401. {
  206402. transform.transformPoint (it.x1, it.y1);
  206403. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206404. break;
  206405. }
  206406. }
  206407. }
  206408. }
  206409. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206410. {
  206411. ID2D1PathGeometry* p = 0;
  206412. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206413. ComSmartPtr <ID2D1GeometrySink> sink;
  206414. HRESULT hr = p->Open (&sink);
  206415. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206416. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206417. hr = sink->Close();
  206418. return p;
  206419. }
  206420. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206421. {
  206422. D2D1::Matrix3x2F matrix;
  206423. matrix._11 = transform.mat00;
  206424. matrix._12 = transform.mat10;
  206425. matrix._21 = transform.mat01;
  206426. matrix._22 = transform.mat11;
  206427. matrix._31 = transform.mat02;
  206428. matrix._32 = transform.mat12;
  206429. return matrix;
  206430. }
  206431. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206432. };
  206433. #endif
  206434. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206435. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206436. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206437. // compiled on its own).
  206438. #if JUCE_INCLUDED_FILE
  206439. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206440. // these are in the windows SDK, but need to be repeated here for GCC..
  206441. #ifndef GET_APPCOMMAND_LPARAM
  206442. #define FAPPCOMMAND_MASK 0xF000
  206443. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206444. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206445. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206446. #define APPCOMMAND_MEDIA_STOP 13
  206447. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206448. #define WM_APPCOMMAND 0x0319
  206449. #endif
  206450. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206451. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206452. extern bool juce_IsRunningInWine();
  206453. #ifndef ULW_ALPHA
  206454. #define ULW_ALPHA 0x00000002
  206455. #endif
  206456. #ifndef AC_SRC_ALPHA
  206457. #define AC_SRC_ALPHA 0x01
  206458. #endif
  206459. static HPALETTE palette = 0;
  206460. static bool createPaletteIfNeeded = true;
  206461. static bool shouldDeactivateTitleBar = true;
  206462. #define WM_TRAYNOTIFY WM_USER + 100
  206463. using ::abs;
  206464. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206465. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206466. bool Desktop::canUseSemiTransparentWindows() throw()
  206467. {
  206468. if (updateLayeredWindow == 0)
  206469. {
  206470. if (! juce_IsRunningInWine())
  206471. {
  206472. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206473. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206474. }
  206475. }
  206476. return updateLayeredWindow != 0;
  206477. }
  206478. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206479. {
  206480. return upright;
  206481. }
  206482. const int extendedKeyModifier = 0x10000;
  206483. const int KeyPress::spaceKey = VK_SPACE;
  206484. const int KeyPress::returnKey = VK_RETURN;
  206485. const int KeyPress::escapeKey = VK_ESCAPE;
  206486. const int KeyPress::backspaceKey = VK_BACK;
  206487. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206488. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206489. const int KeyPress::tabKey = VK_TAB;
  206490. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206491. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206492. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206493. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206494. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206495. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206496. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206497. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206498. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206499. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206500. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206501. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206502. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206503. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206504. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206505. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206506. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206507. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206508. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206509. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206510. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206511. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206512. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206513. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206514. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206515. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206516. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206517. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206518. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206519. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206520. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206521. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206522. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206523. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206524. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206525. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206526. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206527. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206528. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206529. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206530. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206531. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206532. const int KeyPress::playKey = 0x30000;
  206533. const int KeyPress::stopKey = 0x30001;
  206534. const int KeyPress::fastForwardKey = 0x30002;
  206535. const int KeyPress::rewindKey = 0x30003;
  206536. class WindowsBitmapImage : public Image::SharedImage
  206537. {
  206538. public:
  206539. HBITMAP hBitmap;
  206540. BITMAPV4HEADER bitmapInfo;
  206541. HDC hdc;
  206542. unsigned char* bitmapData;
  206543. WindowsBitmapImage (const Image::PixelFormat format_,
  206544. const int w, const int h, const bool clearImage)
  206545. : Image::SharedImage (format_, w, h)
  206546. {
  206547. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206548. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206549. zerostruct (bitmapInfo);
  206550. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206551. bitmapInfo.bV4Width = w;
  206552. bitmapInfo.bV4Height = h;
  206553. bitmapInfo.bV4Planes = 1;
  206554. bitmapInfo.bV4CSType = 1;
  206555. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206556. if (format_ == Image::ARGB)
  206557. {
  206558. bitmapInfo.bV4AlphaMask = 0xff000000;
  206559. bitmapInfo.bV4RedMask = 0xff0000;
  206560. bitmapInfo.bV4GreenMask = 0xff00;
  206561. bitmapInfo.bV4BlueMask = 0xff;
  206562. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206563. }
  206564. else
  206565. {
  206566. bitmapInfo.bV4V4Compression = BI_RGB;
  206567. }
  206568. lineStride = -((w * pixelStride + 3) & ~3);
  206569. HDC dc = GetDC (0);
  206570. hdc = CreateCompatibleDC (dc);
  206571. ReleaseDC (0, dc);
  206572. SetMapMode (hdc, MM_TEXT);
  206573. hBitmap = CreateDIBSection (hdc,
  206574. (BITMAPINFO*) &(bitmapInfo),
  206575. DIB_RGB_COLORS,
  206576. (void**) &bitmapData,
  206577. 0, 0);
  206578. SelectObject (hdc, hBitmap);
  206579. if (format_ == Image::ARGB && clearImage)
  206580. zeromem (bitmapData, abs (h * lineStride));
  206581. imageData = bitmapData - (lineStride * (h - 1));
  206582. }
  206583. ~WindowsBitmapImage()
  206584. {
  206585. DeleteDC (hdc);
  206586. DeleteObject (hBitmap);
  206587. }
  206588. Image::ImageType getType() const { return Image::NativeImage; }
  206589. LowLevelGraphicsContext* createLowLevelContext()
  206590. {
  206591. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206592. }
  206593. Image::SharedImage* clone()
  206594. {
  206595. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206596. for (int i = 0; i < height; ++i)
  206597. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206598. return im;
  206599. }
  206600. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206601. const int x, const int y,
  206602. const RectangleList& maskedRegion,
  206603. const uint8 updateLayeredWindowAlpha) throw()
  206604. {
  206605. static HDRAWDIB hdd = 0;
  206606. static bool needToCreateDrawDib = true;
  206607. if (needToCreateDrawDib)
  206608. {
  206609. needToCreateDrawDib = false;
  206610. HDC dc = GetDC (0);
  206611. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206612. ReleaseDC (0, dc);
  206613. // only open if we're not palettised
  206614. if (n > 8)
  206615. hdd = DrawDibOpen();
  206616. }
  206617. if (createPaletteIfNeeded)
  206618. {
  206619. HDC dc = GetDC (0);
  206620. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206621. ReleaseDC (0, dc);
  206622. if (n <= 8)
  206623. palette = CreateHalftonePalette (dc);
  206624. createPaletteIfNeeded = false;
  206625. }
  206626. if (palette != 0)
  206627. {
  206628. SelectPalette (dc, palette, FALSE);
  206629. RealizePalette (dc);
  206630. SetStretchBltMode (dc, HALFTONE);
  206631. }
  206632. SetMapMode (dc, MM_TEXT);
  206633. if (transparent)
  206634. {
  206635. POINT p, pos;
  206636. SIZE size;
  206637. RECT windowBounds;
  206638. GetWindowRect (hwnd, &windowBounds);
  206639. p.x = -x;
  206640. p.y = -y;
  206641. pos.x = windowBounds.left;
  206642. pos.y = windowBounds.top;
  206643. size.cx = windowBounds.right - windowBounds.left;
  206644. size.cy = windowBounds.bottom - windowBounds.top;
  206645. BLENDFUNCTION bf;
  206646. bf.AlphaFormat = AC_SRC_ALPHA;
  206647. bf.BlendFlags = 0;
  206648. bf.BlendOp = AC_SRC_OVER;
  206649. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206650. if (! maskedRegion.isEmpty())
  206651. {
  206652. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206653. {
  206654. const Rectangle<int>& r = *i.getRectangle();
  206655. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206656. }
  206657. }
  206658. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206659. }
  206660. else
  206661. {
  206662. int savedDC = 0;
  206663. if (! maskedRegion.isEmpty())
  206664. {
  206665. savedDC = SaveDC (dc);
  206666. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206667. {
  206668. const Rectangle<int>& r = *i.getRectangle();
  206669. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206670. }
  206671. }
  206672. if (hdd == 0)
  206673. {
  206674. StretchDIBits (dc,
  206675. x, y, width, height,
  206676. 0, 0, width, height,
  206677. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206678. DIB_RGB_COLORS, SRCCOPY);
  206679. }
  206680. else
  206681. {
  206682. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206683. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206684. 0, 0, width, height, 0);
  206685. }
  206686. if (! maskedRegion.isEmpty())
  206687. RestoreDC (dc, savedDC);
  206688. }
  206689. }
  206690. private:
  206691. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206692. };
  206693. namespace IconConverters
  206694. {
  206695. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206696. {
  206697. Image im;
  206698. if (bitmap != 0)
  206699. {
  206700. BITMAP bm;
  206701. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206702. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206703. {
  206704. HDC tempDC = GetDC (0);
  206705. HDC dc = CreateCompatibleDC (tempDC);
  206706. ReleaseDC (0, tempDC);
  206707. SelectObject (dc, bitmap);
  206708. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206709. Image::BitmapData imageData (im, true);
  206710. for (int y = bm.bmHeight; --y >= 0;)
  206711. {
  206712. for (int x = bm.bmWidth; --x >= 0;)
  206713. {
  206714. COLORREF col = GetPixel (dc, x, y);
  206715. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206716. (uint8) GetGValue (col),
  206717. (uint8) GetBValue (col)));
  206718. }
  206719. }
  206720. DeleteDC (dc);
  206721. }
  206722. }
  206723. return im;
  206724. }
  206725. const Image createImageFromHICON (HICON icon)
  206726. {
  206727. ICONINFO info;
  206728. if (GetIconInfo (icon, &info))
  206729. {
  206730. Image mask (createImageFromHBITMAP (info.hbmMask));
  206731. Image image (createImageFromHBITMAP (info.hbmColor));
  206732. if (mask.isValid() && image.isValid())
  206733. {
  206734. for (int y = image.getHeight(); --y >= 0;)
  206735. {
  206736. for (int x = image.getWidth(); --x >= 0;)
  206737. {
  206738. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206739. if (brightness > 0.0f)
  206740. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206741. }
  206742. }
  206743. return image;
  206744. }
  206745. }
  206746. return Image::null;
  206747. }
  206748. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206749. {
  206750. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206751. Image bitmap (nativeBitmap);
  206752. {
  206753. Graphics g (bitmap);
  206754. g.drawImageAt (image, 0, 0);
  206755. }
  206756. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206757. ICONINFO info;
  206758. info.fIcon = isIcon;
  206759. info.xHotspot = hotspotX;
  206760. info.yHotspot = hotspotY;
  206761. info.hbmMask = mask;
  206762. info.hbmColor = nativeBitmap->hBitmap;
  206763. HICON hi = CreateIconIndirect (&info);
  206764. DeleteObject (mask);
  206765. return hi;
  206766. }
  206767. }
  206768. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206769. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206770. {
  206771. SHORT k = (SHORT) keyCode;
  206772. if ((keyCode & extendedKeyModifier) == 0
  206773. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206774. k += (SHORT) 'A' - (SHORT) 'a';
  206775. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206776. (SHORT) '+', VK_OEM_PLUS,
  206777. (SHORT) '-', VK_OEM_MINUS,
  206778. (SHORT) '.', VK_OEM_PERIOD,
  206779. (SHORT) ';', VK_OEM_1,
  206780. (SHORT) ':', VK_OEM_1,
  206781. (SHORT) '/', VK_OEM_2,
  206782. (SHORT) '?', VK_OEM_2,
  206783. (SHORT) '[', VK_OEM_4,
  206784. (SHORT) ']', VK_OEM_6 };
  206785. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206786. if (k == translatedValues [i])
  206787. k = translatedValues [i + 1];
  206788. return (GetKeyState (k) & 0x8000) != 0;
  206789. }
  206790. class Win32ComponentPeer : public ComponentPeer
  206791. {
  206792. public:
  206793. enum RenderingEngineType
  206794. {
  206795. softwareRenderingEngine = 0,
  206796. direct2DRenderingEngine
  206797. };
  206798. Win32ComponentPeer (Component* const component,
  206799. const int windowStyleFlags,
  206800. HWND parentToAddTo_)
  206801. : ComponentPeer (component, windowStyleFlags),
  206802. dontRepaint (false),
  206803. #if JUCE_DIRECT2D
  206804. currentRenderingEngine (direct2DRenderingEngine),
  206805. #else
  206806. currentRenderingEngine (softwareRenderingEngine),
  206807. #endif
  206808. fullScreen (false),
  206809. isDragging (false),
  206810. isMouseOver (false),
  206811. hasCreatedCaret (false),
  206812. currentWindowIcon (0),
  206813. dropTarget (0),
  206814. updateLayeredWindowAlpha (255),
  206815. parentToAddTo (parentToAddTo_)
  206816. {
  206817. callFunctionIfNotLocked (&createWindowCallback, this);
  206818. setTitle (component->getName());
  206819. if ((windowStyleFlags & windowHasDropShadow) != 0
  206820. && Desktop::canUseSemiTransparentWindows())
  206821. {
  206822. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206823. if (shadower != 0)
  206824. shadower->setOwner (component);
  206825. }
  206826. }
  206827. ~Win32ComponentPeer()
  206828. {
  206829. setTaskBarIcon (Image());
  206830. shadower = 0;
  206831. // do this before the next bit to avoid messages arriving for this window
  206832. // before it's destroyed
  206833. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206834. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206835. if (currentWindowIcon != 0)
  206836. DestroyIcon (currentWindowIcon);
  206837. if (dropTarget != 0)
  206838. {
  206839. dropTarget->Release();
  206840. dropTarget = 0;
  206841. }
  206842. #if JUCE_DIRECT2D
  206843. direct2DContext = 0;
  206844. #endif
  206845. }
  206846. void* getNativeHandle() const
  206847. {
  206848. return hwnd;
  206849. }
  206850. void setVisible (bool shouldBeVisible)
  206851. {
  206852. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206853. if (shouldBeVisible)
  206854. InvalidateRect (hwnd, 0, 0);
  206855. else
  206856. lastPaintTime = 0;
  206857. }
  206858. void setTitle (const String& title)
  206859. {
  206860. SetWindowText (hwnd, title);
  206861. }
  206862. void setPosition (int x, int y)
  206863. {
  206864. offsetWithinParent (x, y);
  206865. SetWindowPos (hwnd, 0,
  206866. x - windowBorder.getLeft(),
  206867. y - windowBorder.getTop(),
  206868. 0, 0,
  206869. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206870. }
  206871. void repaintNowIfTransparent()
  206872. {
  206873. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206874. handlePaintMessage();
  206875. }
  206876. void updateBorderSize()
  206877. {
  206878. WINDOWINFO info;
  206879. info.cbSize = sizeof (info);
  206880. if (GetWindowInfo (hwnd, &info))
  206881. {
  206882. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206883. info.rcClient.left - info.rcWindow.left,
  206884. info.rcWindow.bottom - info.rcClient.bottom,
  206885. info.rcWindow.right - info.rcClient.right);
  206886. }
  206887. #if JUCE_DIRECT2D
  206888. if (direct2DContext != 0)
  206889. direct2DContext->resized();
  206890. #endif
  206891. }
  206892. void setSize (int w, int h)
  206893. {
  206894. SetWindowPos (hwnd, 0, 0, 0,
  206895. w + windowBorder.getLeftAndRight(),
  206896. h + windowBorder.getTopAndBottom(),
  206897. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206898. updateBorderSize();
  206899. repaintNowIfTransparent();
  206900. }
  206901. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206902. {
  206903. fullScreen = isNowFullScreen;
  206904. offsetWithinParent (x, y);
  206905. SetWindowPos (hwnd, 0,
  206906. x - windowBorder.getLeft(),
  206907. y - windowBorder.getTop(),
  206908. w + windowBorder.getLeftAndRight(),
  206909. h + windowBorder.getTopAndBottom(),
  206910. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206911. updateBorderSize();
  206912. repaintNowIfTransparent();
  206913. }
  206914. const Rectangle<int> getBounds() const
  206915. {
  206916. RECT r;
  206917. GetWindowRect (hwnd, &r);
  206918. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206919. HWND parentH = GetParent (hwnd);
  206920. if (parentH != 0)
  206921. {
  206922. GetWindowRect (parentH, &r);
  206923. bounds.translate (-r.left, -r.top);
  206924. }
  206925. return windowBorder.subtractedFrom (bounds);
  206926. }
  206927. const Point<int> getScreenPosition() const
  206928. {
  206929. RECT r;
  206930. GetWindowRect (hwnd, &r);
  206931. return Point<int> (r.left + windowBorder.getLeft(),
  206932. r.top + windowBorder.getTop());
  206933. }
  206934. const Point<int> localToGlobal (const Point<int>& relativePosition)
  206935. {
  206936. return relativePosition + getScreenPosition();
  206937. }
  206938. const Point<int> globalToLocal (const Point<int>& screenPosition)
  206939. {
  206940. return screenPosition - getScreenPosition();
  206941. }
  206942. void setAlpha (float newAlpha)
  206943. {
  206944. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  206945. if (component->isOpaque())
  206946. {
  206947. if (newAlpha < 1.0f)
  206948. {
  206949. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  206950. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  206951. }
  206952. else
  206953. {
  206954. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  206955. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  206956. }
  206957. }
  206958. else
  206959. {
  206960. updateLayeredWindowAlpha = intAlpha;
  206961. component->repaint();
  206962. }
  206963. }
  206964. void setMinimised (bool shouldBeMinimised)
  206965. {
  206966. if (shouldBeMinimised != isMinimised())
  206967. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206968. }
  206969. bool isMinimised() const
  206970. {
  206971. WINDOWPLACEMENT wp;
  206972. wp.length = sizeof (WINDOWPLACEMENT);
  206973. GetWindowPlacement (hwnd, &wp);
  206974. return wp.showCmd == SW_SHOWMINIMIZED;
  206975. }
  206976. void setFullScreen (bool shouldBeFullScreen)
  206977. {
  206978. setMinimised (false);
  206979. if (fullScreen != shouldBeFullScreen)
  206980. {
  206981. fullScreen = shouldBeFullScreen;
  206982. const WeakReference<Component> deletionChecker (component);
  206983. if (! fullScreen)
  206984. {
  206985. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206986. if (hasTitleBar())
  206987. ShowWindow (hwnd, SW_SHOWNORMAL);
  206988. if (! boundsCopy.isEmpty())
  206989. {
  206990. setBounds (boundsCopy.getX(),
  206991. boundsCopy.getY(),
  206992. boundsCopy.getWidth(),
  206993. boundsCopy.getHeight(),
  206994. false);
  206995. }
  206996. }
  206997. else
  206998. {
  206999. if (hasTitleBar())
  207000. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207001. else
  207002. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207003. }
  207004. if (deletionChecker != 0)
  207005. handleMovedOrResized();
  207006. }
  207007. }
  207008. bool isFullScreen() const
  207009. {
  207010. if (! hasTitleBar())
  207011. return fullScreen;
  207012. WINDOWPLACEMENT wp;
  207013. wp.length = sizeof (wp);
  207014. GetWindowPlacement (hwnd, &wp);
  207015. return wp.showCmd == SW_SHOWMAXIMIZED;
  207016. }
  207017. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207018. {
  207019. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  207020. && isPositiveAndBelow (position.getY(), component->getHeight())))
  207021. return false;
  207022. RECT r;
  207023. GetWindowRect (hwnd, &r);
  207024. POINT p;
  207025. p.x = position.getX() + r.left + windowBorder.getLeft();
  207026. p.y = position.getY() + r.top + windowBorder.getTop();
  207027. HWND w = WindowFromPoint (p);
  207028. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207029. }
  207030. const BorderSize getFrameSize() const
  207031. {
  207032. return windowBorder;
  207033. }
  207034. bool setAlwaysOnTop (bool alwaysOnTop)
  207035. {
  207036. const bool oldDeactivate = shouldDeactivateTitleBar;
  207037. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207038. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207039. 0, 0, 0, 0,
  207040. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207041. shouldDeactivateTitleBar = oldDeactivate;
  207042. if (shadower != 0)
  207043. shadower->componentBroughtToFront (*component);
  207044. return true;
  207045. }
  207046. void toFront (bool makeActive)
  207047. {
  207048. setMinimised (false);
  207049. const bool oldDeactivate = shouldDeactivateTitleBar;
  207050. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207051. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207052. shouldDeactivateTitleBar = oldDeactivate;
  207053. if (! makeActive)
  207054. {
  207055. // in this case a broughttofront call won't have occured, so do it now..
  207056. handleBroughtToFront();
  207057. }
  207058. }
  207059. void toBehind (ComponentPeer* other)
  207060. {
  207061. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207062. jassert (otherPeer != 0); // wrong type of window?
  207063. if (otherPeer != 0)
  207064. {
  207065. setMinimised (false);
  207066. // must be careful not to try to put a topmost window behind a normal one, or win32
  207067. // promotes the normal one to be topmost!
  207068. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207069. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207070. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207071. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207072. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207073. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207074. }
  207075. }
  207076. bool isFocused() const
  207077. {
  207078. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207079. }
  207080. void grabFocus()
  207081. {
  207082. const bool oldDeactivate = shouldDeactivateTitleBar;
  207083. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207084. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207085. shouldDeactivateTitleBar = oldDeactivate;
  207086. }
  207087. void textInputRequired (const Point<int>&)
  207088. {
  207089. if (! hasCreatedCaret)
  207090. {
  207091. hasCreatedCaret = true;
  207092. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207093. }
  207094. ShowCaret (hwnd);
  207095. SetCaretPos (0, 0);
  207096. }
  207097. void repaint (const Rectangle<int>& area)
  207098. {
  207099. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207100. InvalidateRect (hwnd, &r, FALSE);
  207101. }
  207102. void performAnyPendingRepaintsNow()
  207103. {
  207104. MSG m;
  207105. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207106. DispatchMessage (&m);
  207107. }
  207108. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207109. {
  207110. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207111. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207112. return 0;
  207113. }
  207114. void setTaskBarIcon (const Image& image)
  207115. {
  207116. if (image.isValid())
  207117. {
  207118. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207119. if (taskBarIcon == 0)
  207120. {
  207121. taskBarIcon = new NOTIFYICONDATA();
  207122. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  207123. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207124. taskBarIcon->hWnd = (HWND) hwnd;
  207125. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207126. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207127. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207128. taskBarIcon->hIcon = hicon;
  207129. taskBarIcon->szTip[0] = 0;
  207130. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207131. }
  207132. else
  207133. {
  207134. HICON oldIcon = taskBarIcon->hIcon;
  207135. taskBarIcon->hIcon = hicon;
  207136. taskBarIcon->uFlags = NIF_ICON;
  207137. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207138. DestroyIcon (oldIcon);
  207139. }
  207140. }
  207141. else if (taskBarIcon != 0)
  207142. {
  207143. taskBarIcon->uFlags = 0;
  207144. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207145. DestroyIcon (taskBarIcon->hIcon);
  207146. taskBarIcon = 0;
  207147. }
  207148. }
  207149. void setTaskBarIconToolTip (const String& toolTip) const
  207150. {
  207151. if (taskBarIcon != 0)
  207152. {
  207153. taskBarIcon->uFlags = NIF_TIP;
  207154. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207155. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207156. }
  207157. }
  207158. void handleTaskBarEvent (const LPARAM lParam)
  207159. {
  207160. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207161. {
  207162. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207163. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207164. {
  207165. Component* const current = Component::getCurrentlyModalComponent();
  207166. if (current != 0)
  207167. current->inputAttemptWhenModal();
  207168. }
  207169. }
  207170. else
  207171. {
  207172. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207173. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207174. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207175. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207176. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207177. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207178. eventMods = eventMods.withoutMouseButtons();
  207179. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207180. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  207181. Point<int>(), Time (getMouseEventTime()), 1, false);
  207182. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207183. {
  207184. SetFocus (hwnd);
  207185. SetForegroundWindow (hwnd);
  207186. component->mouseDown (e);
  207187. }
  207188. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207189. {
  207190. component->mouseUp (e);
  207191. }
  207192. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207193. {
  207194. component->mouseDoubleClick (e);
  207195. }
  207196. else if (lParam == WM_MOUSEMOVE)
  207197. {
  207198. component->mouseMove (e);
  207199. }
  207200. }
  207201. }
  207202. bool isInside (HWND h) const
  207203. {
  207204. return GetAncestor (hwnd, GA_ROOT) == h;
  207205. }
  207206. static void updateKeyModifiers() throw()
  207207. {
  207208. int keyMods = 0;
  207209. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207210. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207211. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207212. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207213. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207214. }
  207215. static void updateModifiersFromWParam (const WPARAM wParam)
  207216. {
  207217. int mouseMods = 0;
  207218. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207219. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207220. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207221. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207222. updateKeyModifiers();
  207223. }
  207224. static int64 getMouseEventTime()
  207225. {
  207226. static int64 eventTimeOffset = 0;
  207227. static DWORD lastMessageTime = 0;
  207228. const DWORD thisMessageTime = GetMessageTime();
  207229. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207230. {
  207231. lastMessageTime = thisMessageTime;
  207232. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207233. }
  207234. return eventTimeOffset + thisMessageTime;
  207235. }
  207236. bool dontRepaint;
  207237. static ModifierKeys currentModifiers;
  207238. static ModifierKeys modifiersAtLastCallback;
  207239. private:
  207240. HWND hwnd, parentToAddTo;
  207241. ScopedPointer<DropShadower> shadower;
  207242. RenderingEngineType currentRenderingEngine;
  207243. #if JUCE_DIRECT2D
  207244. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207245. #endif
  207246. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207247. BorderSize windowBorder;
  207248. HICON currentWindowIcon;
  207249. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207250. IDropTarget* dropTarget;
  207251. uint8 updateLayeredWindowAlpha;
  207252. class TemporaryImage : public Timer
  207253. {
  207254. public:
  207255. TemporaryImage() {}
  207256. ~TemporaryImage() {}
  207257. const Image& getImage (const bool transparent, const int w, const int h)
  207258. {
  207259. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207260. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207261. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207262. startTimer (3000);
  207263. return image;
  207264. }
  207265. void timerCallback()
  207266. {
  207267. stopTimer();
  207268. image = Image::null;
  207269. }
  207270. private:
  207271. Image image;
  207272. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207273. };
  207274. TemporaryImage offscreenImageGenerator;
  207275. class WindowClassHolder : public DeletedAtShutdown
  207276. {
  207277. public:
  207278. WindowClassHolder()
  207279. : windowClassName ("JUCE_")
  207280. {
  207281. // this name has to be different for each app/dll instance because otherwise
  207282. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207283. // window class).
  207284. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207285. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207286. TCHAR moduleFile [1024];
  207287. moduleFile[0] = 0;
  207288. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207289. WORD iconNum = 0;
  207290. WNDCLASSEX wcex;
  207291. wcex.cbSize = sizeof (wcex);
  207292. wcex.style = CS_OWNDC;
  207293. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207294. wcex.lpszClassName = windowClassName;
  207295. wcex.cbClsExtra = 0;
  207296. wcex.cbWndExtra = 32;
  207297. wcex.hInstance = moduleHandle;
  207298. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207299. iconNum = 1;
  207300. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207301. wcex.hCursor = 0;
  207302. wcex.hbrBackground = 0;
  207303. wcex.lpszMenuName = 0;
  207304. RegisterClassEx (&wcex);
  207305. }
  207306. ~WindowClassHolder()
  207307. {
  207308. if (ComponentPeer::getNumPeers() == 0)
  207309. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207310. clearSingletonInstance();
  207311. }
  207312. String windowClassName;
  207313. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207314. };
  207315. static void* createWindowCallback (void* userData)
  207316. {
  207317. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207318. return 0;
  207319. }
  207320. void createWindow()
  207321. {
  207322. DWORD exstyle = WS_EX_ACCEPTFILES;
  207323. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207324. if (hasTitleBar())
  207325. {
  207326. type |= WS_OVERLAPPED;
  207327. if ((styleFlags & windowHasCloseButton) != 0)
  207328. {
  207329. type |= WS_SYSMENU;
  207330. }
  207331. else
  207332. {
  207333. // annoyingly, windows won't let you have a min/max button without a close button
  207334. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207335. }
  207336. if ((styleFlags & windowIsResizable) != 0)
  207337. type |= WS_THICKFRAME;
  207338. }
  207339. else if (parentToAddTo != 0)
  207340. {
  207341. type |= WS_CHILD;
  207342. }
  207343. else
  207344. {
  207345. type |= WS_POPUP | WS_SYSMENU;
  207346. }
  207347. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207348. exstyle |= WS_EX_TOOLWINDOW;
  207349. else
  207350. exstyle |= WS_EX_APPWINDOW;
  207351. if ((styleFlags & windowHasMinimiseButton) != 0)
  207352. type |= WS_MINIMIZEBOX;
  207353. if ((styleFlags & windowHasMaximiseButton) != 0)
  207354. type |= WS_MAXIMIZEBOX;
  207355. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207356. exstyle |= WS_EX_TRANSPARENT;
  207357. if ((styleFlags & windowIsSemiTransparent) != 0
  207358. && Desktop::canUseSemiTransparentWindows())
  207359. exstyle |= WS_EX_LAYERED;
  207360. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207361. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207362. #if JUCE_DIRECT2D
  207363. updateDirect2DContext();
  207364. #endif
  207365. if (hwnd != 0)
  207366. {
  207367. SetWindowLongPtr (hwnd, 0, 0);
  207368. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207369. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207370. if (dropTarget == 0)
  207371. dropTarget = new JuceDropTarget (this);
  207372. RegisterDragDrop (hwnd, dropTarget);
  207373. updateBorderSize();
  207374. // Calling this function here is (for some reason) necessary to make Windows
  207375. // correctly enable the menu items that we specify in the wm_initmenu message.
  207376. GetSystemMenu (hwnd, false);
  207377. const float alpha = component->getAlpha();
  207378. if (alpha < 1.0f)
  207379. setAlpha (alpha);
  207380. }
  207381. else
  207382. {
  207383. jassertfalse;
  207384. }
  207385. }
  207386. static void* destroyWindowCallback (void* handle)
  207387. {
  207388. RevokeDragDrop ((HWND) handle);
  207389. DestroyWindow ((HWND) handle);
  207390. return 0;
  207391. }
  207392. static void* toFrontCallback1 (void* h)
  207393. {
  207394. SetForegroundWindow ((HWND) h);
  207395. return 0;
  207396. }
  207397. static void* toFrontCallback2 (void* h)
  207398. {
  207399. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207400. return 0;
  207401. }
  207402. static void* setFocusCallback (void* h)
  207403. {
  207404. SetFocus ((HWND) h);
  207405. return 0;
  207406. }
  207407. static void* getFocusCallback (void*)
  207408. {
  207409. return GetFocus();
  207410. }
  207411. void offsetWithinParent (int& x, int& y) const
  207412. {
  207413. if (isUsingUpdateLayeredWindow())
  207414. {
  207415. HWND parentHwnd = GetParent (hwnd);
  207416. if (parentHwnd != 0)
  207417. {
  207418. RECT parentRect;
  207419. GetWindowRect (parentHwnd, &parentRect);
  207420. x += parentRect.left;
  207421. y += parentRect.top;
  207422. }
  207423. }
  207424. }
  207425. bool isUsingUpdateLayeredWindow() const
  207426. {
  207427. return ! component->isOpaque();
  207428. }
  207429. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207430. void setIcon (const Image& newIcon)
  207431. {
  207432. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207433. if (hicon != 0)
  207434. {
  207435. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207436. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207437. if (currentWindowIcon != 0)
  207438. DestroyIcon (currentWindowIcon);
  207439. currentWindowIcon = hicon;
  207440. }
  207441. }
  207442. void handlePaintMessage()
  207443. {
  207444. #if JUCE_DIRECT2D
  207445. if (direct2DContext != 0)
  207446. {
  207447. RECT r;
  207448. if (GetUpdateRect (hwnd, &r, false))
  207449. {
  207450. direct2DContext->start();
  207451. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207452. handlePaint (*direct2DContext);
  207453. direct2DContext->end();
  207454. }
  207455. }
  207456. else
  207457. #endif
  207458. {
  207459. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207460. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207461. PAINTSTRUCT paintStruct;
  207462. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207463. // message and become re-entrant, but that's OK
  207464. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207465. // corrupt the image it's using to paint into, so do a check here.
  207466. static bool reentrant = false;
  207467. if (reentrant)
  207468. {
  207469. DeleteObject (rgn);
  207470. EndPaint (hwnd, &paintStruct);
  207471. return;
  207472. }
  207473. reentrant = true;
  207474. // this is the rectangle to update..
  207475. int x = paintStruct.rcPaint.left;
  207476. int y = paintStruct.rcPaint.top;
  207477. int w = paintStruct.rcPaint.right - x;
  207478. int h = paintStruct.rcPaint.bottom - y;
  207479. const bool transparent = isUsingUpdateLayeredWindow();
  207480. if (transparent)
  207481. {
  207482. // it's not possible to have a transparent window with a title bar at the moment!
  207483. jassert (! hasTitleBar());
  207484. RECT r;
  207485. GetWindowRect (hwnd, &r);
  207486. x = y = 0;
  207487. w = r.right - r.left;
  207488. h = r.bottom - r.top;
  207489. }
  207490. if (w > 0 && h > 0)
  207491. {
  207492. clearMaskedRegion();
  207493. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207494. RectangleList contextClip;
  207495. const Rectangle<int> clipBounds (0, 0, w, h);
  207496. bool needToPaintAll = true;
  207497. if (regionType == COMPLEXREGION && ! transparent)
  207498. {
  207499. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207500. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207501. DeleteObject (clipRgn);
  207502. char rgnData [8192];
  207503. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207504. if (res > 0 && res <= sizeof (rgnData))
  207505. {
  207506. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207507. if (hdr->iType == RDH_RECTANGLES
  207508. && hdr->rcBound.right - hdr->rcBound.left >= w
  207509. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207510. {
  207511. needToPaintAll = false;
  207512. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207513. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207514. while (--num >= 0)
  207515. {
  207516. if (rects->right <= x + w && rects->bottom <= y + h)
  207517. {
  207518. const int cx = jmax (x, (int) rects->left);
  207519. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207520. .getIntersection (clipBounds));
  207521. }
  207522. else
  207523. {
  207524. needToPaintAll = true;
  207525. break;
  207526. }
  207527. ++rects;
  207528. }
  207529. }
  207530. }
  207531. }
  207532. if (needToPaintAll)
  207533. {
  207534. contextClip.clear();
  207535. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207536. }
  207537. if (transparent)
  207538. {
  207539. RectangleList::Iterator i (contextClip);
  207540. while (i.next())
  207541. offscreenImage.clear (*i.getRectangle());
  207542. }
  207543. // if the component's not opaque, this won't draw properly unless the platform can support this
  207544. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207545. updateCurrentModifiers();
  207546. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207547. handlePaint (context);
  207548. if (! dontRepaint)
  207549. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207550. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207551. }
  207552. DeleteObject (rgn);
  207553. EndPaint (hwnd, &paintStruct);
  207554. reentrant = false;
  207555. }
  207556. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207557. _fpreset(); // because some graphics cards can unmask FP exceptions
  207558. #endif
  207559. lastPaintTime = Time::getMillisecondCounter();
  207560. }
  207561. void doMouseEvent (const Point<int>& position)
  207562. {
  207563. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207564. }
  207565. const StringArray getAvailableRenderingEngines()
  207566. {
  207567. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207568. #if JUCE_DIRECT2D
  207569. // xxx is this correct? Seems to enable it on Vista too??
  207570. OSVERSIONINFO info;
  207571. zerostruct (info);
  207572. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207573. GetVersionEx (&info);
  207574. if (info.dwMajorVersion >= 6)
  207575. s.add ("Direct2D");
  207576. #endif
  207577. return s;
  207578. }
  207579. int getCurrentRenderingEngine() throw()
  207580. {
  207581. return currentRenderingEngine;
  207582. }
  207583. #if JUCE_DIRECT2D
  207584. void updateDirect2DContext()
  207585. {
  207586. if (currentRenderingEngine != direct2DRenderingEngine)
  207587. direct2DContext = 0;
  207588. else if (direct2DContext == 0)
  207589. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207590. }
  207591. #endif
  207592. void setCurrentRenderingEngine (int index)
  207593. {
  207594. (void) index;
  207595. #if JUCE_DIRECT2D
  207596. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207597. updateDirect2DContext();
  207598. repaint (component->getLocalBounds());
  207599. #endif
  207600. }
  207601. void doMouseMove (const Point<int>& position)
  207602. {
  207603. if (! isMouseOver)
  207604. {
  207605. isMouseOver = true;
  207606. updateKeyModifiers();
  207607. TRACKMOUSEEVENT tme;
  207608. tme.cbSize = sizeof (tme);
  207609. tme.dwFlags = TME_LEAVE;
  207610. tme.hwndTrack = hwnd;
  207611. tme.dwHoverTime = 0;
  207612. if (! TrackMouseEvent (&tme))
  207613. jassertfalse;
  207614. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207615. }
  207616. else if (! isDragging)
  207617. {
  207618. if (! contains (position, false))
  207619. return;
  207620. }
  207621. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207622. static uint32 lastMouseTime = 0;
  207623. const uint32 now = Time::getMillisecondCounter();
  207624. const int maxMouseMovesPerSecond = 60;
  207625. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207626. {
  207627. lastMouseTime = now;
  207628. doMouseEvent (position);
  207629. }
  207630. }
  207631. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207632. {
  207633. if (GetCapture() != hwnd)
  207634. SetCapture (hwnd);
  207635. doMouseMove (position);
  207636. updateModifiersFromWParam (wParam);
  207637. isDragging = true;
  207638. doMouseEvent (position);
  207639. }
  207640. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207641. {
  207642. updateModifiersFromWParam (wParam);
  207643. isDragging = false;
  207644. // release the mouse capture if the user has released all buttons
  207645. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207646. ReleaseCapture();
  207647. doMouseEvent (position);
  207648. }
  207649. void doCaptureChanged()
  207650. {
  207651. if (isDragging)
  207652. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207653. }
  207654. void doMouseExit()
  207655. {
  207656. isMouseOver = false;
  207657. doMouseEvent (getCurrentMousePos());
  207658. }
  207659. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207660. {
  207661. updateKeyModifiers();
  207662. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207663. handleMouseWheel (0, position, getMouseEventTime(),
  207664. isVertical ? 0.0f : amount,
  207665. isVertical ? amount : 0.0f);
  207666. }
  207667. void sendModifierKeyChangeIfNeeded()
  207668. {
  207669. if (modifiersAtLastCallback != currentModifiers)
  207670. {
  207671. modifiersAtLastCallback = currentModifiers;
  207672. handleModifierKeysChange();
  207673. }
  207674. }
  207675. bool doKeyUp (const WPARAM key)
  207676. {
  207677. updateKeyModifiers();
  207678. switch (key)
  207679. {
  207680. case VK_SHIFT:
  207681. case VK_CONTROL:
  207682. case VK_MENU:
  207683. case VK_CAPITAL:
  207684. case VK_LWIN:
  207685. case VK_RWIN:
  207686. case VK_APPS:
  207687. case VK_NUMLOCK:
  207688. case VK_SCROLL:
  207689. case VK_LSHIFT:
  207690. case VK_RSHIFT:
  207691. case VK_LCONTROL:
  207692. case VK_LMENU:
  207693. case VK_RCONTROL:
  207694. case VK_RMENU:
  207695. sendModifierKeyChangeIfNeeded();
  207696. }
  207697. return handleKeyUpOrDown (false)
  207698. || Component::getCurrentlyModalComponent() != 0;
  207699. }
  207700. bool doKeyDown (const WPARAM key)
  207701. {
  207702. updateKeyModifiers();
  207703. bool used = false;
  207704. switch (key)
  207705. {
  207706. case VK_SHIFT:
  207707. case VK_LSHIFT:
  207708. case VK_RSHIFT:
  207709. case VK_CONTROL:
  207710. case VK_LCONTROL:
  207711. case VK_RCONTROL:
  207712. case VK_MENU:
  207713. case VK_LMENU:
  207714. case VK_RMENU:
  207715. case VK_LWIN:
  207716. case VK_RWIN:
  207717. case VK_CAPITAL:
  207718. case VK_NUMLOCK:
  207719. case VK_SCROLL:
  207720. case VK_APPS:
  207721. sendModifierKeyChangeIfNeeded();
  207722. break;
  207723. case VK_LEFT:
  207724. case VK_RIGHT:
  207725. case VK_UP:
  207726. case VK_DOWN:
  207727. case VK_PRIOR:
  207728. case VK_NEXT:
  207729. case VK_HOME:
  207730. case VK_END:
  207731. case VK_DELETE:
  207732. case VK_INSERT:
  207733. case VK_F1:
  207734. case VK_F2:
  207735. case VK_F3:
  207736. case VK_F4:
  207737. case VK_F5:
  207738. case VK_F6:
  207739. case VK_F7:
  207740. case VK_F8:
  207741. case VK_F9:
  207742. case VK_F10:
  207743. case VK_F11:
  207744. case VK_F12:
  207745. case VK_F13:
  207746. case VK_F14:
  207747. case VK_F15:
  207748. case VK_F16:
  207749. used = handleKeyUpOrDown (true);
  207750. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207751. break;
  207752. case VK_ADD:
  207753. case VK_SUBTRACT:
  207754. case VK_MULTIPLY:
  207755. case VK_DIVIDE:
  207756. case VK_SEPARATOR:
  207757. case VK_DECIMAL:
  207758. used = handleKeyUpOrDown (true);
  207759. break;
  207760. default:
  207761. used = handleKeyUpOrDown (true);
  207762. {
  207763. MSG msg;
  207764. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207765. {
  207766. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207767. // manually generate the key-press event that matches this key-down.
  207768. const UINT keyChar = MapVirtualKey (key, 2);
  207769. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207770. }
  207771. }
  207772. break;
  207773. }
  207774. if (Component::getCurrentlyModalComponent() != 0)
  207775. used = true;
  207776. return used;
  207777. }
  207778. bool doKeyChar (int key, const LPARAM flags)
  207779. {
  207780. updateKeyModifiers();
  207781. juce_wchar textChar = (juce_wchar) key;
  207782. const int virtualScanCode = (flags >> 16) & 0xff;
  207783. if (key >= '0' && key <= '9')
  207784. {
  207785. switch (virtualScanCode) // check for a numeric keypad scan-code
  207786. {
  207787. case 0x52:
  207788. case 0x4f:
  207789. case 0x50:
  207790. case 0x51:
  207791. case 0x4b:
  207792. case 0x4c:
  207793. case 0x4d:
  207794. case 0x47:
  207795. case 0x48:
  207796. case 0x49:
  207797. key = (key - '0') + KeyPress::numberPad0;
  207798. break;
  207799. default:
  207800. break;
  207801. }
  207802. }
  207803. else
  207804. {
  207805. // convert the scan code to an unmodified character code..
  207806. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207807. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207808. keyChar = LOWORD (keyChar);
  207809. if (keyChar != 0)
  207810. key = (int) keyChar;
  207811. // avoid sending junk text characters for some control-key combinations
  207812. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207813. textChar = 0;
  207814. }
  207815. return handleKeyPress (key, textChar);
  207816. }
  207817. bool doAppCommand (const LPARAM lParam)
  207818. {
  207819. int key = 0;
  207820. switch (GET_APPCOMMAND_LPARAM (lParam))
  207821. {
  207822. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  207823. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  207824. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  207825. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  207826. default: break;
  207827. }
  207828. if (key != 0)
  207829. {
  207830. updateKeyModifiers();
  207831. if (hwnd == GetActiveWindow())
  207832. {
  207833. handleKeyPress (key, 0);
  207834. return true;
  207835. }
  207836. }
  207837. return false;
  207838. }
  207839. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  207840. {
  207841. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207842. {
  207843. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  207844. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  207845. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207846. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  207847. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  207848. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  207849. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  207850. r->left = pos.getX();
  207851. r->top = pos.getY();
  207852. r->right = pos.getRight();
  207853. r->bottom = pos.getBottom();
  207854. }
  207855. return TRUE;
  207856. }
  207857. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  207858. {
  207859. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207860. {
  207861. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  207862. && ! Component::isMouseButtonDownAnywhere())
  207863. {
  207864. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207865. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  207866. constrainer->checkBounds (pos, current,
  207867. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207868. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207869. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207870. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207871. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207872. wp->x = pos.getX();
  207873. wp->y = pos.getY();
  207874. wp->cx = pos.getWidth();
  207875. wp->cy = pos.getHeight();
  207876. }
  207877. }
  207878. return 0;
  207879. }
  207880. void handleAppActivation (const WPARAM wParam)
  207881. {
  207882. modifiersAtLastCallback = -1;
  207883. updateKeyModifiers();
  207884. if (isMinimised())
  207885. {
  207886. component->repaint();
  207887. handleMovedOrResized();
  207888. if (! ComponentPeer::isValidPeer (this))
  207889. return;
  207890. }
  207891. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  207892. {
  207893. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  207894. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207895. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207896. }
  207897. else
  207898. {
  207899. handleBroughtToFront();
  207900. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207901. Component::getCurrentlyModalComponent()->toFront (true);
  207902. }
  207903. }
  207904. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207905. {
  207906. public:
  207907. JuceDropTarget (Win32ComponentPeer* const owner_)
  207908. : owner (owner_)
  207909. {
  207910. }
  207911. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207912. {
  207913. updateFileList (pDataObject);
  207914. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207915. *pdwEffect = DROPEFFECT_COPY;
  207916. return S_OK;
  207917. }
  207918. HRESULT __stdcall DragLeave()
  207919. {
  207920. owner->handleFileDragExit (files);
  207921. return S_OK;
  207922. }
  207923. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207924. {
  207925. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207926. *pdwEffect = DROPEFFECT_COPY;
  207927. return S_OK;
  207928. }
  207929. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207930. {
  207931. updateFileList (pDataObject);
  207932. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207933. *pdwEffect = DROPEFFECT_COPY;
  207934. return S_OK;
  207935. }
  207936. private:
  207937. Win32ComponentPeer* const owner;
  207938. StringArray files;
  207939. void updateFileList (IDataObject* const pDataObject)
  207940. {
  207941. files.clear();
  207942. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207943. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207944. if (pDataObject->GetData (&format, &medium) == S_OK)
  207945. {
  207946. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207947. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207948. unsigned int i = 0;
  207949. if (pDropFiles->fWide)
  207950. {
  207951. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207952. for (;;)
  207953. {
  207954. unsigned int len = 0;
  207955. while (i + len < totalLen && fname [i + len] != 0)
  207956. ++len;
  207957. if (len == 0)
  207958. break;
  207959. files.add (String (fname + i, len));
  207960. i += len + 1;
  207961. }
  207962. }
  207963. else
  207964. {
  207965. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207966. for (;;)
  207967. {
  207968. unsigned int len = 0;
  207969. while (i + len < totalLen && fname [i + len] != 0)
  207970. ++len;
  207971. if (len == 0)
  207972. break;
  207973. files.add (String (fname + i, len));
  207974. i += len + 1;
  207975. }
  207976. }
  207977. GlobalUnlock (medium.hGlobal);
  207978. }
  207979. }
  207980. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  207981. };
  207982. void doSettingChange()
  207983. {
  207984. Desktop::getInstance().refreshMonitorSizes();
  207985. if (fullScreen && ! isMinimised())
  207986. {
  207987. const Rectangle<int> r (component->getParentMonitorArea());
  207988. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207989. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207990. }
  207991. }
  207992. public:
  207993. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207994. {
  207995. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207996. if (peer != 0)
  207997. {
  207998. jassert (isValidPeer (peer));
  207999. return peer->peerWindowProc (h, message, wParam, lParam);
  208000. }
  208001. return DefWindowProcW (h, message, wParam, lParam);
  208002. }
  208003. private:
  208004. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  208005. {
  208006. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  208007. return callback (userData);
  208008. else
  208009. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  208010. }
  208011. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208012. {
  208013. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208014. }
  208015. const Point<int> getCurrentMousePos() throw()
  208016. {
  208017. RECT wr;
  208018. GetWindowRect (hwnd, &wr);
  208019. const DWORD mp = GetMessagePos();
  208020. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208021. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208022. }
  208023. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208024. {
  208025. switch (message)
  208026. {
  208027. case WM_NCHITTEST:
  208028. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208029. return HTTRANSPARENT;
  208030. else if (! hasTitleBar())
  208031. return HTCLIENT;
  208032. break;
  208033. case WM_PAINT:
  208034. handlePaintMessage();
  208035. return 0;
  208036. case WM_NCPAINT:
  208037. if (wParam != 1)
  208038. handlePaintMessage();
  208039. if (hasTitleBar())
  208040. break;
  208041. return 0;
  208042. case WM_ERASEBKGND:
  208043. case WM_NCCALCSIZE:
  208044. if (hasTitleBar())
  208045. break;
  208046. return 1;
  208047. case WM_MOUSEMOVE:
  208048. doMouseMove (getPointFromLParam (lParam));
  208049. return 0;
  208050. case WM_MOUSELEAVE:
  208051. doMouseExit();
  208052. return 0;
  208053. case WM_LBUTTONDOWN:
  208054. case WM_MBUTTONDOWN:
  208055. case WM_RBUTTONDOWN:
  208056. doMouseDown (getPointFromLParam (lParam), wParam);
  208057. return 0;
  208058. case WM_LBUTTONUP:
  208059. case WM_MBUTTONUP:
  208060. case WM_RBUTTONUP:
  208061. doMouseUp (getPointFromLParam (lParam), wParam);
  208062. return 0;
  208063. case WM_CAPTURECHANGED:
  208064. doCaptureChanged();
  208065. return 0;
  208066. case WM_NCMOUSEMOVE:
  208067. if (hasTitleBar())
  208068. break;
  208069. return 0;
  208070. case 0x020A: /* WM_MOUSEWHEEL */
  208071. case 0x020E: /* WM_MOUSEHWHEEL */
  208072. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  208073. return 0;
  208074. case WM_SIZING:
  208075. return handleSizeConstraining ((RECT*) lParam, wParam);
  208076. case WM_WINDOWPOSCHANGING:
  208077. return handlePositionChanging ((WINDOWPOS*) lParam);
  208078. case WM_WINDOWPOSCHANGED:
  208079. {
  208080. const Point<int> pos (getCurrentMousePos());
  208081. if (contains (pos, false))
  208082. doMouseEvent (pos);
  208083. }
  208084. handleMovedOrResized();
  208085. if (dontRepaint)
  208086. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208087. return 0;
  208088. case WM_KEYDOWN:
  208089. case WM_SYSKEYDOWN:
  208090. if (doKeyDown (wParam))
  208091. return 0;
  208092. break;
  208093. case WM_KEYUP:
  208094. case WM_SYSKEYUP:
  208095. if (doKeyUp (wParam))
  208096. return 0;
  208097. break;
  208098. case WM_CHAR:
  208099. if (doKeyChar ((int) wParam, lParam))
  208100. return 0;
  208101. break;
  208102. case WM_APPCOMMAND:
  208103. if (doAppCommand (lParam))
  208104. return TRUE;
  208105. break;
  208106. case WM_SETFOCUS:
  208107. updateKeyModifiers();
  208108. handleFocusGain();
  208109. break;
  208110. case WM_KILLFOCUS:
  208111. if (hasCreatedCaret)
  208112. {
  208113. hasCreatedCaret = false;
  208114. DestroyCaret();
  208115. }
  208116. handleFocusLoss();
  208117. break;
  208118. case WM_ACTIVATEAPP:
  208119. // Windows does weird things to process priority when you swap apps,
  208120. // so this forces an update when the app is brought to the front
  208121. if (wParam != FALSE)
  208122. juce_repeatLastProcessPriority();
  208123. else
  208124. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208125. juce_CheckCurrentlyFocusedTopLevelWindow();
  208126. modifiersAtLastCallback = -1;
  208127. return 0;
  208128. case WM_ACTIVATE:
  208129. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208130. {
  208131. handleAppActivation (wParam);
  208132. return 0;
  208133. }
  208134. break;
  208135. case WM_NCACTIVATE:
  208136. // while a temporary window is being shown, prevent Windows from deactivating the
  208137. // title bars of our main windows.
  208138. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208139. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208140. break;
  208141. case WM_MOUSEACTIVATE:
  208142. if (! component->getMouseClickGrabsKeyboardFocus())
  208143. return MA_NOACTIVATE;
  208144. break;
  208145. case WM_SHOWWINDOW:
  208146. if (wParam != 0)
  208147. handleBroughtToFront();
  208148. break;
  208149. case WM_CLOSE:
  208150. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208151. handleUserClosingWindow();
  208152. return 0;
  208153. case WM_QUERYENDSESSION:
  208154. if (JUCEApplication::getInstance() != 0)
  208155. {
  208156. JUCEApplication::getInstance()->systemRequestedQuit();
  208157. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208158. }
  208159. return TRUE;
  208160. case WM_TRAYNOTIFY:
  208161. handleTaskBarEvent (lParam);
  208162. break;
  208163. case WM_SYNCPAINT:
  208164. return 0;
  208165. case WM_PALETTECHANGED:
  208166. InvalidateRect (h, 0, 0);
  208167. break;
  208168. case WM_DISPLAYCHANGE:
  208169. InvalidateRect (h, 0, 0);
  208170. createPaletteIfNeeded = true;
  208171. // intentional fall-through...
  208172. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208173. doSettingChange();
  208174. break;
  208175. case WM_INITMENU:
  208176. if (! hasTitleBar())
  208177. {
  208178. if (isFullScreen())
  208179. {
  208180. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208181. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208182. }
  208183. else if (! isMinimised())
  208184. {
  208185. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208186. }
  208187. }
  208188. break;
  208189. case WM_SYSCOMMAND:
  208190. switch (wParam & 0xfff0)
  208191. {
  208192. case SC_CLOSE:
  208193. if (sendInputAttemptWhenModalMessage())
  208194. return 0;
  208195. if (hasTitleBar())
  208196. {
  208197. PostMessage (h, WM_CLOSE, 0, 0);
  208198. return 0;
  208199. }
  208200. break;
  208201. case SC_KEYMENU:
  208202. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  208203. // situations that can arise if a modal loop is started from an alt-key keypress).
  208204. if (hasTitleBar() && h == GetCapture())
  208205. ReleaseCapture();
  208206. break;
  208207. case SC_MAXIMIZE:
  208208. if (! sendInputAttemptWhenModalMessage())
  208209. setFullScreen (true);
  208210. return 0;
  208211. case SC_MINIMIZE:
  208212. if (sendInputAttemptWhenModalMessage())
  208213. return 0;
  208214. if (! hasTitleBar())
  208215. {
  208216. setMinimised (true);
  208217. return 0;
  208218. }
  208219. break;
  208220. case SC_RESTORE:
  208221. if (sendInputAttemptWhenModalMessage())
  208222. return 0;
  208223. if (hasTitleBar())
  208224. {
  208225. if (isFullScreen())
  208226. {
  208227. setFullScreen (false);
  208228. return 0;
  208229. }
  208230. }
  208231. else
  208232. {
  208233. if (isMinimised())
  208234. setMinimised (false);
  208235. else if (isFullScreen())
  208236. setFullScreen (false);
  208237. return 0;
  208238. }
  208239. break;
  208240. }
  208241. break;
  208242. case WM_NCLBUTTONDOWN:
  208243. case WM_NCRBUTTONDOWN:
  208244. case WM_NCMBUTTONDOWN:
  208245. sendInputAttemptWhenModalMessage();
  208246. break;
  208247. //case WM_IME_STARTCOMPOSITION;
  208248. // return 0;
  208249. case WM_GETDLGCODE:
  208250. return DLGC_WANTALLKEYS;
  208251. default:
  208252. if (taskBarIcon != 0)
  208253. {
  208254. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208255. if (message == taskbarCreatedMessage)
  208256. {
  208257. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208258. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208259. }
  208260. }
  208261. break;
  208262. }
  208263. return DefWindowProcW (h, message, wParam, lParam);
  208264. }
  208265. bool sendInputAttemptWhenModalMessage()
  208266. {
  208267. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208268. {
  208269. Component* const current = Component::getCurrentlyModalComponent();
  208270. if (current != 0)
  208271. current->inputAttemptWhenModal();
  208272. return true;
  208273. }
  208274. return false;
  208275. }
  208276. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208277. };
  208278. ModifierKeys Win32ComponentPeer::currentModifiers;
  208279. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208280. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208281. {
  208282. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208283. }
  208284. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208285. void ModifierKeys::updateCurrentModifiers() throw()
  208286. {
  208287. currentModifiers = Win32ComponentPeer::currentModifiers;
  208288. }
  208289. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208290. {
  208291. Win32ComponentPeer::updateKeyModifiers();
  208292. int mouseMods = 0;
  208293. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208294. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208295. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208296. Win32ComponentPeer::currentModifiers
  208297. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208298. return Win32ComponentPeer::currentModifiers;
  208299. }
  208300. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208301. {
  208302. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208303. if (wp != 0)
  208304. wp->setTaskBarIcon (newImage);
  208305. }
  208306. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208307. {
  208308. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208309. if (wp != 0)
  208310. wp->setTaskBarIconToolTip (tooltip);
  208311. }
  208312. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208313. {
  208314. DWORD val = GetWindowLong (h, styleType);
  208315. if (bitIsSet)
  208316. val |= feature;
  208317. else
  208318. val &= ~feature;
  208319. SetWindowLongPtr (h, styleType, val);
  208320. SetWindowPos (h, 0, 0, 0, 0, 0,
  208321. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208322. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208323. }
  208324. bool Process::isForegroundProcess()
  208325. {
  208326. HWND fg = GetForegroundWindow();
  208327. if (fg == 0)
  208328. return true;
  208329. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208330. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208331. // have to see if any of our windows are children of the foreground window
  208332. fg = GetAncestor (fg, GA_ROOT);
  208333. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208334. {
  208335. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208336. if (wp != 0 && wp->isInside (fg))
  208337. return true;
  208338. }
  208339. return false;
  208340. }
  208341. bool AlertWindow::showNativeDialogBox (const String& title,
  208342. const String& bodyText,
  208343. bool isOkCancel)
  208344. {
  208345. return MessageBox (0, bodyText, title,
  208346. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208347. : MB_OK)) == IDOK;
  208348. }
  208349. void Desktop::createMouseInputSources()
  208350. {
  208351. mouseSources.add (new MouseInputSource (0, true));
  208352. }
  208353. const Point<int> MouseInputSource::getCurrentMousePosition()
  208354. {
  208355. POINT mousePos;
  208356. GetCursorPos (&mousePos);
  208357. return Point<int> (mousePos.x, mousePos.y);
  208358. }
  208359. void Desktop::setMousePosition (const Point<int>& newPosition)
  208360. {
  208361. SetCursorPos (newPosition.getX(), newPosition.getY());
  208362. }
  208363. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208364. {
  208365. return createSoftwareImage (format, width, height, clearImage);
  208366. }
  208367. class ScreenSaverDefeater : public Timer,
  208368. public DeletedAtShutdown
  208369. {
  208370. public:
  208371. ScreenSaverDefeater()
  208372. {
  208373. startTimer (10000);
  208374. timerCallback();
  208375. }
  208376. ~ScreenSaverDefeater() {}
  208377. void timerCallback()
  208378. {
  208379. if (Process::isForegroundProcess())
  208380. {
  208381. // simulate a shift key getting pressed..
  208382. INPUT input[2];
  208383. input[0].type = INPUT_KEYBOARD;
  208384. input[0].ki.wVk = VK_SHIFT;
  208385. input[0].ki.dwFlags = 0;
  208386. input[0].ki.dwExtraInfo = 0;
  208387. input[1].type = INPUT_KEYBOARD;
  208388. input[1].ki.wVk = VK_SHIFT;
  208389. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208390. input[1].ki.dwExtraInfo = 0;
  208391. SendInput (2, input, sizeof (INPUT));
  208392. }
  208393. }
  208394. };
  208395. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208396. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208397. {
  208398. if (isEnabled)
  208399. deleteAndZero (screenSaverDefeater);
  208400. else if (screenSaverDefeater == 0)
  208401. screenSaverDefeater = new ScreenSaverDefeater();
  208402. }
  208403. bool Desktop::isScreenSaverEnabled()
  208404. {
  208405. return screenSaverDefeater == 0;
  208406. }
  208407. /* (The code below is the "correct" way to disable the screen saver, but it
  208408. completely fails on winXP when the saver is password-protected...)
  208409. static bool juce_screenSaverEnabled = true;
  208410. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208411. {
  208412. juce_screenSaverEnabled = isEnabled;
  208413. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208414. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208415. }
  208416. bool Desktop::isScreenSaverEnabled() throw()
  208417. {
  208418. return juce_screenSaverEnabled;
  208419. }
  208420. */
  208421. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208422. {
  208423. if (enableOrDisable)
  208424. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208425. }
  208426. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208427. {
  208428. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208429. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208430. return TRUE;
  208431. }
  208432. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208433. {
  208434. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208435. // make sure the first in the list is the main monitor
  208436. for (int i = 1; i < monitorCoords.size(); ++i)
  208437. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208438. monitorCoords.swap (i, 0);
  208439. if (monitorCoords.size() == 0)
  208440. {
  208441. RECT r;
  208442. GetWindowRect (GetDesktopWindow(), &r);
  208443. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208444. }
  208445. if (clipToWorkArea)
  208446. {
  208447. // clip the main monitor to the active non-taskbar area
  208448. RECT r;
  208449. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208450. Rectangle<int>& screen = monitorCoords.getReference (0);
  208451. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208452. jmax (screen.getY(), (int) r.top));
  208453. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208454. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208455. }
  208456. }
  208457. const Image juce_createIconForFile (const File& file)
  208458. {
  208459. Image image;
  208460. WCHAR filename [1024];
  208461. file.getFullPathName().copyToUnicode (filename, 1023);
  208462. WORD iconNum = 0;
  208463. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208464. filename, &iconNum);
  208465. if (icon != 0)
  208466. {
  208467. image = IconConverters::createImageFromHICON (icon);
  208468. DestroyIcon (icon);
  208469. }
  208470. return image;
  208471. }
  208472. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208473. {
  208474. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208475. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208476. Image im (image);
  208477. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208478. {
  208479. im = im.rescaled (maxW, maxH);
  208480. hotspotX = (hotspotX * maxW) / image.getWidth();
  208481. hotspotY = (hotspotY * maxH) / image.getHeight();
  208482. }
  208483. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208484. }
  208485. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208486. {
  208487. if (cursorHandle != 0 && ! isStandard)
  208488. DestroyCursor ((HCURSOR) cursorHandle);
  208489. }
  208490. enum
  208491. {
  208492. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208493. };
  208494. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208495. {
  208496. LPCTSTR cursorName = IDC_ARROW;
  208497. switch (type)
  208498. {
  208499. case NormalCursor: break;
  208500. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208501. case WaitCursor: cursorName = IDC_WAIT; break;
  208502. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208503. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208504. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208505. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208506. case LeftRightResizeCursor:
  208507. case LeftEdgeResizeCursor:
  208508. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208509. case UpDownResizeCursor:
  208510. case TopEdgeResizeCursor:
  208511. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208512. case TopLeftCornerResizeCursor:
  208513. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208514. case TopRightCornerResizeCursor:
  208515. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208516. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208517. case DraggingHandCursor:
  208518. {
  208519. static void* dragHandCursor = 0;
  208520. if (dragHandCursor == 0)
  208521. {
  208522. static const unsigned char dragHandData[] =
  208523. { 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,
  208524. 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,
  208525. 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 };
  208526. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208527. }
  208528. return dragHandCursor;
  208529. }
  208530. default:
  208531. jassertfalse; break;
  208532. }
  208533. HCURSOR cursorH = LoadCursor (0, cursorName);
  208534. if (cursorH == 0)
  208535. cursorH = LoadCursor (0, IDC_ARROW);
  208536. return cursorH;
  208537. }
  208538. void MouseCursor::showInWindow (ComponentPeer*) const
  208539. {
  208540. HCURSOR c = (HCURSOR) getHandle();
  208541. if (c == 0)
  208542. c = LoadCursor (0, IDC_ARROW);
  208543. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208544. c = 0;
  208545. SetCursor (c);
  208546. }
  208547. void MouseCursor::showInAllWindows() const
  208548. {
  208549. showInWindow (0);
  208550. }
  208551. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208552. {
  208553. public:
  208554. JuceDropSource() {}
  208555. ~JuceDropSource() {}
  208556. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208557. {
  208558. if (escapePressed)
  208559. return DRAGDROP_S_CANCEL;
  208560. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208561. return DRAGDROP_S_DROP;
  208562. return S_OK;
  208563. }
  208564. HRESULT __stdcall GiveFeedback (DWORD)
  208565. {
  208566. return DRAGDROP_S_USEDEFAULTCURSORS;
  208567. }
  208568. };
  208569. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208570. {
  208571. public:
  208572. JuceEnumFormatEtc (const FORMATETC* const format_)
  208573. : format (format_),
  208574. index (0)
  208575. {
  208576. }
  208577. ~JuceEnumFormatEtc() {}
  208578. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208579. {
  208580. if (result == 0)
  208581. return E_POINTER;
  208582. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208583. newOne->index = index;
  208584. *result = newOne;
  208585. return S_OK;
  208586. }
  208587. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208588. {
  208589. if (pceltFetched != 0)
  208590. *pceltFetched = 0;
  208591. else if (celt != 1)
  208592. return S_FALSE;
  208593. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208594. {
  208595. copyFormatEtc (lpFormatEtc [0], *format);
  208596. ++index;
  208597. if (pceltFetched != 0)
  208598. *pceltFetched = 1;
  208599. return S_OK;
  208600. }
  208601. return S_FALSE;
  208602. }
  208603. HRESULT __stdcall Skip (ULONG celt)
  208604. {
  208605. if (index + (int) celt >= 1)
  208606. return S_FALSE;
  208607. index += celt;
  208608. return S_OK;
  208609. }
  208610. HRESULT __stdcall Reset()
  208611. {
  208612. index = 0;
  208613. return S_OK;
  208614. }
  208615. private:
  208616. const FORMATETC* const format;
  208617. int index;
  208618. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208619. {
  208620. dest = source;
  208621. if (source.ptd != 0)
  208622. {
  208623. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208624. *(dest.ptd) = *(source.ptd);
  208625. }
  208626. }
  208627. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208628. };
  208629. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208630. {
  208631. public:
  208632. JuceDataObject (JuceDropSource* const dropSource_,
  208633. const FORMATETC* const format_,
  208634. const STGMEDIUM* const medium_)
  208635. : dropSource (dropSource_),
  208636. format (format_),
  208637. medium (medium_)
  208638. {
  208639. }
  208640. ~JuceDataObject()
  208641. {
  208642. jassert (refCount == 0);
  208643. }
  208644. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208645. {
  208646. if ((pFormatEtc->tymed & format->tymed) != 0
  208647. && pFormatEtc->cfFormat == format->cfFormat
  208648. && pFormatEtc->dwAspect == format->dwAspect)
  208649. {
  208650. pMedium->tymed = format->tymed;
  208651. pMedium->pUnkForRelease = 0;
  208652. if (format->tymed == TYMED_HGLOBAL)
  208653. {
  208654. const SIZE_T len = GlobalSize (medium->hGlobal);
  208655. void* const src = GlobalLock (medium->hGlobal);
  208656. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208657. memcpy (dst, src, len);
  208658. GlobalUnlock (medium->hGlobal);
  208659. pMedium->hGlobal = dst;
  208660. return S_OK;
  208661. }
  208662. }
  208663. return DV_E_FORMATETC;
  208664. }
  208665. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208666. {
  208667. if (f == 0)
  208668. return E_INVALIDARG;
  208669. if (f->tymed == format->tymed
  208670. && f->cfFormat == format->cfFormat
  208671. && f->dwAspect == format->dwAspect)
  208672. return S_OK;
  208673. return DV_E_FORMATETC;
  208674. }
  208675. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208676. {
  208677. pFormatEtcOut->ptd = 0;
  208678. return E_NOTIMPL;
  208679. }
  208680. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208681. {
  208682. if (result == 0)
  208683. return E_POINTER;
  208684. if (direction == DATADIR_GET)
  208685. {
  208686. *result = new JuceEnumFormatEtc (format);
  208687. return S_OK;
  208688. }
  208689. *result = 0;
  208690. return E_NOTIMPL;
  208691. }
  208692. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208693. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208694. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208695. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208696. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208697. private:
  208698. JuceDropSource* const dropSource;
  208699. const FORMATETC* const format;
  208700. const STGMEDIUM* const medium;
  208701. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  208702. };
  208703. static HDROP createHDrop (const StringArray& fileNames)
  208704. {
  208705. int totalChars = 0;
  208706. for (int i = fileNames.size(); --i >= 0;)
  208707. totalChars += fileNames[i].length() + 1;
  208708. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208709. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208710. if (hDrop != 0)
  208711. {
  208712. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208713. pDropFiles->pFiles = sizeof (DROPFILES);
  208714. pDropFiles->fWide = true;
  208715. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208716. for (int i = 0; i < fileNames.size(); ++i)
  208717. {
  208718. fileNames[i].copyToUnicode (fname, 2048);
  208719. fname += fileNames[i].length() + 1;
  208720. }
  208721. *fname = 0;
  208722. GlobalUnlock (hDrop);
  208723. }
  208724. return hDrop;
  208725. }
  208726. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208727. {
  208728. JuceDropSource* const source = new JuceDropSource();
  208729. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208730. DWORD effect;
  208731. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208732. data->Release();
  208733. source->Release();
  208734. return res == DRAGDROP_S_DROP;
  208735. }
  208736. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208737. {
  208738. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208739. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208740. medium.hGlobal = createHDrop (files);
  208741. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208742. : DROPEFFECT_COPY);
  208743. }
  208744. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208745. {
  208746. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208747. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208748. const int numChars = text.length();
  208749. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208750. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208751. text.copyToUnicode (data, numChars + 1);
  208752. format.cfFormat = CF_UNICODETEXT;
  208753. GlobalUnlock (medium.hGlobal);
  208754. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208755. }
  208756. #endif
  208757. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208758. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208759. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208760. // compiled on its own).
  208761. #if JUCE_INCLUDED_FILE
  208762. namespace FileChooserHelpers
  208763. {
  208764. static bool areThereAnyAlwaysOnTopWindows()
  208765. {
  208766. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208767. {
  208768. Component* c = Desktop::getInstance().getComponent (i);
  208769. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208770. return true;
  208771. }
  208772. return false;
  208773. }
  208774. struct FileChooserCallbackInfo
  208775. {
  208776. String initialPath;
  208777. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208778. ScopedPointer<Component> customComponent;
  208779. };
  208780. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208781. {
  208782. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208783. if (msg == BFFM_INITIALIZED)
  208784. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208785. else if (msg == BFFM_VALIDATEFAILEDW)
  208786. info->returnedString = (LPCWSTR) lParam;
  208787. else if (msg == BFFM_VALIDATEFAILEDA)
  208788. info->returnedString = (const char*) lParam;
  208789. return 0;
  208790. }
  208791. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208792. {
  208793. if (uiMsg == WM_INITDIALOG)
  208794. {
  208795. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208796. HWND dialogH = GetParent (hdlg);
  208797. jassert (dialogH != 0);
  208798. if (dialogH == 0)
  208799. dialogH = hdlg;
  208800. RECT r, cr;
  208801. GetWindowRect (dialogH, &r);
  208802. GetClientRect (dialogH, &cr);
  208803. SetWindowPos (dialogH, 0,
  208804. r.left, r.top,
  208805. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208806. jmax (150, (int) (r.bottom - r.top)),
  208807. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208808. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208809. customComp->addToDesktop (0, dialogH);
  208810. }
  208811. else if (uiMsg == WM_NOTIFY)
  208812. {
  208813. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208814. if (ofn->hdr.code == CDN_SELCHANGE)
  208815. {
  208816. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208817. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208818. if (comp != 0)
  208819. {
  208820. WCHAR path [MAX_PATH * 2];
  208821. zerostruct (path);
  208822. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208823. comp->selectedFileChanged (File (path));
  208824. }
  208825. }
  208826. }
  208827. return 0;
  208828. }
  208829. class CustomComponentHolder : public Component
  208830. {
  208831. public:
  208832. CustomComponentHolder (Component* customComp)
  208833. {
  208834. setVisible (true);
  208835. setOpaque (true);
  208836. addAndMakeVisible (customComp);
  208837. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208838. }
  208839. void paint (Graphics& g)
  208840. {
  208841. g.fillAll (Colours::lightgrey);
  208842. }
  208843. void resized()
  208844. {
  208845. if (getNumChildComponents() > 0)
  208846. getChildComponent(0)->setBounds (getLocalBounds());
  208847. }
  208848. private:
  208849. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  208850. };
  208851. }
  208852. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208853. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208854. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208855. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208856. {
  208857. using namespace FileChooserHelpers;
  208858. HeapBlock<WCHAR> files;
  208859. const int charsAvailableForResult = 32768;
  208860. files.calloc (charsAvailableForResult + 1);
  208861. int filenameOffset = 0;
  208862. FileChooserCallbackInfo info;
  208863. // use a modal window as the parent for this dialog box
  208864. // to block input from other app windows
  208865. Component parentWindow (String::empty);
  208866. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208867. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208868. mainMon.getY() + mainMon.getHeight() / 4,
  208869. 0, 0);
  208870. parentWindow.setOpaque (true);
  208871. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208872. parentWindow.addToDesktop (0);
  208873. if (extraInfoComponent == 0)
  208874. parentWindow.enterModalState();
  208875. if (currentFileOrDirectory.isDirectory())
  208876. {
  208877. info.initialPath = currentFileOrDirectory.getFullPathName();
  208878. }
  208879. else
  208880. {
  208881. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208882. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208883. }
  208884. if (selectsDirectory)
  208885. {
  208886. BROWSEINFO bi;
  208887. zerostruct (bi);
  208888. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208889. bi.pszDisplayName = files;
  208890. bi.lpszTitle = title;
  208891. bi.lParam = (LPARAM) &info;
  208892. bi.lpfn = browseCallbackProc;
  208893. #ifdef BIF_USENEWUI
  208894. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208895. #else
  208896. bi.ulFlags = 0x50;
  208897. #endif
  208898. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208899. if (! SHGetPathFromIDListW (list, files))
  208900. {
  208901. files[0] = 0;
  208902. info.returnedString = String::empty;
  208903. }
  208904. LPMALLOC al;
  208905. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208906. al->Free (list);
  208907. if (info.returnedString.isNotEmpty())
  208908. {
  208909. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208910. return;
  208911. }
  208912. }
  208913. else
  208914. {
  208915. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208916. if (warnAboutOverwritingExistingFiles)
  208917. flags |= OFN_OVERWRITEPROMPT;
  208918. if (selectMultipleFiles)
  208919. flags |= OFN_ALLOWMULTISELECT;
  208920. if (extraInfoComponent != 0)
  208921. {
  208922. flags |= OFN_ENABLEHOOK;
  208923. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208924. info.customComponent->enterModalState();
  208925. }
  208926. WCHAR filters [1024];
  208927. zerostruct (filters);
  208928. filter.copyToUnicode (filters, 1024);
  208929. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  208930. OPENFILENAMEW of;
  208931. zerostruct (of);
  208932. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208933. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208934. #else
  208935. of.lStructSize = sizeof (of);
  208936. #endif
  208937. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208938. of.lpstrFilter = filters;
  208939. of.nFilterIndex = 1;
  208940. of.lpstrFile = files;
  208941. of.nMaxFile = charsAvailableForResult;
  208942. of.lpstrInitialDir = info.initialPath;
  208943. of.lpstrTitle = title;
  208944. of.Flags = flags;
  208945. of.lCustData = (LPARAM) &info;
  208946. if (extraInfoComponent != 0)
  208947. of.lpfnHook = &openCallback;
  208948. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208949. : GetOpenFileName (&of)))
  208950. return;
  208951. filenameOffset = of.nFileOffset;
  208952. }
  208953. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208954. {
  208955. const WCHAR* filename = files + filenameOffset;
  208956. while (*filename != 0)
  208957. {
  208958. results.add (File (String (files) + "\\" + String (filename)));
  208959. filename += CharacterFunctions::length (filename) + 1;
  208960. }
  208961. }
  208962. else if (files[0] != 0)
  208963. {
  208964. results.add (File (String (files)));
  208965. }
  208966. }
  208967. #endif
  208968. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208969. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208970. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208971. // compiled on its own).
  208972. #if JUCE_INCLUDED_FILE
  208973. void SystemClipboard::copyTextToClipboard (const String& text)
  208974. {
  208975. if (OpenClipboard (0) != 0)
  208976. {
  208977. if (EmptyClipboard() != 0)
  208978. {
  208979. const int len = text.length();
  208980. if (len > 0)
  208981. {
  208982. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  208983. (len + 1) * sizeof (wchar_t));
  208984. if (bufH != 0)
  208985. {
  208986. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208987. text.copyToUnicode (data, len);
  208988. GlobalUnlock (bufH);
  208989. SetClipboardData (CF_UNICODETEXT, bufH);
  208990. }
  208991. }
  208992. }
  208993. CloseClipboard();
  208994. }
  208995. }
  208996. const String SystemClipboard::getTextFromClipboard()
  208997. {
  208998. String result;
  208999. if (OpenClipboard (0) != 0)
  209000. {
  209001. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209002. if (bufH != 0)
  209003. {
  209004. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209005. if (data != 0)
  209006. {
  209007. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209008. GlobalUnlock (bufH);
  209009. }
  209010. }
  209011. CloseClipboard();
  209012. }
  209013. return result;
  209014. }
  209015. #endif
  209016. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209017. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209018. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209019. // compiled on its own).
  209020. #if JUCE_INCLUDED_FILE
  209021. namespace ActiveXHelpers
  209022. {
  209023. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209024. {
  209025. public:
  209026. JuceIStorage() {}
  209027. ~JuceIStorage() {}
  209028. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209029. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209030. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209031. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209032. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209033. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209034. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209035. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209036. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209037. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209038. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209039. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209040. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209041. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209042. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209043. };
  209044. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209045. {
  209046. HWND window;
  209047. public:
  209048. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209049. ~JuceOleInPlaceFrame() {}
  209050. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209051. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209052. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209053. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209054. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209055. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209056. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209057. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209058. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209059. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209060. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209061. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209062. };
  209063. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209064. {
  209065. HWND window;
  209066. JuceOleInPlaceFrame* frame;
  209067. public:
  209068. JuceIOleInPlaceSite (HWND window_)
  209069. : window (window_),
  209070. frame (new JuceOleInPlaceFrame (window))
  209071. {}
  209072. ~JuceIOleInPlaceSite()
  209073. {
  209074. frame->Release();
  209075. }
  209076. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209077. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209078. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209079. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209080. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209081. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209082. {
  209083. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209084. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209085. */
  209086. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209087. if (lplpDoc != 0) *lplpDoc = 0;
  209088. lpFrameInfo->fMDIApp = FALSE;
  209089. lpFrameInfo->hwndFrame = window;
  209090. lpFrameInfo->haccel = 0;
  209091. lpFrameInfo->cAccelEntries = 0;
  209092. return S_OK;
  209093. }
  209094. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209095. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209096. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209097. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209098. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209099. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209100. };
  209101. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209102. {
  209103. JuceIOleInPlaceSite* inplaceSite;
  209104. public:
  209105. JuceIOleClientSite (HWND window)
  209106. : inplaceSite (new JuceIOleInPlaceSite (window))
  209107. {}
  209108. ~JuceIOleClientSite()
  209109. {
  209110. inplaceSite->Release();
  209111. }
  209112. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209113. {
  209114. if (type == IID_IOleInPlaceSite)
  209115. {
  209116. inplaceSite->AddRef();
  209117. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209118. return S_OK;
  209119. }
  209120. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209121. }
  209122. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209123. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209124. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209125. HRESULT __stdcall ShowObject() { return S_OK; }
  209126. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209127. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209128. };
  209129. static Array<ActiveXControlComponent*> activeXComps;
  209130. static HWND getHWND (const ActiveXControlComponent* const component)
  209131. {
  209132. HWND hwnd = 0;
  209133. const IID iid = IID_IOleWindow;
  209134. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209135. if (window != 0)
  209136. {
  209137. window->GetWindow (&hwnd);
  209138. window->Release();
  209139. }
  209140. return hwnd;
  209141. }
  209142. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209143. {
  209144. RECT activeXRect, peerRect;
  209145. GetWindowRect (hwnd, &activeXRect);
  209146. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209147. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209148. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209149. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209150. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209151. switch (message)
  209152. {
  209153. case WM_MOUSEMOVE:
  209154. case WM_LBUTTONDOWN:
  209155. case WM_MBUTTONDOWN:
  209156. case WM_RBUTTONDOWN:
  209157. case WM_LBUTTONUP:
  209158. case WM_MBUTTONUP:
  209159. case WM_RBUTTONUP:
  209160. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209161. break;
  209162. default:
  209163. break;
  209164. }
  209165. }
  209166. }
  209167. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209168. {
  209169. ActiveXControlComponent& owner;
  209170. bool wasShowing;
  209171. public:
  209172. HWND controlHWND;
  209173. IStorage* storage;
  209174. IOleClientSite* clientSite;
  209175. IOleObject* control;
  209176. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209177. : ComponentMovementWatcher (&owner_),
  209178. owner (owner_),
  209179. wasShowing (owner_.isShowing()),
  209180. controlHWND (0),
  209181. storage (new ActiveXHelpers::JuceIStorage()),
  209182. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209183. control (0)
  209184. {
  209185. }
  209186. ~Pimpl()
  209187. {
  209188. if (control != 0)
  209189. {
  209190. control->Close (OLECLOSE_NOSAVE);
  209191. control->Release();
  209192. }
  209193. clientSite->Release();
  209194. storage->Release();
  209195. }
  209196. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209197. {
  209198. Component* const topComp = owner.getTopLevelComponent();
  209199. if (topComp->getPeer() != 0)
  209200. {
  209201. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  209202. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209203. }
  209204. }
  209205. void componentPeerChanged()
  209206. {
  209207. const bool isShowingNow = owner.isShowing();
  209208. if (wasShowing != isShowingNow)
  209209. {
  209210. wasShowing = isShowingNow;
  209211. owner.setControlVisible (isShowingNow);
  209212. }
  209213. componentMovedOrResized (true, true);
  209214. }
  209215. void componentVisibilityChanged (Component&)
  209216. {
  209217. componentPeerChanged();
  209218. }
  209219. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209220. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209221. {
  209222. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209223. {
  209224. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209225. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209226. {
  209227. switch (message)
  209228. {
  209229. case WM_MOUSEMOVE:
  209230. case WM_LBUTTONDOWN:
  209231. case WM_MBUTTONDOWN:
  209232. case WM_RBUTTONDOWN:
  209233. case WM_LBUTTONUP:
  209234. case WM_MBUTTONUP:
  209235. case WM_RBUTTONUP:
  209236. case WM_LBUTTONDBLCLK:
  209237. case WM_MBUTTONDBLCLK:
  209238. case WM_RBUTTONDBLCLK:
  209239. if (ax->isShowing())
  209240. {
  209241. ComponentPeer* const peer = ax->getPeer();
  209242. if (peer != 0)
  209243. {
  209244. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209245. if (! ax->areMouseEventsAllowed())
  209246. return 0;
  209247. }
  209248. }
  209249. break;
  209250. default:
  209251. break;
  209252. }
  209253. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209254. }
  209255. }
  209256. return DefWindowProc (hwnd, message, wParam, lParam);
  209257. }
  209258. };
  209259. ActiveXControlComponent::ActiveXControlComponent()
  209260. : originalWndProc (0),
  209261. mouseEventsAllowed (true)
  209262. {
  209263. ActiveXHelpers::activeXComps.add (this);
  209264. }
  209265. ActiveXControlComponent::~ActiveXControlComponent()
  209266. {
  209267. deleteControl();
  209268. ActiveXHelpers::activeXComps.removeValue (this);
  209269. }
  209270. void ActiveXControlComponent::paint (Graphics& g)
  209271. {
  209272. if (control == 0)
  209273. g.fillAll (Colours::lightgrey);
  209274. }
  209275. bool ActiveXControlComponent::createControl (const void* controlIID)
  209276. {
  209277. deleteControl();
  209278. ComponentPeer* const peer = getPeer();
  209279. // the component must have already been added to a real window when you call this!
  209280. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209281. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209282. {
  209283. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209284. HWND hwnd = (HWND) peer->getNativeHandle();
  209285. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209286. HRESULT hr;
  209287. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209288. newControl->clientSite, newControl->storage,
  209289. (void**) &(newControl->control))) == S_OK)
  209290. {
  209291. newControl->control->SetHostNames (L"Juce", 0);
  209292. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209293. {
  209294. RECT rect;
  209295. rect.left = pos.getX();
  209296. rect.top = pos.getY();
  209297. rect.right = pos.getX() + getWidth();
  209298. rect.bottom = pos.getY() + getHeight();
  209299. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209300. {
  209301. control = newControl;
  209302. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209303. control->controlHWND = ActiveXHelpers::getHWND (this);
  209304. if (control->controlHWND != 0)
  209305. {
  209306. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209307. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209308. }
  209309. return true;
  209310. }
  209311. }
  209312. }
  209313. }
  209314. return false;
  209315. }
  209316. void ActiveXControlComponent::deleteControl()
  209317. {
  209318. control = 0;
  209319. originalWndProc = 0;
  209320. }
  209321. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209322. {
  209323. void* result = 0;
  209324. if (control != 0 && control->control != 0
  209325. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209326. return result;
  209327. return 0;
  209328. }
  209329. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209330. {
  209331. if (control->controlHWND != 0)
  209332. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209333. }
  209334. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209335. {
  209336. if (control->controlHWND != 0)
  209337. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209338. }
  209339. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209340. {
  209341. mouseEventsAllowed = eventsCanReachControl;
  209342. }
  209343. #endif
  209344. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209345. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209346. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209347. // compiled on its own).
  209348. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209349. using namespace QTOLibrary;
  209350. using namespace QTOControlLib;
  209351. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209352. static bool isQTAvailable = false;
  209353. class QuickTimeMovieComponent::Pimpl
  209354. {
  209355. public:
  209356. Pimpl() : dataHandle (0)
  209357. {
  209358. }
  209359. ~Pimpl()
  209360. {
  209361. clearHandle();
  209362. }
  209363. void clearHandle()
  209364. {
  209365. if (dataHandle != 0)
  209366. {
  209367. DisposeHandle (dataHandle);
  209368. dataHandle = 0;
  209369. }
  209370. }
  209371. IQTControlPtr qtControl;
  209372. IQTMoviePtr qtMovie;
  209373. Handle dataHandle;
  209374. };
  209375. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209376. : movieLoaded (false),
  209377. controllerVisible (true)
  209378. {
  209379. pimpl = new Pimpl();
  209380. setMouseEventsAllowed (false);
  209381. }
  209382. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209383. {
  209384. closeMovie();
  209385. pimpl->qtControl = 0;
  209386. deleteControl();
  209387. pimpl = 0;
  209388. }
  209389. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209390. {
  209391. if (! isQTAvailable)
  209392. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209393. return isQTAvailable;
  209394. }
  209395. void QuickTimeMovieComponent::createControlIfNeeded()
  209396. {
  209397. if (isShowing() && ! isControlCreated())
  209398. {
  209399. const IID qtIID = __uuidof (QTControl);
  209400. if (createControl (&qtIID))
  209401. {
  209402. const IID qtInterfaceIID = __uuidof (IQTControl);
  209403. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209404. if (pimpl->qtControl != 0)
  209405. {
  209406. pimpl->qtControl->Release(); // it has one ref too many at this point
  209407. pimpl->qtControl->QuickTimeInitialize();
  209408. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209409. if (movieFile != File::nonexistent)
  209410. loadMovie (movieFile, controllerVisible);
  209411. }
  209412. }
  209413. }
  209414. }
  209415. bool QuickTimeMovieComponent::isControlCreated() const
  209416. {
  209417. return isControlOpen();
  209418. }
  209419. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209420. const bool isControllerVisible)
  209421. {
  209422. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209423. movieFile = File::nonexistent;
  209424. movieLoaded = false;
  209425. pimpl->qtMovie = 0;
  209426. controllerVisible = isControllerVisible;
  209427. createControlIfNeeded();
  209428. if (isControlCreated())
  209429. {
  209430. if (pimpl->qtControl != 0)
  209431. {
  209432. pimpl->qtControl->Put_MovieHandle (0);
  209433. pimpl->clearHandle();
  209434. Movie movie;
  209435. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209436. {
  209437. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209438. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209439. if (pimpl->qtMovie != 0)
  209440. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209441. : qtMovieControllerTypeNone);
  209442. }
  209443. if (movie == 0)
  209444. pimpl->clearHandle();
  209445. }
  209446. movieLoaded = (pimpl->qtMovie != 0);
  209447. }
  209448. else
  209449. {
  209450. // You're trying to open a movie when the control hasn't yet been created, probably because
  209451. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209452. jassertfalse;
  209453. }
  209454. return movieLoaded;
  209455. }
  209456. void QuickTimeMovieComponent::closeMovie()
  209457. {
  209458. stop();
  209459. movieFile = File::nonexistent;
  209460. movieLoaded = false;
  209461. pimpl->qtMovie = 0;
  209462. if (pimpl->qtControl != 0)
  209463. pimpl->qtControl->Put_MovieHandle (0);
  209464. pimpl->clearHandle();
  209465. }
  209466. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209467. {
  209468. return movieFile;
  209469. }
  209470. bool QuickTimeMovieComponent::isMovieOpen() const
  209471. {
  209472. return movieLoaded;
  209473. }
  209474. double QuickTimeMovieComponent::getMovieDuration() const
  209475. {
  209476. if (pimpl->qtMovie != 0)
  209477. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209478. return 0.0;
  209479. }
  209480. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209481. {
  209482. if (pimpl->qtMovie != 0)
  209483. {
  209484. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209485. width = r.right - r.left;
  209486. height = r.bottom - r.top;
  209487. }
  209488. else
  209489. {
  209490. width = height = 0;
  209491. }
  209492. }
  209493. void QuickTimeMovieComponent::play()
  209494. {
  209495. if (pimpl->qtMovie != 0)
  209496. pimpl->qtMovie->Play();
  209497. }
  209498. void QuickTimeMovieComponent::stop()
  209499. {
  209500. if (pimpl->qtMovie != 0)
  209501. pimpl->qtMovie->Stop();
  209502. }
  209503. bool QuickTimeMovieComponent::isPlaying() const
  209504. {
  209505. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209506. }
  209507. void QuickTimeMovieComponent::setPosition (const double seconds)
  209508. {
  209509. if (pimpl->qtMovie != 0)
  209510. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209511. }
  209512. double QuickTimeMovieComponent::getPosition() const
  209513. {
  209514. if (pimpl->qtMovie != 0)
  209515. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209516. return 0.0;
  209517. }
  209518. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209519. {
  209520. if (pimpl->qtMovie != 0)
  209521. pimpl->qtMovie->PutRate (newSpeed);
  209522. }
  209523. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209524. {
  209525. if (pimpl->qtMovie != 0)
  209526. {
  209527. pimpl->qtMovie->PutAudioVolume (newVolume);
  209528. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209529. }
  209530. }
  209531. float QuickTimeMovieComponent::getMovieVolume() const
  209532. {
  209533. if (pimpl->qtMovie != 0)
  209534. return pimpl->qtMovie->GetAudioVolume();
  209535. return 0.0f;
  209536. }
  209537. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209538. {
  209539. if (pimpl->qtMovie != 0)
  209540. pimpl->qtMovie->PutLoop (shouldLoop);
  209541. }
  209542. bool QuickTimeMovieComponent::isLooping() const
  209543. {
  209544. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209545. }
  209546. bool QuickTimeMovieComponent::isControllerVisible() const
  209547. {
  209548. return controllerVisible;
  209549. }
  209550. void QuickTimeMovieComponent::parentHierarchyChanged()
  209551. {
  209552. createControlIfNeeded();
  209553. QTCompBaseClass::parentHierarchyChanged();
  209554. }
  209555. void QuickTimeMovieComponent::visibilityChanged()
  209556. {
  209557. createControlIfNeeded();
  209558. QTCompBaseClass::visibilityChanged();
  209559. }
  209560. void QuickTimeMovieComponent::paint (Graphics& g)
  209561. {
  209562. if (! isControlCreated())
  209563. g.fillAll (Colours::black);
  209564. }
  209565. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209566. {
  209567. Handle dataRef = 0;
  209568. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209569. if (err == noErr)
  209570. {
  209571. Str255 suffix;
  209572. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209573. StringPtr name = suffix;
  209574. err = PtrAndHand (name, dataRef, name[0] + 1);
  209575. if (err == noErr)
  209576. {
  209577. long atoms[3];
  209578. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209579. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209580. atoms[2] = EndianU32_NtoB (MovieFileType);
  209581. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209582. if (err == noErr)
  209583. return dataRef;
  209584. }
  209585. DisposeHandle (dataRef);
  209586. }
  209587. return 0;
  209588. }
  209589. static CFStringRef juceStringToCFString (const String& s)
  209590. {
  209591. const int len = s.length();
  209592. const juce_wchar* const t = s;
  209593. HeapBlock <UniChar> temp (len + 2);
  209594. for (int i = 0; i <= len; ++i)
  209595. temp[i] = t[i];
  209596. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209597. }
  209598. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209599. {
  209600. Boolean trueBool = true;
  209601. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209602. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209603. props[prop].propValueSize = sizeof (trueBool);
  209604. props[prop].propValueAddress = &trueBool;
  209605. ++prop;
  209606. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209607. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209608. props[prop].propValueSize = sizeof (trueBool);
  209609. props[prop].propValueAddress = &trueBool;
  209610. ++prop;
  209611. Boolean isActive = true;
  209612. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209613. props[prop].propID = kQTNewMoviePropertyID_Active;
  209614. props[prop].propValueSize = sizeof (isActive);
  209615. props[prop].propValueAddress = &isActive;
  209616. ++prop;
  209617. MacSetPort (0);
  209618. jassert (prop <= 5);
  209619. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209620. return err == noErr;
  209621. }
  209622. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209623. {
  209624. if (input == 0)
  209625. return false;
  209626. dataHandle = 0;
  209627. bool ok = false;
  209628. QTNewMoviePropertyElement props[5];
  209629. zeromem (props, sizeof (props));
  209630. int prop = 0;
  209631. DataReferenceRecord dr;
  209632. props[prop].propClass = kQTPropertyClass_DataLocation;
  209633. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209634. props[prop].propValueSize = sizeof (dr);
  209635. props[prop].propValueAddress = &dr;
  209636. ++prop;
  209637. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209638. if (fin != 0)
  209639. {
  209640. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209641. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209642. &dr.dataRef, &dr.dataRefType);
  209643. ok = openMovie (props, prop, movie);
  209644. DisposeHandle (dr.dataRef);
  209645. CFRelease (filePath);
  209646. }
  209647. else
  209648. {
  209649. // sanity-check because this currently needs to load the whole stream into memory..
  209650. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209651. dataHandle = NewHandle ((Size) input->getTotalLength());
  209652. HLock (dataHandle);
  209653. // read the entire stream into memory - this is a pain, but can't get it to work
  209654. // properly using a custom callback to supply the data.
  209655. input->read (*dataHandle, (int) input->getTotalLength());
  209656. HUnlock (dataHandle);
  209657. // different types to get QT to try. (We should really be a bit smarter here by
  209658. // working out in advance which one the stream contains, rather than just trying
  209659. // each one)
  209660. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209661. "\04.avi", "\04.m4a" };
  209662. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209663. {
  209664. /* // this fails for some bizarre reason - it can be bodged to work with
  209665. // movies, but can't seem to do it for other file types..
  209666. QTNewMovieUserProcRecord procInfo;
  209667. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209668. procInfo.getMovieUserProcRefcon = this;
  209669. procInfo.defaultDataRef.dataRef = dataRef;
  209670. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209671. props[prop].propClass = kQTPropertyClass_DataLocation;
  209672. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209673. props[prop].propValueSize = sizeof (procInfo);
  209674. props[prop].propValueAddress = (void*) &procInfo;
  209675. ++prop; */
  209676. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209677. dr.dataRefType = HandleDataHandlerSubType;
  209678. ok = openMovie (props, prop, movie);
  209679. DisposeHandle (dr.dataRef);
  209680. }
  209681. }
  209682. return ok;
  209683. }
  209684. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209685. const bool isControllerVisible)
  209686. {
  209687. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209688. movieFile = movieFile_;
  209689. return ok;
  209690. }
  209691. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209692. const bool isControllerVisible)
  209693. {
  209694. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209695. }
  209696. void QuickTimeMovieComponent::goToStart()
  209697. {
  209698. setPosition (0.0);
  209699. }
  209700. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209701. const RectanglePlacement& placement)
  209702. {
  209703. int normalWidth, normalHeight;
  209704. getMovieNormalSize (normalWidth, normalHeight);
  209705. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209706. {
  209707. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209708. placement.applyTo (x, y, w, h,
  209709. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209710. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209711. if (w > 0 && h > 0)
  209712. {
  209713. setBounds (roundToInt (x), roundToInt (y),
  209714. roundToInt (w), roundToInt (h));
  209715. }
  209716. }
  209717. else
  209718. {
  209719. setBounds (spaceToFitWithin);
  209720. }
  209721. }
  209722. #endif
  209723. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209724. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209725. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209726. // compiled on its own).
  209727. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209728. class WebBrowserComponentInternal : public ActiveXControlComponent
  209729. {
  209730. public:
  209731. WebBrowserComponentInternal()
  209732. : browser (0),
  209733. connectionPoint (0),
  209734. adviseCookie (0)
  209735. {
  209736. }
  209737. ~WebBrowserComponentInternal()
  209738. {
  209739. if (connectionPoint != 0)
  209740. connectionPoint->Unadvise (adviseCookie);
  209741. if (browser != 0)
  209742. browser->Release();
  209743. }
  209744. void createBrowser()
  209745. {
  209746. createControl (&CLSID_WebBrowser);
  209747. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209748. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209749. if (connectionPointContainer != 0)
  209750. {
  209751. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209752. &connectionPoint);
  209753. if (connectionPoint != 0)
  209754. {
  209755. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209756. jassert (owner != 0);
  209757. EventHandler* handler = new EventHandler (owner);
  209758. connectionPoint->Advise (handler, &adviseCookie);
  209759. handler->Release();
  209760. }
  209761. }
  209762. }
  209763. void goToURL (const String& url,
  209764. const StringArray* headers,
  209765. const MemoryBlock* postData)
  209766. {
  209767. if (browser != 0)
  209768. {
  209769. LPSAFEARRAY sa = 0;
  209770. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209771. VariantInit (&flags);
  209772. VariantInit (&frame);
  209773. VariantInit (&postDataVar);
  209774. VariantInit (&headersVar);
  209775. if (headers != 0)
  209776. {
  209777. V_VT (&headersVar) = VT_BSTR;
  209778. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209779. }
  209780. if (postData != 0 && postData->getSize() > 0)
  209781. {
  209782. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209783. if (sa != 0)
  209784. {
  209785. void* data = 0;
  209786. SafeArrayAccessData (sa, &data);
  209787. jassert (data != 0);
  209788. if (data != 0)
  209789. {
  209790. postData->copyTo (data, 0, postData->getSize());
  209791. SafeArrayUnaccessData (sa);
  209792. VARIANT postDataVar2;
  209793. VariantInit (&postDataVar2);
  209794. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209795. V_ARRAY (&postDataVar2) = sa;
  209796. postDataVar = postDataVar2;
  209797. }
  209798. }
  209799. }
  209800. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209801. &flags, &frame,
  209802. &postDataVar, &headersVar);
  209803. if (sa != 0)
  209804. SafeArrayDestroy (sa);
  209805. VariantClear (&flags);
  209806. VariantClear (&frame);
  209807. VariantClear (&postDataVar);
  209808. VariantClear (&headersVar);
  209809. }
  209810. }
  209811. IWebBrowser2* browser;
  209812. private:
  209813. IConnectionPoint* connectionPoint;
  209814. DWORD adviseCookie;
  209815. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209816. public ComponentMovementWatcher
  209817. {
  209818. public:
  209819. EventHandler (WebBrowserComponent* const owner_)
  209820. : ComponentMovementWatcher (owner_),
  209821. owner (owner_)
  209822. {
  209823. }
  209824. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209825. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209826. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209827. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209828. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  209829. {
  209830. switch (dispIdMember)
  209831. {
  209832. case DISPID_BEFORENAVIGATE2:
  209833. {
  209834. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209835. String url;
  209836. if ((vurl->vt & VT_BYREF) != 0)
  209837. url = *vurl->pbstrVal;
  209838. else
  209839. url = vurl->bstrVal;
  209840. *pDispParams->rgvarg->pboolVal
  209841. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209842. : VARIANT_TRUE;
  209843. return S_OK;
  209844. }
  209845. default:
  209846. break;
  209847. }
  209848. return E_NOTIMPL;
  209849. }
  209850. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209851. void componentPeerChanged() {}
  209852. void componentVisibilityChanged (Component&)
  209853. {
  209854. owner->visibilityChanged();
  209855. }
  209856. private:
  209857. WebBrowserComponent* const owner;
  209858. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  209859. };
  209860. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  209861. };
  209862. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209863. : browser (0),
  209864. blankPageShown (false),
  209865. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209866. {
  209867. setOpaque (true);
  209868. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209869. }
  209870. WebBrowserComponent::~WebBrowserComponent()
  209871. {
  209872. delete browser;
  209873. }
  209874. void WebBrowserComponent::goToURL (const String& url,
  209875. const StringArray* headers,
  209876. const MemoryBlock* postData)
  209877. {
  209878. lastURL = url;
  209879. lastHeaders.clear();
  209880. if (headers != 0)
  209881. lastHeaders = *headers;
  209882. lastPostData.setSize (0);
  209883. if (postData != 0)
  209884. lastPostData = *postData;
  209885. blankPageShown = false;
  209886. browser->goToURL (url, headers, postData);
  209887. }
  209888. void WebBrowserComponent::stop()
  209889. {
  209890. if (browser->browser != 0)
  209891. browser->browser->Stop();
  209892. }
  209893. void WebBrowserComponent::goBack()
  209894. {
  209895. lastURL = String::empty;
  209896. blankPageShown = false;
  209897. if (browser->browser != 0)
  209898. browser->browser->GoBack();
  209899. }
  209900. void WebBrowserComponent::goForward()
  209901. {
  209902. lastURL = String::empty;
  209903. if (browser->browser != 0)
  209904. browser->browser->GoForward();
  209905. }
  209906. void WebBrowserComponent::refresh()
  209907. {
  209908. if (browser->browser != 0)
  209909. browser->browser->Refresh();
  209910. }
  209911. void WebBrowserComponent::paint (Graphics& g)
  209912. {
  209913. if (browser->browser == 0)
  209914. g.fillAll (Colours::white);
  209915. }
  209916. void WebBrowserComponent::checkWindowAssociation()
  209917. {
  209918. if (isShowing())
  209919. {
  209920. if (browser->browser == 0 && getPeer() != 0)
  209921. {
  209922. browser->createBrowser();
  209923. reloadLastURL();
  209924. }
  209925. else
  209926. {
  209927. if (blankPageShown)
  209928. goBack();
  209929. }
  209930. }
  209931. else
  209932. {
  209933. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209934. {
  209935. // when the component becomes invisible, some stuff like flash
  209936. // carries on playing audio, so we need to force it onto a blank
  209937. // page to avoid this..
  209938. blankPageShown = true;
  209939. browser->goToURL ("about:blank", 0, 0);
  209940. }
  209941. }
  209942. }
  209943. void WebBrowserComponent::reloadLastURL()
  209944. {
  209945. if (lastURL.isNotEmpty())
  209946. {
  209947. goToURL (lastURL, &lastHeaders, &lastPostData);
  209948. lastURL = String::empty;
  209949. }
  209950. }
  209951. void WebBrowserComponent::parentHierarchyChanged()
  209952. {
  209953. checkWindowAssociation();
  209954. }
  209955. void WebBrowserComponent::resized()
  209956. {
  209957. browser->setSize (getWidth(), getHeight());
  209958. }
  209959. void WebBrowserComponent::visibilityChanged()
  209960. {
  209961. checkWindowAssociation();
  209962. }
  209963. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209964. {
  209965. return true;
  209966. }
  209967. #endif
  209968. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209969. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209970. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209971. // compiled on its own).
  209972. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209973. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209974. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209975. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209976. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209977. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209978. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209979. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209980. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209981. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209982. #define WGL_ACCELERATION_ARB 0x2003
  209983. #define WGL_SWAP_METHOD_ARB 0x2007
  209984. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209985. #define WGL_PIXEL_TYPE_ARB 0x2013
  209986. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209987. #define WGL_COLOR_BITS_ARB 0x2014
  209988. #define WGL_RED_BITS_ARB 0x2015
  209989. #define WGL_GREEN_BITS_ARB 0x2017
  209990. #define WGL_BLUE_BITS_ARB 0x2019
  209991. #define WGL_ALPHA_BITS_ARB 0x201B
  209992. #define WGL_DEPTH_BITS_ARB 0x2022
  209993. #define WGL_STENCIL_BITS_ARB 0x2023
  209994. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209995. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209996. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209997. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209998. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209999. #define WGL_STEREO_ARB 0x2012
  210000. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210001. #define WGL_SAMPLES_ARB 0x2042
  210002. #define WGL_TYPE_RGBA_ARB 0x202B
  210003. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210004. {
  210005. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210006. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210007. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210008. else
  210009. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210010. }
  210011. class WindowedGLContext : public OpenGLContext
  210012. {
  210013. public:
  210014. WindowedGLContext (Component* const component_,
  210015. HGLRC contextToShareWith,
  210016. const OpenGLPixelFormat& pixelFormat)
  210017. : renderContext (0),
  210018. dc (0),
  210019. component (component_)
  210020. {
  210021. jassert (component != 0);
  210022. createNativeWindow();
  210023. // Use a default pixel format that should be supported everywhere
  210024. PIXELFORMATDESCRIPTOR pfd;
  210025. zerostruct (pfd);
  210026. pfd.nSize = sizeof (pfd);
  210027. pfd.nVersion = 1;
  210028. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210029. pfd.iPixelType = PFD_TYPE_RGBA;
  210030. pfd.cColorBits = 24;
  210031. pfd.cDepthBits = 16;
  210032. const int format = ChoosePixelFormat (dc, &pfd);
  210033. if (format != 0)
  210034. SetPixelFormat (dc, format, &pfd);
  210035. renderContext = wglCreateContext (dc);
  210036. makeActive();
  210037. setPixelFormat (pixelFormat);
  210038. if (contextToShareWith != 0 && renderContext != 0)
  210039. wglShareLists (contextToShareWith, renderContext);
  210040. }
  210041. ~WindowedGLContext()
  210042. {
  210043. deleteContext();
  210044. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210045. nativeWindow = 0;
  210046. }
  210047. void deleteContext()
  210048. {
  210049. makeInactive();
  210050. if (renderContext != 0)
  210051. {
  210052. wglDeleteContext (renderContext);
  210053. renderContext = 0;
  210054. }
  210055. }
  210056. bool makeActive() const throw()
  210057. {
  210058. jassert (renderContext != 0);
  210059. return wglMakeCurrent (dc, renderContext) != 0;
  210060. }
  210061. bool makeInactive() const throw()
  210062. {
  210063. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210064. }
  210065. bool isActive() const throw()
  210066. {
  210067. return wglGetCurrentContext() == renderContext;
  210068. }
  210069. const OpenGLPixelFormat getPixelFormat() const
  210070. {
  210071. OpenGLPixelFormat pf;
  210072. makeActive();
  210073. StringArray availableExtensions;
  210074. getWglExtensions (dc, availableExtensions);
  210075. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210076. return pf;
  210077. }
  210078. void* getRawContext() const throw()
  210079. {
  210080. return renderContext;
  210081. }
  210082. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210083. {
  210084. makeActive();
  210085. PIXELFORMATDESCRIPTOR pfd;
  210086. zerostruct (pfd);
  210087. pfd.nSize = sizeof (pfd);
  210088. pfd.nVersion = 1;
  210089. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210090. pfd.iPixelType = PFD_TYPE_RGBA;
  210091. pfd.iLayerType = PFD_MAIN_PLANE;
  210092. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210093. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210094. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210095. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210096. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210097. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210098. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210099. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210100. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210101. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210102. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210103. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210104. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210105. int format = 0;
  210106. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210107. StringArray availableExtensions;
  210108. getWglExtensions (dc, availableExtensions);
  210109. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210110. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210111. {
  210112. int attributes[64];
  210113. int n = 0;
  210114. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210115. attributes[n++] = GL_TRUE;
  210116. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210117. attributes[n++] = GL_TRUE;
  210118. attributes[n++] = WGL_ACCELERATION_ARB;
  210119. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210120. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210121. attributes[n++] = GL_TRUE;
  210122. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210123. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210124. attributes[n++] = WGL_COLOR_BITS_ARB;
  210125. attributes[n++] = pfd.cColorBits;
  210126. attributes[n++] = WGL_RED_BITS_ARB;
  210127. attributes[n++] = pixelFormat.redBits;
  210128. attributes[n++] = WGL_GREEN_BITS_ARB;
  210129. attributes[n++] = pixelFormat.greenBits;
  210130. attributes[n++] = WGL_BLUE_BITS_ARB;
  210131. attributes[n++] = pixelFormat.blueBits;
  210132. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210133. attributes[n++] = pixelFormat.alphaBits;
  210134. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210135. attributes[n++] = pixelFormat.depthBufferBits;
  210136. if (pixelFormat.stencilBufferBits > 0)
  210137. {
  210138. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210139. attributes[n++] = pixelFormat.stencilBufferBits;
  210140. }
  210141. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210142. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210143. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210144. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210145. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210146. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210147. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210148. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210149. if (availableExtensions.contains ("WGL_ARB_multisample")
  210150. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210151. {
  210152. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210153. attributes[n++] = 1;
  210154. attributes[n++] = WGL_SAMPLES_ARB;
  210155. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210156. }
  210157. attributes[n++] = 0;
  210158. UINT formatsCount;
  210159. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210160. (void) ok;
  210161. jassert (ok);
  210162. }
  210163. else
  210164. {
  210165. format = ChoosePixelFormat (dc, &pfd);
  210166. }
  210167. if (format != 0)
  210168. {
  210169. makeInactive();
  210170. // win32 can't change the pixel format of a window, so need to delete the
  210171. // old one and create a new one..
  210172. jassert (nativeWindow != 0);
  210173. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210174. nativeWindow = 0;
  210175. createNativeWindow();
  210176. if (SetPixelFormat (dc, format, &pfd))
  210177. {
  210178. wglDeleteContext (renderContext);
  210179. renderContext = wglCreateContext (dc);
  210180. jassert (renderContext != 0);
  210181. return renderContext != 0;
  210182. }
  210183. }
  210184. return false;
  210185. }
  210186. void updateWindowPosition (int x, int y, int w, int h, int)
  210187. {
  210188. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210189. x, y, w, h,
  210190. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210191. }
  210192. void repaint()
  210193. {
  210194. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210195. }
  210196. void swapBuffers()
  210197. {
  210198. SwapBuffers (dc);
  210199. }
  210200. bool setSwapInterval (int numFramesPerSwap)
  210201. {
  210202. makeActive();
  210203. StringArray availableExtensions;
  210204. getWglExtensions (dc, availableExtensions);
  210205. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210206. return availableExtensions.contains ("WGL_EXT_swap_control")
  210207. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210208. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210209. }
  210210. int getSwapInterval() const
  210211. {
  210212. makeActive();
  210213. StringArray availableExtensions;
  210214. getWglExtensions (dc, availableExtensions);
  210215. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210216. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210217. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210218. return wglGetSwapIntervalEXT();
  210219. return 0;
  210220. }
  210221. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210222. {
  210223. jassert (isActive());
  210224. StringArray availableExtensions;
  210225. getWglExtensions (dc, availableExtensions);
  210226. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210227. int numTypes = 0;
  210228. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210229. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210230. {
  210231. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210232. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210233. jassertfalse;
  210234. }
  210235. else
  210236. {
  210237. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210238. }
  210239. OpenGLPixelFormat pf;
  210240. for (int i = 0; i < numTypes; ++i)
  210241. {
  210242. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210243. {
  210244. bool alreadyListed = false;
  210245. for (int j = results.size(); --j >= 0;)
  210246. if (pf == *results.getUnchecked(j))
  210247. alreadyListed = true;
  210248. if (! alreadyListed)
  210249. results.add (new OpenGLPixelFormat (pf));
  210250. }
  210251. }
  210252. }
  210253. void* getNativeWindowHandle() const
  210254. {
  210255. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210256. }
  210257. HGLRC renderContext;
  210258. private:
  210259. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210260. Component* const component;
  210261. HDC dc;
  210262. void createNativeWindow()
  210263. {
  210264. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210265. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210266. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210267. nativeWindow->dontRepaint = true;
  210268. nativeWindow->setVisible (true);
  210269. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210270. }
  210271. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210272. OpenGLPixelFormat& result,
  210273. const StringArray& availableExtensions) const throw()
  210274. {
  210275. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210276. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210277. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210278. {
  210279. int attributes[32];
  210280. int numAttributes = 0;
  210281. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210282. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210283. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210284. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210285. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210286. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210287. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210288. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210289. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210290. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210291. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210292. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210293. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210294. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210295. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210296. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210297. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210298. int values[32];
  210299. zeromem (values, sizeof (values));
  210300. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210301. {
  210302. int n = 0;
  210303. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210304. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210305. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210306. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210307. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210308. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210309. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210310. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210311. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210312. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210313. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210314. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210315. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210316. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210317. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210318. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210319. return isValidFormat;
  210320. }
  210321. else
  210322. {
  210323. jassertfalse;
  210324. }
  210325. }
  210326. else
  210327. {
  210328. PIXELFORMATDESCRIPTOR pfd;
  210329. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210330. {
  210331. result.redBits = pfd.cRedBits;
  210332. result.greenBits = pfd.cGreenBits;
  210333. result.blueBits = pfd.cBlueBits;
  210334. result.alphaBits = pfd.cAlphaBits;
  210335. result.depthBufferBits = pfd.cDepthBits;
  210336. result.stencilBufferBits = pfd.cStencilBits;
  210337. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210338. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210339. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210340. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210341. result.fullSceneAntiAliasingNumSamples = 0;
  210342. return true;
  210343. }
  210344. else
  210345. {
  210346. jassertfalse;
  210347. }
  210348. }
  210349. return false;
  210350. }
  210351. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210352. };
  210353. OpenGLContext* OpenGLComponent::createContext()
  210354. {
  210355. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210356. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210357. preferredPixelFormat));
  210358. return (c->renderContext != 0) ? c.release() : 0;
  210359. }
  210360. void* OpenGLComponent::getNativeWindowHandle() const
  210361. {
  210362. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210363. }
  210364. void juce_glViewport (const int w, const int h)
  210365. {
  210366. glViewport (0, 0, w, h);
  210367. }
  210368. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210369. OwnedArray <OpenGLPixelFormat>& results)
  210370. {
  210371. Component tempComp;
  210372. {
  210373. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210374. wc.makeActive();
  210375. wc.findAlternativeOpenGLPixelFormats (results);
  210376. }
  210377. }
  210378. #endif
  210379. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210380. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210381. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210382. // compiled on its own).
  210383. #if JUCE_INCLUDED_FILE
  210384. #if JUCE_USE_CDREADER
  210385. namespace CDReaderHelpers
  210386. {
  210387. #define FILE_ANY_ACCESS 0
  210388. #ifndef FILE_READ_ACCESS
  210389. #define FILE_READ_ACCESS 1
  210390. #endif
  210391. #ifndef FILE_WRITE_ACCESS
  210392. #define FILE_WRITE_ACCESS 2
  210393. #endif
  210394. #define METHOD_BUFFERED 0
  210395. #define IOCTL_SCSI_BASE 4
  210396. #define SCSI_IOCTL_DATA_OUT 0
  210397. #define SCSI_IOCTL_DATA_IN 1
  210398. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210399. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210400. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210401. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210402. #define SENSE_LEN 14
  210403. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210404. #define SRB_DIR_IN 0x08
  210405. #define SRB_DIR_OUT 0x10
  210406. #define SRB_EVENT_NOTIFY 0x40
  210407. #define SC_HA_INQUIRY 0x00
  210408. #define SC_GET_DEV_TYPE 0x01
  210409. #define SC_EXEC_SCSI_CMD 0x02
  210410. #define SS_PENDING 0x00
  210411. #define SS_COMP 0x01
  210412. #define SS_ERR 0x04
  210413. enum
  210414. {
  210415. READTYPE_ANY = 0,
  210416. READTYPE_ATAPI1 = 1,
  210417. READTYPE_ATAPI2 = 2,
  210418. READTYPE_READ6 = 3,
  210419. READTYPE_READ10 = 4,
  210420. READTYPE_READ_D8 = 5,
  210421. READTYPE_READ_D4 = 6,
  210422. READTYPE_READ_D4_1 = 7,
  210423. READTYPE_READ10_2 = 8
  210424. };
  210425. struct SCSI_PASS_THROUGH
  210426. {
  210427. USHORT Length;
  210428. UCHAR ScsiStatus;
  210429. UCHAR PathId;
  210430. UCHAR TargetId;
  210431. UCHAR Lun;
  210432. UCHAR CdbLength;
  210433. UCHAR SenseInfoLength;
  210434. UCHAR DataIn;
  210435. ULONG DataTransferLength;
  210436. ULONG TimeOutValue;
  210437. ULONG DataBufferOffset;
  210438. ULONG SenseInfoOffset;
  210439. UCHAR Cdb[16];
  210440. };
  210441. struct SCSI_PASS_THROUGH_DIRECT
  210442. {
  210443. USHORT Length;
  210444. UCHAR ScsiStatus;
  210445. UCHAR PathId;
  210446. UCHAR TargetId;
  210447. UCHAR Lun;
  210448. UCHAR CdbLength;
  210449. UCHAR SenseInfoLength;
  210450. UCHAR DataIn;
  210451. ULONG DataTransferLength;
  210452. ULONG TimeOutValue;
  210453. PVOID DataBuffer;
  210454. ULONG SenseInfoOffset;
  210455. UCHAR Cdb[16];
  210456. };
  210457. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210458. {
  210459. SCSI_PASS_THROUGH_DIRECT spt;
  210460. ULONG Filler;
  210461. UCHAR ucSenseBuf[32];
  210462. };
  210463. struct SCSI_ADDRESS
  210464. {
  210465. ULONG Length;
  210466. UCHAR PortNumber;
  210467. UCHAR PathId;
  210468. UCHAR TargetId;
  210469. UCHAR Lun;
  210470. };
  210471. #pragma pack(1)
  210472. struct SRB_GDEVBlock
  210473. {
  210474. BYTE SRB_Cmd;
  210475. BYTE SRB_Status;
  210476. BYTE SRB_HaID;
  210477. BYTE SRB_Flags;
  210478. DWORD SRB_Hdr_Rsvd;
  210479. BYTE SRB_Target;
  210480. BYTE SRB_Lun;
  210481. BYTE SRB_DeviceType;
  210482. BYTE SRB_Rsvd1;
  210483. BYTE pad[68];
  210484. };
  210485. struct SRB_ExecSCSICmd
  210486. {
  210487. BYTE SRB_Cmd;
  210488. BYTE SRB_Status;
  210489. BYTE SRB_HaID;
  210490. BYTE SRB_Flags;
  210491. DWORD SRB_Hdr_Rsvd;
  210492. BYTE SRB_Target;
  210493. BYTE SRB_Lun;
  210494. WORD SRB_Rsvd1;
  210495. DWORD SRB_BufLen;
  210496. BYTE *SRB_BufPointer;
  210497. BYTE SRB_SenseLen;
  210498. BYTE SRB_CDBLen;
  210499. BYTE SRB_HaStat;
  210500. BYTE SRB_TargStat;
  210501. VOID *SRB_PostProc;
  210502. BYTE SRB_Rsvd2[20];
  210503. BYTE CDBByte[16];
  210504. BYTE SenseArea[SENSE_LEN + 2];
  210505. };
  210506. struct SRB
  210507. {
  210508. BYTE SRB_Cmd;
  210509. BYTE SRB_Status;
  210510. BYTE SRB_HaId;
  210511. BYTE SRB_Flags;
  210512. DWORD SRB_Hdr_Rsvd;
  210513. };
  210514. struct TOCTRACK
  210515. {
  210516. BYTE rsvd;
  210517. BYTE ADR;
  210518. BYTE trackNumber;
  210519. BYTE rsvd2;
  210520. BYTE addr[4];
  210521. };
  210522. struct TOC
  210523. {
  210524. WORD tocLen;
  210525. BYTE firstTrack;
  210526. BYTE lastTrack;
  210527. TOCTRACK tracks[100];
  210528. };
  210529. #pragma pack()
  210530. struct CDDeviceDescription
  210531. {
  210532. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210533. {
  210534. }
  210535. void createDescription (const char* data)
  210536. {
  210537. description << String (data + 8, 8).trim() // vendor
  210538. << ' ' << String (data + 16, 16).trim() // product id
  210539. << ' ' << String (data + 32, 4).trim(); // rev
  210540. }
  210541. String description;
  210542. BYTE ha, tgt, lun;
  210543. char scsiDriveLetter; // will be 0 if not using scsi
  210544. };
  210545. class CDReadBuffer
  210546. {
  210547. public:
  210548. CDReadBuffer (const int numberOfFrames)
  210549. : startFrame (0), numFrames (0), dataStartOffset (0),
  210550. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210551. buffer (bufferSize), wantsIndex (false)
  210552. {
  210553. }
  210554. bool isZero() const throw()
  210555. {
  210556. for (int i = 0; i < dataLength; ++i)
  210557. if (buffer [dataStartOffset + i] != 0)
  210558. return false;
  210559. return true;
  210560. }
  210561. int startFrame, numFrames, dataStartOffset;
  210562. int dataLength, bufferSize, index;
  210563. HeapBlock<BYTE> buffer;
  210564. bool wantsIndex;
  210565. };
  210566. class CDDeviceHandle;
  210567. class CDController
  210568. {
  210569. public:
  210570. CDController() : initialised (false) {}
  210571. virtual ~CDController() {}
  210572. virtual bool read (CDReadBuffer&) = 0;
  210573. virtual void shutDown() {}
  210574. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210575. int getLastIndex();
  210576. public:
  210577. CDDeviceHandle* deviceInfo;
  210578. int framesToCheck, framesOverlap;
  210579. bool initialised;
  210580. void prepare (SRB_ExecSCSICmd& s);
  210581. void perform (SRB_ExecSCSICmd& s);
  210582. void setPaused (bool paused);
  210583. };
  210584. class CDDeviceHandle
  210585. {
  210586. public:
  210587. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210588. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210589. {
  210590. }
  210591. ~CDDeviceHandle()
  210592. {
  210593. if (controller != 0)
  210594. {
  210595. controller->shutDown();
  210596. controller = 0;
  210597. }
  210598. if (scsiHandle != 0)
  210599. CloseHandle (scsiHandle);
  210600. }
  210601. bool readTOC (TOC* lpToc);
  210602. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210603. void openDrawer (bool shouldBeOpen);
  210604. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210605. CDDeviceDescription info;
  210606. HANDLE scsiHandle;
  210607. BYTE readType;
  210608. private:
  210609. ScopedPointer<CDController> controller;
  210610. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210611. };
  210612. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210613. {
  210614. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210615. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210616. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210617. if (h == INVALID_HANDLE_VALUE)
  210618. {
  210619. flags ^= GENERIC_WRITE;
  210620. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210621. }
  210622. return h;
  210623. }
  210624. void findCDDevices (Array<CDDeviceDescription>& list)
  210625. {
  210626. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210627. {
  210628. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210629. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210630. {
  210631. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210632. if (h != INVALID_HANDLE_VALUE)
  210633. {
  210634. char buffer[100];
  210635. zeromem (buffer, sizeof (buffer));
  210636. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210637. zerostruct (p);
  210638. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210639. p.spt.CdbLength = 6;
  210640. p.spt.SenseInfoLength = 24;
  210641. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210642. p.spt.DataTransferLength = sizeof (buffer);
  210643. p.spt.TimeOutValue = 2;
  210644. p.spt.DataBuffer = buffer;
  210645. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210646. p.spt.Cdb[0] = 0x12;
  210647. p.spt.Cdb[4] = 100;
  210648. DWORD bytesReturned = 0;
  210649. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210650. &p, sizeof (p), &p, sizeof (p),
  210651. &bytesReturned, 0) != 0)
  210652. {
  210653. CDDeviceDescription dev;
  210654. dev.scsiDriveLetter = driveLetter;
  210655. dev.createDescription (buffer);
  210656. SCSI_ADDRESS scsiAddr;
  210657. zerostruct (scsiAddr);
  210658. scsiAddr.Length = sizeof (scsiAddr);
  210659. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210660. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210661. &bytesReturned, 0) != 0)
  210662. {
  210663. dev.ha = scsiAddr.PortNumber;
  210664. dev.tgt = scsiAddr.TargetId;
  210665. dev.lun = scsiAddr.Lun;
  210666. list.add (dev);
  210667. }
  210668. }
  210669. CloseHandle (h);
  210670. }
  210671. }
  210672. }
  210673. }
  210674. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210675. HANDLE& deviceHandle, const bool retryOnFailure)
  210676. {
  210677. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210678. zerostruct (s);
  210679. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210680. s.spt.CdbLength = srb->SRB_CDBLen;
  210681. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210682. ? SCSI_IOCTL_DATA_IN
  210683. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210684. ? SCSI_IOCTL_DATA_OUT
  210685. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210686. s.spt.DataTransferLength = srb->SRB_BufLen;
  210687. s.spt.TimeOutValue = 5;
  210688. s.spt.DataBuffer = srb->SRB_BufPointer;
  210689. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210690. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210691. srb->SRB_Status = SS_ERR;
  210692. srb->SRB_TargStat = 0x0004;
  210693. DWORD bytesReturned = 0;
  210694. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210695. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210696. {
  210697. srb->SRB_Status = SS_COMP;
  210698. }
  210699. else if (retryOnFailure)
  210700. {
  210701. const DWORD error = GetLastError();
  210702. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210703. {
  210704. if (error != ERROR_INVALID_HANDLE)
  210705. CloseHandle (deviceHandle);
  210706. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210707. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210708. }
  210709. }
  210710. return srb->SRB_Status;
  210711. }
  210712. // Controller types..
  210713. class ControllerType1 : public CDController
  210714. {
  210715. public:
  210716. ControllerType1() {}
  210717. bool read (CDReadBuffer& rb)
  210718. {
  210719. if (rb.numFrames * 2352 > rb.bufferSize)
  210720. return false;
  210721. SRB_ExecSCSICmd s;
  210722. prepare (s);
  210723. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210724. s.SRB_BufLen = rb.bufferSize;
  210725. s.SRB_BufPointer = rb.buffer;
  210726. s.SRB_CDBLen = 12;
  210727. s.CDBByte[0] = 0xBE;
  210728. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210729. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210730. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210731. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210732. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  210733. perform (s);
  210734. if (s.SRB_Status != SS_COMP)
  210735. return false;
  210736. rb.dataLength = rb.numFrames * 2352;
  210737. rb.dataStartOffset = 0;
  210738. return true;
  210739. }
  210740. };
  210741. class ControllerType2 : public CDController
  210742. {
  210743. public:
  210744. ControllerType2() {}
  210745. void shutDown()
  210746. {
  210747. if (initialised)
  210748. {
  210749. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210750. SRB_ExecSCSICmd s;
  210751. prepare (s);
  210752. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210753. s.SRB_BufLen = 0x0C;
  210754. s.SRB_BufPointer = bufPointer;
  210755. s.SRB_CDBLen = 6;
  210756. s.CDBByte[0] = 0x15;
  210757. s.CDBByte[4] = 0x0C;
  210758. perform (s);
  210759. }
  210760. }
  210761. bool init()
  210762. {
  210763. SRB_ExecSCSICmd s;
  210764. s.SRB_Status = SS_ERR;
  210765. if (deviceInfo->readType == READTYPE_READ10_2)
  210766. {
  210767. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210768. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210769. for (int i = 0; i < 2; ++i)
  210770. {
  210771. prepare (s);
  210772. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210773. s.SRB_BufLen = 0x14;
  210774. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  210775. s.SRB_CDBLen = 6;
  210776. s.CDBByte[0] = 0x15;
  210777. s.CDBByte[1] = 0x10;
  210778. s.CDBByte[4] = 0x14;
  210779. perform (s);
  210780. if (s.SRB_Status != SS_COMP)
  210781. return false;
  210782. }
  210783. }
  210784. else
  210785. {
  210786. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  210787. prepare (s);
  210788. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210789. s.SRB_BufLen = 0x0C;
  210790. s.SRB_BufPointer = bufPointer;
  210791. s.SRB_CDBLen = 6;
  210792. s.CDBByte[0] = 0x15;
  210793. s.CDBByte[4] = 0x0C;
  210794. perform (s);
  210795. }
  210796. return s.SRB_Status == SS_COMP;
  210797. }
  210798. bool read (CDReadBuffer& rb)
  210799. {
  210800. if (rb.numFrames * 2352 > rb.bufferSize)
  210801. return false;
  210802. if (! initialised)
  210803. {
  210804. initialised = init();
  210805. if (! initialised)
  210806. return false;
  210807. }
  210808. SRB_ExecSCSICmd s;
  210809. prepare (s);
  210810. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210811. s.SRB_BufLen = rb.bufferSize;
  210812. s.SRB_BufPointer = rb.buffer;
  210813. s.SRB_CDBLen = 10;
  210814. s.CDBByte[0] = 0x28;
  210815. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210816. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210817. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210818. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210819. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210820. perform (s);
  210821. if (s.SRB_Status != SS_COMP)
  210822. return false;
  210823. rb.dataLength = rb.numFrames * 2352;
  210824. rb.dataStartOffset = 0;
  210825. return true;
  210826. }
  210827. };
  210828. class ControllerType3 : public CDController
  210829. {
  210830. public:
  210831. ControllerType3() {}
  210832. bool read (CDReadBuffer& rb)
  210833. {
  210834. if (rb.numFrames * 2352 > rb.bufferSize)
  210835. return false;
  210836. if (! initialised)
  210837. {
  210838. setPaused (false);
  210839. initialised = true;
  210840. }
  210841. SRB_ExecSCSICmd s;
  210842. prepare (s);
  210843. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210844. s.SRB_BufLen = rb.numFrames * 2352;
  210845. s.SRB_BufPointer = rb.buffer;
  210846. s.SRB_CDBLen = 12;
  210847. s.CDBByte[0] = 0xD8;
  210848. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210849. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210850. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210851. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  210852. perform (s);
  210853. if (s.SRB_Status != SS_COMP)
  210854. return false;
  210855. rb.dataLength = rb.numFrames * 2352;
  210856. rb.dataStartOffset = 0;
  210857. return true;
  210858. }
  210859. };
  210860. class ControllerType4 : public CDController
  210861. {
  210862. public:
  210863. ControllerType4() {}
  210864. bool selectD4Mode()
  210865. {
  210866. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  210867. SRB_ExecSCSICmd s;
  210868. prepare (s);
  210869. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210870. s.SRB_CDBLen = 6;
  210871. s.SRB_BufLen = 12;
  210872. s.SRB_BufPointer = bufPointer;
  210873. s.CDBByte[0] = 0x15;
  210874. s.CDBByte[1] = 0x10;
  210875. s.CDBByte[4] = 0x08;
  210876. perform (s);
  210877. return s.SRB_Status == SS_COMP;
  210878. }
  210879. bool read (CDReadBuffer& rb)
  210880. {
  210881. if (rb.numFrames * 2352 > rb.bufferSize)
  210882. return false;
  210883. if (! initialised)
  210884. {
  210885. setPaused (true);
  210886. if (deviceInfo->readType == READTYPE_READ_D4_1)
  210887. selectD4Mode();
  210888. initialised = true;
  210889. }
  210890. SRB_ExecSCSICmd s;
  210891. prepare (s);
  210892. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210893. s.SRB_BufLen = rb.bufferSize;
  210894. s.SRB_BufPointer = rb.buffer;
  210895. s.SRB_CDBLen = 10;
  210896. s.CDBByte[0] = 0xD4;
  210897. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210898. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210899. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210900. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210901. perform (s);
  210902. if (s.SRB_Status != SS_COMP)
  210903. return false;
  210904. rb.dataLength = rb.numFrames * 2352;
  210905. rb.dataStartOffset = 0;
  210906. return true;
  210907. }
  210908. };
  210909. void CDController::prepare (SRB_ExecSCSICmd& s)
  210910. {
  210911. zerostruct (s);
  210912. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210913. s.SRB_HaID = deviceInfo->info.ha;
  210914. s.SRB_Target = deviceInfo->info.tgt;
  210915. s.SRB_Lun = deviceInfo->info.lun;
  210916. s.SRB_SenseLen = SENSE_LEN;
  210917. }
  210918. void CDController::perform (SRB_ExecSCSICmd& s)
  210919. {
  210920. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210921. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  210922. }
  210923. void CDController::setPaused (bool paused)
  210924. {
  210925. SRB_ExecSCSICmd s;
  210926. prepare (s);
  210927. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210928. s.SRB_CDBLen = 10;
  210929. s.CDBByte[0] = 0x4B;
  210930. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  210931. perform (s);
  210932. }
  210933. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  210934. {
  210935. if (overlapBuffer != 0)
  210936. {
  210937. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  210938. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  210939. if (doJitter
  210940. && overlapBuffer->startFrame > 0
  210941. && overlapBuffer->numFrames > 0
  210942. && overlapBuffer->dataLength > 0)
  210943. {
  210944. const int numFrames = rb.numFrames;
  210945. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  210946. {
  210947. rb.startFrame -= framesOverlap;
  210948. if (framesToCheck < framesOverlap
  210949. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  210950. rb.numFrames += framesOverlap;
  210951. }
  210952. else
  210953. {
  210954. overlapBuffer->dataLength = 0;
  210955. overlapBuffer->startFrame = 0;
  210956. overlapBuffer->numFrames = 0;
  210957. }
  210958. }
  210959. if (! read (rb))
  210960. return false;
  210961. if (doJitter)
  210962. {
  210963. const int checkLen = framesToCheck * 2352;
  210964. const int maxToCheck = rb.dataLength - checkLen;
  210965. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  210966. return true;
  210967. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  210968. bool found = false;
  210969. for (int i = 0; i < maxToCheck; ++i)
  210970. {
  210971. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  210972. {
  210973. i += checkLen;
  210974. rb.dataStartOffset = i;
  210975. rb.dataLength -= i;
  210976. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  210977. found = true;
  210978. break;
  210979. }
  210980. }
  210981. rb.numFrames = rb.dataLength / 2352;
  210982. rb.dataLength = 2352 * rb.numFrames;
  210983. if (! found)
  210984. return false;
  210985. }
  210986. if (canDoJitter)
  210987. {
  210988. memcpy (overlapBuffer->buffer,
  210989. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  210990. 2352 * framesToCheck);
  210991. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  210992. overlapBuffer->numFrames = framesToCheck;
  210993. overlapBuffer->dataLength = 2352 * framesToCheck;
  210994. overlapBuffer->dataStartOffset = 0;
  210995. }
  210996. else
  210997. {
  210998. overlapBuffer->startFrame = 0;
  210999. overlapBuffer->numFrames = 0;
  211000. overlapBuffer->dataLength = 0;
  211001. }
  211002. return true;
  211003. }
  211004. return read (rb);
  211005. }
  211006. int CDController::getLastIndex()
  211007. {
  211008. char qdata[100];
  211009. SRB_ExecSCSICmd s;
  211010. prepare (s);
  211011. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211012. s.SRB_BufLen = sizeof (qdata);
  211013. s.SRB_BufPointer = (BYTE*) qdata;
  211014. s.SRB_CDBLen = 12;
  211015. s.CDBByte[0] = 0x42;
  211016. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211017. s.CDBByte[2] = 64;
  211018. s.CDBByte[3] = 1; // get current position
  211019. s.CDBByte[7] = 0;
  211020. s.CDBByte[8] = (BYTE) sizeof (qdata);
  211021. perform (s);
  211022. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  211023. }
  211024. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211025. {
  211026. SRB_ExecSCSICmd s;
  211027. zerostruct (s);
  211028. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211029. s.SRB_HaID = info.ha;
  211030. s.SRB_Target = info.tgt;
  211031. s.SRB_Lun = info.lun;
  211032. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211033. s.SRB_BufLen = 0x324;
  211034. s.SRB_BufPointer = (BYTE*) lpToc;
  211035. s.SRB_SenseLen = 0x0E;
  211036. s.SRB_CDBLen = 0x0A;
  211037. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211038. s.CDBByte[0] = 0x43;
  211039. s.CDBByte[1] = 0x00;
  211040. s.CDBByte[7] = 0x03;
  211041. s.CDBByte[8] = 0x24;
  211042. performScsiCommand (s.SRB_PostProc, s);
  211043. return (s.SRB_Status == SS_COMP);
  211044. }
  211045. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  211046. {
  211047. ResetEvent (event);
  211048. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  211049. if (status == SS_PENDING)
  211050. WaitForSingleObject (event, 4000);
  211051. CloseHandle (event);
  211052. }
  211053. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  211054. {
  211055. if (controller == 0)
  211056. {
  211057. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211058. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211059. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211060. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211061. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211062. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211063. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211064. }
  211065. buffer.index = 0;
  211066. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  211067. {
  211068. if (buffer.wantsIndex)
  211069. buffer.index = controller->getLastIndex();
  211070. return true;
  211071. }
  211072. return false;
  211073. }
  211074. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211075. {
  211076. if (shouldBeOpen)
  211077. {
  211078. if (controller != 0)
  211079. {
  211080. controller->shutDown();
  211081. controller = 0;
  211082. }
  211083. if (scsiHandle != 0)
  211084. {
  211085. CloseHandle (scsiHandle);
  211086. scsiHandle = 0;
  211087. }
  211088. }
  211089. SRB_ExecSCSICmd s;
  211090. zerostruct (s);
  211091. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211092. s.SRB_HaID = info.ha;
  211093. s.SRB_Target = info.tgt;
  211094. s.SRB_Lun = info.lun;
  211095. s.SRB_SenseLen = SENSE_LEN;
  211096. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211097. s.SRB_BufLen = 0;
  211098. s.SRB_BufPointer = 0;
  211099. s.SRB_CDBLen = 12;
  211100. s.CDBByte[0] = 0x1b;
  211101. s.CDBByte[1] = (BYTE) (info.lun << 5);
  211102. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  211103. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211104. performScsiCommand (s.SRB_PostProc, s);
  211105. }
  211106. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  211107. {
  211108. controller = newController;
  211109. readType = (BYTE) type;
  211110. controller->deviceInfo = this;
  211111. controller->framesToCheck = 1;
  211112. controller->framesOverlap = 3;
  211113. bool passed = false;
  211114. memset (rb.buffer, 0xcd, rb.bufferSize);
  211115. if (controller->read (rb))
  211116. {
  211117. passed = true;
  211118. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  211119. int wrong = 0;
  211120. for (int i = rb.dataLength / 4; --i >= 0;)
  211121. {
  211122. if (*p++ == (int) 0xcdcdcdcd)
  211123. {
  211124. if (++wrong == 4)
  211125. {
  211126. passed = false;
  211127. break;
  211128. }
  211129. }
  211130. else
  211131. {
  211132. wrong = 0;
  211133. }
  211134. }
  211135. }
  211136. if (! passed)
  211137. {
  211138. controller->shutDown();
  211139. controller = 0;
  211140. }
  211141. return passed;
  211142. }
  211143. struct CDDeviceWrapper
  211144. {
  211145. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  211146. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  211147. {
  211148. // xxx jitter never seemed to actually be enabled (??)
  211149. }
  211150. CDDeviceHandle deviceHandle;
  211151. CDReadBuffer overlapBuffer;
  211152. bool jitter;
  211153. };
  211154. int getAddressOfTrack (const TOCTRACK& t) throw()
  211155. {
  211156. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  211157. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  211158. }
  211159. const int samplesPerFrame = 44100 / 75;
  211160. const int bytesPerFrame = samplesPerFrame * 4;
  211161. const int framesPerIndexRead = 4;
  211162. }
  211163. const StringArray AudioCDReader::getAvailableCDNames()
  211164. {
  211165. using namespace CDReaderHelpers;
  211166. StringArray results;
  211167. Array<CDDeviceDescription> list;
  211168. findCDDevices (list);
  211169. for (int i = 0; i < list.size(); ++i)
  211170. {
  211171. String s;
  211172. if (list[i].scsiDriveLetter > 0)
  211173. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211174. s << list[i].description;
  211175. results.add (s);
  211176. }
  211177. return results;
  211178. }
  211179. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211180. {
  211181. using namespace CDReaderHelpers;
  211182. Array<CDDeviceDescription> list;
  211183. findCDDevices (list);
  211184. if (isPositiveAndBelow (deviceIndex, list.size()))
  211185. {
  211186. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  211187. if (h != INVALID_HANDLE_VALUE)
  211188. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  211189. }
  211190. return 0;
  211191. }
  211192. AudioCDReader::AudioCDReader (void* handle_)
  211193. : AudioFormatReader (0, "CD Audio"),
  211194. handle (handle_),
  211195. indexingEnabled (false),
  211196. lastIndex (0),
  211197. firstFrameInBuffer (0),
  211198. samplesInBuffer (0)
  211199. {
  211200. using namespace CDReaderHelpers;
  211201. jassert (handle_ != 0);
  211202. refreshTrackLengths();
  211203. sampleRate = 44100.0;
  211204. bitsPerSample = 16;
  211205. numChannels = 2;
  211206. usesFloatingPointData = false;
  211207. buffer.setSize (4 * bytesPerFrame, true);
  211208. }
  211209. AudioCDReader::~AudioCDReader()
  211210. {
  211211. using namespace CDReaderHelpers;
  211212. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211213. delete device;
  211214. }
  211215. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211216. int64 startSampleInFile, int numSamples)
  211217. {
  211218. using namespace CDReaderHelpers;
  211219. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211220. bool ok = true;
  211221. while (numSamples > 0)
  211222. {
  211223. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211224. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211225. if (startSampleInFile >= bufferStartSample
  211226. && startSampleInFile < bufferEndSample)
  211227. {
  211228. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211229. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211230. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211231. const short* src = (const short*) buffer.getData();
  211232. src += 2 * (startSampleInFile - bufferStartSample);
  211233. for (int i = 0; i < toDo; ++i)
  211234. {
  211235. l[i] = src [i << 1] << 16;
  211236. if (r != 0)
  211237. r[i] = src [(i << 1) + 1] << 16;
  211238. }
  211239. startOffsetInDestBuffer += toDo;
  211240. startSampleInFile += toDo;
  211241. numSamples -= toDo;
  211242. }
  211243. else
  211244. {
  211245. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211246. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211247. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211248. {
  211249. device->overlapBuffer.dataLength = 0;
  211250. device->overlapBuffer.startFrame = 0;
  211251. device->overlapBuffer.numFrames = 0;
  211252. device->jitter = false;
  211253. }
  211254. firstFrameInBuffer = frameNeeded;
  211255. lastIndex = 0;
  211256. CDReadBuffer readBuffer (framesInBuffer + 4);
  211257. readBuffer.wantsIndex = indexingEnabled;
  211258. int i;
  211259. for (i = 5; --i >= 0;)
  211260. {
  211261. readBuffer.startFrame = frameNeeded;
  211262. readBuffer.numFrames = framesInBuffer;
  211263. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211264. break;
  211265. else
  211266. device->overlapBuffer.dataLength = 0;
  211267. }
  211268. if (i >= 0)
  211269. {
  211270. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211271. samplesInBuffer = readBuffer.dataLength >> 2;
  211272. lastIndex = readBuffer.index;
  211273. }
  211274. else
  211275. {
  211276. int* l = destSamples[0] + startOffsetInDestBuffer;
  211277. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211278. while (--numSamples >= 0)
  211279. {
  211280. *l++ = 0;
  211281. if (r != 0)
  211282. *r++ = 0;
  211283. }
  211284. // sometimes the read fails for just the very last couple of blocks, so
  211285. // we'll ignore and errors in the last half-second of the disk..
  211286. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211287. break;
  211288. }
  211289. }
  211290. }
  211291. return ok;
  211292. }
  211293. bool AudioCDReader::isCDStillPresent() const
  211294. {
  211295. using namespace CDReaderHelpers;
  211296. TOC toc;
  211297. zerostruct (toc);
  211298. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211299. }
  211300. void AudioCDReader::refreshTrackLengths()
  211301. {
  211302. using namespace CDReaderHelpers;
  211303. trackStartSamples.clear();
  211304. zeromem (audioTracks, sizeof (audioTracks));
  211305. TOC toc;
  211306. zerostruct (toc);
  211307. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211308. {
  211309. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211310. for (int i = 0; i <= numTracks; ++i)
  211311. {
  211312. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211313. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211314. }
  211315. }
  211316. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211317. }
  211318. bool AudioCDReader::isTrackAudio (int trackNum) const
  211319. {
  211320. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211321. }
  211322. void AudioCDReader::enableIndexScanning (bool b)
  211323. {
  211324. indexingEnabled = b;
  211325. }
  211326. int AudioCDReader::getLastIndex() const
  211327. {
  211328. return lastIndex;
  211329. }
  211330. int AudioCDReader::getIndexAt (int samplePos)
  211331. {
  211332. using namespace CDReaderHelpers;
  211333. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211334. const int frameNeeded = samplePos / samplesPerFrame;
  211335. device->overlapBuffer.dataLength = 0;
  211336. device->overlapBuffer.startFrame = 0;
  211337. device->overlapBuffer.numFrames = 0;
  211338. device->jitter = false;
  211339. firstFrameInBuffer = 0;
  211340. lastIndex = 0;
  211341. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211342. readBuffer.wantsIndex = true;
  211343. int i;
  211344. for (i = 5; --i >= 0;)
  211345. {
  211346. readBuffer.startFrame = frameNeeded;
  211347. readBuffer.numFrames = framesPerIndexRead;
  211348. if (device->deviceHandle.readAudio (readBuffer))
  211349. break;
  211350. }
  211351. if (i >= 0)
  211352. return readBuffer.index;
  211353. return -1;
  211354. }
  211355. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211356. {
  211357. using namespace CDReaderHelpers;
  211358. Array <int> indexes;
  211359. const int trackStart = getPositionOfTrackStart (trackNumber);
  211360. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211361. bool needToScan = true;
  211362. if (trackEnd - trackStart > 20 * 44100)
  211363. {
  211364. // check the end of the track for indexes before scanning the whole thing
  211365. needToScan = false;
  211366. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211367. bool seenAnIndex = false;
  211368. while (pos <= trackEnd - samplesPerFrame)
  211369. {
  211370. const int index = getIndexAt (pos);
  211371. if (index == 0)
  211372. {
  211373. // lead-out, so skip back a bit if we've not found any indexes yet..
  211374. if (seenAnIndex)
  211375. break;
  211376. pos -= 44100 * 5;
  211377. if (pos < trackStart)
  211378. break;
  211379. }
  211380. else
  211381. {
  211382. if (index > 0)
  211383. seenAnIndex = true;
  211384. if (index > 1)
  211385. {
  211386. needToScan = true;
  211387. break;
  211388. }
  211389. pos += samplesPerFrame * framesPerIndexRead;
  211390. }
  211391. }
  211392. }
  211393. if (needToScan)
  211394. {
  211395. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211396. int pos = trackStart;
  211397. int last = -1;
  211398. while (pos < trackEnd - samplesPerFrame * 10)
  211399. {
  211400. const int frameNeeded = pos / samplesPerFrame;
  211401. device->overlapBuffer.dataLength = 0;
  211402. device->overlapBuffer.startFrame = 0;
  211403. device->overlapBuffer.numFrames = 0;
  211404. device->jitter = false;
  211405. firstFrameInBuffer = 0;
  211406. CDReadBuffer readBuffer (4);
  211407. readBuffer.wantsIndex = true;
  211408. int i;
  211409. for (i = 5; --i >= 0;)
  211410. {
  211411. readBuffer.startFrame = frameNeeded;
  211412. readBuffer.numFrames = framesPerIndexRead;
  211413. if (device->deviceHandle.readAudio (readBuffer))
  211414. break;
  211415. }
  211416. if (i < 0)
  211417. break;
  211418. if (readBuffer.index > last && readBuffer.index > 1)
  211419. {
  211420. last = readBuffer.index;
  211421. indexes.add (pos);
  211422. }
  211423. pos += samplesPerFrame * framesPerIndexRead;
  211424. }
  211425. indexes.removeValue (trackStart);
  211426. }
  211427. return indexes;
  211428. }
  211429. void AudioCDReader::ejectDisk()
  211430. {
  211431. using namespace CDReaderHelpers;
  211432. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211433. }
  211434. #endif
  211435. #if JUCE_USE_CDBURNER
  211436. namespace CDBurnerHelpers
  211437. {
  211438. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211439. {
  211440. CoInitialize (0);
  211441. IDiscMaster* dm;
  211442. IDiscRecorder* result = 0;
  211443. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211444. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211445. IID_IDiscMaster,
  211446. (void**) &dm)))
  211447. {
  211448. if (SUCCEEDED (dm->Open()))
  211449. {
  211450. IEnumDiscRecorders* drEnum = 0;
  211451. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211452. {
  211453. IDiscRecorder* dr = 0;
  211454. DWORD dummy;
  211455. int index = 0;
  211456. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211457. {
  211458. if (indexToOpen == index)
  211459. {
  211460. result = dr;
  211461. break;
  211462. }
  211463. else if (list != 0)
  211464. {
  211465. BSTR path;
  211466. if (SUCCEEDED (dr->GetPath (&path)))
  211467. list->add ((const WCHAR*) path);
  211468. }
  211469. ++index;
  211470. dr->Release();
  211471. }
  211472. drEnum->Release();
  211473. }
  211474. if (master == 0)
  211475. dm->Close();
  211476. }
  211477. if (master != 0)
  211478. *master = dm;
  211479. else
  211480. dm->Release();
  211481. }
  211482. return result;
  211483. }
  211484. }
  211485. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211486. public Timer
  211487. {
  211488. public:
  211489. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211490. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211491. listener (0), progress (0), shouldCancel (false)
  211492. {
  211493. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211494. jassert (SUCCEEDED (hr));
  211495. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211496. //jassert (SUCCEEDED (hr));
  211497. lastState = getDiskState();
  211498. startTimer (2000);
  211499. }
  211500. ~Pimpl() {}
  211501. void releaseObjects()
  211502. {
  211503. discRecorder->Close();
  211504. if (redbook != 0)
  211505. redbook->Release();
  211506. discRecorder->Release();
  211507. discMaster->Release();
  211508. Release();
  211509. }
  211510. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211511. {
  211512. if (listener != 0 && ! shouldCancel)
  211513. shouldCancel = listener->audioCDBurnProgress (progress);
  211514. *pbCancel = shouldCancel;
  211515. return S_OK;
  211516. }
  211517. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211518. {
  211519. progress = nCompleted / (float) nTotal;
  211520. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211521. return E_NOTIMPL;
  211522. }
  211523. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211524. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211525. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211526. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211527. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211528. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211529. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211530. class ScopedDiscOpener
  211531. {
  211532. public:
  211533. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211534. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211535. private:
  211536. Pimpl& pimpl;
  211537. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211538. };
  211539. DiskState getDiskState()
  211540. {
  211541. const ScopedDiscOpener opener (*this);
  211542. long type, flags;
  211543. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211544. if (FAILED (hr))
  211545. return unknown;
  211546. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211547. return writableDiskPresent;
  211548. if (type == 0)
  211549. return noDisc;
  211550. else
  211551. return readOnlyDiskPresent;
  211552. }
  211553. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211554. {
  211555. ComSmartPtr<IPropertyStorage> prop;
  211556. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211557. return defaultReturn;
  211558. PROPSPEC iPropSpec;
  211559. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211560. iPropSpec.lpwstr = name;
  211561. PROPVARIANT iPropVariant;
  211562. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211563. ? defaultReturn : (int) iPropVariant.lVal;
  211564. }
  211565. bool setIntProperty (const LPOLESTR name, const int value) const
  211566. {
  211567. ComSmartPtr<IPropertyStorage> prop;
  211568. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211569. return false;
  211570. PROPSPEC iPropSpec;
  211571. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211572. iPropSpec.lpwstr = name;
  211573. PROPVARIANT iPropVariant;
  211574. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211575. return false;
  211576. iPropVariant.lVal = (long) value;
  211577. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211578. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211579. }
  211580. void timerCallback()
  211581. {
  211582. const DiskState state = getDiskState();
  211583. if (state != lastState)
  211584. {
  211585. lastState = state;
  211586. owner.sendChangeMessage();
  211587. }
  211588. }
  211589. AudioCDBurner& owner;
  211590. DiskState lastState;
  211591. IDiscMaster* discMaster;
  211592. IDiscRecorder* discRecorder;
  211593. IRedbookDiscMaster* redbook;
  211594. AudioCDBurner::BurnProgressListener* listener;
  211595. float progress;
  211596. bool shouldCancel;
  211597. };
  211598. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211599. {
  211600. IDiscMaster* discMaster = 0;
  211601. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211602. if (discRecorder != 0)
  211603. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211604. }
  211605. AudioCDBurner::~AudioCDBurner()
  211606. {
  211607. if (pimpl != 0)
  211608. pimpl.release()->releaseObjects();
  211609. }
  211610. const StringArray AudioCDBurner::findAvailableDevices()
  211611. {
  211612. StringArray devs;
  211613. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211614. return devs;
  211615. }
  211616. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211617. {
  211618. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211619. if (b->pimpl == 0)
  211620. b = 0;
  211621. return b.release();
  211622. }
  211623. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211624. {
  211625. return pimpl->getDiskState();
  211626. }
  211627. bool AudioCDBurner::isDiskPresent() const
  211628. {
  211629. return getDiskState() == writableDiskPresent;
  211630. }
  211631. bool AudioCDBurner::openTray()
  211632. {
  211633. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211634. return SUCCEEDED (pimpl->discRecorder->Eject());
  211635. }
  211636. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211637. {
  211638. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211639. DiskState oldState = getDiskState();
  211640. DiskState newState = oldState;
  211641. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211642. {
  211643. newState = getDiskState();
  211644. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211645. }
  211646. return newState;
  211647. }
  211648. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211649. {
  211650. Array<int> results;
  211651. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211652. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211653. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211654. if (speeds[i] <= maxSpeed)
  211655. results.add (speeds[i]);
  211656. results.addIfNotAlreadyThere (maxSpeed);
  211657. return results;
  211658. }
  211659. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211660. {
  211661. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211662. return false;
  211663. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211664. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211665. }
  211666. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211667. {
  211668. long blocksFree = 0;
  211669. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211670. return blocksFree;
  211671. }
  211672. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211673. bool performFakeBurnForTesting, int writeSpeed)
  211674. {
  211675. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211676. pimpl->listener = listener;
  211677. pimpl->progress = 0;
  211678. pimpl->shouldCancel = false;
  211679. UINT_PTR cookie;
  211680. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211681. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211682. ejectDiscAfterwards);
  211683. String error;
  211684. if (hr != S_OK)
  211685. {
  211686. const char* e = "Couldn't open or write to the CD device";
  211687. if (hr == IMAPI_E_USERABORT)
  211688. e = "User cancelled the write operation";
  211689. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211690. e = "No Disk present";
  211691. error = e;
  211692. }
  211693. pimpl->discMaster->ProgressUnadvise (cookie);
  211694. pimpl->listener = 0;
  211695. return error;
  211696. }
  211697. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211698. {
  211699. if (audioSource == 0)
  211700. return false;
  211701. ScopedPointer<AudioSource> source (audioSource);
  211702. long bytesPerBlock;
  211703. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211704. const int samplesPerBlock = bytesPerBlock / 4;
  211705. bool ok = true;
  211706. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211707. HeapBlock <byte> buffer (bytesPerBlock);
  211708. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211709. int samplesDone = 0;
  211710. source->prepareToPlay (samplesPerBlock, 44100.0);
  211711. while (ok)
  211712. {
  211713. {
  211714. AudioSourceChannelInfo info;
  211715. info.buffer = &sourceBuffer;
  211716. info.numSamples = samplesPerBlock;
  211717. info.startSample = 0;
  211718. sourceBuffer.clear();
  211719. source->getNextAudioBlock (info);
  211720. }
  211721. zeromem (buffer, bytesPerBlock);
  211722. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  211723. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  211724. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  211725. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  211726. CDSampleFormat left (buffer, 2);
  211727. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  211728. CDSampleFormat right (buffer + 2, 2);
  211729. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  211730. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  211731. if (FAILED (hr))
  211732. ok = false;
  211733. samplesDone += samplesPerBlock;
  211734. if (samplesDone >= numSamples)
  211735. break;
  211736. }
  211737. hr = pimpl->redbook->CloseAudioTrack();
  211738. return ok && hr == S_OK;
  211739. }
  211740. #endif
  211741. #endif
  211742. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  211743. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  211744. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211745. // compiled on its own).
  211746. #if JUCE_INCLUDED_FILE
  211747. class MidiInCollector
  211748. {
  211749. public:
  211750. MidiInCollector (MidiInput* const input_,
  211751. MidiInputCallback& callback_)
  211752. : deviceHandle (0),
  211753. input (input_),
  211754. callback (callback_),
  211755. concatenator (4096),
  211756. isStarted (false),
  211757. startTime (0)
  211758. {
  211759. }
  211760. ~MidiInCollector()
  211761. {
  211762. stop();
  211763. if (deviceHandle != 0)
  211764. {
  211765. int count = 5;
  211766. while (--count >= 0)
  211767. {
  211768. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  211769. break;
  211770. Sleep (20);
  211771. }
  211772. }
  211773. }
  211774. void handleMessage (const uint32 message, const uint32 timeStamp)
  211775. {
  211776. if ((message & 0xff) >= 0x80 && isStarted)
  211777. {
  211778. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  211779. writeFinishedBlocks();
  211780. }
  211781. }
  211782. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  211783. {
  211784. if (isStarted)
  211785. {
  211786. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  211787. writeFinishedBlocks();
  211788. }
  211789. }
  211790. void start()
  211791. {
  211792. jassert (deviceHandle != 0);
  211793. if (deviceHandle != 0 && ! isStarted)
  211794. {
  211795. activeMidiCollectors.addIfNotAlreadyThere (this);
  211796. for (int i = 0; i < (int) numHeaders; ++i)
  211797. headers[i].write (deviceHandle);
  211798. startTime = Time::getMillisecondCounter();
  211799. MMRESULT res = midiInStart (deviceHandle);
  211800. if (res == MMSYSERR_NOERROR)
  211801. {
  211802. concatenator.reset();
  211803. isStarted = true;
  211804. }
  211805. else
  211806. {
  211807. unprepareAllHeaders();
  211808. }
  211809. }
  211810. }
  211811. void stop()
  211812. {
  211813. if (isStarted)
  211814. {
  211815. isStarted = false;
  211816. midiInReset (deviceHandle);
  211817. midiInStop (deviceHandle);
  211818. activeMidiCollectors.removeValue (this);
  211819. unprepareAllHeaders();
  211820. concatenator.reset();
  211821. }
  211822. }
  211823. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211824. {
  211825. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  211826. if (activeMidiCollectors.contains (collector))
  211827. {
  211828. if (uMsg == MIM_DATA)
  211829. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  211830. else if (uMsg == MIM_LONGDATA)
  211831. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211832. }
  211833. }
  211834. HMIDIIN deviceHandle;
  211835. private:
  211836. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  211837. MidiInput* input;
  211838. MidiInputCallback& callback;
  211839. MidiDataConcatenator concatenator;
  211840. bool volatile isStarted;
  211841. uint32 startTime;
  211842. class MidiHeader
  211843. {
  211844. public:
  211845. MidiHeader()
  211846. {
  211847. zerostruct (hdr);
  211848. hdr.lpData = data;
  211849. hdr.dwBufferLength = numElementsInArray (data);
  211850. }
  211851. void write (HMIDIIN deviceHandle)
  211852. {
  211853. hdr.dwBytesRecorded = 0;
  211854. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211855. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  211856. }
  211857. void writeIfFinished (HMIDIIN deviceHandle)
  211858. {
  211859. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211860. {
  211861. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211862. (void) res;
  211863. write (deviceHandle);
  211864. }
  211865. }
  211866. void unprepare (HMIDIIN deviceHandle)
  211867. {
  211868. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211869. {
  211870. int c = 10;
  211871. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  211872. Thread::sleep (20);
  211873. jassert (c >= 0);
  211874. }
  211875. }
  211876. private:
  211877. MIDIHDR hdr;
  211878. char data [256];
  211879. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  211880. };
  211881. enum { numHeaders = 32 };
  211882. MidiHeader headers [numHeaders];
  211883. void writeFinishedBlocks()
  211884. {
  211885. for (int i = 0; i < (int) numHeaders; ++i)
  211886. headers[i].writeIfFinished (deviceHandle);
  211887. }
  211888. void unprepareAllHeaders()
  211889. {
  211890. for (int i = 0; i < (int) numHeaders; ++i)
  211891. headers[i].unprepare (deviceHandle);
  211892. }
  211893. double convertTimeStamp (uint32 timeStamp)
  211894. {
  211895. timeStamp += startTime;
  211896. const uint32 now = Time::getMillisecondCounter();
  211897. if (timeStamp > now)
  211898. {
  211899. if (timeStamp > now + 2)
  211900. --startTime;
  211901. timeStamp = now;
  211902. }
  211903. return timeStamp * 0.001;
  211904. }
  211905. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  211906. };
  211907. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  211908. const StringArray MidiInput::getDevices()
  211909. {
  211910. StringArray s;
  211911. const int num = midiInGetNumDevs();
  211912. for (int i = 0; i < num; ++i)
  211913. {
  211914. MIDIINCAPS mc;
  211915. zerostruct (mc);
  211916. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211917. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211918. }
  211919. return s;
  211920. }
  211921. int MidiInput::getDefaultDeviceIndex()
  211922. {
  211923. return 0;
  211924. }
  211925. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211926. {
  211927. if (callback == 0)
  211928. return 0;
  211929. UINT deviceId = MIDI_MAPPER;
  211930. int n = 0;
  211931. String name;
  211932. const int num = midiInGetNumDevs();
  211933. for (int i = 0; i < num; ++i)
  211934. {
  211935. MIDIINCAPS mc;
  211936. zerostruct (mc);
  211937. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211938. {
  211939. if (index == n)
  211940. {
  211941. deviceId = i;
  211942. name = String (mc.szPname, numElementsInArray (mc.szPname));
  211943. break;
  211944. }
  211945. ++n;
  211946. }
  211947. }
  211948. ScopedPointer <MidiInput> in (new MidiInput (name));
  211949. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  211950. HMIDIIN h;
  211951. HRESULT err = midiInOpen (&h, deviceId,
  211952. (DWORD_PTR) &MidiInCollector::midiInCallback,
  211953. (DWORD_PTR) (MidiInCollector*) collector,
  211954. CALLBACK_FUNCTION);
  211955. if (err == MMSYSERR_NOERROR)
  211956. {
  211957. collector->deviceHandle = h;
  211958. in->internal = collector.release();
  211959. return in.release();
  211960. }
  211961. return 0;
  211962. }
  211963. MidiInput::MidiInput (const String& name_)
  211964. : name (name_),
  211965. internal (0)
  211966. {
  211967. }
  211968. MidiInput::~MidiInput()
  211969. {
  211970. delete static_cast <MidiInCollector*> (internal);
  211971. }
  211972. void MidiInput::start()
  211973. {
  211974. static_cast <MidiInCollector*> (internal)->start();
  211975. }
  211976. void MidiInput::stop()
  211977. {
  211978. static_cast <MidiInCollector*> (internal)->stop();
  211979. }
  211980. struct MidiOutHandle
  211981. {
  211982. int refCount;
  211983. UINT deviceId;
  211984. HMIDIOUT handle;
  211985. static Array<MidiOutHandle*> activeHandles;
  211986. private:
  211987. JUCE_LEAK_DETECTOR (MidiOutHandle);
  211988. };
  211989. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211990. const StringArray MidiOutput::getDevices()
  211991. {
  211992. StringArray s;
  211993. const int num = midiOutGetNumDevs();
  211994. for (int i = 0; i < num; ++i)
  211995. {
  211996. MIDIOUTCAPS mc;
  211997. zerostruct (mc);
  211998. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211999. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212000. }
  212001. return s;
  212002. }
  212003. int MidiOutput::getDefaultDeviceIndex()
  212004. {
  212005. const int num = midiOutGetNumDevs();
  212006. int n = 0;
  212007. for (int i = 0; i < num; ++i)
  212008. {
  212009. MIDIOUTCAPS mc;
  212010. zerostruct (mc);
  212011. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212012. {
  212013. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212014. return n;
  212015. ++n;
  212016. }
  212017. }
  212018. return 0;
  212019. }
  212020. MidiOutput* MidiOutput::openDevice (int index)
  212021. {
  212022. UINT deviceId = MIDI_MAPPER;
  212023. const int num = midiOutGetNumDevs();
  212024. int i, n = 0;
  212025. for (i = 0; i < num; ++i)
  212026. {
  212027. MIDIOUTCAPS mc;
  212028. zerostruct (mc);
  212029. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212030. {
  212031. // use the microsoft sw synth as a default - best not to allow deviceId
  212032. // to be MIDI_MAPPER, or else device sharing breaks
  212033. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212034. deviceId = i;
  212035. if (index == n)
  212036. {
  212037. deviceId = i;
  212038. break;
  212039. }
  212040. ++n;
  212041. }
  212042. }
  212043. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212044. {
  212045. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212046. if (han != 0 && han->deviceId == deviceId)
  212047. {
  212048. han->refCount++;
  212049. MidiOutput* const out = new MidiOutput();
  212050. out->internal = han;
  212051. return out;
  212052. }
  212053. }
  212054. for (i = 4; --i >= 0;)
  212055. {
  212056. HMIDIOUT h = 0;
  212057. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212058. if (res == MMSYSERR_NOERROR)
  212059. {
  212060. MidiOutHandle* const han = new MidiOutHandle();
  212061. han->deviceId = deviceId;
  212062. han->refCount = 1;
  212063. han->handle = h;
  212064. MidiOutHandle::activeHandles.add (han);
  212065. MidiOutput* const out = new MidiOutput();
  212066. out->internal = han;
  212067. return out;
  212068. }
  212069. else if (res == MMSYSERR_ALLOCATED)
  212070. {
  212071. Sleep (100);
  212072. }
  212073. else
  212074. {
  212075. break;
  212076. }
  212077. }
  212078. return 0;
  212079. }
  212080. MidiOutput::~MidiOutput()
  212081. {
  212082. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212083. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212084. {
  212085. midiOutClose (h->handle);
  212086. MidiOutHandle::activeHandles.removeValue (h);
  212087. delete h;
  212088. }
  212089. }
  212090. void MidiOutput::reset()
  212091. {
  212092. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212093. midiOutReset (h->handle);
  212094. }
  212095. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212096. {
  212097. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212098. DWORD n;
  212099. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212100. {
  212101. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212102. rightVol = nn[0] / (float) 0xffff;
  212103. leftVol = nn[1] / (float) 0xffff;
  212104. return true;
  212105. }
  212106. else
  212107. {
  212108. rightVol = leftVol = 1.0f;
  212109. return false;
  212110. }
  212111. }
  212112. void MidiOutput::setVolume (float leftVol, float rightVol)
  212113. {
  212114. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212115. DWORD n;
  212116. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212117. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212118. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212119. midiOutSetVolume (handle->handle, n);
  212120. }
  212121. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212122. {
  212123. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212124. if (message.getRawDataSize() > 3
  212125. || message.isSysEx())
  212126. {
  212127. MIDIHDR h;
  212128. zerostruct (h);
  212129. h.lpData = (char*) message.getRawData();
  212130. h.dwBufferLength = message.getRawDataSize();
  212131. h.dwBytesRecorded = message.getRawDataSize();
  212132. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212133. {
  212134. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212135. if (res == MMSYSERR_NOERROR)
  212136. {
  212137. while ((h.dwFlags & MHDR_DONE) == 0)
  212138. Sleep (1);
  212139. int count = 500; // 1 sec timeout
  212140. while (--count >= 0)
  212141. {
  212142. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212143. if (res == MIDIERR_STILLPLAYING)
  212144. Sleep (2);
  212145. else
  212146. break;
  212147. }
  212148. }
  212149. }
  212150. }
  212151. else
  212152. {
  212153. midiOutShortMsg (handle->handle,
  212154. *(unsigned int*) message.getRawData());
  212155. }
  212156. }
  212157. #endif
  212158. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212159. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212160. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212161. // compiled on its own).
  212162. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212163. #undef WINDOWS
  212164. // #define ASIO_DEBUGGING 1
  212165. #undef log
  212166. #if ASIO_DEBUGGING
  212167. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212168. #else
  212169. #define log(a) {}
  212170. #endif
  212171. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212172. to be pretty random about whether or not they do this. If you hit an error using these functions
  212173. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212174. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212175. */
  212176. #define JUCE_ASIOCALLBACK __cdecl
  212177. namespace ASIODebugging
  212178. {
  212179. #if ASIO_DEBUGGING
  212180. static void log (const String& context, long error)
  212181. {
  212182. String err ("unknown error");
  212183. if (error == ASE_NotPresent) err = "Not Present";
  212184. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212185. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212186. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212187. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212188. else if (error == ASE_NoClock) err = "No Clock";
  212189. else if (error == ASE_NoMemory) err = "Out of memory";
  212190. log ("!!error: " + context + " - " + err);
  212191. }
  212192. #define logError(a, b) ASIODebugging::log ((a), (b))
  212193. #else
  212194. #define logError(a, b) {}
  212195. #endif
  212196. }
  212197. class ASIOAudioIODevice;
  212198. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212199. static const int maxASIOChannels = 160;
  212200. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212201. private Timer
  212202. {
  212203. public:
  212204. Component ourWindow;
  212205. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212206. const String& optionalDllForDirectLoading_)
  212207. : AudioIODevice (name_, "ASIO"),
  212208. asioObject (0),
  212209. classId (classId_),
  212210. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212211. currentBitDepth (16),
  212212. currentSampleRate (0),
  212213. isOpen_ (false),
  212214. isStarted (false),
  212215. postOutput (true),
  212216. insideControlPanelModalLoop (false),
  212217. shouldUsePreferredSize (false)
  212218. {
  212219. name = name_;
  212220. ourWindow.addToDesktop (0);
  212221. windowHandle = ourWindow.getWindowHandle();
  212222. jassert (currentASIODev [slotNumber] == 0);
  212223. currentASIODev [slotNumber] = this;
  212224. openDevice();
  212225. }
  212226. ~ASIOAudioIODevice()
  212227. {
  212228. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212229. if (currentASIODev[i] == this)
  212230. currentASIODev[i] = 0;
  212231. close();
  212232. log ("ASIO - exiting");
  212233. removeCurrentDriver();
  212234. }
  212235. void updateSampleRates()
  212236. {
  212237. // find a list of sample rates..
  212238. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212239. sampleRates.clear();
  212240. if (asioObject != 0)
  212241. {
  212242. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212243. {
  212244. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212245. if (err == 0)
  212246. {
  212247. sampleRates.add ((int) possibleSampleRates[index]);
  212248. log ("rate: " + String ((int) possibleSampleRates[index]));
  212249. }
  212250. else if (err != ASE_NoClock)
  212251. {
  212252. logError ("CanSampleRate", err);
  212253. }
  212254. }
  212255. if (sampleRates.size() == 0)
  212256. {
  212257. double cr = 0;
  212258. const long err = asioObject->getSampleRate (&cr);
  212259. log ("No sample rates supported - current rate: " + String ((int) cr));
  212260. if (err == 0)
  212261. sampleRates.add ((int) cr);
  212262. }
  212263. }
  212264. }
  212265. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212266. const StringArray getInputChannelNames() { return inputChannelNames; }
  212267. int getNumSampleRates() { return sampleRates.size(); }
  212268. double getSampleRate (int index) { return sampleRates [index]; }
  212269. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212270. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212271. int getDefaultBufferSize() { return preferredSize; }
  212272. const String open (const BigInteger& inputChannels,
  212273. const BigInteger& outputChannels,
  212274. double sr,
  212275. int bufferSizeSamples)
  212276. {
  212277. close();
  212278. currentCallback = 0;
  212279. if (bufferSizeSamples <= 0)
  212280. shouldUsePreferredSize = true;
  212281. if (asioObject == 0 || ! isASIOOpen)
  212282. {
  212283. log ("Warning: device not open");
  212284. const String err (openDevice());
  212285. if (asioObject == 0 || ! isASIOOpen)
  212286. return err;
  212287. }
  212288. isStarted = false;
  212289. bufferIndex = -1;
  212290. long err = 0;
  212291. long newPreferredSize = 0;
  212292. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212293. minSize = 0;
  212294. maxSize = 0;
  212295. newPreferredSize = 0;
  212296. granularity = 0;
  212297. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212298. {
  212299. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212300. shouldUsePreferredSize = true;
  212301. preferredSize = newPreferredSize;
  212302. }
  212303. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212304. // dynamic changes to the buffer size...
  212305. shouldUsePreferredSize = shouldUsePreferredSize
  212306. || getName().containsIgnoreCase ("Digidesign");
  212307. if (shouldUsePreferredSize)
  212308. {
  212309. log ("Using preferred size for buffer..");
  212310. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212311. {
  212312. bufferSizeSamples = preferredSize;
  212313. }
  212314. else
  212315. {
  212316. bufferSizeSamples = 1024;
  212317. logError ("GetBufferSize1", err);
  212318. }
  212319. shouldUsePreferredSize = false;
  212320. }
  212321. int sampleRate = roundDoubleToInt (sr);
  212322. currentSampleRate = sampleRate;
  212323. currentBlockSizeSamples = bufferSizeSamples;
  212324. currentChansOut.clear();
  212325. currentChansIn.clear();
  212326. zeromem (inBuffers, sizeof (inBuffers));
  212327. zeromem (outBuffers, sizeof (outBuffers));
  212328. updateSampleRates();
  212329. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212330. sampleRate = sampleRates[0];
  212331. jassert (sampleRate != 0);
  212332. if (sampleRate == 0)
  212333. sampleRate = 44100;
  212334. long numSources = 32;
  212335. ASIOClockSource clocks[32];
  212336. zeromem (clocks, sizeof (clocks));
  212337. asioObject->getClockSources (clocks, &numSources);
  212338. bool isSourceSet = false;
  212339. // careful not to remove this loop because it does more than just logging!
  212340. int i;
  212341. for (i = 0; i < numSources; ++i)
  212342. {
  212343. String s ("clock: ");
  212344. s += clocks[i].name;
  212345. if (clocks[i].isCurrentSource)
  212346. {
  212347. isSourceSet = true;
  212348. s << " (cur)";
  212349. }
  212350. log (s);
  212351. }
  212352. if (numSources > 1 && ! isSourceSet)
  212353. {
  212354. log ("setting clock source");
  212355. asioObject->setClockSource (clocks[0].index);
  212356. Thread::sleep (20);
  212357. }
  212358. else
  212359. {
  212360. if (numSources == 0)
  212361. {
  212362. log ("ASIO - no clock sources!");
  212363. }
  212364. }
  212365. double cr = 0;
  212366. err = asioObject->getSampleRate (&cr);
  212367. if (err == 0)
  212368. {
  212369. currentSampleRate = cr;
  212370. }
  212371. else
  212372. {
  212373. logError ("GetSampleRate", err);
  212374. currentSampleRate = 0;
  212375. }
  212376. error = String::empty;
  212377. needToReset = false;
  212378. isReSync = false;
  212379. err = 0;
  212380. bool buffersCreated = false;
  212381. if (currentSampleRate != sampleRate)
  212382. {
  212383. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212384. err = asioObject->setSampleRate (sampleRate);
  212385. if (err == ASE_NoClock && numSources > 0)
  212386. {
  212387. log ("trying to set a clock source..");
  212388. Thread::sleep (10);
  212389. err = asioObject->setClockSource (clocks[0].index);
  212390. if (err != 0)
  212391. {
  212392. logError ("SetClock", err);
  212393. }
  212394. Thread::sleep (10);
  212395. err = asioObject->setSampleRate (sampleRate);
  212396. }
  212397. }
  212398. if (err == 0)
  212399. {
  212400. currentSampleRate = sampleRate;
  212401. if (needToReset)
  212402. {
  212403. if (isReSync)
  212404. {
  212405. log ("Resync request");
  212406. }
  212407. log ("! Resetting ASIO after sample rate change");
  212408. removeCurrentDriver();
  212409. loadDriver();
  212410. const String error (initDriver());
  212411. if (error.isNotEmpty())
  212412. {
  212413. log ("ASIOInit: " + error);
  212414. }
  212415. needToReset = false;
  212416. isReSync = false;
  212417. }
  212418. numActiveInputChans = 0;
  212419. numActiveOutputChans = 0;
  212420. ASIOBufferInfo* info = bufferInfos;
  212421. int i;
  212422. for (i = 0; i < totalNumInputChans; ++i)
  212423. {
  212424. if (inputChannels[i])
  212425. {
  212426. currentChansIn.setBit (i);
  212427. info->isInput = 1;
  212428. info->channelNum = i;
  212429. info->buffers[0] = info->buffers[1] = 0;
  212430. ++info;
  212431. ++numActiveInputChans;
  212432. }
  212433. }
  212434. for (i = 0; i < totalNumOutputChans; ++i)
  212435. {
  212436. if (outputChannels[i])
  212437. {
  212438. currentChansOut.setBit (i);
  212439. info->isInput = 0;
  212440. info->channelNum = i;
  212441. info->buffers[0] = info->buffers[1] = 0;
  212442. ++info;
  212443. ++numActiveOutputChans;
  212444. }
  212445. }
  212446. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212447. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212448. if (currentASIODev[0] == this)
  212449. {
  212450. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212451. callbacks.asioMessage = &asioMessagesCallback0;
  212452. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212453. }
  212454. else if (currentASIODev[1] == this)
  212455. {
  212456. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212457. callbacks.asioMessage = &asioMessagesCallback1;
  212458. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212459. }
  212460. else if (currentASIODev[2] == this)
  212461. {
  212462. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212463. callbacks.asioMessage = &asioMessagesCallback2;
  212464. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212465. }
  212466. else
  212467. {
  212468. jassertfalse;
  212469. }
  212470. log ("disposing buffers");
  212471. err = asioObject->disposeBuffers();
  212472. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212473. err = asioObject->createBuffers (bufferInfos,
  212474. totalBuffers,
  212475. currentBlockSizeSamples,
  212476. &callbacks);
  212477. if (err != 0)
  212478. {
  212479. currentBlockSizeSamples = preferredSize;
  212480. logError ("create buffers 2", err);
  212481. asioObject->disposeBuffers();
  212482. err = asioObject->createBuffers (bufferInfos,
  212483. totalBuffers,
  212484. currentBlockSizeSamples,
  212485. &callbacks);
  212486. }
  212487. if (err == 0)
  212488. {
  212489. buffersCreated = true;
  212490. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212491. int n = 0;
  212492. Array <int> types;
  212493. currentBitDepth = 16;
  212494. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212495. {
  212496. if (inputChannels[i])
  212497. {
  212498. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212499. ASIOChannelInfo channelInfo;
  212500. zerostruct (channelInfo);
  212501. channelInfo.channel = i;
  212502. channelInfo.isInput = 1;
  212503. asioObject->getChannelInfo (&channelInfo);
  212504. types.addIfNotAlreadyThere (channelInfo.type);
  212505. typeToFormatParameters (channelInfo.type,
  212506. inputChannelBitDepths[n],
  212507. inputChannelBytesPerSample[n],
  212508. inputChannelIsFloat[n],
  212509. inputChannelLittleEndian[n]);
  212510. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212511. ++n;
  212512. }
  212513. }
  212514. jassert (numActiveInputChans == n);
  212515. n = 0;
  212516. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212517. {
  212518. if (outputChannels[i])
  212519. {
  212520. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212521. ASIOChannelInfo channelInfo;
  212522. zerostruct (channelInfo);
  212523. channelInfo.channel = i;
  212524. channelInfo.isInput = 0;
  212525. asioObject->getChannelInfo (&channelInfo);
  212526. types.addIfNotAlreadyThere (channelInfo.type);
  212527. typeToFormatParameters (channelInfo.type,
  212528. outputChannelBitDepths[n],
  212529. outputChannelBytesPerSample[n],
  212530. outputChannelIsFloat[n],
  212531. outputChannelLittleEndian[n]);
  212532. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212533. ++n;
  212534. }
  212535. }
  212536. jassert (numActiveOutputChans == n);
  212537. for (i = types.size(); --i >= 0;)
  212538. {
  212539. log ("channel format: " + String (types[i]));
  212540. }
  212541. jassert (n <= totalBuffers);
  212542. for (i = 0; i < numActiveOutputChans; ++i)
  212543. {
  212544. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212545. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212546. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212547. {
  212548. log ("!! Null buffers");
  212549. }
  212550. else
  212551. {
  212552. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212553. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212554. }
  212555. }
  212556. inputLatency = outputLatency = 0;
  212557. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212558. {
  212559. log ("ASIO - no latencies");
  212560. }
  212561. else
  212562. {
  212563. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212564. }
  212565. isOpen_ = true;
  212566. log ("starting ASIO");
  212567. calledback = false;
  212568. err = asioObject->start();
  212569. if (err != 0)
  212570. {
  212571. isOpen_ = false;
  212572. log ("ASIO - stop on failure");
  212573. Thread::sleep (10);
  212574. asioObject->stop();
  212575. error = "Can't start device";
  212576. Thread::sleep (10);
  212577. }
  212578. else
  212579. {
  212580. int count = 300;
  212581. while (--count > 0 && ! calledback)
  212582. Thread::sleep (10);
  212583. isStarted = true;
  212584. if (! calledback)
  212585. {
  212586. error = "Device didn't start correctly";
  212587. log ("ASIO didn't callback - stopping..");
  212588. asioObject->stop();
  212589. }
  212590. }
  212591. }
  212592. else
  212593. {
  212594. error = "Can't create i/o buffers";
  212595. }
  212596. }
  212597. else
  212598. {
  212599. error = "Can't set sample rate: ";
  212600. error << sampleRate;
  212601. }
  212602. if (error.isNotEmpty())
  212603. {
  212604. logError (error, err);
  212605. if (asioObject != 0 && buffersCreated)
  212606. asioObject->disposeBuffers();
  212607. Thread::sleep (20);
  212608. isStarted = false;
  212609. isOpen_ = false;
  212610. const String errorCopy (error);
  212611. close(); // (this resets the error string)
  212612. error = errorCopy;
  212613. }
  212614. needToReset = false;
  212615. isReSync = false;
  212616. return error;
  212617. }
  212618. void close()
  212619. {
  212620. error = String::empty;
  212621. stopTimer();
  212622. stop();
  212623. if (isASIOOpen && isOpen_)
  212624. {
  212625. const ScopedLock sl (callbackLock);
  212626. isOpen_ = false;
  212627. isStarted = false;
  212628. needToReset = false;
  212629. isReSync = false;
  212630. log ("ASIO - stopping");
  212631. if (asioObject != 0)
  212632. {
  212633. Thread::sleep (20);
  212634. asioObject->stop();
  212635. Thread::sleep (10);
  212636. asioObject->disposeBuffers();
  212637. }
  212638. Thread::sleep (10);
  212639. }
  212640. }
  212641. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212642. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212643. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212644. double getCurrentSampleRate() { return currentSampleRate; }
  212645. int getCurrentBitDepth() { return currentBitDepth; }
  212646. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212647. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212648. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212649. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212650. void start (AudioIODeviceCallback* callback)
  212651. {
  212652. if (callback != 0)
  212653. {
  212654. callback->audioDeviceAboutToStart (this);
  212655. const ScopedLock sl (callbackLock);
  212656. currentCallback = callback;
  212657. }
  212658. }
  212659. void stop()
  212660. {
  212661. AudioIODeviceCallback* const lastCallback = currentCallback;
  212662. {
  212663. const ScopedLock sl (callbackLock);
  212664. currentCallback = 0;
  212665. }
  212666. if (lastCallback != 0)
  212667. lastCallback->audioDeviceStopped();
  212668. }
  212669. const String getLastError() { return error; }
  212670. bool hasControlPanel() const { return true; }
  212671. bool showControlPanel()
  212672. {
  212673. log ("ASIO - showing control panel");
  212674. Component modalWindow (String::empty);
  212675. modalWindow.setOpaque (true);
  212676. modalWindow.addToDesktop (0);
  212677. modalWindow.enterModalState();
  212678. bool done = false;
  212679. JUCE_TRY
  212680. {
  212681. // are there are devices that need to be closed before showing their control panel?
  212682. // close();
  212683. insideControlPanelModalLoop = true;
  212684. const uint32 started = Time::getMillisecondCounter();
  212685. if (asioObject != 0)
  212686. {
  212687. asioObject->controlPanel();
  212688. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212689. log ("spent: " + String (spent));
  212690. if (spent > 300)
  212691. {
  212692. shouldUsePreferredSize = true;
  212693. done = true;
  212694. }
  212695. }
  212696. }
  212697. JUCE_CATCH_ALL
  212698. insideControlPanelModalLoop = false;
  212699. return done;
  212700. }
  212701. void resetRequest() throw()
  212702. {
  212703. needToReset = true;
  212704. }
  212705. void resyncRequest() throw()
  212706. {
  212707. needToReset = true;
  212708. isReSync = true;
  212709. }
  212710. void timerCallback()
  212711. {
  212712. if (! insideControlPanelModalLoop)
  212713. {
  212714. stopTimer();
  212715. // used to cause a reset
  212716. log ("! ASIO restart request!");
  212717. if (isOpen_)
  212718. {
  212719. AudioIODeviceCallback* const oldCallback = currentCallback;
  212720. close();
  212721. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212722. currentSampleRate, currentBlockSizeSamples);
  212723. if (oldCallback != 0)
  212724. start (oldCallback);
  212725. }
  212726. }
  212727. else
  212728. {
  212729. startTimer (100);
  212730. }
  212731. }
  212732. private:
  212733. IASIO* volatile asioObject;
  212734. ASIOCallbacks callbacks;
  212735. void* windowHandle;
  212736. CLSID classId;
  212737. const String optionalDllForDirectLoading;
  212738. String error;
  212739. long totalNumInputChans, totalNumOutputChans;
  212740. StringArray inputChannelNames, outputChannelNames;
  212741. Array<int> sampleRates, bufferSizes;
  212742. long inputLatency, outputLatency;
  212743. long minSize, maxSize, preferredSize, granularity;
  212744. int volatile currentBlockSizeSamples;
  212745. int volatile currentBitDepth;
  212746. double volatile currentSampleRate;
  212747. BigInteger currentChansOut, currentChansIn;
  212748. AudioIODeviceCallback* volatile currentCallback;
  212749. CriticalSection callbackLock;
  212750. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212751. float* inBuffers [maxASIOChannels];
  212752. float* outBuffers [maxASIOChannels];
  212753. int inputChannelBitDepths [maxASIOChannels];
  212754. int outputChannelBitDepths [maxASIOChannels];
  212755. int inputChannelBytesPerSample [maxASIOChannels];
  212756. int outputChannelBytesPerSample [maxASIOChannels];
  212757. bool inputChannelIsFloat [maxASIOChannels];
  212758. bool outputChannelIsFloat [maxASIOChannels];
  212759. bool inputChannelLittleEndian [maxASIOChannels];
  212760. bool outputChannelLittleEndian [maxASIOChannels];
  212761. WaitableEvent event1;
  212762. HeapBlock <float> tempBuffer;
  212763. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212764. bool isOpen_, isStarted;
  212765. bool volatile isASIOOpen;
  212766. bool volatile calledback;
  212767. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212768. bool volatile insideControlPanelModalLoop;
  212769. bool volatile shouldUsePreferredSize;
  212770. void removeCurrentDriver()
  212771. {
  212772. if (asioObject != 0)
  212773. {
  212774. asioObject->Release();
  212775. asioObject = 0;
  212776. }
  212777. }
  212778. bool loadDriver()
  212779. {
  212780. removeCurrentDriver();
  212781. JUCE_TRY
  212782. {
  212783. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212784. classId, (void**) &asioObject) == S_OK)
  212785. {
  212786. return true;
  212787. }
  212788. // If a class isn't registered but we have a path for it, we can fallback to
  212789. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212790. if (optionalDllForDirectLoading.isNotEmpty())
  212791. {
  212792. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  212793. if (h != 0)
  212794. {
  212795. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212796. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212797. if (dllGetClassObject != 0)
  212798. {
  212799. IClassFactory* classFactory = 0;
  212800. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212801. if (classFactory != 0)
  212802. {
  212803. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212804. classFactory->Release();
  212805. }
  212806. return asioObject != 0;
  212807. }
  212808. }
  212809. }
  212810. }
  212811. JUCE_CATCH_ALL
  212812. asioObject = 0;
  212813. return false;
  212814. }
  212815. const String initDriver()
  212816. {
  212817. if (asioObject != 0)
  212818. {
  212819. char buffer [256];
  212820. zeromem (buffer, sizeof (buffer));
  212821. if (! asioObject->init (windowHandle))
  212822. {
  212823. asioObject->getErrorMessage (buffer);
  212824. return String (buffer, sizeof (buffer) - 1);
  212825. }
  212826. // just in case any daft drivers expect this to be called..
  212827. asioObject->getDriverName (buffer);
  212828. return String::empty;
  212829. }
  212830. return "No Driver";
  212831. }
  212832. const String openDevice()
  212833. {
  212834. // use this in case the driver starts opening dialog boxes..
  212835. Component modalWindow (String::empty);
  212836. modalWindow.setOpaque (true);
  212837. modalWindow.addToDesktop (0);
  212838. modalWindow.enterModalState();
  212839. // open the device and get its info..
  212840. log ("opening ASIO device: " + getName());
  212841. needToReset = false;
  212842. isReSync = false;
  212843. outputChannelNames.clear();
  212844. inputChannelNames.clear();
  212845. bufferSizes.clear();
  212846. sampleRates.clear();
  212847. isASIOOpen = false;
  212848. isOpen_ = false;
  212849. totalNumInputChans = 0;
  212850. totalNumOutputChans = 0;
  212851. numActiveInputChans = 0;
  212852. numActiveOutputChans = 0;
  212853. currentCallback = 0;
  212854. error = String::empty;
  212855. if (getName().isEmpty())
  212856. return error;
  212857. long err = 0;
  212858. if (loadDriver())
  212859. {
  212860. if ((error = initDriver()).isEmpty())
  212861. {
  212862. numActiveInputChans = 0;
  212863. numActiveOutputChans = 0;
  212864. totalNumInputChans = 0;
  212865. totalNumOutputChans = 0;
  212866. if (asioObject != 0
  212867. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212868. {
  212869. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212870. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212871. {
  212872. // find a list of buffer sizes..
  212873. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212874. if (granularity >= 0)
  212875. {
  212876. granularity = jmax (1, (int) granularity);
  212877. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212878. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212879. }
  212880. else if (granularity < 0)
  212881. {
  212882. for (int i = 0; i < 18; ++i)
  212883. {
  212884. const int s = (1 << i);
  212885. if (s >= minSize && s <= maxSize)
  212886. bufferSizes.add (s);
  212887. }
  212888. }
  212889. if (! bufferSizes.contains (preferredSize))
  212890. bufferSizes.insert (0, preferredSize);
  212891. double currentRate = 0;
  212892. asioObject->getSampleRate (&currentRate);
  212893. if (currentRate <= 0.0 || currentRate > 192001.0)
  212894. {
  212895. log ("setting sample rate");
  212896. err = asioObject->setSampleRate (44100.0);
  212897. if (err != 0)
  212898. {
  212899. logError ("setting sample rate", err);
  212900. }
  212901. asioObject->getSampleRate (&currentRate);
  212902. }
  212903. currentSampleRate = currentRate;
  212904. postOutput = (asioObject->outputReady() == 0);
  212905. if (postOutput)
  212906. {
  212907. log ("ASIO outputReady = ok");
  212908. }
  212909. updateSampleRates();
  212910. // ..because cubase does it at this point
  212911. inputLatency = outputLatency = 0;
  212912. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212913. {
  212914. log ("ASIO - no latencies");
  212915. }
  212916. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212917. // create some dummy buffers now.. because cubase does..
  212918. numActiveInputChans = 0;
  212919. numActiveOutputChans = 0;
  212920. ASIOBufferInfo* info = bufferInfos;
  212921. int i, numChans = 0;
  212922. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212923. {
  212924. info->isInput = 1;
  212925. info->channelNum = i;
  212926. info->buffers[0] = info->buffers[1] = 0;
  212927. ++info;
  212928. ++numChans;
  212929. }
  212930. const int outputBufferIndex = numChans;
  212931. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212932. {
  212933. info->isInput = 0;
  212934. info->channelNum = i;
  212935. info->buffers[0] = info->buffers[1] = 0;
  212936. ++info;
  212937. ++numChans;
  212938. }
  212939. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212940. if (currentASIODev[0] == this)
  212941. {
  212942. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212943. callbacks.asioMessage = &asioMessagesCallback0;
  212944. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212945. }
  212946. else if (currentASIODev[1] == this)
  212947. {
  212948. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212949. callbacks.asioMessage = &asioMessagesCallback1;
  212950. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212951. }
  212952. else if (currentASIODev[2] == this)
  212953. {
  212954. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212955. callbacks.asioMessage = &asioMessagesCallback2;
  212956. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212957. }
  212958. else
  212959. {
  212960. jassertfalse;
  212961. }
  212962. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212963. if (preferredSize > 0)
  212964. {
  212965. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212966. if (err != 0)
  212967. {
  212968. logError ("dummy buffers", err);
  212969. }
  212970. }
  212971. long newInps = 0, newOuts = 0;
  212972. asioObject->getChannels (&newInps, &newOuts);
  212973. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212974. {
  212975. totalNumInputChans = newInps;
  212976. totalNumOutputChans = newOuts;
  212977. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212978. }
  212979. updateSampleRates();
  212980. ASIOChannelInfo channelInfo;
  212981. channelInfo.type = 0;
  212982. for (i = 0; i < totalNumInputChans; ++i)
  212983. {
  212984. zerostruct (channelInfo);
  212985. channelInfo.channel = i;
  212986. channelInfo.isInput = 1;
  212987. asioObject->getChannelInfo (&channelInfo);
  212988. inputChannelNames.add (String (channelInfo.name));
  212989. }
  212990. for (i = 0; i < totalNumOutputChans; ++i)
  212991. {
  212992. zerostruct (channelInfo);
  212993. channelInfo.channel = i;
  212994. channelInfo.isInput = 0;
  212995. asioObject->getChannelInfo (&channelInfo);
  212996. outputChannelNames.add (String (channelInfo.name));
  212997. typeToFormatParameters (channelInfo.type,
  212998. outputChannelBitDepths[i],
  212999. outputChannelBytesPerSample[i],
  213000. outputChannelIsFloat[i],
  213001. outputChannelLittleEndian[i]);
  213002. if (i < 2)
  213003. {
  213004. // clear the channels that are used with the dummy stuff
  213005. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213006. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213007. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213008. }
  213009. }
  213010. outputChannelNames.trim();
  213011. inputChannelNames.trim();
  213012. outputChannelNames.appendNumbersToDuplicates (false, true);
  213013. inputChannelNames.appendNumbersToDuplicates (false, true);
  213014. // start and stop because cubase does it..
  213015. asioObject->getLatencies (&inputLatency, &outputLatency);
  213016. if ((err = asioObject->start()) != 0)
  213017. {
  213018. // ignore an error here, as it might start later after setting other stuff up
  213019. logError ("ASIO start", err);
  213020. }
  213021. Thread::sleep (100);
  213022. asioObject->stop();
  213023. }
  213024. else
  213025. {
  213026. error = "Can't detect buffer sizes";
  213027. }
  213028. }
  213029. else
  213030. {
  213031. error = "Can't detect asio channels";
  213032. }
  213033. }
  213034. }
  213035. else
  213036. {
  213037. error = "No such device";
  213038. }
  213039. if (error.isNotEmpty())
  213040. {
  213041. logError (error, err);
  213042. if (asioObject != 0)
  213043. asioObject->disposeBuffers();
  213044. removeCurrentDriver();
  213045. isASIOOpen = false;
  213046. }
  213047. else
  213048. {
  213049. isASIOOpen = true;
  213050. log ("ASIO device open");
  213051. }
  213052. isOpen_ = false;
  213053. needToReset = false;
  213054. isReSync = false;
  213055. return error;
  213056. }
  213057. void JUCE_ASIOCALLBACK callback (const long index)
  213058. {
  213059. if (isStarted)
  213060. {
  213061. bufferIndex = index;
  213062. processBuffer();
  213063. }
  213064. else
  213065. {
  213066. if (postOutput && (asioObject != 0))
  213067. asioObject->outputReady();
  213068. }
  213069. calledback = true;
  213070. }
  213071. void processBuffer()
  213072. {
  213073. const ASIOBufferInfo* const infos = bufferInfos;
  213074. const int bi = bufferIndex;
  213075. const ScopedLock sl (callbackLock);
  213076. if (needToReset)
  213077. {
  213078. needToReset = false;
  213079. if (isReSync)
  213080. {
  213081. log ("! ASIO resync");
  213082. isReSync = false;
  213083. }
  213084. else
  213085. {
  213086. startTimer (20);
  213087. }
  213088. }
  213089. if (bi >= 0)
  213090. {
  213091. const int samps = currentBlockSizeSamples;
  213092. if (currentCallback != 0)
  213093. {
  213094. int i;
  213095. for (i = 0; i < numActiveInputChans; ++i)
  213096. {
  213097. float* const dst = inBuffers[i];
  213098. jassert (dst != 0);
  213099. const char* const src = (const char*) (infos[i].buffers[bi]);
  213100. if (inputChannelIsFloat[i])
  213101. {
  213102. memcpy (dst, src, samps * sizeof (float));
  213103. }
  213104. else
  213105. {
  213106. jassert (dst == tempBuffer + (samps * i));
  213107. switch (inputChannelBitDepths[i])
  213108. {
  213109. case 16:
  213110. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213111. samps, inputChannelLittleEndian[i]);
  213112. break;
  213113. case 24:
  213114. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213115. samps, inputChannelLittleEndian[i]);
  213116. break;
  213117. case 32:
  213118. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213119. samps, inputChannelLittleEndian[i]);
  213120. break;
  213121. case 64:
  213122. jassertfalse;
  213123. break;
  213124. }
  213125. }
  213126. }
  213127. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213128. outBuffers, numActiveOutputChans, samps);
  213129. for (i = 0; i < numActiveOutputChans; ++i)
  213130. {
  213131. float* const src = outBuffers[i];
  213132. jassert (src != 0);
  213133. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213134. if (outputChannelIsFloat[i])
  213135. {
  213136. memcpy (dst, src, samps * sizeof (float));
  213137. }
  213138. else
  213139. {
  213140. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213141. switch (outputChannelBitDepths[i])
  213142. {
  213143. case 16:
  213144. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213145. samps, outputChannelLittleEndian[i]);
  213146. break;
  213147. case 24:
  213148. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213149. samps, outputChannelLittleEndian[i]);
  213150. break;
  213151. case 32:
  213152. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213153. samps, outputChannelLittleEndian[i]);
  213154. break;
  213155. case 64:
  213156. jassertfalse;
  213157. break;
  213158. }
  213159. }
  213160. }
  213161. }
  213162. else
  213163. {
  213164. for (int i = 0; i < numActiveOutputChans; ++i)
  213165. {
  213166. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213167. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213168. }
  213169. }
  213170. }
  213171. if (postOutput)
  213172. asioObject->outputReady();
  213173. }
  213174. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213175. {
  213176. if (currentASIODev[0] != 0)
  213177. currentASIODev[0]->callback (index);
  213178. return 0;
  213179. }
  213180. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213181. {
  213182. if (currentASIODev[1] != 0)
  213183. currentASIODev[1]->callback (index);
  213184. return 0;
  213185. }
  213186. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213187. {
  213188. if (currentASIODev[2] != 0)
  213189. currentASIODev[2]->callback (index);
  213190. return 0;
  213191. }
  213192. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213193. {
  213194. if (currentASIODev[0] != 0)
  213195. currentASIODev[0]->callback (index);
  213196. }
  213197. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213198. {
  213199. if (currentASIODev[1] != 0)
  213200. currentASIODev[1]->callback (index);
  213201. }
  213202. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213203. {
  213204. if (currentASIODev[2] != 0)
  213205. currentASIODev[2]->callback (index);
  213206. }
  213207. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213208. {
  213209. return asioMessagesCallback (selector, value, 0);
  213210. }
  213211. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213212. {
  213213. return asioMessagesCallback (selector, value, 1);
  213214. }
  213215. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213216. {
  213217. return asioMessagesCallback (selector, value, 2);
  213218. }
  213219. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213220. {
  213221. switch (selector)
  213222. {
  213223. case kAsioSelectorSupported:
  213224. if (value == kAsioResetRequest
  213225. || value == kAsioEngineVersion
  213226. || value == kAsioResyncRequest
  213227. || value == kAsioLatenciesChanged
  213228. || value == kAsioSupportsInputMonitor)
  213229. return 1;
  213230. break;
  213231. case kAsioBufferSizeChange:
  213232. break;
  213233. case kAsioResetRequest:
  213234. if (currentASIODev[deviceIndex] != 0)
  213235. currentASIODev[deviceIndex]->resetRequest();
  213236. return 1;
  213237. case kAsioResyncRequest:
  213238. if (currentASIODev[deviceIndex] != 0)
  213239. currentASIODev[deviceIndex]->resyncRequest();
  213240. return 1;
  213241. case kAsioLatenciesChanged:
  213242. return 1;
  213243. case kAsioEngineVersion:
  213244. return 2;
  213245. case kAsioSupportsTimeInfo:
  213246. case kAsioSupportsTimeCode:
  213247. return 0;
  213248. }
  213249. return 0;
  213250. }
  213251. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213252. {
  213253. }
  213254. static void convertInt16ToFloat (const char* src,
  213255. float* dest,
  213256. const int srcStrideBytes,
  213257. int numSamples,
  213258. const bool littleEndian) throw()
  213259. {
  213260. const double g = 1.0 / 32768.0;
  213261. if (littleEndian)
  213262. {
  213263. while (--numSamples >= 0)
  213264. {
  213265. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213266. src += srcStrideBytes;
  213267. }
  213268. }
  213269. else
  213270. {
  213271. while (--numSamples >= 0)
  213272. {
  213273. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213274. src += srcStrideBytes;
  213275. }
  213276. }
  213277. }
  213278. static void convertFloatToInt16 (const float* src,
  213279. char* dest,
  213280. const int dstStrideBytes,
  213281. int numSamples,
  213282. const bool littleEndian) throw()
  213283. {
  213284. const double maxVal = (double) 0x7fff;
  213285. if (littleEndian)
  213286. {
  213287. while (--numSamples >= 0)
  213288. {
  213289. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213290. dest += dstStrideBytes;
  213291. }
  213292. }
  213293. else
  213294. {
  213295. while (--numSamples >= 0)
  213296. {
  213297. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213298. dest += dstStrideBytes;
  213299. }
  213300. }
  213301. }
  213302. static void convertInt24ToFloat (const char* src,
  213303. float* dest,
  213304. const int srcStrideBytes,
  213305. int numSamples,
  213306. const bool littleEndian) throw()
  213307. {
  213308. const double g = 1.0 / 0x7fffff;
  213309. if (littleEndian)
  213310. {
  213311. while (--numSamples >= 0)
  213312. {
  213313. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213314. src += srcStrideBytes;
  213315. }
  213316. }
  213317. else
  213318. {
  213319. while (--numSamples >= 0)
  213320. {
  213321. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213322. src += srcStrideBytes;
  213323. }
  213324. }
  213325. }
  213326. static void convertFloatToInt24 (const float* src,
  213327. char* dest,
  213328. const int dstStrideBytes,
  213329. int numSamples,
  213330. const bool littleEndian) throw()
  213331. {
  213332. const double maxVal = (double) 0x7fffff;
  213333. if (littleEndian)
  213334. {
  213335. while (--numSamples >= 0)
  213336. {
  213337. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213338. dest += dstStrideBytes;
  213339. }
  213340. }
  213341. else
  213342. {
  213343. while (--numSamples >= 0)
  213344. {
  213345. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213346. dest += dstStrideBytes;
  213347. }
  213348. }
  213349. }
  213350. static void convertInt32ToFloat (const char* src,
  213351. float* dest,
  213352. const int srcStrideBytes,
  213353. int numSamples,
  213354. const bool littleEndian) throw()
  213355. {
  213356. const double g = 1.0 / 0x7fffffff;
  213357. if (littleEndian)
  213358. {
  213359. while (--numSamples >= 0)
  213360. {
  213361. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213362. src += srcStrideBytes;
  213363. }
  213364. }
  213365. else
  213366. {
  213367. while (--numSamples >= 0)
  213368. {
  213369. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213370. src += srcStrideBytes;
  213371. }
  213372. }
  213373. }
  213374. static void convertFloatToInt32 (const float* src,
  213375. char* dest,
  213376. const int dstStrideBytes,
  213377. int numSamples,
  213378. const bool littleEndian) throw()
  213379. {
  213380. const double maxVal = (double) 0x7fffffff;
  213381. if (littleEndian)
  213382. {
  213383. while (--numSamples >= 0)
  213384. {
  213385. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213386. dest += dstStrideBytes;
  213387. }
  213388. }
  213389. else
  213390. {
  213391. while (--numSamples >= 0)
  213392. {
  213393. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213394. dest += dstStrideBytes;
  213395. }
  213396. }
  213397. }
  213398. static void typeToFormatParameters (const long type,
  213399. int& bitDepth,
  213400. int& byteStride,
  213401. bool& formatIsFloat,
  213402. bool& littleEndian) throw()
  213403. {
  213404. bitDepth = 0;
  213405. littleEndian = false;
  213406. formatIsFloat = false;
  213407. switch (type)
  213408. {
  213409. case ASIOSTInt16MSB:
  213410. case ASIOSTInt16LSB:
  213411. case ASIOSTInt32MSB16:
  213412. case ASIOSTInt32LSB16:
  213413. bitDepth = 16; break;
  213414. case ASIOSTFloat32MSB:
  213415. case ASIOSTFloat32LSB:
  213416. formatIsFloat = true;
  213417. bitDepth = 32; break;
  213418. case ASIOSTInt32MSB:
  213419. case ASIOSTInt32LSB:
  213420. bitDepth = 32; break;
  213421. case ASIOSTInt24MSB:
  213422. case ASIOSTInt24LSB:
  213423. case ASIOSTInt32MSB24:
  213424. case ASIOSTInt32LSB24:
  213425. case ASIOSTInt32MSB18:
  213426. case ASIOSTInt32MSB20:
  213427. case ASIOSTInt32LSB18:
  213428. case ASIOSTInt32LSB20:
  213429. bitDepth = 24; break;
  213430. case ASIOSTFloat64MSB:
  213431. case ASIOSTFloat64LSB:
  213432. default:
  213433. bitDepth = 64;
  213434. break;
  213435. }
  213436. switch (type)
  213437. {
  213438. case ASIOSTInt16MSB:
  213439. case ASIOSTInt32MSB16:
  213440. case ASIOSTFloat32MSB:
  213441. case ASIOSTFloat64MSB:
  213442. case ASIOSTInt32MSB:
  213443. case ASIOSTInt32MSB18:
  213444. case ASIOSTInt32MSB20:
  213445. case ASIOSTInt32MSB24:
  213446. case ASIOSTInt24MSB:
  213447. littleEndian = false; break;
  213448. case ASIOSTInt16LSB:
  213449. case ASIOSTInt32LSB16:
  213450. case ASIOSTFloat32LSB:
  213451. case ASIOSTFloat64LSB:
  213452. case ASIOSTInt32LSB:
  213453. case ASIOSTInt32LSB18:
  213454. case ASIOSTInt32LSB20:
  213455. case ASIOSTInt32LSB24:
  213456. case ASIOSTInt24LSB:
  213457. littleEndian = true; break;
  213458. default:
  213459. break;
  213460. }
  213461. switch (type)
  213462. {
  213463. case ASIOSTInt16LSB:
  213464. case ASIOSTInt16MSB:
  213465. byteStride = 2; break;
  213466. case ASIOSTInt24LSB:
  213467. case ASIOSTInt24MSB:
  213468. byteStride = 3; break;
  213469. case ASIOSTInt32MSB16:
  213470. case ASIOSTInt32LSB16:
  213471. case ASIOSTInt32MSB:
  213472. case ASIOSTInt32MSB18:
  213473. case ASIOSTInt32MSB20:
  213474. case ASIOSTInt32MSB24:
  213475. case ASIOSTInt32LSB:
  213476. case ASIOSTInt32LSB18:
  213477. case ASIOSTInt32LSB20:
  213478. case ASIOSTInt32LSB24:
  213479. case ASIOSTFloat32LSB:
  213480. case ASIOSTFloat32MSB:
  213481. byteStride = 4; break;
  213482. case ASIOSTFloat64MSB:
  213483. case ASIOSTFloat64LSB:
  213484. byteStride = 8; break;
  213485. default:
  213486. break;
  213487. }
  213488. }
  213489. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213490. };
  213491. class ASIOAudioIODeviceType : public AudioIODeviceType
  213492. {
  213493. public:
  213494. ASIOAudioIODeviceType()
  213495. : AudioIODeviceType ("ASIO"),
  213496. hasScanned (false)
  213497. {
  213498. CoInitialize (0);
  213499. }
  213500. ~ASIOAudioIODeviceType()
  213501. {
  213502. }
  213503. void scanForDevices()
  213504. {
  213505. hasScanned = true;
  213506. deviceNames.clear();
  213507. classIds.clear();
  213508. HKEY hk = 0;
  213509. int index = 0;
  213510. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213511. {
  213512. for (;;)
  213513. {
  213514. char name [256];
  213515. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213516. {
  213517. addDriverInfo (name, hk);
  213518. }
  213519. else
  213520. {
  213521. break;
  213522. }
  213523. }
  213524. RegCloseKey (hk);
  213525. }
  213526. }
  213527. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213528. {
  213529. jassert (hasScanned); // need to call scanForDevices() before doing this
  213530. return deviceNames;
  213531. }
  213532. int getDefaultDeviceIndex (bool) const
  213533. {
  213534. jassert (hasScanned); // need to call scanForDevices() before doing this
  213535. for (int i = deviceNames.size(); --i >= 0;)
  213536. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213537. return i; // asio4all is a safe choice for a default..
  213538. #if JUCE_DEBUG
  213539. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213540. return 1; // (the digi m-box driver crashes the app when you run
  213541. // it in the debugger, which can be a bit annoying)
  213542. #endif
  213543. return 0;
  213544. }
  213545. static int findFreeSlot()
  213546. {
  213547. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213548. if (currentASIODev[i] == 0)
  213549. return i;
  213550. jassertfalse; // unfortunately you can only have a finite number
  213551. // of ASIO devices open at the same time..
  213552. return -1;
  213553. }
  213554. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213555. {
  213556. jassert (hasScanned); // need to call scanForDevices() before doing this
  213557. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213558. }
  213559. bool hasSeparateInputsAndOutputs() const { return false; }
  213560. AudioIODevice* createDevice (const String& outputDeviceName,
  213561. const String& inputDeviceName)
  213562. {
  213563. // ASIO can't open two different devices for input and output - they must be the same one.
  213564. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213565. jassert (hasScanned); // need to call scanForDevices() before doing this
  213566. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213567. : inputDeviceName);
  213568. if (index >= 0)
  213569. {
  213570. const int freeSlot = findFreeSlot();
  213571. if (freeSlot >= 0)
  213572. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213573. }
  213574. return 0;
  213575. }
  213576. private:
  213577. StringArray deviceNames;
  213578. OwnedArray <CLSID> classIds;
  213579. bool hasScanned;
  213580. static bool checkClassIsOk (const String& classId)
  213581. {
  213582. HKEY hk = 0;
  213583. bool ok = false;
  213584. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213585. {
  213586. int index = 0;
  213587. for (;;)
  213588. {
  213589. WCHAR buf [512];
  213590. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213591. {
  213592. if (classId.equalsIgnoreCase (buf))
  213593. {
  213594. HKEY subKey, pathKey;
  213595. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213596. {
  213597. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213598. {
  213599. WCHAR pathName [1024];
  213600. DWORD dtype = REG_SZ;
  213601. DWORD dsize = sizeof (pathName);
  213602. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213603. ok = File (pathName).exists();
  213604. RegCloseKey (pathKey);
  213605. }
  213606. RegCloseKey (subKey);
  213607. }
  213608. break;
  213609. }
  213610. }
  213611. else
  213612. {
  213613. break;
  213614. }
  213615. }
  213616. RegCloseKey (hk);
  213617. }
  213618. return ok;
  213619. }
  213620. void addDriverInfo (const String& keyName, HKEY hk)
  213621. {
  213622. HKEY subKey;
  213623. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213624. {
  213625. WCHAR buf [256];
  213626. zerostruct (buf);
  213627. DWORD dtype = REG_SZ;
  213628. DWORD dsize = sizeof (buf);
  213629. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213630. {
  213631. if (dsize > 0 && checkClassIsOk (buf))
  213632. {
  213633. CLSID classId;
  213634. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213635. {
  213636. dtype = REG_SZ;
  213637. dsize = sizeof (buf);
  213638. String deviceName;
  213639. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213640. deviceName = buf;
  213641. else
  213642. deviceName = keyName;
  213643. log ("found " + deviceName);
  213644. deviceNames.add (deviceName);
  213645. classIds.add (new CLSID (classId));
  213646. }
  213647. }
  213648. RegCloseKey (subKey);
  213649. }
  213650. }
  213651. }
  213652. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213653. };
  213654. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  213655. {
  213656. return new ASIOAudioIODeviceType();
  213657. }
  213658. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213659. void* guid,
  213660. const String& optionalDllForDirectLoading)
  213661. {
  213662. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213663. if (freeSlot < 0)
  213664. return 0;
  213665. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213666. }
  213667. #undef logError
  213668. #undef log
  213669. #endif
  213670. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213671. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213672. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213673. // compiled on its own).
  213674. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213675. END_JUCE_NAMESPACE
  213676. extern "C"
  213677. {
  213678. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213679. typedef struct typeDSBUFFERDESC
  213680. {
  213681. DWORD dwSize;
  213682. DWORD dwFlags;
  213683. DWORD dwBufferBytes;
  213684. DWORD dwReserved;
  213685. LPWAVEFORMATEX lpwfxFormat;
  213686. GUID guid3DAlgorithm;
  213687. } DSBUFFERDESC;
  213688. struct IDirectSoundBuffer;
  213689. #undef INTERFACE
  213690. #define INTERFACE IDirectSound
  213691. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213692. {
  213693. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213694. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213695. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213696. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213697. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213698. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213699. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213700. STDMETHOD(Compact) (THIS) PURE;
  213701. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213702. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213703. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213704. };
  213705. #undef INTERFACE
  213706. #define INTERFACE IDirectSoundBuffer
  213707. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213708. {
  213709. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213710. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213711. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213712. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213713. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213714. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213715. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213716. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213717. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213718. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213719. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213720. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213721. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213722. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213723. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213724. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213725. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213726. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213727. STDMETHOD(Stop) (THIS) PURE;
  213728. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213729. STDMETHOD(Restore) (THIS) PURE;
  213730. };
  213731. typedef struct typeDSCBUFFERDESC
  213732. {
  213733. DWORD dwSize;
  213734. DWORD dwFlags;
  213735. DWORD dwBufferBytes;
  213736. DWORD dwReserved;
  213737. LPWAVEFORMATEX lpwfxFormat;
  213738. } DSCBUFFERDESC;
  213739. struct IDirectSoundCaptureBuffer;
  213740. #undef INTERFACE
  213741. #define INTERFACE IDirectSoundCapture
  213742. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213743. {
  213744. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213745. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213746. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213747. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213748. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213749. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213750. };
  213751. #undef INTERFACE
  213752. #define INTERFACE IDirectSoundCaptureBuffer
  213753. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213754. {
  213755. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213756. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213757. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213758. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213759. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213760. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213761. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213762. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213763. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213764. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213765. STDMETHOD(Stop) (THIS) PURE;
  213766. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213767. };
  213768. };
  213769. BEGIN_JUCE_NAMESPACE
  213770. namespace
  213771. {
  213772. const String getDSErrorMessage (HRESULT hr)
  213773. {
  213774. const char* result = 0;
  213775. switch (hr)
  213776. {
  213777. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213778. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213779. case E_INVALIDARG: result = "Invalid parameter"; break;
  213780. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213781. case E_FAIL: result = "Generic error"; break;
  213782. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213783. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213784. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213785. case E_NOTIMPL: result = "Unsupported function"; break;
  213786. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213787. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213788. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213789. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213790. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213791. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213792. case E_NOINTERFACE: result = "No interface"; break;
  213793. case S_OK: result = "No error"; break;
  213794. default: return "Unknown error: " + String ((int) hr);
  213795. }
  213796. return result;
  213797. }
  213798. #define DS_DEBUGGING 1
  213799. #ifdef DS_DEBUGGING
  213800. #define CATCH JUCE_CATCH_EXCEPTION
  213801. #undef log
  213802. #define log(a) Logger::writeToLog(a);
  213803. #undef logError
  213804. #define logError(a) logDSError(a, __LINE__);
  213805. static void logDSError (HRESULT hr, int lineNum)
  213806. {
  213807. if (hr != S_OK)
  213808. {
  213809. String error ("DS error at line ");
  213810. error << lineNum << " - " << getDSErrorMessage (hr);
  213811. log (error);
  213812. }
  213813. }
  213814. #else
  213815. #define CATCH JUCE_CATCH_ALL
  213816. #define log(a)
  213817. #define logError(a)
  213818. #endif
  213819. #define DSOUND_FUNCTION(functionName, params) \
  213820. typedef HRESULT (WINAPI *type##functionName) params; \
  213821. static type##functionName ds##functionName = 0;
  213822. #define DSOUND_FUNCTION_LOAD(functionName) \
  213823. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213824. jassert (ds##functionName != 0);
  213825. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213826. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213827. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213828. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213829. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213830. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213831. void initialiseDSoundFunctions()
  213832. {
  213833. if (dsDirectSoundCreate == 0)
  213834. {
  213835. HMODULE h = LoadLibraryA ("dsound.dll");
  213836. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213837. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213838. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213839. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213840. }
  213841. }
  213842. }
  213843. class DSoundInternalOutChannel
  213844. {
  213845. public:
  213846. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  213847. int bufferSize, float* left, float* right)
  213848. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213849. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213850. pDirectSound (0), pOutputBuffer (0)
  213851. {
  213852. }
  213853. ~DSoundInternalOutChannel()
  213854. {
  213855. close();
  213856. }
  213857. void close()
  213858. {
  213859. HRESULT hr;
  213860. if (pOutputBuffer != 0)
  213861. {
  213862. log ("closing dsound out: " + name);
  213863. hr = pOutputBuffer->Stop();
  213864. logError (hr);
  213865. hr = pOutputBuffer->Release();
  213866. pOutputBuffer = 0;
  213867. logError (hr);
  213868. }
  213869. if (pDirectSound != 0)
  213870. {
  213871. hr = pDirectSound->Release();
  213872. pDirectSound = 0;
  213873. logError (hr);
  213874. }
  213875. }
  213876. const String open()
  213877. {
  213878. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213879. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213880. pDirectSound = 0;
  213881. pOutputBuffer = 0;
  213882. writeOffset = 0;
  213883. String error;
  213884. HRESULT hr = E_NOINTERFACE;
  213885. if (dsDirectSoundCreate != 0)
  213886. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213887. if (hr == S_OK)
  213888. {
  213889. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213890. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213891. const int numChannels = 2;
  213892. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213893. logError (hr);
  213894. if (hr == S_OK)
  213895. {
  213896. IDirectSoundBuffer* pPrimaryBuffer;
  213897. DSBUFFERDESC primaryDesc;
  213898. zerostruct (primaryDesc);
  213899. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213900. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213901. primaryDesc.dwBufferBytes = 0;
  213902. primaryDesc.lpwfxFormat = 0;
  213903. log ("opening dsound out step 2");
  213904. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213905. logError (hr);
  213906. if (hr == S_OK)
  213907. {
  213908. WAVEFORMATEX wfFormat;
  213909. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213910. wfFormat.nChannels = (unsigned short) numChannels;
  213911. wfFormat.nSamplesPerSec = sampleRate;
  213912. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213913. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213914. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213915. wfFormat.cbSize = 0;
  213916. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213917. logError (hr);
  213918. if (hr == S_OK)
  213919. {
  213920. DSBUFFERDESC secondaryDesc;
  213921. zerostruct (secondaryDesc);
  213922. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213923. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213924. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213925. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213926. secondaryDesc.lpwfxFormat = &wfFormat;
  213927. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213928. logError (hr);
  213929. if (hr == S_OK)
  213930. {
  213931. log ("opening dsound out step 3");
  213932. DWORD dwDataLen;
  213933. unsigned char* pDSBuffData;
  213934. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213935. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213936. logError (hr);
  213937. if (hr == S_OK)
  213938. {
  213939. zeromem (pDSBuffData, dwDataLen);
  213940. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213941. if (hr == S_OK)
  213942. {
  213943. hr = pOutputBuffer->SetCurrentPosition (0);
  213944. if (hr == S_OK)
  213945. {
  213946. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213947. if (hr == S_OK)
  213948. return String::empty;
  213949. }
  213950. }
  213951. }
  213952. }
  213953. }
  213954. }
  213955. }
  213956. }
  213957. error = getDSErrorMessage (hr);
  213958. close();
  213959. return error;
  213960. }
  213961. void synchronisePosition()
  213962. {
  213963. if (pOutputBuffer != 0)
  213964. {
  213965. DWORD playCursor;
  213966. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213967. }
  213968. }
  213969. bool service()
  213970. {
  213971. if (pOutputBuffer == 0)
  213972. return true;
  213973. DWORD playCursor, writeCursor;
  213974. for (;;)
  213975. {
  213976. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213977. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213978. {
  213979. pOutputBuffer->Restore();
  213980. continue;
  213981. }
  213982. if (hr == S_OK)
  213983. break;
  213984. logError (hr);
  213985. jassertfalse;
  213986. return true;
  213987. }
  213988. int playWriteGap = writeCursor - playCursor;
  213989. if (playWriteGap < 0)
  213990. playWriteGap += totalBytesPerBuffer;
  213991. int bytesEmpty = playCursor - writeOffset;
  213992. if (bytesEmpty < 0)
  213993. bytesEmpty += totalBytesPerBuffer;
  213994. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213995. {
  213996. writeOffset = writeCursor;
  213997. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213998. }
  213999. if (bytesEmpty >= bytesPerBuffer)
  214000. {
  214001. void* lpbuf1 = 0;
  214002. void* lpbuf2 = 0;
  214003. DWORD dwSize1 = 0;
  214004. DWORD dwSize2 = 0;
  214005. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214006. &lpbuf1, &dwSize1,
  214007. &lpbuf2, &dwSize2, 0);
  214008. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214009. {
  214010. pOutputBuffer->Restore();
  214011. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214012. &lpbuf1, &dwSize1,
  214013. &lpbuf2, &dwSize2, 0);
  214014. }
  214015. if (hr == S_OK)
  214016. {
  214017. if (bitDepth == 16)
  214018. {
  214019. int* dest = static_cast<int*> (lpbuf1);
  214020. const float* left = leftBuffer;
  214021. const float* right = rightBuffer;
  214022. int samples1 = dwSize1 >> 2;
  214023. int samples2 = dwSize2 >> 2;
  214024. if (left == 0)
  214025. {
  214026. while (--samples1 >= 0)
  214027. *dest++ = (convertInputValue (*right++) << 16);
  214028. dest = static_cast<int*> (lpbuf2);
  214029. while (--samples2 >= 0)
  214030. *dest++ = (convertInputValue (*right++) << 16);
  214031. }
  214032. else if (right == 0)
  214033. {
  214034. while (--samples1 >= 0)
  214035. *dest++ = (0xffff & convertInputValue (*left++));
  214036. dest = static_cast<int*> (lpbuf2);
  214037. while (--samples2 >= 0)
  214038. *dest++ = (0xffff & convertInputValue (*left++));
  214039. }
  214040. else
  214041. {
  214042. while (--samples1 >= 0)
  214043. {
  214044. const int l = convertInputValue (*left++);
  214045. const int r = convertInputValue (*right++);
  214046. *dest++ = (r << 16) | (0xffff & l);
  214047. }
  214048. dest = static_cast<int*> (lpbuf2);
  214049. while (--samples2 >= 0)
  214050. {
  214051. const int l = convertInputValue (*left++);
  214052. const int r = convertInputValue (*right++);
  214053. *dest++ = (r << 16) | (0xffff & l);
  214054. }
  214055. }
  214056. }
  214057. else
  214058. {
  214059. jassertfalse;
  214060. }
  214061. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214062. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214063. }
  214064. else
  214065. {
  214066. jassertfalse;
  214067. logError (hr);
  214068. }
  214069. bytesEmpty -= bytesPerBuffer;
  214070. return true;
  214071. }
  214072. else
  214073. {
  214074. return false;
  214075. }
  214076. }
  214077. int bitDepth;
  214078. bool doneFlag;
  214079. private:
  214080. String name;
  214081. LPGUID guid;
  214082. int sampleRate, bufferSizeSamples;
  214083. float* leftBuffer;
  214084. float* rightBuffer;
  214085. IDirectSound* pDirectSound;
  214086. IDirectSoundBuffer* pOutputBuffer;
  214087. DWORD writeOffset;
  214088. int totalBytesPerBuffer, bytesPerBuffer;
  214089. unsigned int lastPlayCursor;
  214090. static inline int convertInputValue (const float v) throw()
  214091. {
  214092. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  214093. }
  214094. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  214095. };
  214096. struct DSoundInternalInChannel
  214097. {
  214098. public:
  214099. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  214100. int bufferSize, float* left, float* right)
  214101. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214102. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214103. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  214104. {
  214105. }
  214106. ~DSoundInternalInChannel()
  214107. {
  214108. close();
  214109. }
  214110. void close()
  214111. {
  214112. HRESULT hr;
  214113. if (pInputBuffer != 0)
  214114. {
  214115. log ("closing dsound in: " + name);
  214116. hr = pInputBuffer->Stop();
  214117. logError (hr);
  214118. hr = pInputBuffer->Release();
  214119. pInputBuffer = 0;
  214120. logError (hr);
  214121. }
  214122. if (pDirectSoundCapture != 0)
  214123. {
  214124. hr = pDirectSoundCapture->Release();
  214125. pDirectSoundCapture = 0;
  214126. logError (hr);
  214127. }
  214128. if (pDirectSound != 0)
  214129. {
  214130. hr = pDirectSound->Release();
  214131. pDirectSound = 0;
  214132. logError (hr);
  214133. }
  214134. }
  214135. const String open()
  214136. {
  214137. log ("opening dsound in device: " + name
  214138. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214139. pDirectSound = 0;
  214140. pDirectSoundCapture = 0;
  214141. pInputBuffer = 0;
  214142. readOffset = 0;
  214143. totalBytesPerBuffer = 0;
  214144. String error;
  214145. HRESULT hr = E_NOINTERFACE;
  214146. if (dsDirectSoundCaptureCreate != 0)
  214147. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214148. logError (hr);
  214149. if (hr == S_OK)
  214150. {
  214151. const int numChannels = 2;
  214152. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214153. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214154. WAVEFORMATEX wfFormat;
  214155. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214156. wfFormat.nChannels = (unsigned short)numChannels;
  214157. wfFormat.nSamplesPerSec = sampleRate;
  214158. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214159. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214160. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214161. wfFormat.cbSize = 0;
  214162. DSCBUFFERDESC captureDesc;
  214163. zerostruct (captureDesc);
  214164. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214165. captureDesc.dwFlags = 0;
  214166. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214167. captureDesc.lpwfxFormat = &wfFormat;
  214168. log ("opening dsound in step 2");
  214169. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214170. logError (hr);
  214171. if (hr == S_OK)
  214172. {
  214173. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214174. logError (hr);
  214175. if (hr == S_OK)
  214176. return String::empty;
  214177. }
  214178. }
  214179. error = getDSErrorMessage (hr);
  214180. close();
  214181. return error;
  214182. }
  214183. void synchronisePosition()
  214184. {
  214185. if (pInputBuffer != 0)
  214186. {
  214187. DWORD capturePos;
  214188. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214189. }
  214190. }
  214191. bool service()
  214192. {
  214193. if (pInputBuffer == 0)
  214194. return true;
  214195. DWORD capturePos, readPos;
  214196. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214197. logError (hr);
  214198. if (hr != S_OK)
  214199. return true;
  214200. int bytesFilled = readPos - readOffset;
  214201. if (bytesFilled < 0)
  214202. bytesFilled += totalBytesPerBuffer;
  214203. if (bytesFilled >= bytesPerBuffer)
  214204. {
  214205. LPBYTE lpbuf1 = 0;
  214206. LPBYTE lpbuf2 = 0;
  214207. DWORD dwsize1 = 0;
  214208. DWORD dwsize2 = 0;
  214209. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  214210. (void**) &lpbuf1, &dwsize1,
  214211. (void**) &lpbuf2, &dwsize2, 0);
  214212. if (hr == S_OK)
  214213. {
  214214. if (bitDepth == 16)
  214215. {
  214216. const float g = 1.0f / 32768.0f;
  214217. float* destL = leftBuffer;
  214218. float* destR = rightBuffer;
  214219. int samples1 = dwsize1 >> 2;
  214220. int samples2 = dwsize2 >> 2;
  214221. const short* src = (const short*)lpbuf1;
  214222. if (destL == 0)
  214223. {
  214224. while (--samples1 >= 0)
  214225. {
  214226. ++src;
  214227. *destR++ = *src++ * g;
  214228. }
  214229. src = (const short*)lpbuf2;
  214230. while (--samples2 >= 0)
  214231. {
  214232. ++src;
  214233. *destR++ = *src++ * g;
  214234. }
  214235. }
  214236. else if (destR == 0)
  214237. {
  214238. while (--samples1 >= 0)
  214239. {
  214240. *destL++ = *src++ * g;
  214241. ++src;
  214242. }
  214243. src = (const short*)lpbuf2;
  214244. while (--samples2 >= 0)
  214245. {
  214246. *destL++ = *src++ * g;
  214247. ++src;
  214248. }
  214249. }
  214250. else
  214251. {
  214252. while (--samples1 >= 0)
  214253. {
  214254. *destL++ = *src++ * g;
  214255. *destR++ = *src++ * g;
  214256. }
  214257. src = (const short*)lpbuf2;
  214258. while (--samples2 >= 0)
  214259. {
  214260. *destL++ = *src++ * g;
  214261. *destR++ = *src++ * g;
  214262. }
  214263. }
  214264. }
  214265. else
  214266. {
  214267. jassertfalse;
  214268. }
  214269. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214270. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214271. }
  214272. else
  214273. {
  214274. logError (hr);
  214275. jassertfalse;
  214276. }
  214277. bytesFilled -= bytesPerBuffer;
  214278. return true;
  214279. }
  214280. else
  214281. {
  214282. return false;
  214283. }
  214284. }
  214285. unsigned int readOffset;
  214286. int bytesPerBuffer, totalBytesPerBuffer;
  214287. int bitDepth;
  214288. bool doneFlag;
  214289. private:
  214290. String name;
  214291. LPGUID guid;
  214292. int sampleRate, bufferSizeSamples;
  214293. float* leftBuffer;
  214294. float* rightBuffer;
  214295. IDirectSound* pDirectSound;
  214296. IDirectSoundCapture* pDirectSoundCapture;
  214297. IDirectSoundCaptureBuffer* pInputBuffer;
  214298. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214299. };
  214300. class DSoundAudioIODevice : public AudioIODevice,
  214301. public Thread
  214302. {
  214303. public:
  214304. DSoundAudioIODevice (const String& deviceName,
  214305. const int outputDeviceIndex_,
  214306. const int inputDeviceIndex_)
  214307. : AudioIODevice (deviceName, "DirectSound"),
  214308. Thread ("Juce DSound"),
  214309. isOpen_ (false),
  214310. isStarted (false),
  214311. outputDeviceIndex (outputDeviceIndex_),
  214312. inputDeviceIndex (inputDeviceIndex_),
  214313. totalSamplesOut (0),
  214314. sampleRate (0.0),
  214315. inputBuffers (1, 1),
  214316. outputBuffers (1, 1),
  214317. callback (0),
  214318. bufferSizeSamples (0)
  214319. {
  214320. if (outputDeviceIndex_ >= 0)
  214321. {
  214322. outChannels.add (TRANS("Left"));
  214323. outChannels.add (TRANS("Right"));
  214324. }
  214325. if (inputDeviceIndex_ >= 0)
  214326. {
  214327. inChannels.add (TRANS("Left"));
  214328. inChannels.add (TRANS("Right"));
  214329. }
  214330. }
  214331. ~DSoundAudioIODevice()
  214332. {
  214333. close();
  214334. }
  214335. const String open (const BigInteger& inputChannels,
  214336. const BigInteger& outputChannels,
  214337. double sampleRate, int bufferSizeSamples)
  214338. {
  214339. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214340. isOpen_ = lastError.isEmpty();
  214341. return lastError;
  214342. }
  214343. void close()
  214344. {
  214345. stop();
  214346. if (isOpen_)
  214347. {
  214348. closeDevice();
  214349. isOpen_ = false;
  214350. }
  214351. }
  214352. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214353. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214354. double getCurrentSampleRate() { return sampleRate; }
  214355. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214356. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214357. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214358. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214359. const StringArray getOutputChannelNames() { return outChannels; }
  214360. const StringArray getInputChannelNames() { return inChannels; }
  214361. int getNumSampleRates() { return 4; }
  214362. int getDefaultBufferSize() { return 2560; }
  214363. int getNumBufferSizesAvailable() { return 50; }
  214364. double getSampleRate (int index)
  214365. {
  214366. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214367. return samps [jlimit (0, 3, index)];
  214368. }
  214369. int getBufferSizeSamples (int index)
  214370. {
  214371. int n = 64;
  214372. for (int i = 0; i < index; ++i)
  214373. n += (n < 512) ? 32
  214374. : ((n < 1024) ? 64
  214375. : ((n < 2048) ? 128 : 256));
  214376. return n;
  214377. }
  214378. int getCurrentBitDepth()
  214379. {
  214380. int i, bits = 256;
  214381. for (i = inChans.size(); --i >= 0;)
  214382. bits = jmin (bits, inChans[i]->bitDepth);
  214383. for (i = outChans.size(); --i >= 0;)
  214384. bits = jmin (bits, outChans[i]->bitDepth);
  214385. if (bits > 32)
  214386. bits = 16;
  214387. return bits;
  214388. }
  214389. void start (AudioIODeviceCallback* call)
  214390. {
  214391. if (isOpen_ && call != 0 && ! isStarted)
  214392. {
  214393. if (! isThreadRunning())
  214394. {
  214395. // something gone wrong and the thread's stopped..
  214396. isOpen_ = false;
  214397. return;
  214398. }
  214399. call->audioDeviceAboutToStart (this);
  214400. const ScopedLock sl (startStopLock);
  214401. callback = call;
  214402. isStarted = true;
  214403. }
  214404. }
  214405. void stop()
  214406. {
  214407. if (isStarted)
  214408. {
  214409. AudioIODeviceCallback* const callbackLocal = callback;
  214410. {
  214411. const ScopedLock sl (startStopLock);
  214412. isStarted = false;
  214413. }
  214414. if (callbackLocal != 0)
  214415. callbackLocal->audioDeviceStopped();
  214416. }
  214417. }
  214418. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214419. const String getLastError() { return lastError; }
  214420. StringArray inChannels, outChannels;
  214421. int outputDeviceIndex, inputDeviceIndex;
  214422. private:
  214423. bool isOpen_;
  214424. bool isStarted;
  214425. String lastError;
  214426. OwnedArray <DSoundInternalInChannel> inChans;
  214427. OwnedArray <DSoundInternalOutChannel> outChans;
  214428. WaitableEvent startEvent;
  214429. int bufferSizeSamples;
  214430. int volatile totalSamplesOut;
  214431. int64 volatile lastBlockTime;
  214432. double sampleRate;
  214433. BigInteger enabledInputs, enabledOutputs;
  214434. AudioSampleBuffer inputBuffers, outputBuffers;
  214435. AudioIODeviceCallback* callback;
  214436. CriticalSection startStopLock;
  214437. const String openDevice (const BigInteger& inputChannels,
  214438. const BigInteger& outputChannels,
  214439. double sampleRate_, int bufferSizeSamples_);
  214440. void closeDevice()
  214441. {
  214442. isStarted = false;
  214443. stopThread (5000);
  214444. inChans.clear();
  214445. outChans.clear();
  214446. inputBuffers.setSize (1, 1);
  214447. outputBuffers.setSize (1, 1);
  214448. }
  214449. void resync()
  214450. {
  214451. if (! threadShouldExit())
  214452. {
  214453. sleep (5);
  214454. int i;
  214455. for (i = 0; i < outChans.size(); ++i)
  214456. outChans.getUnchecked(i)->synchronisePosition();
  214457. for (i = 0; i < inChans.size(); ++i)
  214458. inChans.getUnchecked(i)->synchronisePosition();
  214459. }
  214460. }
  214461. public:
  214462. void run()
  214463. {
  214464. while (! threadShouldExit())
  214465. {
  214466. if (wait (100))
  214467. break;
  214468. }
  214469. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214470. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214471. while (! threadShouldExit())
  214472. {
  214473. int numToDo = 0;
  214474. uint32 startTime = Time::getMillisecondCounter();
  214475. int i;
  214476. for (i = inChans.size(); --i >= 0;)
  214477. {
  214478. inChans.getUnchecked(i)->doneFlag = false;
  214479. ++numToDo;
  214480. }
  214481. for (i = outChans.size(); --i >= 0;)
  214482. {
  214483. outChans.getUnchecked(i)->doneFlag = false;
  214484. ++numToDo;
  214485. }
  214486. if (numToDo > 0)
  214487. {
  214488. const int maxCount = 3;
  214489. int count = maxCount;
  214490. for (;;)
  214491. {
  214492. for (i = inChans.size(); --i >= 0;)
  214493. {
  214494. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214495. if ((! in->doneFlag) && in->service())
  214496. {
  214497. in->doneFlag = true;
  214498. --numToDo;
  214499. }
  214500. }
  214501. for (i = outChans.size(); --i >= 0;)
  214502. {
  214503. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214504. if ((! out->doneFlag) && out->service())
  214505. {
  214506. out->doneFlag = true;
  214507. --numToDo;
  214508. }
  214509. }
  214510. if (numToDo <= 0)
  214511. break;
  214512. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214513. {
  214514. resync();
  214515. break;
  214516. }
  214517. if (--count <= 0)
  214518. {
  214519. Sleep (1);
  214520. count = maxCount;
  214521. }
  214522. if (threadShouldExit())
  214523. return;
  214524. }
  214525. }
  214526. else
  214527. {
  214528. sleep (1);
  214529. }
  214530. const ScopedLock sl (startStopLock);
  214531. if (isStarted)
  214532. {
  214533. JUCE_TRY
  214534. {
  214535. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214536. inputBuffers.getNumChannels(),
  214537. outputBuffers.getArrayOfChannels(),
  214538. outputBuffers.getNumChannels(),
  214539. bufferSizeSamples);
  214540. }
  214541. JUCE_CATCH_EXCEPTION
  214542. totalSamplesOut += bufferSizeSamples;
  214543. }
  214544. else
  214545. {
  214546. outputBuffers.clear();
  214547. totalSamplesOut = 0;
  214548. sleep (1);
  214549. }
  214550. }
  214551. }
  214552. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214553. };
  214554. class DSoundAudioIODeviceType : public AudioIODeviceType
  214555. {
  214556. public:
  214557. DSoundAudioIODeviceType()
  214558. : AudioIODeviceType ("DirectSound"),
  214559. hasScanned (false)
  214560. {
  214561. initialiseDSoundFunctions();
  214562. }
  214563. void scanForDevices()
  214564. {
  214565. hasScanned = true;
  214566. outputDeviceNames.clear();
  214567. outputGuids.clear();
  214568. inputDeviceNames.clear();
  214569. inputGuids.clear();
  214570. if (dsDirectSoundEnumerateW != 0)
  214571. {
  214572. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214573. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214574. }
  214575. }
  214576. const StringArray getDeviceNames (bool wantInputNames) const
  214577. {
  214578. jassert (hasScanned); // need to call scanForDevices() before doing this
  214579. return wantInputNames ? inputDeviceNames
  214580. : outputDeviceNames;
  214581. }
  214582. int getDefaultDeviceIndex (bool /*forInput*/) const
  214583. {
  214584. jassert (hasScanned); // need to call scanForDevices() before doing this
  214585. return 0;
  214586. }
  214587. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214588. {
  214589. jassert (hasScanned); // need to call scanForDevices() before doing this
  214590. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214591. if (d == 0)
  214592. return -1;
  214593. return asInput ? d->inputDeviceIndex
  214594. : d->outputDeviceIndex;
  214595. }
  214596. bool hasSeparateInputsAndOutputs() const { return true; }
  214597. AudioIODevice* createDevice (const String& outputDeviceName,
  214598. const String& inputDeviceName)
  214599. {
  214600. jassert (hasScanned); // need to call scanForDevices() before doing this
  214601. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214602. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214603. if (outputIndex >= 0 || inputIndex >= 0)
  214604. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214605. : inputDeviceName,
  214606. outputIndex, inputIndex);
  214607. return 0;
  214608. }
  214609. StringArray outputDeviceNames, inputDeviceNames;
  214610. OwnedArray <GUID> outputGuids, inputGuids;
  214611. private:
  214612. bool hasScanned;
  214613. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214614. {
  214615. desc = desc.trim();
  214616. if (desc.isNotEmpty())
  214617. {
  214618. const String origDesc (desc);
  214619. int n = 2;
  214620. while (outputDeviceNames.contains (desc))
  214621. desc = origDesc + " (" + String (n++) + ")";
  214622. outputDeviceNames.add (desc);
  214623. if (lpGUID != 0)
  214624. outputGuids.add (new GUID (*lpGUID));
  214625. else
  214626. outputGuids.add (0);
  214627. }
  214628. return TRUE;
  214629. }
  214630. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214631. {
  214632. return ((DSoundAudioIODeviceType*) object)
  214633. ->outputEnumProc (lpGUID, String (description));
  214634. }
  214635. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214636. {
  214637. return ((DSoundAudioIODeviceType*) object)
  214638. ->outputEnumProc (lpGUID, String (description));
  214639. }
  214640. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214641. {
  214642. desc = desc.trim();
  214643. if (desc.isNotEmpty())
  214644. {
  214645. const String origDesc (desc);
  214646. int n = 2;
  214647. while (inputDeviceNames.contains (desc))
  214648. desc = origDesc + " (" + String (n++) + ")";
  214649. inputDeviceNames.add (desc);
  214650. if (lpGUID != 0)
  214651. inputGuids.add (new GUID (*lpGUID));
  214652. else
  214653. inputGuids.add (0);
  214654. }
  214655. return TRUE;
  214656. }
  214657. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214658. {
  214659. return ((DSoundAudioIODeviceType*) object)
  214660. ->inputEnumProc (lpGUID, String (description));
  214661. }
  214662. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214663. {
  214664. return ((DSoundAudioIODeviceType*) object)
  214665. ->inputEnumProc (lpGUID, String (description));
  214666. }
  214667. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214668. };
  214669. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214670. const BigInteger& outputChannels,
  214671. double sampleRate_, int bufferSizeSamples_)
  214672. {
  214673. closeDevice();
  214674. totalSamplesOut = 0;
  214675. sampleRate = sampleRate_;
  214676. if (bufferSizeSamples_ <= 0)
  214677. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214678. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214679. DSoundAudioIODeviceType dlh;
  214680. dlh.scanForDevices();
  214681. enabledInputs = inputChannels;
  214682. enabledInputs.setRange (inChannels.size(),
  214683. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214684. false);
  214685. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214686. inputBuffers.clear();
  214687. int i, numIns = 0;
  214688. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214689. {
  214690. float* left = 0;
  214691. if (enabledInputs[i])
  214692. left = inputBuffers.getSampleData (numIns++);
  214693. float* right = 0;
  214694. if (enabledInputs[i + 1])
  214695. right = inputBuffers.getSampleData (numIns++);
  214696. if (left != 0 || right != 0)
  214697. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214698. dlh.inputGuids [inputDeviceIndex],
  214699. (int) sampleRate, bufferSizeSamples,
  214700. left, right));
  214701. }
  214702. enabledOutputs = outputChannels;
  214703. enabledOutputs.setRange (outChannels.size(),
  214704. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214705. false);
  214706. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214707. outputBuffers.clear();
  214708. int numOuts = 0;
  214709. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214710. {
  214711. float* left = 0;
  214712. if (enabledOutputs[i])
  214713. left = outputBuffers.getSampleData (numOuts++);
  214714. float* right = 0;
  214715. if (enabledOutputs[i + 1])
  214716. right = outputBuffers.getSampleData (numOuts++);
  214717. if (left != 0 || right != 0)
  214718. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214719. dlh.outputGuids [outputDeviceIndex],
  214720. (int) sampleRate, bufferSizeSamples,
  214721. left, right));
  214722. }
  214723. String error;
  214724. // boost our priority while opening the devices to try to get better sync between them
  214725. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214726. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214727. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214728. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214729. for (i = 0; i < outChans.size(); ++i)
  214730. {
  214731. error = outChans[i]->open();
  214732. if (error.isNotEmpty())
  214733. {
  214734. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214735. break;
  214736. }
  214737. }
  214738. if (error.isEmpty())
  214739. {
  214740. for (i = 0; i < inChans.size(); ++i)
  214741. {
  214742. error = inChans[i]->open();
  214743. if (error.isNotEmpty())
  214744. {
  214745. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214746. break;
  214747. }
  214748. }
  214749. }
  214750. if (error.isEmpty())
  214751. {
  214752. totalSamplesOut = 0;
  214753. for (i = 0; i < outChans.size(); ++i)
  214754. outChans.getUnchecked(i)->synchronisePosition();
  214755. for (i = 0; i < inChans.size(); ++i)
  214756. inChans.getUnchecked(i)->synchronisePosition();
  214757. startThread (9);
  214758. sleep (10);
  214759. notify();
  214760. }
  214761. else
  214762. {
  214763. log (error);
  214764. }
  214765. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214766. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214767. return error;
  214768. }
  214769. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214770. {
  214771. return new DSoundAudioIODeviceType();
  214772. }
  214773. #undef log
  214774. #endif
  214775. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214776. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214777. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214778. // compiled on its own).
  214779. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214780. #ifndef WASAPI_ENABLE_LOGGING
  214781. #define WASAPI_ENABLE_LOGGING 0
  214782. #endif
  214783. namespace WasapiClasses
  214784. {
  214785. void logFailure (HRESULT hr)
  214786. {
  214787. (void) hr;
  214788. #if WASAPI_ENABLE_LOGGING
  214789. if (FAILED (hr))
  214790. {
  214791. String e;
  214792. e << Time::getCurrentTime().toString (true, true, true, true)
  214793. << " -- WASAPI error: ";
  214794. switch (hr)
  214795. {
  214796. case E_POINTER: e << "E_POINTER"; break;
  214797. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  214798. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  214799. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214800. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214801. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214802. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  214803. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214804. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  214805. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214806. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  214807. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  214808. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214809. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214810. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214811. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214812. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214813. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214814. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214815. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214816. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214817. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214818. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214819. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  214820. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214821. default: e << String::toHexString ((int) hr); break;
  214822. }
  214823. DBG (e);
  214824. jassertfalse;
  214825. }
  214826. #endif
  214827. }
  214828. #undef check
  214829. bool check (HRESULT hr)
  214830. {
  214831. logFailure (hr);
  214832. return SUCCEEDED (hr);
  214833. }
  214834. const String getDeviceID (IMMDevice* const device)
  214835. {
  214836. String s;
  214837. WCHAR* deviceId = 0;
  214838. if (check (device->GetId (&deviceId)))
  214839. {
  214840. s = String (deviceId);
  214841. CoTaskMemFree (deviceId);
  214842. }
  214843. return s;
  214844. }
  214845. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  214846. {
  214847. EDataFlow flow = eRender;
  214848. ComSmartPtr <IMMEndpoint> endPoint;
  214849. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  214850. (void) check (endPoint->GetDataFlow (&flow));
  214851. return flow;
  214852. }
  214853. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214854. {
  214855. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214856. }
  214857. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214858. {
  214859. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214860. : sizeof (WAVEFORMATEX));
  214861. }
  214862. class WASAPIDeviceBase
  214863. {
  214864. public:
  214865. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214866. : device (device_),
  214867. sampleRate (0),
  214868. numChannels (0),
  214869. actualNumChannels (0),
  214870. defaultSampleRate (0),
  214871. minBufferSize (0),
  214872. defaultBufferSize (0),
  214873. latencySamples (0),
  214874. useExclusiveMode (useExclusiveMode_)
  214875. {
  214876. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214877. ComSmartPtr <IAudioClient> tempClient (createClient());
  214878. if (tempClient == 0)
  214879. return;
  214880. REFERENCE_TIME defaultPeriod, minPeriod;
  214881. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214882. return;
  214883. WAVEFORMATEX* mixFormat = 0;
  214884. if (! check (tempClient->GetMixFormat (&mixFormat)))
  214885. return;
  214886. WAVEFORMATEXTENSIBLE format;
  214887. copyWavFormat (format, mixFormat);
  214888. CoTaskMemFree (mixFormat);
  214889. actualNumChannels = numChannels = format.Format.nChannels;
  214890. defaultSampleRate = format.Format.nSamplesPerSec;
  214891. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  214892. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  214893. rates.addUsingDefaultSort (defaultSampleRate);
  214894. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214895. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214896. {
  214897. if (ratesToTest[i] == defaultSampleRate)
  214898. continue;
  214899. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214900. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214901. (WAVEFORMATEX*) &format, 0)))
  214902. if (! rates.contains (ratesToTest[i]))
  214903. rates.addUsingDefaultSort (ratesToTest[i]);
  214904. }
  214905. }
  214906. ~WASAPIDeviceBase()
  214907. {
  214908. device = 0;
  214909. CloseHandle (clientEvent);
  214910. }
  214911. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214912. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214913. {
  214914. sampleRate = newSampleRate;
  214915. channels = newChannels;
  214916. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214917. numChannels = channels.getHighestBit() + 1;
  214918. if (numChannels == 0)
  214919. return true;
  214920. client = createClient();
  214921. if (client != 0
  214922. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214923. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214924. {
  214925. channelMaps.clear();
  214926. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214927. if (channels[i])
  214928. channelMaps.add (i);
  214929. REFERENCE_TIME latency;
  214930. if (check (client->GetStreamLatency (&latency)))
  214931. latencySamples = refTimeToSamples (latency, sampleRate);
  214932. (void) check (client->GetBufferSize (&actualBufferSize));
  214933. return check (client->SetEventHandle (clientEvent));
  214934. }
  214935. return false;
  214936. }
  214937. void closeClient()
  214938. {
  214939. if (client != 0)
  214940. client->Stop();
  214941. client = 0;
  214942. ResetEvent (clientEvent);
  214943. }
  214944. ComSmartPtr <IMMDevice> device;
  214945. ComSmartPtr <IAudioClient> client;
  214946. double sampleRate, defaultSampleRate;
  214947. int numChannels, actualNumChannels;
  214948. int minBufferSize, defaultBufferSize, latencySamples;
  214949. const bool useExclusiveMode;
  214950. Array <double> rates;
  214951. HANDLE clientEvent;
  214952. BigInteger channels;
  214953. Array <int> channelMaps;
  214954. UINT32 actualBufferSize;
  214955. int bytesPerSample;
  214956. virtual void updateFormat (bool isFloat) = 0;
  214957. private:
  214958. const ComSmartPtr <IAudioClient> createClient()
  214959. {
  214960. ComSmartPtr <IAudioClient> client;
  214961. if (device != 0)
  214962. {
  214963. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  214964. logFailure (hr);
  214965. }
  214966. return client;
  214967. }
  214968. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214969. {
  214970. WAVEFORMATEXTENSIBLE format;
  214971. zerostruct (format);
  214972. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214973. {
  214974. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214975. }
  214976. else
  214977. {
  214978. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214979. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214980. }
  214981. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214982. format.Format.nChannels = (WORD) numChannels;
  214983. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214984. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214985. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214986. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214987. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214988. switch (numChannels)
  214989. {
  214990. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214991. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214992. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214993. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214994. 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;
  214995. default: break;
  214996. }
  214997. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214998. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214999. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215000. logFailure (hr);
  215001. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215002. {
  215003. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215004. hr = S_OK;
  215005. }
  215006. CoTaskMemFree (nearestFormat);
  215007. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215008. if (useExclusiveMode)
  215009. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215010. GUID session;
  215011. if (hr == S_OK
  215012. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215013. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215014. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215015. {
  215016. actualNumChannels = format.Format.nChannels;
  215017. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215018. bytesPerSample = format.Format.wBitsPerSample / 8;
  215019. updateFormat (isFloat);
  215020. return true;
  215021. }
  215022. return false;
  215023. }
  215024. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  215025. };
  215026. class WASAPIInputDevice : public WASAPIDeviceBase
  215027. {
  215028. public:
  215029. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215030. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215031. reservoir (1, 1)
  215032. {
  215033. }
  215034. ~WASAPIInputDevice()
  215035. {
  215036. close();
  215037. }
  215038. bool open (const double newSampleRate, const BigInteger& newChannels)
  215039. {
  215040. reservoirSize = 0;
  215041. reservoirCapacity = 16384;
  215042. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215043. return openClient (newSampleRate, newChannels)
  215044. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  215045. (void**) captureClient.resetAndGetPointerAddress())));
  215046. }
  215047. void close()
  215048. {
  215049. closeClient();
  215050. captureClient = 0;
  215051. reservoir.setSize (0);
  215052. }
  215053. template <class SourceType>
  215054. void updateFormatWithType (SourceType*)
  215055. {
  215056. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215057. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215058. }
  215059. void updateFormat (bool isFloat)
  215060. {
  215061. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215062. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215063. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215064. else updateFormatWithType ((AudioData::Int16*) 0);
  215065. }
  215066. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215067. {
  215068. if (numChannels <= 0)
  215069. return;
  215070. int offset = 0;
  215071. while (bufferSize > 0)
  215072. {
  215073. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215074. {
  215075. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215076. for (int i = 0; i < numDestBuffers; ++i)
  215077. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215078. bufferSize -= samplesToDo;
  215079. offset += samplesToDo;
  215080. reservoirSize = 0;
  215081. }
  215082. else
  215083. {
  215084. UINT32 packetLength = 0;
  215085. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215086. break;
  215087. if (packetLength == 0)
  215088. {
  215089. if (thread.threadShouldExit()
  215090. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215091. break;
  215092. continue;
  215093. }
  215094. uint8* inputData;
  215095. UINT32 numSamplesAvailable;
  215096. DWORD flags;
  215097. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215098. {
  215099. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215100. for (int i = 0; i < numDestBuffers; ++i)
  215101. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215102. bufferSize -= samplesToDo;
  215103. offset += samplesToDo;
  215104. if (samplesToDo < (int) numSamplesAvailable)
  215105. {
  215106. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215107. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215108. bytesPerSample * actualNumChannels * reservoirSize);
  215109. }
  215110. captureClient->ReleaseBuffer (numSamplesAvailable);
  215111. }
  215112. }
  215113. }
  215114. }
  215115. ComSmartPtr <IAudioCaptureClient> captureClient;
  215116. MemoryBlock reservoir;
  215117. int reservoirSize, reservoirCapacity;
  215118. ScopedPointer <AudioData::Converter> converter;
  215119. private:
  215120. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  215121. };
  215122. class WASAPIOutputDevice : public WASAPIDeviceBase
  215123. {
  215124. public:
  215125. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215126. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215127. {
  215128. }
  215129. ~WASAPIOutputDevice()
  215130. {
  215131. close();
  215132. }
  215133. bool open (const double newSampleRate, const BigInteger& newChannels)
  215134. {
  215135. return openClient (newSampleRate, newChannels)
  215136. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215137. }
  215138. void close()
  215139. {
  215140. closeClient();
  215141. renderClient = 0;
  215142. }
  215143. template <class DestType>
  215144. void updateFormatWithType (DestType*)
  215145. {
  215146. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215147. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215148. }
  215149. void updateFormat (bool isFloat)
  215150. {
  215151. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215152. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215153. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215154. else updateFormatWithType ((AudioData::Int16*) 0);
  215155. }
  215156. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215157. {
  215158. if (numChannels <= 0)
  215159. return;
  215160. int offset = 0;
  215161. while (bufferSize > 0)
  215162. {
  215163. UINT32 padding = 0;
  215164. if (! check (client->GetCurrentPadding (&padding)))
  215165. return;
  215166. int samplesToDo = useExclusiveMode ? bufferSize
  215167. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215168. if (samplesToDo <= 0)
  215169. {
  215170. if (thread.threadShouldExit()
  215171. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215172. break;
  215173. continue;
  215174. }
  215175. uint8* outputData = 0;
  215176. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215177. {
  215178. for (int i = 0; i < numSrcBuffers; ++i)
  215179. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  215180. renderClient->ReleaseBuffer (samplesToDo, 0);
  215181. offset += samplesToDo;
  215182. bufferSize -= samplesToDo;
  215183. }
  215184. }
  215185. }
  215186. ComSmartPtr <IAudioRenderClient> renderClient;
  215187. ScopedPointer <AudioData::Converter> converter;
  215188. private:
  215189. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  215190. };
  215191. class WASAPIAudioIODevice : public AudioIODevice,
  215192. public Thread
  215193. {
  215194. public:
  215195. WASAPIAudioIODevice (const String& deviceName,
  215196. const String& outputDeviceId_,
  215197. const String& inputDeviceId_,
  215198. const bool useExclusiveMode_)
  215199. : AudioIODevice (deviceName, "Windows Audio"),
  215200. Thread ("Juce WASAPI"),
  215201. isOpen_ (false),
  215202. isStarted (false),
  215203. outputDeviceId (outputDeviceId_),
  215204. inputDeviceId (inputDeviceId_),
  215205. useExclusiveMode (useExclusiveMode_),
  215206. currentBufferSizeSamples (0),
  215207. currentSampleRate (0),
  215208. callback (0)
  215209. {
  215210. }
  215211. ~WASAPIAudioIODevice()
  215212. {
  215213. close();
  215214. }
  215215. bool initialise()
  215216. {
  215217. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215218. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215219. latencyIn = latencyOut = 0;
  215220. Array <double> ratesIn, ratesOut;
  215221. if (createDevices())
  215222. {
  215223. jassert (inputDevice != 0 || outputDevice != 0);
  215224. if (inputDevice != 0 && outputDevice != 0)
  215225. {
  215226. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215227. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215228. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215229. sampleRates = inputDevice->rates;
  215230. sampleRates.removeValuesNotIn (outputDevice->rates);
  215231. }
  215232. else
  215233. {
  215234. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215235. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215236. defaultSampleRate = d->defaultSampleRate;
  215237. minBufferSize = d->minBufferSize;
  215238. defaultBufferSize = d->defaultBufferSize;
  215239. sampleRates = d->rates;
  215240. }
  215241. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215242. if (minBufferSize != defaultBufferSize)
  215243. bufferSizes.addUsingDefaultSort (minBufferSize);
  215244. int n = 64;
  215245. for (int i = 0; i < 40; ++i)
  215246. {
  215247. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215248. bufferSizes.addUsingDefaultSort (n);
  215249. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215250. }
  215251. return true;
  215252. }
  215253. return false;
  215254. }
  215255. const StringArray getOutputChannelNames()
  215256. {
  215257. StringArray outChannels;
  215258. if (outputDevice != 0)
  215259. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215260. outChannels.add ("Output channel " + String (i));
  215261. return outChannels;
  215262. }
  215263. const StringArray getInputChannelNames()
  215264. {
  215265. StringArray inChannels;
  215266. if (inputDevice != 0)
  215267. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215268. inChannels.add ("Input channel " + String (i));
  215269. return inChannels;
  215270. }
  215271. int getNumSampleRates() { return sampleRates.size(); }
  215272. double getSampleRate (int index) { return sampleRates [index]; }
  215273. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215274. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215275. int getDefaultBufferSize() { return defaultBufferSize; }
  215276. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215277. double getCurrentSampleRate() { return currentSampleRate; }
  215278. int getCurrentBitDepth() { return 32; }
  215279. int getOutputLatencyInSamples() { return latencyOut; }
  215280. int getInputLatencyInSamples() { return latencyIn; }
  215281. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215282. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215283. const String getLastError() { return lastError; }
  215284. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215285. double sampleRate, int bufferSizeSamples)
  215286. {
  215287. close();
  215288. lastError = String::empty;
  215289. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215290. {
  215291. lastError = "The input and output devices don't share a common sample rate!";
  215292. return lastError;
  215293. }
  215294. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215295. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215296. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215297. {
  215298. lastError = "Couldn't open the input device!";
  215299. return lastError;
  215300. }
  215301. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215302. {
  215303. close();
  215304. lastError = "Couldn't open the output device!";
  215305. return lastError;
  215306. }
  215307. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215308. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215309. startThread (8);
  215310. Thread::sleep (5);
  215311. if (inputDevice != 0 && inputDevice->client != 0)
  215312. {
  215313. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215314. HRESULT hr = inputDevice->client->Start();
  215315. logFailure (hr); //xxx handle this
  215316. }
  215317. if (outputDevice != 0 && outputDevice->client != 0)
  215318. {
  215319. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215320. HRESULT hr = outputDevice->client->Start();
  215321. logFailure (hr); //xxx handle this
  215322. }
  215323. isOpen_ = true;
  215324. return lastError;
  215325. }
  215326. void close()
  215327. {
  215328. stop();
  215329. signalThreadShouldExit();
  215330. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215331. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215332. stopThread (5000);
  215333. if (inputDevice != 0) inputDevice->close();
  215334. if (outputDevice != 0) outputDevice->close();
  215335. isOpen_ = false;
  215336. }
  215337. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215338. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215339. void start (AudioIODeviceCallback* call)
  215340. {
  215341. if (isOpen_ && call != 0 && ! isStarted)
  215342. {
  215343. if (! isThreadRunning())
  215344. {
  215345. // something's gone wrong and the thread's stopped..
  215346. isOpen_ = false;
  215347. return;
  215348. }
  215349. call->audioDeviceAboutToStart (this);
  215350. const ScopedLock sl (startStopLock);
  215351. callback = call;
  215352. isStarted = true;
  215353. }
  215354. }
  215355. void stop()
  215356. {
  215357. if (isStarted)
  215358. {
  215359. AudioIODeviceCallback* const callbackLocal = callback;
  215360. {
  215361. const ScopedLock sl (startStopLock);
  215362. isStarted = false;
  215363. }
  215364. if (callbackLocal != 0)
  215365. callbackLocal->audioDeviceStopped();
  215366. }
  215367. }
  215368. void setMMThreadPriority()
  215369. {
  215370. DynamicLibraryLoader dll ("avrt.dll");
  215371. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215372. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215373. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215374. {
  215375. DWORD dummy = 0;
  215376. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215377. if (h != 0)
  215378. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215379. }
  215380. }
  215381. void run()
  215382. {
  215383. setMMThreadPriority();
  215384. const int bufferSize = currentBufferSizeSamples;
  215385. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215386. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215387. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215388. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215389. float** const inputBuffers = ins.getArrayOfChannels();
  215390. float** const outputBuffers = outs.getArrayOfChannels();
  215391. ins.clear();
  215392. while (! threadShouldExit())
  215393. {
  215394. if (inputDevice != 0)
  215395. {
  215396. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215397. if (threadShouldExit())
  215398. break;
  215399. }
  215400. JUCE_TRY
  215401. {
  215402. const ScopedLock sl (startStopLock);
  215403. if (isStarted)
  215404. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215405. outputBuffers, numOutputBuffers, bufferSize);
  215406. else
  215407. outs.clear();
  215408. }
  215409. JUCE_CATCH_EXCEPTION
  215410. if (outputDevice != 0)
  215411. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215412. }
  215413. }
  215414. String outputDeviceId, inputDeviceId;
  215415. String lastError;
  215416. private:
  215417. // Device stats...
  215418. ScopedPointer<WASAPIInputDevice> inputDevice;
  215419. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215420. const bool useExclusiveMode;
  215421. double defaultSampleRate;
  215422. int minBufferSize, defaultBufferSize;
  215423. int latencyIn, latencyOut;
  215424. Array <double> sampleRates;
  215425. Array <int> bufferSizes;
  215426. // Active state...
  215427. bool isOpen_, isStarted;
  215428. int currentBufferSizeSamples;
  215429. double currentSampleRate;
  215430. AudioIODeviceCallback* callback;
  215431. CriticalSection startStopLock;
  215432. bool createDevices()
  215433. {
  215434. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215435. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215436. return false;
  215437. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215438. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215439. return false;
  215440. UINT32 numDevices = 0;
  215441. if (! check (deviceCollection->GetCount (&numDevices)))
  215442. return false;
  215443. for (UINT32 i = 0; i < numDevices; ++i)
  215444. {
  215445. ComSmartPtr <IMMDevice> device;
  215446. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215447. continue;
  215448. const String deviceId (getDeviceID (device));
  215449. if (deviceId.isEmpty())
  215450. continue;
  215451. const EDataFlow flow = getDataFlow (device);
  215452. if (deviceId == inputDeviceId && flow == eCapture)
  215453. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215454. else if (deviceId == outputDeviceId && flow == eRender)
  215455. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215456. }
  215457. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215458. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215459. }
  215460. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215461. };
  215462. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215463. {
  215464. public:
  215465. WASAPIAudioIODeviceType()
  215466. : AudioIODeviceType ("Windows Audio"),
  215467. hasScanned (false)
  215468. {
  215469. }
  215470. ~WASAPIAudioIODeviceType()
  215471. {
  215472. }
  215473. void scanForDevices()
  215474. {
  215475. hasScanned = true;
  215476. outputDeviceNames.clear();
  215477. inputDeviceNames.clear();
  215478. outputDeviceIds.clear();
  215479. inputDeviceIds.clear();
  215480. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215481. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215482. return;
  215483. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215484. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215485. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215486. UINT32 numDevices = 0;
  215487. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215488. && check (deviceCollection->GetCount (&numDevices))))
  215489. return;
  215490. for (UINT32 i = 0; i < numDevices; ++i)
  215491. {
  215492. ComSmartPtr <IMMDevice> device;
  215493. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215494. continue;
  215495. const String deviceId (getDeviceID (device));
  215496. DWORD state = 0;
  215497. if (! check (device->GetState (&state)))
  215498. continue;
  215499. if (state != DEVICE_STATE_ACTIVE)
  215500. continue;
  215501. String name;
  215502. {
  215503. ComSmartPtr <IPropertyStore> properties;
  215504. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215505. continue;
  215506. PROPVARIANT value;
  215507. PropVariantInit (&value);
  215508. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215509. name = value.pwszVal;
  215510. PropVariantClear (&value);
  215511. }
  215512. const EDataFlow flow = getDataFlow (device);
  215513. if (flow == eRender)
  215514. {
  215515. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215516. outputDeviceIds.insert (index, deviceId);
  215517. outputDeviceNames.insert (index, name);
  215518. }
  215519. else if (flow == eCapture)
  215520. {
  215521. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215522. inputDeviceIds.insert (index, deviceId);
  215523. inputDeviceNames.insert (index, name);
  215524. }
  215525. }
  215526. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215527. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215528. }
  215529. const StringArray getDeviceNames (bool wantInputNames) const
  215530. {
  215531. jassert (hasScanned); // need to call scanForDevices() before doing this
  215532. return wantInputNames ? inputDeviceNames
  215533. : outputDeviceNames;
  215534. }
  215535. int getDefaultDeviceIndex (bool /*forInput*/) const
  215536. {
  215537. jassert (hasScanned); // need to call scanForDevices() before doing this
  215538. return 0;
  215539. }
  215540. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215541. {
  215542. jassert (hasScanned); // need to call scanForDevices() before doing this
  215543. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215544. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215545. : outputDeviceIds.indexOf (d->outputDeviceId));
  215546. }
  215547. bool hasSeparateInputsAndOutputs() const { return true; }
  215548. AudioIODevice* createDevice (const String& outputDeviceName,
  215549. const String& inputDeviceName)
  215550. {
  215551. jassert (hasScanned); // need to call scanForDevices() before doing this
  215552. const bool useExclusiveMode = false;
  215553. ScopedPointer<WASAPIAudioIODevice> device;
  215554. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215555. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215556. if (outputIndex >= 0 || inputIndex >= 0)
  215557. {
  215558. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215559. : inputDeviceName,
  215560. outputDeviceIds [outputIndex],
  215561. inputDeviceIds [inputIndex],
  215562. useExclusiveMode);
  215563. if (! device->initialise())
  215564. device = 0;
  215565. }
  215566. return device.release();
  215567. }
  215568. StringArray outputDeviceNames, outputDeviceIds;
  215569. StringArray inputDeviceNames, inputDeviceIds;
  215570. private:
  215571. bool hasScanned;
  215572. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215573. {
  215574. String s;
  215575. IMMDevice* dev = 0;
  215576. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215577. eMultimedia, &dev)))
  215578. {
  215579. WCHAR* deviceId = 0;
  215580. if (check (dev->GetId (&deviceId)))
  215581. {
  215582. s = String (deviceId);
  215583. CoTaskMemFree (deviceId);
  215584. }
  215585. dev->Release();
  215586. }
  215587. return s;
  215588. }
  215589. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215590. };
  215591. }
  215592. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215593. {
  215594. return new WasapiClasses::WASAPIAudioIODeviceType();
  215595. }
  215596. #endif
  215597. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215598. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215599. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215600. // compiled on its own).
  215601. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215602. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215603. {
  215604. public:
  215605. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215606. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215607. const ComSmartPtr <IBaseFilter>& filter_,
  215608. int minWidth, int minHeight,
  215609. int maxWidth, int maxHeight)
  215610. : owner (owner_),
  215611. captureGraphBuilder (captureGraphBuilder_),
  215612. filter (filter_),
  215613. ok (false),
  215614. imageNeedsFlipping (false),
  215615. width (0),
  215616. height (0),
  215617. activeUsers (0),
  215618. recordNextFrameTime (false),
  215619. previewMaxFPS (60)
  215620. {
  215621. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215622. if (FAILED (hr))
  215623. return;
  215624. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215625. if (FAILED (hr))
  215626. return;
  215627. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215628. if (FAILED (hr))
  215629. return;
  215630. {
  215631. ComSmartPtr <IAMStreamConfig> streamConfig;
  215632. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215633. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215634. if (streamConfig != 0)
  215635. {
  215636. getVideoSizes (streamConfig);
  215637. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215638. return;
  215639. }
  215640. }
  215641. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215642. if (FAILED (hr))
  215643. return;
  215644. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215645. if (FAILED (hr))
  215646. return;
  215647. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215648. if (FAILED (hr))
  215649. return;
  215650. if (! connectFilters (filter, smartTee))
  215651. return;
  215652. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215653. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215654. if (FAILED (hr))
  215655. return;
  215656. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215657. if (FAILED (hr))
  215658. return;
  215659. AM_MEDIA_TYPE mt;
  215660. zerostruct (mt);
  215661. mt.majortype = MEDIATYPE_Video;
  215662. mt.subtype = MEDIASUBTYPE_RGB24;
  215663. mt.formattype = FORMAT_VideoInfo;
  215664. sampleGrabber->SetMediaType (&mt);
  215665. callback = new GrabberCallback (*this);
  215666. hr = sampleGrabber->SetCallback (callback, 1);
  215667. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215668. if (FAILED (hr))
  215669. return;
  215670. ComSmartPtr <IPin> grabberInputPin;
  215671. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215672. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215673. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215674. return;
  215675. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215676. if (FAILED (hr))
  215677. return;
  215678. zerostruct (mt);
  215679. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215680. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215681. width = pVih->bmiHeader.biWidth;
  215682. height = pVih->bmiHeader.biHeight;
  215683. ComSmartPtr <IBaseFilter> nullFilter;
  215684. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215685. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215686. if (connectFilters (sampleGrabberBase, nullFilter)
  215687. && addGraphToRot())
  215688. {
  215689. activeImage = Image (Image::RGB, width, height, true);
  215690. loadingImage = Image (Image::RGB, width, height, true);
  215691. ok = true;
  215692. }
  215693. }
  215694. ~DShowCameraDeviceInteral()
  215695. {
  215696. if (mediaControl != 0)
  215697. mediaControl->Stop();
  215698. removeGraphFromRot();
  215699. for (int i = viewerComps.size(); --i >= 0;)
  215700. viewerComps.getUnchecked(i)->ownerDeleted();
  215701. callback = 0;
  215702. graphBuilder = 0;
  215703. sampleGrabber = 0;
  215704. mediaControl = 0;
  215705. filter = 0;
  215706. captureGraphBuilder = 0;
  215707. smartTee = 0;
  215708. smartTeePreviewOutputPin = 0;
  215709. smartTeeCaptureOutputPin = 0;
  215710. asfWriter = 0;
  215711. }
  215712. void addUser()
  215713. {
  215714. if (ok && activeUsers++ == 0)
  215715. mediaControl->Run();
  215716. }
  215717. void removeUser()
  215718. {
  215719. if (ok && --activeUsers == 0)
  215720. mediaControl->Stop();
  215721. }
  215722. int getPreviewMaxFPS() const
  215723. {
  215724. return previewMaxFPS;
  215725. }
  215726. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215727. {
  215728. if (recordNextFrameTime)
  215729. {
  215730. const double defaultCameraLatency = 0.1;
  215731. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215732. recordNextFrameTime = false;
  215733. ComSmartPtr <IPin> pin;
  215734. if (getPin (filter, PINDIR_OUTPUT, pin))
  215735. {
  215736. ComSmartPtr <IAMPushSource> pushSource;
  215737. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  215738. if (pushSource != 0)
  215739. {
  215740. REFERENCE_TIME latency = 0;
  215741. hr = pushSource->GetLatency (&latency);
  215742. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215743. }
  215744. }
  215745. }
  215746. {
  215747. const int lineStride = width * 3;
  215748. const ScopedLock sl (imageSwapLock);
  215749. {
  215750. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215751. for (int i = 0; i < height; ++i)
  215752. memcpy (destData.getLinePointer ((height - 1) - i),
  215753. buffer + lineStride * i,
  215754. lineStride);
  215755. }
  215756. imageNeedsFlipping = true;
  215757. }
  215758. if (listeners.size() > 0)
  215759. callListeners (loadingImage);
  215760. sendChangeMessage();
  215761. }
  215762. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215763. {
  215764. if (imageNeedsFlipping)
  215765. {
  215766. const ScopedLock sl (imageSwapLock);
  215767. swapVariables (loadingImage, activeImage);
  215768. imageNeedsFlipping = false;
  215769. }
  215770. RectanglePlacement rp (RectanglePlacement::centred);
  215771. double dx = 0, dy = 0, dw = width, dh = height;
  215772. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215773. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215774. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215775. {
  215776. Graphics::ScopedSaveState ss (g);
  215777. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215778. g.fillAll (Colours::black);
  215779. }
  215780. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215781. }
  215782. bool createFileCaptureFilter (const File& file, int quality)
  215783. {
  215784. removeFileCaptureFilter();
  215785. file.deleteFile();
  215786. mediaControl->Stop();
  215787. firstRecordedTime = Time();
  215788. recordNextFrameTime = true;
  215789. previewMaxFPS = 60;
  215790. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215791. if (SUCCEEDED (hr))
  215792. {
  215793. ComSmartPtr <IFileSinkFilter> fileSink;
  215794. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  215795. if (SUCCEEDED (hr))
  215796. {
  215797. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  215798. if (SUCCEEDED (hr))
  215799. {
  215800. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215801. if (SUCCEEDED (hr))
  215802. {
  215803. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215804. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  215805. asfConfig->SetIndexMode (true);
  215806. ComSmartPtr <IWMProfileManager> profileManager;
  215807. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  215808. // This gibberish is the DirectShow profile for a video-only wmv file.
  215809. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  215810. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  215811. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215812. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  215813. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215814. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  215815. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  215816. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  215817. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215818. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215819. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215820. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  215821. "biclrused=\"0\" biclrimportant=\"0\"/>"
  215822. "</videoinfoheader>"
  215823. "</wmmediatype>"
  215824. "</streamconfig>"
  215825. "</profile>");
  215826. const int fps[] = { 10, 15, 30 };
  215827. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  215828. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215829. maxFramesPerSecond = (quality >> 24) & 0xff;
  215830. prof = prof.replace ("$WIDTH", String (width))
  215831. .replace ("$HEIGHT", String (height))
  215832. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  215833. ComSmartPtr <IWMProfile> currentProfile;
  215834. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  215835. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215836. if (SUCCEEDED (hr))
  215837. {
  215838. ComSmartPtr <IPin> asfWriterInputPin;
  215839. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  215840. {
  215841. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215842. if (SUCCEEDED (hr) && ok && activeUsers > 0
  215843. && SUCCEEDED (mediaControl->Run()))
  215844. {
  215845. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  215846. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215847. previewMaxFPS = (quality >> 16) & 0xff;
  215848. return true;
  215849. }
  215850. }
  215851. }
  215852. }
  215853. }
  215854. }
  215855. }
  215856. removeFileCaptureFilter();
  215857. if (ok && activeUsers > 0)
  215858. mediaControl->Run();
  215859. return false;
  215860. }
  215861. void removeFileCaptureFilter()
  215862. {
  215863. mediaControl->Stop();
  215864. if (asfWriter != 0)
  215865. {
  215866. graphBuilder->RemoveFilter (asfWriter);
  215867. asfWriter = 0;
  215868. }
  215869. if (ok && activeUsers > 0)
  215870. mediaControl->Run();
  215871. previewMaxFPS = 60;
  215872. }
  215873. void addListener (CameraDevice::Listener* listenerToAdd)
  215874. {
  215875. const ScopedLock sl (listenerLock);
  215876. if (listeners.size() == 0)
  215877. addUser();
  215878. listeners.addIfNotAlreadyThere (listenerToAdd);
  215879. }
  215880. void removeListener (CameraDevice::Listener* listenerToRemove)
  215881. {
  215882. const ScopedLock sl (listenerLock);
  215883. listeners.removeValue (listenerToRemove);
  215884. if (listeners.size() == 0)
  215885. removeUser();
  215886. }
  215887. void callListeners (const Image& image)
  215888. {
  215889. const ScopedLock sl (listenerLock);
  215890. for (int i = listeners.size(); --i >= 0;)
  215891. {
  215892. CameraDevice::Listener* const l = listeners[i];
  215893. if (l != 0)
  215894. l->imageReceived (image);
  215895. }
  215896. }
  215897. class DShowCaptureViewerComp : public Component,
  215898. public ChangeListener
  215899. {
  215900. public:
  215901. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215902. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  215903. {
  215904. setOpaque (true);
  215905. owner->addChangeListener (this);
  215906. owner->addUser();
  215907. owner->viewerComps.add (this);
  215908. setSize (owner->width, owner->height);
  215909. }
  215910. ~DShowCaptureViewerComp()
  215911. {
  215912. if (owner != 0)
  215913. {
  215914. owner->viewerComps.removeValue (this);
  215915. owner->removeUser();
  215916. owner->removeChangeListener (this);
  215917. }
  215918. }
  215919. void ownerDeleted()
  215920. {
  215921. owner = 0;
  215922. }
  215923. void paint (Graphics& g)
  215924. {
  215925. g.setColour (Colours::black);
  215926. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215927. if (owner != 0)
  215928. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215929. else
  215930. g.fillAll (Colours::black);
  215931. }
  215932. void changeListenerCallback (ChangeBroadcaster*)
  215933. {
  215934. const int64 now = Time::currentTimeMillis();
  215935. if (now >= lastRepaintTime + (1000 / maxFPS))
  215936. {
  215937. lastRepaintTime = now;
  215938. repaint();
  215939. if (owner != 0)
  215940. maxFPS = owner->getPreviewMaxFPS();
  215941. }
  215942. }
  215943. private:
  215944. DShowCameraDeviceInteral* owner;
  215945. int maxFPS;
  215946. int64 lastRepaintTime;
  215947. };
  215948. bool ok;
  215949. int width, height;
  215950. Time firstRecordedTime;
  215951. Array <DShowCaptureViewerComp*> viewerComps;
  215952. private:
  215953. CameraDevice* const owner;
  215954. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215955. ComSmartPtr <IBaseFilter> filter;
  215956. ComSmartPtr <IBaseFilter> smartTee;
  215957. ComSmartPtr <IGraphBuilder> graphBuilder;
  215958. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215959. ComSmartPtr <IMediaControl> mediaControl;
  215960. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215961. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215962. ComSmartPtr <IBaseFilter> asfWriter;
  215963. int activeUsers;
  215964. Array <int> widths, heights;
  215965. DWORD graphRegistrationID;
  215966. CriticalSection imageSwapLock;
  215967. bool imageNeedsFlipping;
  215968. Image loadingImage;
  215969. Image activeImage;
  215970. bool recordNextFrameTime;
  215971. int previewMaxFPS;
  215972. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215973. {
  215974. widths.clear();
  215975. heights.clear();
  215976. int count = 0, size = 0;
  215977. streamConfig->GetNumberOfCapabilities (&count, &size);
  215978. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215979. {
  215980. for (int i = 0; i < count; ++i)
  215981. {
  215982. VIDEO_STREAM_CONFIG_CAPS scc;
  215983. AM_MEDIA_TYPE* config;
  215984. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215985. if (SUCCEEDED (hr))
  215986. {
  215987. const int w = scc.InputSize.cx;
  215988. const int h = scc.InputSize.cy;
  215989. bool duplicate = false;
  215990. for (int j = widths.size(); --j >= 0;)
  215991. {
  215992. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215993. {
  215994. duplicate = true;
  215995. break;
  215996. }
  215997. }
  215998. if (! duplicate)
  215999. {
  216000. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216001. widths.add (w);
  216002. heights.add (h);
  216003. }
  216004. deleteMediaType (config);
  216005. }
  216006. }
  216007. }
  216008. }
  216009. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216010. const int minWidth, const int minHeight,
  216011. const int maxWidth, const int maxHeight)
  216012. {
  216013. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216014. streamConfig->GetNumberOfCapabilities (&count, &size);
  216015. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216016. {
  216017. AM_MEDIA_TYPE* config;
  216018. VIDEO_STREAM_CONFIG_CAPS scc;
  216019. for (int i = 0; i < count; ++i)
  216020. {
  216021. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216022. if (SUCCEEDED (hr))
  216023. {
  216024. if (scc.InputSize.cx >= minWidth
  216025. && scc.InputSize.cy >= minHeight
  216026. && scc.InputSize.cx <= maxWidth
  216027. && scc.InputSize.cy <= maxHeight)
  216028. {
  216029. int area = scc.InputSize.cx * scc.InputSize.cy;
  216030. if (area > bestArea)
  216031. {
  216032. bestIndex = i;
  216033. bestArea = area;
  216034. }
  216035. }
  216036. deleteMediaType (config);
  216037. }
  216038. }
  216039. if (bestIndex >= 0)
  216040. {
  216041. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216042. hr = streamConfig->SetFormat (config);
  216043. deleteMediaType (config);
  216044. return SUCCEEDED (hr);
  216045. }
  216046. }
  216047. return false;
  216048. }
  216049. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216050. {
  216051. ComSmartPtr <IEnumPins> enumerator;
  216052. ComSmartPtr <IPin> pin;
  216053. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216054. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216055. {
  216056. PIN_DIRECTION dir;
  216057. pin->QueryDirection (&dir);
  216058. if (wantedDirection == dir)
  216059. {
  216060. PIN_INFO info;
  216061. zerostruct (info);
  216062. pin->QueryPinInfo (&info);
  216063. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216064. {
  216065. result = pin;
  216066. return true;
  216067. }
  216068. }
  216069. }
  216070. return false;
  216071. }
  216072. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216073. {
  216074. ComSmartPtr <IPin> in, out;
  216075. return getPin (first, PINDIR_OUTPUT, out)
  216076. && getPin (second, PINDIR_INPUT, in)
  216077. && SUCCEEDED (graphBuilder->Connect (out, in));
  216078. }
  216079. bool addGraphToRot()
  216080. {
  216081. ComSmartPtr <IRunningObjectTable> rot;
  216082. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216083. return false;
  216084. ComSmartPtr <IMoniker> moniker;
  216085. WCHAR buffer[128];
  216086. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216087. if (FAILED (hr))
  216088. return false;
  216089. graphRegistrationID = 0;
  216090. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216091. }
  216092. void removeGraphFromRot()
  216093. {
  216094. ComSmartPtr <IRunningObjectTable> rot;
  216095. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216096. rot->Revoke (graphRegistrationID);
  216097. }
  216098. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216099. {
  216100. if (pmt->cbFormat != 0)
  216101. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216102. if (pmt->pUnk != 0)
  216103. pmt->pUnk->Release();
  216104. CoTaskMemFree (pmt);
  216105. }
  216106. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216107. {
  216108. public:
  216109. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216110. : owner (owner_)
  216111. {
  216112. }
  216113. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216114. {
  216115. return E_FAIL;
  216116. }
  216117. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216118. {
  216119. owner.handleFrame (time, buffer, bufferSize);
  216120. return S_OK;
  216121. }
  216122. private:
  216123. DShowCameraDeviceInteral& owner;
  216124. GrabberCallback (const GrabberCallback&);
  216125. GrabberCallback& operator= (const GrabberCallback&);
  216126. };
  216127. ComSmartPtr <GrabberCallback> callback;
  216128. Array <CameraDevice::Listener*> listeners;
  216129. CriticalSection listenerLock;
  216130. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  216131. };
  216132. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216133. : name (name_)
  216134. {
  216135. isRecording = false;
  216136. }
  216137. CameraDevice::~CameraDevice()
  216138. {
  216139. stopRecording();
  216140. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216141. internal = 0;
  216142. }
  216143. Component* CameraDevice::createViewerComponent()
  216144. {
  216145. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216146. }
  216147. const String CameraDevice::getFileExtension()
  216148. {
  216149. return ".wmv";
  216150. }
  216151. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216152. {
  216153. stopRecording();
  216154. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216155. d->addUser();
  216156. isRecording = d->createFileCaptureFilter (file, quality);
  216157. }
  216158. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216159. {
  216160. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216161. return d->firstRecordedTime;
  216162. }
  216163. void CameraDevice::stopRecording()
  216164. {
  216165. if (isRecording)
  216166. {
  216167. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216168. d->removeFileCaptureFilter();
  216169. d->removeUser();
  216170. isRecording = false;
  216171. }
  216172. }
  216173. void CameraDevice::addListener (Listener* listenerToAdd)
  216174. {
  216175. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216176. if (listenerToAdd != 0)
  216177. d->addListener (listenerToAdd);
  216178. }
  216179. void CameraDevice::removeListener (Listener* listenerToRemove)
  216180. {
  216181. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216182. if (listenerToRemove != 0)
  216183. d->removeListener (listenerToRemove);
  216184. }
  216185. namespace
  216186. {
  216187. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216188. const int deviceIndexToOpen,
  216189. String& name)
  216190. {
  216191. int index = 0;
  216192. ComSmartPtr <IBaseFilter> result;
  216193. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216194. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216195. if (SUCCEEDED (hr))
  216196. {
  216197. ComSmartPtr <IEnumMoniker> enumerator;
  216198. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216199. if (SUCCEEDED (hr) && enumerator != 0)
  216200. {
  216201. ComSmartPtr <IMoniker> moniker;
  216202. ULONG fetched;
  216203. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216204. {
  216205. ComSmartPtr <IBaseFilter> captureFilter;
  216206. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216207. if (SUCCEEDED (hr))
  216208. {
  216209. ComSmartPtr <IPropertyBag> propertyBag;
  216210. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216211. if (SUCCEEDED (hr))
  216212. {
  216213. VARIANT var;
  216214. var.vt = VT_BSTR;
  216215. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216216. propertyBag = 0;
  216217. if (SUCCEEDED (hr))
  216218. {
  216219. if (names != 0)
  216220. names->add (var.bstrVal);
  216221. if (index == deviceIndexToOpen)
  216222. {
  216223. name = var.bstrVal;
  216224. result = captureFilter;
  216225. break;
  216226. }
  216227. ++index;
  216228. }
  216229. }
  216230. }
  216231. }
  216232. }
  216233. }
  216234. return result;
  216235. }
  216236. }
  216237. const StringArray CameraDevice::getAvailableDevices()
  216238. {
  216239. StringArray devs;
  216240. String dummy;
  216241. enumerateCameras (&devs, -1, dummy);
  216242. return devs;
  216243. }
  216244. CameraDevice* CameraDevice::openDevice (int index,
  216245. int minWidth, int minHeight,
  216246. int maxWidth, int maxHeight)
  216247. {
  216248. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216249. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216250. if (SUCCEEDED (hr))
  216251. {
  216252. String name;
  216253. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216254. if (filter != 0)
  216255. {
  216256. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216257. DShowCameraDeviceInteral* const intern
  216258. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216259. minWidth, minHeight, maxWidth, maxHeight);
  216260. cam->internal = intern;
  216261. if (intern->ok)
  216262. return cam.release();
  216263. }
  216264. }
  216265. return 0;
  216266. }
  216267. #endif
  216268. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216269. #endif
  216270. // Auto-link the other win32 libs that are needed by library calls..
  216271. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216272. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216273. // Auto-links to various win32 libs that are needed by library calls..
  216274. #pragma comment(lib, "kernel32.lib")
  216275. #pragma comment(lib, "user32.lib")
  216276. #pragma comment(lib, "shell32.lib")
  216277. #pragma comment(lib, "gdi32.lib")
  216278. #pragma comment(lib, "vfw32.lib")
  216279. #pragma comment(lib, "comdlg32.lib")
  216280. #pragma comment(lib, "winmm.lib")
  216281. #pragma comment(lib, "wininet.lib")
  216282. #pragma comment(lib, "ole32.lib")
  216283. #pragma comment(lib, "oleaut32.lib")
  216284. #pragma comment(lib, "advapi32.lib")
  216285. #pragma comment(lib, "ws2_32.lib")
  216286. #pragma comment(lib, "version.lib")
  216287. #ifdef _NATIVE_WCHAR_T_DEFINED
  216288. #ifdef _DEBUG
  216289. #pragma comment(lib, "comsuppwd.lib")
  216290. #else
  216291. #pragma comment(lib, "comsuppw.lib")
  216292. #endif
  216293. #else
  216294. #ifdef _DEBUG
  216295. #pragma comment(lib, "comsuppd.lib")
  216296. #else
  216297. #pragma comment(lib, "comsupp.lib")
  216298. #endif
  216299. #endif
  216300. #if JUCE_OPENGL
  216301. #pragma comment(lib, "OpenGL32.Lib")
  216302. #pragma comment(lib, "GlU32.Lib")
  216303. #endif
  216304. #if JUCE_QUICKTIME
  216305. #pragma comment (lib, "QTMLClient.lib")
  216306. #endif
  216307. #if JUCE_USE_CAMERA
  216308. #pragma comment (lib, "Strmiids.lib")
  216309. #pragma comment (lib, "wmvcore.lib")
  216310. #endif
  216311. #if JUCE_DIRECT2D
  216312. #pragma comment (lib, "Dwrite.lib")
  216313. #pragma comment (lib, "D2d1.lib")
  216314. #endif
  216315. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216316. #endif
  216317. END_JUCE_NAMESPACE
  216318. #endif
  216319. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216320. #endif
  216321. #if JUCE_LINUX
  216322. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216323. /*
  216324. This file wraps together all the mac-specific code, so that
  216325. we can include all the native headers just once, and compile all our
  216326. platform-specific stuff in one big lump, keeping it out of the way of
  216327. the rest of the codebase.
  216328. */
  216329. #if JUCE_LINUX
  216330. #undef JUCE_BUILD_NATIVE
  216331. #define JUCE_BUILD_NATIVE 1
  216332. BEGIN_JUCE_NAMESPACE
  216333. #define JUCE_INCLUDED_FILE 1
  216334. // Now include the actual code files..
  216335. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216336. /*
  216337. This file contains posix routines that are common to both the Linux and Mac builds.
  216338. It gets included directly in the cpp files for these platforms.
  216339. */
  216340. CriticalSection::CriticalSection() throw()
  216341. {
  216342. pthread_mutexattr_t atts;
  216343. pthread_mutexattr_init (&atts);
  216344. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216345. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216346. pthread_mutex_init (&internal, &atts);
  216347. }
  216348. CriticalSection::~CriticalSection() throw()
  216349. {
  216350. pthread_mutex_destroy (&internal);
  216351. }
  216352. void CriticalSection::enter() const throw()
  216353. {
  216354. pthread_mutex_lock (&internal);
  216355. }
  216356. bool CriticalSection::tryEnter() const throw()
  216357. {
  216358. return pthread_mutex_trylock (&internal) == 0;
  216359. }
  216360. void CriticalSection::exit() const throw()
  216361. {
  216362. pthread_mutex_unlock (&internal);
  216363. }
  216364. class WaitableEventImpl
  216365. {
  216366. public:
  216367. WaitableEventImpl (const bool manualReset_)
  216368. : triggered (false),
  216369. manualReset (manualReset_)
  216370. {
  216371. pthread_cond_init (&condition, 0);
  216372. pthread_mutexattr_t atts;
  216373. pthread_mutexattr_init (&atts);
  216374. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216375. pthread_mutex_init (&mutex, &atts);
  216376. }
  216377. ~WaitableEventImpl()
  216378. {
  216379. pthread_cond_destroy (&condition);
  216380. pthread_mutex_destroy (&mutex);
  216381. }
  216382. bool wait (const int timeOutMillisecs) throw()
  216383. {
  216384. pthread_mutex_lock (&mutex);
  216385. if (! triggered)
  216386. {
  216387. if (timeOutMillisecs < 0)
  216388. {
  216389. do
  216390. {
  216391. pthread_cond_wait (&condition, &mutex);
  216392. }
  216393. while (! triggered);
  216394. }
  216395. else
  216396. {
  216397. struct timeval now;
  216398. gettimeofday (&now, 0);
  216399. struct timespec time;
  216400. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216401. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216402. if (time.tv_nsec >= 1000000000)
  216403. {
  216404. time.tv_nsec -= 1000000000;
  216405. time.tv_sec++;
  216406. }
  216407. do
  216408. {
  216409. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216410. {
  216411. pthread_mutex_unlock (&mutex);
  216412. return false;
  216413. }
  216414. }
  216415. while (! triggered);
  216416. }
  216417. }
  216418. if (! manualReset)
  216419. triggered = false;
  216420. pthread_mutex_unlock (&mutex);
  216421. return true;
  216422. }
  216423. void signal() throw()
  216424. {
  216425. pthread_mutex_lock (&mutex);
  216426. triggered = true;
  216427. pthread_cond_broadcast (&condition);
  216428. pthread_mutex_unlock (&mutex);
  216429. }
  216430. void reset() throw()
  216431. {
  216432. pthread_mutex_lock (&mutex);
  216433. triggered = false;
  216434. pthread_mutex_unlock (&mutex);
  216435. }
  216436. private:
  216437. pthread_cond_t condition;
  216438. pthread_mutex_t mutex;
  216439. bool triggered;
  216440. const bool manualReset;
  216441. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216442. };
  216443. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216444. : internal (new WaitableEventImpl (manualReset))
  216445. {
  216446. }
  216447. WaitableEvent::~WaitableEvent() throw()
  216448. {
  216449. delete static_cast <WaitableEventImpl*> (internal);
  216450. }
  216451. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216452. {
  216453. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216454. }
  216455. void WaitableEvent::signal() const throw()
  216456. {
  216457. static_cast <WaitableEventImpl*> (internal)->signal();
  216458. }
  216459. void WaitableEvent::reset() const throw()
  216460. {
  216461. static_cast <WaitableEventImpl*> (internal)->reset();
  216462. }
  216463. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216464. {
  216465. struct timespec time;
  216466. time.tv_sec = millisecs / 1000;
  216467. time.tv_nsec = (millisecs % 1000) * 1000000;
  216468. nanosleep (&time, 0);
  216469. }
  216470. const juce_wchar File::separator = '/';
  216471. const String File::separatorString ("/");
  216472. const File File::getCurrentWorkingDirectory()
  216473. {
  216474. HeapBlock<char> heapBuffer;
  216475. char localBuffer [1024];
  216476. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216477. int bufferSize = 4096;
  216478. while (cwd == 0 && errno == ERANGE)
  216479. {
  216480. heapBuffer.malloc (bufferSize);
  216481. cwd = getcwd (heapBuffer, bufferSize - 1);
  216482. bufferSize += 1024;
  216483. }
  216484. return File (String::fromUTF8 (cwd));
  216485. }
  216486. bool File::setAsCurrentWorkingDirectory() const
  216487. {
  216488. return chdir (getFullPathName().toUTF8()) == 0;
  216489. }
  216490. namespace
  216491. {
  216492. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216493. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216494. #else
  216495. typedef struct stat juce_statStruct;
  216496. #endif
  216497. bool juce_stat (const String& fileName, juce_statStruct& info)
  216498. {
  216499. return fileName.isNotEmpty()
  216500. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216501. && (stat64 (fileName.toUTF8(), &info) == 0);
  216502. #else
  216503. && (stat (fileName.toUTF8(), &info) == 0);
  216504. #endif
  216505. }
  216506. // if this file doesn't exist, find a parent of it that does..
  216507. bool juce_doStatFS (File f, struct statfs& result)
  216508. {
  216509. for (int i = 5; --i >= 0;)
  216510. {
  216511. if (f.exists())
  216512. break;
  216513. f = f.getParentDirectory();
  216514. }
  216515. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216516. }
  216517. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216518. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216519. {
  216520. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216521. {
  216522. juce_statStruct info;
  216523. const bool statOk = juce_stat (path, info);
  216524. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216525. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216526. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216527. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216528. }
  216529. if (isReadOnly != 0)
  216530. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216531. }
  216532. }
  216533. bool File::isDirectory() const
  216534. {
  216535. juce_statStruct info;
  216536. return fullPath.isEmpty()
  216537. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216538. }
  216539. bool File::exists() const
  216540. {
  216541. juce_statStruct info;
  216542. return fullPath.isNotEmpty()
  216543. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216544. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216545. #else
  216546. && (lstat (fullPath.toUTF8(), &info) == 0);
  216547. #endif
  216548. }
  216549. bool File::existsAsFile() const
  216550. {
  216551. return exists() && ! isDirectory();
  216552. }
  216553. int64 File::getSize() const
  216554. {
  216555. juce_statStruct info;
  216556. return juce_stat (fullPath, info) ? info.st_size : 0;
  216557. }
  216558. bool File::hasWriteAccess() const
  216559. {
  216560. if (exists())
  216561. return access (fullPath.toUTF8(), W_OK) == 0;
  216562. if ((! isDirectory()) && fullPath.containsChar (separator))
  216563. return getParentDirectory().hasWriteAccess();
  216564. return false;
  216565. }
  216566. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216567. {
  216568. juce_statStruct info;
  216569. if (! juce_stat (fullPath, info))
  216570. return false;
  216571. info.st_mode &= 0777; // Just permissions
  216572. if (shouldBeReadOnly)
  216573. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216574. else
  216575. // Give everybody write permission?
  216576. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216577. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216578. }
  216579. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216580. {
  216581. modificationTime = 0;
  216582. accessTime = 0;
  216583. creationTime = 0;
  216584. juce_statStruct info;
  216585. if (juce_stat (fullPath, info))
  216586. {
  216587. modificationTime = (int64) info.st_mtime * 1000;
  216588. accessTime = (int64) info.st_atime * 1000;
  216589. creationTime = (int64) info.st_ctime * 1000;
  216590. }
  216591. }
  216592. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216593. {
  216594. struct utimbuf times;
  216595. times.actime = (time_t) (accessTime / 1000);
  216596. times.modtime = (time_t) (modificationTime / 1000);
  216597. return utime (fullPath.toUTF8(), &times) == 0;
  216598. }
  216599. bool File::deleteFile() const
  216600. {
  216601. if (! exists())
  216602. return true;
  216603. else if (isDirectory())
  216604. return rmdir (fullPath.toUTF8()) == 0;
  216605. else
  216606. return remove (fullPath.toUTF8()) == 0;
  216607. }
  216608. bool File::moveInternal (const File& dest) const
  216609. {
  216610. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216611. return true;
  216612. if (hasWriteAccess() && copyInternal (dest))
  216613. {
  216614. if (deleteFile())
  216615. return true;
  216616. dest.deleteFile();
  216617. }
  216618. return false;
  216619. }
  216620. void File::createDirectoryInternal (const String& fileName) const
  216621. {
  216622. mkdir (fileName.toUTF8(), 0777);
  216623. }
  216624. int64 juce_fileSetPosition (void* handle, int64 pos)
  216625. {
  216626. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216627. return pos;
  216628. return -1;
  216629. }
  216630. void FileInputStream::openHandle()
  216631. {
  216632. totalSize = file.getSize();
  216633. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216634. if (f != -1)
  216635. fileHandle = (void*) f;
  216636. }
  216637. void FileInputStream::closeHandle()
  216638. {
  216639. if (fileHandle != 0)
  216640. {
  216641. close ((int) (pointer_sized_int) fileHandle);
  216642. fileHandle = 0;
  216643. }
  216644. }
  216645. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216646. {
  216647. if (fileHandle != 0)
  216648. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216649. return 0;
  216650. }
  216651. void FileOutputStream::openHandle()
  216652. {
  216653. if (file.exists())
  216654. {
  216655. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216656. if (f != -1)
  216657. {
  216658. currentPosition = lseek (f, 0, SEEK_END);
  216659. if (currentPosition >= 0)
  216660. fileHandle = (void*) f;
  216661. else
  216662. close (f);
  216663. }
  216664. }
  216665. else
  216666. {
  216667. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216668. if (f != -1)
  216669. fileHandle = (void*) f;
  216670. }
  216671. }
  216672. void FileOutputStream::closeHandle()
  216673. {
  216674. if (fileHandle != 0)
  216675. {
  216676. close ((int) (pointer_sized_int) fileHandle);
  216677. fileHandle = 0;
  216678. }
  216679. }
  216680. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216681. {
  216682. if (fileHandle != 0)
  216683. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216684. return 0;
  216685. }
  216686. void FileOutputStream::flushInternal()
  216687. {
  216688. if (fileHandle != 0)
  216689. fsync ((int) (pointer_sized_int) fileHandle);
  216690. }
  216691. const File juce_getExecutableFile()
  216692. {
  216693. Dl_info exeInfo;
  216694. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  216695. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216696. }
  216697. int64 File::getBytesFreeOnVolume() const
  216698. {
  216699. struct statfs buf;
  216700. if (juce_doStatFS (*this, buf))
  216701. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216702. return 0;
  216703. }
  216704. int64 File::getVolumeTotalSize() const
  216705. {
  216706. struct statfs buf;
  216707. if (juce_doStatFS (*this, buf))
  216708. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216709. return 0;
  216710. }
  216711. const String File::getVolumeLabel() const
  216712. {
  216713. #if JUCE_MAC
  216714. struct VolAttrBuf
  216715. {
  216716. u_int32_t length;
  216717. attrreference_t mountPointRef;
  216718. char mountPointSpace [MAXPATHLEN];
  216719. } attrBuf;
  216720. struct attrlist attrList;
  216721. zerostruct (attrList);
  216722. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216723. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216724. File f (*this);
  216725. for (;;)
  216726. {
  216727. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216728. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216729. (int) attrBuf.mountPointRef.attr_length);
  216730. const File parent (f.getParentDirectory());
  216731. if (f == parent)
  216732. break;
  216733. f = parent;
  216734. }
  216735. #endif
  216736. return String::empty;
  216737. }
  216738. int File::getVolumeSerialNumber() const
  216739. {
  216740. return 0; // xxx
  216741. }
  216742. void juce_runSystemCommand (const String& command)
  216743. {
  216744. int result = system (command.toUTF8());
  216745. (void) result;
  216746. }
  216747. const String juce_getOutputFromCommand (const String& command)
  216748. {
  216749. // slight bodge here, as we just pipe the output into a temp file and read it...
  216750. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216751. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216752. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216753. String result (tempFile.loadFileAsString());
  216754. tempFile.deleteFile();
  216755. return result;
  216756. }
  216757. class InterProcessLock::Pimpl
  216758. {
  216759. public:
  216760. Pimpl (const String& name, const int timeOutMillisecs)
  216761. : handle (0), refCount (1)
  216762. {
  216763. #if JUCE_MAC
  216764. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216765. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216766. #else
  216767. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216768. #endif
  216769. temp.create();
  216770. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216771. if (handle != 0)
  216772. {
  216773. struct flock fl;
  216774. zerostruct (fl);
  216775. fl.l_whence = SEEK_SET;
  216776. fl.l_type = F_WRLCK;
  216777. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216778. for (;;)
  216779. {
  216780. const int result = fcntl (handle, F_SETLK, &fl);
  216781. if (result >= 0)
  216782. return;
  216783. if (errno != EINTR)
  216784. {
  216785. if (timeOutMillisecs == 0
  216786. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216787. break;
  216788. Thread::sleep (10);
  216789. }
  216790. }
  216791. }
  216792. closeFile();
  216793. }
  216794. ~Pimpl()
  216795. {
  216796. closeFile();
  216797. }
  216798. void closeFile()
  216799. {
  216800. if (handle != 0)
  216801. {
  216802. struct flock fl;
  216803. zerostruct (fl);
  216804. fl.l_whence = SEEK_SET;
  216805. fl.l_type = F_UNLCK;
  216806. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216807. {}
  216808. close (handle);
  216809. handle = 0;
  216810. }
  216811. }
  216812. int handle, refCount;
  216813. };
  216814. InterProcessLock::InterProcessLock (const String& name_)
  216815. : name (name_)
  216816. {
  216817. }
  216818. InterProcessLock::~InterProcessLock()
  216819. {
  216820. }
  216821. bool InterProcessLock::enter (const int timeOutMillisecs)
  216822. {
  216823. const ScopedLock sl (lock);
  216824. if (pimpl == 0)
  216825. {
  216826. pimpl = new Pimpl (name, timeOutMillisecs);
  216827. if (pimpl->handle == 0)
  216828. pimpl = 0;
  216829. }
  216830. else
  216831. {
  216832. pimpl->refCount++;
  216833. }
  216834. return pimpl != 0;
  216835. }
  216836. void InterProcessLock::exit()
  216837. {
  216838. const ScopedLock sl (lock);
  216839. // Trying to release the lock too many times!
  216840. jassert (pimpl != 0);
  216841. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216842. pimpl = 0;
  216843. }
  216844. void JUCE_API juce_threadEntryPoint (void*);
  216845. void* threadEntryProc (void* userData)
  216846. {
  216847. JUCE_AUTORELEASEPOOL
  216848. juce_threadEntryPoint (userData);
  216849. return 0;
  216850. }
  216851. void Thread::launchThread()
  216852. {
  216853. threadHandle_ = 0;
  216854. pthread_t handle = 0;
  216855. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  216856. {
  216857. pthread_detach (handle);
  216858. threadHandle_ = (void*) handle;
  216859. threadId_ = (ThreadID) threadHandle_;
  216860. }
  216861. }
  216862. void Thread::closeThreadHandle()
  216863. {
  216864. threadId_ = 0;
  216865. threadHandle_ = 0;
  216866. }
  216867. void Thread::killThread()
  216868. {
  216869. if (threadHandle_ != 0)
  216870. pthread_cancel ((pthread_t) threadHandle_);
  216871. }
  216872. void Thread::setCurrentThreadName (const String& /*name*/)
  216873. {
  216874. }
  216875. bool Thread::setThreadPriority (void* handle, int priority)
  216876. {
  216877. struct sched_param param;
  216878. int policy;
  216879. priority = jlimit (0, 10, priority);
  216880. if (handle == 0)
  216881. handle = (void*) pthread_self();
  216882. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  216883. return false;
  216884. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  216885. const int minPriority = sched_get_priority_min (policy);
  216886. const int maxPriority = sched_get_priority_max (policy);
  216887. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  216888. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216889. }
  216890. Thread::ThreadID Thread::getCurrentThreadId()
  216891. {
  216892. return (ThreadID) pthread_self();
  216893. }
  216894. void Thread::yield()
  216895. {
  216896. sched_yield();
  216897. }
  216898. /* Remove this macro if you're having problems compiling the cpu affinity
  216899. calls (the API for these has changed about quite a bit in various Linux
  216900. versions, and a lot of distros seem to ship with obsolete versions)
  216901. */
  216902. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216903. #define SUPPORT_AFFINITIES 1
  216904. #endif
  216905. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216906. {
  216907. #if SUPPORT_AFFINITIES
  216908. cpu_set_t affinity;
  216909. CPU_ZERO (&affinity);
  216910. for (int i = 0; i < 32; ++i)
  216911. if ((affinityMask & (1 << i)) != 0)
  216912. CPU_SET (i, &affinity);
  216913. /*
  216914. N.B. If this line causes a compile error, then you've probably not got the latest
  216915. version of glibc installed.
  216916. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216917. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216918. */
  216919. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216920. sched_yield();
  216921. #else
  216922. /* affinities aren't supported because either the appropriate header files weren't found,
  216923. or the SUPPORT_AFFINITIES macro was turned off
  216924. */
  216925. jassertfalse;
  216926. #endif
  216927. }
  216928. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216929. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216930. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216931. // compiled on its own).
  216932. #if JUCE_INCLUDED_FILE
  216933. enum
  216934. {
  216935. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  216936. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  216937. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  216938. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  216939. };
  216940. bool File::copyInternal (const File& dest) const
  216941. {
  216942. FileInputStream in (*this);
  216943. if (dest.deleteFile())
  216944. {
  216945. {
  216946. FileOutputStream out (dest);
  216947. if (out.failedToOpen())
  216948. return false;
  216949. if (out.writeFromInputStream (in, -1) == getSize())
  216950. return true;
  216951. }
  216952. dest.deleteFile();
  216953. }
  216954. return false;
  216955. }
  216956. void File::findFileSystemRoots (Array<File>& destArray)
  216957. {
  216958. destArray.add (File ("/"));
  216959. }
  216960. bool File::isOnCDRomDrive() const
  216961. {
  216962. struct statfs buf;
  216963. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216964. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  216965. }
  216966. bool File::isOnHardDisk() const
  216967. {
  216968. struct statfs buf;
  216969. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216970. {
  216971. switch (buf.f_type)
  216972. {
  216973. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216974. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216975. case U_NFS_SUPER_MAGIC: // Network NFS
  216976. case U_SMB_SUPER_MAGIC: // Network Samba
  216977. return false;
  216978. default:
  216979. // Assume anything else is a hard-disk (but note it could
  216980. // be a RAM disk. There isn't a good way of determining
  216981. // this for sure)
  216982. return true;
  216983. }
  216984. }
  216985. // Assume so if this fails for some reason
  216986. return true;
  216987. }
  216988. bool File::isOnRemovableDrive() const
  216989. {
  216990. jassertfalse; // xxx not implemented for linux!
  216991. return false;
  216992. }
  216993. bool File::isHidden() const
  216994. {
  216995. return getFileName().startsWithChar ('.');
  216996. }
  216997. namespace
  216998. {
  216999. const File juce_readlink (const String& file, const File& defaultFile)
  217000. {
  217001. const int size = 8192;
  217002. HeapBlock<char> buffer;
  217003. buffer.malloc (size + 4);
  217004. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217005. if (numBytes > 0 && numBytes <= size)
  217006. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217007. return defaultFile;
  217008. }
  217009. }
  217010. const File File::getLinkedTarget() const
  217011. {
  217012. return juce_readlink (getFullPathName().toUTF8(), *this);
  217013. }
  217014. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217015. const File File::getSpecialLocation (const SpecialLocationType type)
  217016. {
  217017. switch (type)
  217018. {
  217019. case userHomeDirectory:
  217020. {
  217021. const char* homeDir = getenv ("HOME");
  217022. if (homeDir == 0)
  217023. {
  217024. struct passwd* const pw = getpwuid (getuid());
  217025. if (pw != 0)
  217026. homeDir = pw->pw_dir;
  217027. }
  217028. return File (String::fromUTF8 (homeDir));
  217029. }
  217030. case userDocumentsDirectory:
  217031. case userMusicDirectory:
  217032. case userMoviesDirectory:
  217033. case userApplicationDataDirectory:
  217034. return File ("~");
  217035. case userDesktopDirectory:
  217036. return File ("~/Desktop");
  217037. case commonApplicationDataDirectory:
  217038. return File ("/var");
  217039. case globalApplicationsDirectory:
  217040. return File ("/usr");
  217041. case tempDirectory:
  217042. {
  217043. File tmp ("/var/tmp");
  217044. if (! tmp.isDirectory())
  217045. {
  217046. tmp = "/tmp";
  217047. if (! tmp.isDirectory())
  217048. tmp = File::getCurrentWorkingDirectory();
  217049. }
  217050. return tmp;
  217051. }
  217052. case invokedExecutableFile:
  217053. if (juce_Argv0 != 0)
  217054. return File (String::fromUTF8 (juce_Argv0));
  217055. // deliberate fall-through...
  217056. case currentExecutableFile:
  217057. case currentApplicationFile:
  217058. return juce_getExecutableFile();
  217059. case hostApplicationPath:
  217060. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217061. default:
  217062. jassertfalse; // unknown type?
  217063. break;
  217064. }
  217065. return File::nonexistent;
  217066. }
  217067. const String File::getVersion() const
  217068. {
  217069. return String::empty; // xxx not yet implemented
  217070. }
  217071. bool File::moveToTrash() const
  217072. {
  217073. if (! exists())
  217074. return true;
  217075. File trashCan ("~/.Trash");
  217076. if (! trashCan.isDirectory())
  217077. trashCan = "~/.local/share/Trash/files";
  217078. if (! trashCan.isDirectory())
  217079. return false;
  217080. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217081. getFileExtension()));
  217082. }
  217083. class DirectoryIterator::NativeIterator::Pimpl
  217084. {
  217085. public:
  217086. Pimpl (const File& directory, const String& wildCard_)
  217087. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217088. wildCard (wildCard_),
  217089. dir (opendir (directory.getFullPathName().toUTF8()))
  217090. {
  217091. wildcardUTF8 = wildCard.toUTF8();
  217092. }
  217093. ~Pimpl()
  217094. {
  217095. if (dir != 0)
  217096. closedir (dir);
  217097. }
  217098. bool next (String& filenameFound,
  217099. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217100. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217101. {
  217102. if (dir != 0)
  217103. {
  217104. for (;;)
  217105. {
  217106. struct dirent* const de = readdir (dir);
  217107. if (de == 0)
  217108. break;
  217109. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217110. {
  217111. filenameFound = String::fromUTF8 (de->d_name);
  217112. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  217113. if (isHidden != 0)
  217114. *isHidden = filenameFound.startsWithChar ('.');
  217115. return true;
  217116. }
  217117. }
  217118. }
  217119. return false;
  217120. }
  217121. private:
  217122. String parentDir, wildCard;
  217123. const char* wildcardUTF8;
  217124. DIR* dir;
  217125. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  217126. };
  217127. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217128. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217129. {
  217130. }
  217131. DirectoryIterator::NativeIterator::~NativeIterator()
  217132. {
  217133. }
  217134. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217135. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217136. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217137. {
  217138. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217139. }
  217140. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217141. {
  217142. String cmdString (fileName.replace (" ", "\\ ",false));
  217143. cmdString << " " << parameters;
  217144. if (URL::isProbablyAWebsiteURL (fileName)
  217145. || cmdString.startsWithIgnoreCase ("file:")
  217146. || URL::isProbablyAnEmailAddress (fileName))
  217147. {
  217148. // create a command that tries to launch a bunch of likely browsers
  217149. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217150. StringArray cmdLines;
  217151. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217152. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217153. cmdString = cmdLines.joinIntoString (" || ");
  217154. }
  217155. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217156. const int cpid = fork();
  217157. if (cpid == 0)
  217158. {
  217159. setsid();
  217160. // Child process
  217161. execve (argv[0], (char**) argv, environ);
  217162. exit (0);
  217163. }
  217164. return cpid >= 0;
  217165. }
  217166. void File::revealToUser() const
  217167. {
  217168. if (isDirectory())
  217169. startAsProcess();
  217170. else if (getParentDirectory().exists())
  217171. getParentDirectory().startAsProcess();
  217172. }
  217173. #endif
  217174. /*** End of inlined file: juce_linux_Files.cpp ***/
  217175. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217176. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217177. // compiled on its own).
  217178. #if JUCE_INCLUDED_FILE
  217179. struct NamedPipeInternal
  217180. {
  217181. String pipeInName, pipeOutName;
  217182. int pipeIn, pipeOut;
  217183. bool volatile createdPipe, blocked, stopReadOperation;
  217184. static void signalHandler (int) {}
  217185. };
  217186. void NamedPipe::cancelPendingReads()
  217187. {
  217188. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217189. {
  217190. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217191. intern->stopReadOperation = true;
  217192. char buffer [1] = { 0 };
  217193. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217194. (void) bytesWritten;
  217195. int timeout = 2000;
  217196. while (intern->blocked && --timeout >= 0)
  217197. Thread::sleep (2);
  217198. intern->stopReadOperation = false;
  217199. }
  217200. }
  217201. void NamedPipe::close()
  217202. {
  217203. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217204. if (intern != 0)
  217205. {
  217206. internal = 0;
  217207. if (intern->pipeIn != -1)
  217208. ::close (intern->pipeIn);
  217209. if (intern->pipeOut != -1)
  217210. ::close (intern->pipeOut);
  217211. if (intern->createdPipe)
  217212. {
  217213. unlink (intern->pipeInName.toUTF8());
  217214. unlink (intern->pipeOutName.toUTF8());
  217215. }
  217216. delete intern;
  217217. }
  217218. }
  217219. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217220. {
  217221. close();
  217222. NamedPipeInternal* const intern = new NamedPipeInternal();
  217223. internal = intern;
  217224. intern->createdPipe = createPipe;
  217225. intern->blocked = false;
  217226. intern->stopReadOperation = false;
  217227. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217228. siginterrupt (SIGPIPE, 1);
  217229. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217230. intern->pipeInName = pipePath + "_in";
  217231. intern->pipeOutName = pipePath + "_out";
  217232. intern->pipeIn = -1;
  217233. intern->pipeOut = -1;
  217234. if (createPipe)
  217235. {
  217236. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217237. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217238. {
  217239. delete intern;
  217240. internal = 0;
  217241. return false;
  217242. }
  217243. }
  217244. return true;
  217245. }
  217246. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217247. {
  217248. int bytesRead = -1;
  217249. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217250. if (intern != 0)
  217251. {
  217252. intern->blocked = true;
  217253. if (intern->pipeIn == -1)
  217254. {
  217255. if (intern->createdPipe)
  217256. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217257. else
  217258. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217259. if (intern->pipeIn == -1)
  217260. {
  217261. intern->blocked = false;
  217262. return -1;
  217263. }
  217264. }
  217265. bytesRead = 0;
  217266. char* p = static_cast<char*> (destBuffer);
  217267. while (bytesRead < maxBytesToRead)
  217268. {
  217269. const int bytesThisTime = maxBytesToRead - bytesRead;
  217270. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217271. if (numRead <= 0 || intern->stopReadOperation)
  217272. {
  217273. bytesRead = -1;
  217274. break;
  217275. }
  217276. bytesRead += numRead;
  217277. p += bytesRead;
  217278. }
  217279. intern->blocked = false;
  217280. }
  217281. return bytesRead;
  217282. }
  217283. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217284. {
  217285. int bytesWritten = -1;
  217286. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217287. if (intern != 0)
  217288. {
  217289. if (intern->pipeOut == -1)
  217290. {
  217291. if (intern->createdPipe)
  217292. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217293. else
  217294. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217295. if (intern->pipeOut == -1)
  217296. {
  217297. return -1;
  217298. }
  217299. }
  217300. const char* p = static_cast<const char*> (sourceBuffer);
  217301. bytesWritten = 0;
  217302. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217303. while (bytesWritten < numBytesToWrite
  217304. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217305. {
  217306. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217307. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217308. if (numWritten <= 0)
  217309. {
  217310. bytesWritten = -1;
  217311. break;
  217312. }
  217313. bytesWritten += numWritten;
  217314. p += bytesWritten;
  217315. }
  217316. }
  217317. return bytesWritten;
  217318. }
  217319. #endif
  217320. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217321. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217322. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217323. // compiled on its own).
  217324. #if JUCE_INCLUDED_FILE
  217325. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217326. {
  217327. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217328. if (s != -1)
  217329. {
  217330. char buf [1024];
  217331. struct ifconf ifc;
  217332. ifc.ifc_len = sizeof (buf);
  217333. ifc.ifc_buf = buf;
  217334. ioctl (s, SIOCGIFCONF, &ifc);
  217335. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217336. {
  217337. struct ifreq ifr;
  217338. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217339. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217340. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217341. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217342. {
  217343. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217344. }
  217345. }
  217346. close (s);
  217347. }
  217348. }
  217349. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217350. const String& emailSubject,
  217351. const String& bodyText,
  217352. const StringArray& filesToAttach)
  217353. {
  217354. jassertfalse; // xxx todo
  217355. return false;
  217356. }
  217357. class WebInputStream : public InputStream
  217358. {
  217359. public:
  217360. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217361. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217362. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217363. : socketHandle (-1), levelsOfRedirection (0),
  217364. address (address_), headers (headers_), postData (postData_), position (0),
  217365. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217366. {
  217367. createConnection (progressCallback, progressCallbackContext);
  217368. if (responseHeaders != 0 && ! isError())
  217369. {
  217370. for (int i = 0; i < headerLines.size(); ++i)
  217371. {
  217372. const String& headersEntry = headerLines[i];
  217373. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217374. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217375. const String previousValue ((*responseHeaders) [key]);
  217376. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217377. }
  217378. }
  217379. }
  217380. ~WebInputStream()
  217381. {
  217382. closeSocket();
  217383. }
  217384. bool isError() const { return socketHandle < 0; }
  217385. bool isExhausted() { return finished; }
  217386. int64 getPosition() { return position; }
  217387. int64 getTotalLength()
  217388. {
  217389. jassertfalse; //xxx to do
  217390. return -1;
  217391. }
  217392. int read (void* buffer, int bytesToRead)
  217393. {
  217394. if (finished || isError())
  217395. return 0;
  217396. fd_set readbits;
  217397. FD_ZERO (&readbits);
  217398. FD_SET (socketHandle, &readbits);
  217399. struct timeval tv;
  217400. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217401. tv.tv_usec = 0;
  217402. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217403. return 0; // (timeout)
  217404. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217405. if (bytesRead == 0)
  217406. finished = true;
  217407. position += bytesRead;
  217408. return bytesRead;
  217409. }
  217410. bool setPosition (int64 wantedPos)
  217411. {
  217412. if (isError())
  217413. return false;
  217414. if (wantedPos != position)
  217415. {
  217416. finished = false;
  217417. if (wantedPos < position)
  217418. {
  217419. closeSocket();
  217420. position = 0;
  217421. createConnection (0, 0);
  217422. }
  217423. skipNextBytes (wantedPos - position);
  217424. }
  217425. return true;
  217426. }
  217427. private:
  217428. int socketHandle, levelsOfRedirection;
  217429. StringArray headerLines;
  217430. String address, headers;
  217431. MemoryBlock postData;
  217432. int64 position;
  217433. bool finished;
  217434. const bool isPost;
  217435. const int timeOutMs;
  217436. void closeSocket()
  217437. {
  217438. if (socketHandle >= 0)
  217439. close (socketHandle);
  217440. socketHandle = -1;
  217441. levelsOfRedirection = 0;
  217442. }
  217443. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217444. {
  217445. closeSocket();
  217446. uint32 timeOutTime = Time::getMillisecondCounter();
  217447. if (timeOutMs == 0)
  217448. timeOutTime += 60000;
  217449. else if (timeOutMs < 0)
  217450. timeOutTime = 0xffffffff;
  217451. else
  217452. timeOutTime += timeOutMs;
  217453. String hostName, hostPath;
  217454. int hostPort;
  217455. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217456. return;
  217457. const struct hostent* host = 0;
  217458. int port = 0;
  217459. String proxyName, proxyPath;
  217460. int proxyPort = 0;
  217461. String proxyURL (getenv ("http_proxy"));
  217462. if (proxyURL.startsWithIgnoreCase ("http://"))
  217463. {
  217464. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217465. return;
  217466. host = gethostbyname (proxyName.toUTF8());
  217467. port = proxyPort;
  217468. }
  217469. else
  217470. {
  217471. host = gethostbyname (hostName.toUTF8());
  217472. port = hostPort;
  217473. }
  217474. if (host == 0)
  217475. return;
  217476. {
  217477. struct sockaddr_in socketAddress;
  217478. zerostruct (socketAddress);
  217479. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217480. socketAddress.sin_family = host->h_addrtype;
  217481. socketAddress.sin_port = htons (port);
  217482. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217483. if (socketHandle == -1)
  217484. return;
  217485. int receiveBufferSize = 16384;
  217486. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217487. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217488. #if JUCE_MAC
  217489. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217490. #endif
  217491. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217492. {
  217493. closeSocket();
  217494. return;
  217495. }
  217496. }
  217497. {
  217498. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217499. hostPath, address, headers, postData, isPost));
  217500. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217501. {
  217502. closeSocket();
  217503. return;
  217504. }
  217505. }
  217506. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217507. if (responseHeader.isNotEmpty())
  217508. {
  217509. headerLines.clear();
  217510. headerLines.addLines (responseHeader);
  217511. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217512. .substring (0, 3).getIntValue();
  217513. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217514. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217515. String location (findHeaderItem (headerLines, "Location:"));
  217516. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217517. {
  217518. if (! location.startsWithIgnoreCase ("http://"))
  217519. location = "http://" + location;
  217520. if (++levelsOfRedirection <= 3)
  217521. {
  217522. address = location;
  217523. createConnection (progressCallback, progressCallbackContext);
  217524. return;
  217525. }
  217526. }
  217527. else
  217528. {
  217529. levelsOfRedirection = 0;
  217530. return;
  217531. }
  217532. }
  217533. closeSocket();
  217534. }
  217535. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217536. {
  217537. int bytesRead = 0, numConsecutiveLFs = 0;
  217538. MemoryBlock buffer (1024, true);
  217539. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217540. && Time::getMillisecondCounter() <= timeOutTime)
  217541. {
  217542. fd_set readbits;
  217543. FD_ZERO (&readbits);
  217544. FD_SET (socketHandle, &readbits);
  217545. struct timeval tv;
  217546. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217547. tv.tv_usec = 0;
  217548. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217549. return String::empty; // (timeout)
  217550. buffer.ensureSize (bytesRead + 8, true);
  217551. char* const dest = (char*) buffer.getData() + bytesRead;
  217552. if (recv (socketHandle, dest, 1, 0) == -1)
  217553. return String::empty;
  217554. const char lastByte = *dest;
  217555. ++bytesRead;
  217556. if (lastByte == '\n')
  217557. ++numConsecutiveLFs;
  217558. else if (lastByte != '\r')
  217559. numConsecutiveLFs = 0;
  217560. }
  217561. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217562. if (header.startsWithIgnoreCase ("HTTP/"))
  217563. return header.trimEnd();
  217564. return String::empty;
  217565. }
  217566. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217567. const String& proxyName, const int proxyPort,
  217568. const String& hostPath, const String& originalURL,
  217569. const String& headers, const MemoryBlock& postData,
  217570. const bool isPost)
  217571. {
  217572. String header (isPost ? "POST " : "GET ");
  217573. if (proxyName.isEmpty())
  217574. {
  217575. header << hostPath << " HTTP/1.0\r\nHost: "
  217576. << hostName << ':' << hostPort;
  217577. }
  217578. else
  217579. {
  217580. header << originalURL << " HTTP/1.0\r\nHost: "
  217581. << proxyName << ':' << proxyPort;
  217582. }
  217583. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217584. << "\r\nConnection: Close\r\nContent-Length: "
  217585. << postData.getSize() << "\r\n"
  217586. << headers << "\r\n";
  217587. MemoryBlock mb;
  217588. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217589. mb.append (postData.getData(), postData.getSize());
  217590. return mb;
  217591. }
  217592. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217593. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217594. {
  217595. size_t totalHeaderSent = 0;
  217596. while (totalHeaderSent < requestHeader.getSize())
  217597. {
  217598. if (Time::getMillisecondCounter() > timeOutTime)
  217599. return false;
  217600. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217601. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217602. return false;
  217603. totalHeaderSent += numToSend;
  217604. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217605. return false;
  217606. }
  217607. return true;
  217608. }
  217609. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217610. {
  217611. if (! url.startsWithIgnoreCase ("http://"))
  217612. return false;
  217613. const int nextSlash = url.indexOfChar (7, '/');
  217614. int nextColon = url.indexOfChar (7, ':');
  217615. if (nextColon > nextSlash && nextSlash > 0)
  217616. nextColon = -1;
  217617. if (nextColon >= 0)
  217618. {
  217619. host = url.substring (7, nextColon);
  217620. if (nextSlash >= 0)
  217621. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217622. else
  217623. port = url.substring (nextColon + 1).getIntValue();
  217624. }
  217625. else
  217626. {
  217627. port = 80;
  217628. if (nextSlash >= 0)
  217629. host = url.substring (7, nextSlash);
  217630. else
  217631. host = url.substring (7);
  217632. }
  217633. if (nextSlash >= 0)
  217634. path = url.substring (nextSlash);
  217635. else
  217636. path = "/";
  217637. return true;
  217638. }
  217639. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217640. {
  217641. for (int i = 0; i < lines.size(); ++i)
  217642. if (lines[i].startsWithIgnoreCase (itemName))
  217643. return lines[i].substring (itemName.length()).trim();
  217644. return String::empty;
  217645. }
  217646. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217647. };
  217648. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217649. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217650. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217651. {
  217652. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217653. progressCallback, progressCallbackContext,
  217654. headers, timeOutMs, responseHeaders));
  217655. return wi->isError() ? 0 : wi.release();
  217656. }
  217657. #endif
  217658. /*** End of inlined file: juce_linux_Network.cpp ***/
  217659. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217660. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217661. // compiled on its own).
  217662. #if JUCE_INCLUDED_FILE
  217663. void Logger::outputDebugString (const String& text)
  217664. {
  217665. std::cerr << text << std::endl;
  217666. }
  217667. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217668. {
  217669. return Linux;
  217670. }
  217671. const String SystemStats::getOperatingSystemName()
  217672. {
  217673. return "Linux";
  217674. }
  217675. bool SystemStats::isOperatingSystem64Bit()
  217676. {
  217677. #if JUCE_64BIT
  217678. return true;
  217679. #else
  217680. //xxx not sure how to find this out?..
  217681. return false;
  217682. #endif
  217683. }
  217684. namespace LinuxStatsHelpers
  217685. {
  217686. const String getCpuInfo (const char* const key)
  217687. {
  217688. StringArray lines;
  217689. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217690. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217691. if (lines[i].startsWithIgnoreCase (key))
  217692. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217693. return String::empty;
  217694. }
  217695. }
  217696. const String SystemStats::getCpuVendor()
  217697. {
  217698. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217699. }
  217700. int SystemStats::getCpuSpeedInMegaherz()
  217701. {
  217702. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  217703. }
  217704. int SystemStats::getMemorySizeInMegabytes()
  217705. {
  217706. struct sysinfo sysi;
  217707. if (sysinfo (&sysi) == 0)
  217708. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217709. return 0;
  217710. }
  217711. int SystemStats::getPageSize()
  217712. {
  217713. return sysconf (_SC_PAGESIZE);
  217714. }
  217715. const String SystemStats::getLogonName()
  217716. {
  217717. const char* user = getenv ("USER");
  217718. if (user == 0)
  217719. {
  217720. struct passwd* const pw = getpwuid (getuid());
  217721. if (pw != 0)
  217722. user = pw->pw_name;
  217723. }
  217724. return String::fromUTF8 (user);
  217725. }
  217726. const String SystemStats::getFullUserName()
  217727. {
  217728. return getLogonName();
  217729. }
  217730. void SystemStats::initialiseStats()
  217731. {
  217732. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  217733. cpuFlags.hasMMX = flags.contains ("mmx");
  217734. cpuFlags.hasSSE = flags.contains ("sse");
  217735. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217736. cpuFlags.has3DNow = flags.contains ("3dnow");
  217737. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  217738. }
  217739. void PlatformUtilities::fpuReset()
  217740. {
  217741. }
  217742. uint32 juce_millisecondsSinceStartup() throw()
  217743. {
  217744. timespec t;
  217745. clock_gettime (CLOCK_MONOTONIC, &t);
  217746. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  217747. }
  217748. int64 Time::getHighResolutionTicks() throw()
  217749. {
  217750. timespec t;
  217751. clock_gettime (CLOCK_MONOTONIC, &t);
  217752. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  217753. }
  217754. int64 Time::getHighResolutionTicksPerSecond() throw()
  217755. {
  217756. return 1000000; // (microseconds)
  217757. }
  217758. double Time::getMillisecondCounterHiRes() throw()
  217759. {
  217760. return getHighResolutionTicks() * 0.001;
  217761. }
  217762. bool Time::setSystemTimeToThisTime() const
  217763. {
  217764. timeval t;
  217765. t.tv_sec = millisSinceEpoch / 1000;
  217766. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  217767. return settimeofday (&t, 0) == 0;
  217768. }
  217769. #endif
  217770. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217771. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217772. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217773. // compiled on its own).
  217774. #if JUCE_INCLUDED_FILE
  217775. /*
  217776. Note that a lot of methods that you'd expect to find in this file actually
  217777. live in juce_posix_SharedCode.h!
  217778. */
  217779. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217780. void Process::setPriority (ProcessPriority prior)
  217781. {
  217782. struct sched_param param;
  217783. int policy, maxp, minp;
  217784. const int p = (int) prior;
  217785. if (p <= 1)
  217786. policy = SCHED_OTHER;
  217787. else
  217788. policy = SCHED_RR;
  217789. minp = sched_get_priority_min (policy);
  217790. maxp = sched_get_priority_max (policy);
  217791. if (p < 2)
  217792. param.sched_priority = 0;
  217793. else if (p == 2 )
  217794. // Set to middle of lower realtime priority range
  217795. param.sched_priority = minp + (maxp - minp) / 4;
  217796. else
  217797. // Set to middle of higher realtime priority range
  217798. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217799. pthread_setschedparam (pthread_self(), policy, &param);
  217800. }
  217801. void Process::terminate()
  217802. {
  217803. exit (0);
  217804. }
  217805. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  217806. {
  217807. static char testResult = 0;
  217808. if (testResult == 0)
  217809. {
  217810. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217811. if (testResult >= 0)
  217812. {
  217813. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217814. testResult = 1;
  217815. }
  217816. }
  217817. return testResult < 0;
  217818. }
  217819. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217820. {
  217821. return juce_isRunningUnderDebugger();
  217822. }
  217823. void Process::raisePrivilege()
  217824. {
  217825. // If running suid root, change effective user
  217826. // to root
  217827. if (geteuid() != 0 && getuid() == 0)
  217828. {
  217829. setreuid (geteuid(), getuid());
  217830. setregid (getegid(), getgid());
  217831. }
  217832. }
  217833. void Process::lowerPrivilege()
  217834. {
  217835. // If runing suid root, change effective user
  217836. // back to real user
  217837. if (geteuid() == 0 && getuid() != 0)
  217838. {
  217839. setreuid (geteuid(), getuid());
  217840. setregid (getegid(), getgid());
  217841. }
  217842. }
  217843. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217844. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217845. {
  217846. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217847. }
  217848. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217849. {
  217850. dlclose(handle);
  217851. }
  217852. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217853. {
  217854. return dlsym (libraryHandle, procedureName.toCString());
  217855. }
  217856. #endif
  217857. #endif
  217858. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217859. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217860. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217861. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217862. // compiled on its own).
  217863. #if JUCE_INCLUDED_FILE
  217864. extern Display* display;
  217865. extern Window juce_messageWindowHandle;
  217866. namespace ClipboardHelpers
  217867. {
  217868. static String localClipboardContent;
  217869. static Atom atom_UTF8_STRING;
  217870. static Atom atom_CLIPBOARD;
  217871. static Atom atom_TARGETS;
  217872. static void initSelectionAtoms()
  217873. {
  217874. static bool isInitialised = false;
  217875. if (! isInitialised)
  217876. {
  217877. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217878. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217879. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217880. }
  217881. }
  217882. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217883. // works only for strings shorter than 1000000 bytes
  217884. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217885. {
  217886. String returnData;
  217887. char* clipData;
  217888. Atom actualType;
  217889. int actualFormat;
  217890. unsigned long numItems, bytesLeft;
  217891. if (XGetWindowProperty (display, window, prop,
  217892. 0L /* offset */, 1000000 /* length (max) */, False,
  217893. AnyPropertyType /* format */,
  217894. &actualType, &actualFormat, &numItems, &bytesLeft,
  217895. (unsigned char**) &clipData) == Success)
  217896. {
  217897. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217898. returnData = String::fromUTF8 (clipData, numItems);
  217899. else if (actualType == XA_STRING && actualFormat == 8)
  217900. returnData = String (clipData, numItems);
  217901. if (clipData != 0)
  217902. XFree (clipData);
  217903. jassert (bytesLeft == 0 || numItems == 1000000);
  217904. }
  217905. XDeleteProperty (display, window, prop);
  217906. return returnData;
  217907. }
  217908. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217909. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217910. {
  217911. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217912. // The selection owner will be asked to set the JUCE_SEL property on the
  217913. // juce_messageWindowHandle with the selection content
  217914. XConvertSelection (display, selection, requestedFormat, property_name,
  217915. juce_messageWindowHandle, CurrentTime);
  217916. int count = 50; // will wait at most for 200 ms
  217917. while (--count >= 0)
  217918. {
  217919. XEvent event;
  217920. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217921. {
  217922. if (event.xselection.property == property_name)
  217923. {
  217924. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217925. selectionContent = readWindowProperty (event.xselection.requestor,
  217926. event.xselection.property,
  217927. requestedFormat);
  217928. return true;
  217929. }
  217930. else
  217931. {
  217932. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217933. }
  217934. }
  217935. // not very elegant.. we could do a select() or something like that...
  217936. // however clipboard content requesting is inherently slow on x11, it
  217937. // often takes 50ms or more so...
  217938. Thread::sleep (4);
  217939. }
  217940. return false;
  217941. }
  217942. }
  217943. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217944. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217945. {
  217946. ClipboardHelpers::initSelectionAtoms();
  217947. // the selection content is sent to the target window as a window property
  217948. XSelectionEvent reply;
  217949. reply.type = SelectionNotify;
  217950. reply.display = evt.display;
  217951. reply.requestor = evt.requestor;
  217952. reply.selection = evt.selection;
  217953. reply.target = evt.target;
  217954. reply.property = None; // == "fail"
  217955. reply.time = evt.time;
  217956. HeapBlock <char> data;
  217957. int propertyFormat = 0, numDataItems = 0;
  217958. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217959. {
  217960. if (evt.target == XA_STRING)
  217961. {
  217962. // format data according to system locale
  217963. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217964. data.calloc (numDataItems + 1);
  217965. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217966. propertyFormat = 8; // bits/item
  217967. }
  217968. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217969. {
  217970. // translate to utf8
  217971. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217972. data.calloc (numDataItems + 1);
  217973. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217974. propertyFormat = 8; // bits/item
  217975. }
  217976. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217977. {
  217978. // another application wants to know what we are able to send
  217979. numDataItems = 2;
  217980. propertyFormat = 32; // atoms are 32-bit
  217981. data.calloc (numDataItems * 4);
  217982. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217983. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217984. atoms[1] = XA_STRING;
  217985. }
  217986. }
  217987. else
  217988. {
  217989. DBG ("requested unsupported clipboard");
  217990. }
  217991. if (data != 0)
  217992. {
  217993. const int maxReasonableSelectionSize = 1000000;
  217994. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217995. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217996. {
  217997. XChangeProperty (evt.display, evt.requestor,
  217998. evt.property, evt.target,
  217999. propertyFormat /* 8 or 32 */, PropModeReplace,
  218000. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218001. reply.property = evt.property; // " == success"
  218002. }
  218003. }
  218004. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218005. }
  218006. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218007. {
  218008. ClipboardHelpers::initSelectionAtoms();
  218009. ClipboardHelpers::localClipboardContent = clipText;
  218010. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218011. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218012. }
  218013. const String SystemClipboard::getTextFromClipboard()
  218014. {
  218015. ClipboardHelpers::initSelectionAtoms();
  218016. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218017. level" clipboard that is supposed to be filled by ctrl-C
  218018. etc). When a clipboard manager is running, the content of this
  218019. selection is preserved even when the original selection owner
  218020. exits.
  218021. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218022. filled by good old x11 apps such as xterm)
  218023. */
  218024. String content;
  218025. Atom selection = XA_PRIMARY;
  218026. Window selectionOwner = None;
  218027. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218028. {
  218029. selection = ClipboardHelpers::atom_CLIPBOARD;
  218030. selectionOwner = XGetSelectionOwner (display, selection);
  218031. }
  218032. if (selectionOwner != None)
  218033. {
  218034. if (selectionOwner == juce_messageWindowHandle)
  218035. {
  218036. content = ClipboardHelpers::localClipboardContent;
  218037. }
  218038. else
  218039. {
  218040. // first try: we want an utf8 string
  218041. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218042. if (! ok)
  218043. {
  218044. // second chance, ask for a good old locale-dependent string ..
  218045. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218046. }
  218047. }
  218048. }
  218049. return content;
  218050. }
  218051. #endif
  218052. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218053. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218054. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218055. // compiled on its own).
  218056. #if JUCE_INCLUDED_FILE
  218057. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218058. #define JUCE_DEBUG_XERRORS 1
  218059. #endif
  218060. Display* display = 0;
  218061. Window juce_messageWindowHandle = None;
  218062. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218063. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218064. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218065. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218066. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218067. class InternalMessageQueue
  218068. {
  218069. public:
  218070. InternalMessageQueue()
  218071. : bytesInSocket (0),
  218072. totalEventCount (0)
  218073. {
  218074. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218075. (void) ret; jassert (ret == 0);
  218076. //setNonBlocking (fd[0]);
  218077. //setNonBlocking (fd[1]);
  218078. }
  218079. ~InternalMessageQueue()
  218080. {
  218081. close (fd[0]);
  218082. close (fd[1]);
  218083. clearSingletonInstance();
  218084. }
  218085. void postMessage (Message* msg)
  218086. {
  218087. const int maxBytesInSocketQueue = 128;
  218088. ScopedLock sl (lock);
  218089. queue.add (msg);
  218090. if (bytesInSocket < maxBytesInSocketQueue)
  218091. {
  218092. ++bytesInSocket;
  218093. ScopedUnlock ul (lock);
  218094. const unsigned char x = 0xff;
  218095. size_t bytesWritten = write (fd[0], &x, 1);
  218096. (void) bytesWritten;
  218097. }
  218098. }
  218099. bool isEmpty() const
  218100. {
  218101. ScopedLock sl (lock);
  218102. return queue.size() == 0;
  218103. }
  218104. bool dispatchNextEvent()
  218105. {
  218106. // This alternates between giving priority to XEvents or internal messages,
  218107. // to keep everything running smoothly..
  218108. if ((++totalEventCount & 1) != 0)
  218109. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218110. else
  218111. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218112. }
  218113. // Wait for an event (either XEvent, or an internal Message)
  218114. bool sleepUntilEvent (const int timeoutMs)
  218115. {
  218116. if (! isEmpty())
  218117. return true;
  218118. if (display != 0)
  218119. {
  218120. ScopedXLock xlock;
  218121. if (XPending (display))
  218122. return true;
  218123. }
  218124. struct timeval tv;
  218125. tv.tv_sec = 0;
  218126. tv.tv_usec = timeoutMs * 1000;
  218127. int fd0 = getWaitHandle();
  218128. int fdmax = fd0;
  218129. fd_set readset;
  218130. FD_ZERO (&readset);
  218131. FD_SET (fd0, &readset);
  218132. if (display != 0)
  218133. {
  218134. ScopedXLock xlock;
  218135. int fd1 = XConnectionNumber (display);
  218136. FD_SET (fd1, &readset);
  218137. fdmax = jmax (fd0, fd1);
  218138. }
  218139. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218140. return (ret > 0); // ret <= 0 if error or timeout
  218141. }
  218142. struct MessageThreadFuncCall
  218143. {
  218144. enum { uniqueID = 0x73774623 };
  218145. MessageCallbackFunction* func;
  218146. void* parameter;
  218147. void* result;
  218148. CriticalSection lock;
  218149. WaitableEvent event;
  218150. };
  218151. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218152. private:
  218153. CriticalSection lock;
  218154. ReferenceCountedArray <Message> queue;
  218155. int fd[2];
  218156. int bytesInSocket;
  218157. int totalEventCount;
  218158. int getWaitHandle() const throw() { return fd[1]; }
  218159. static bool setNonBlocking (int handle)
  218160. {
  218161. int socketFlags = fcntl (handle, F_GETFL, 0);
  218162. if (socketFlags == -1)
  218163. return false;
  218164. socketFlags |= O_NONBLOCK;
  218165. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218166. }
  218167. static bool dispatchNextXEvent()
  218168. {
  218169. if (display == 0)
  218170. return false;
  218171. XEvent evt;
  218172. {
  218173. ScopedXLock xlock;
  218174. if (! XPending (display))
  218175. return false;
  218176. XNextEvent (display, &evt);
  218177. }
  218178. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218179. juce_handleSelectionRequest (evt.xselectionrequest);
  218180. else if (evt.xany.window != juce_messageWindowHandle)
  218181. juce_windowMessageReceive (&evt);
  218182. return true;
  218183. }
  218184. const Message::Ptr popNextMessage()
  218185. {
  218186. const ScopedLock sl (lock);
  218187. if (bytesInSocket > 0)
  218188. {
  218189. --bytesInSocket;
  218190. const ScopedUnlock ul (lock);
  218191. unsigned char x;
  218192. size_t numBytes = read (fd[1], &x, 1);
  218193. (void) numBytes;
  218194. }
  218195. return queue.removeAndReturn (0);
  218196. }
  218197. bool dispatchNextInternalMessage()
  218198. {
  218199. const Message::Ptr msg (popNextMessage());
  218200. if (msg == 0)
  218201. return false;
  218202. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218203. {
  218204. // Handle callback message
  218205. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218206. call->result = (*(call->func)) (call->parameter);
  218207. call->event.signal();
  218208. }
  218209. else
  218210. {
  218211. // Handle "normal" messages
  218212. MessageManager::getInstance()->deliverMessage (msg);
  218213. }
  218214. return true;
  218215. }
  218216. };
  218217. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218218. namespace LinuxErrorHandling
  218219. {
  218220. static bool errorOccurred = false;
  218221. static bool keyboardBreakOccurred = false;
  218222. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218223. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218224. // Usually happens when client-server connection is broken
  218225. static int ioErrorHandler (Display* display)
  218226. {
  218227. DBG ("ERROR: connection to X server broken.. terminating.");
  218228. if (JUCEApplication::isStandaloneApp())
  218229. MessageManager::getInstance()->stopDispatchLoop();
  218230. errorOccurred = true;
  218231. return 0;
  218232. }
  218233. // A protocol error has occurred
  218234. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218235. {
  218236. #if JUCE_DEBUG_XERRORS
  218237. char errorStr[64] = { 0 };
  218238. char requestStr[64] = { 0 };
  218239. XGetErrorText (display, event->error_code, errorStr, 64);
  218240. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218241. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218242. #endif
  218243. return 0;
  218244. }
  218245. static void installXErrorHandlers()
  218246. {
  218247. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218248. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218249. }
  218250. static void removeXErrorHandlers()
  218251. {
  218252. if (JUCEApplication::isStandaloneApp())
  218253. {
  218254. XSetIOErrorHandler (oldIOErrorHandler);
  218255. oldIOErrorHandler = 0;
  218256. XSetErrorHandler (oldErrorHandler);
  218257. oldErrorHandler = 0;
  218258. }
  218259. }
  218260. static void keyboardBreakSignalHandler (int sig)
  218261. {
  218262. if (sig == SIGINT)
  218263. keyboardBreakOccurred = true;
  218264. }
  218265. static void installKeyboardBreakHandler()
  218266. {
  218267. struct sigaction saction;
  218268. sigset_t maskSet;
  218269. sigemptyset (&maskSet);
  218270. saction.sa_handler = keyboardBreakSignalHandler;
  218271. saction.sa_mask = maskSet;
  218272. saction.sa_flags = 0;
  218273. sigaction (SIGINT, &saction, 0);
  218274. }
  218275. }
  218276. void MessageManager::doPlatformSpecificInitialisation()
  218277. {
  218278. if (JUCEApplication::isStandaloneApp())
  218279. {
  218280. // Initialise xlib for multiple thread support
  218281. static bool initThreadCalled = false;
  218282. if (! initThreadCalled)
  218283. {
  218284. if (! XInitThreads())
  218285. {
  218286. // This is fatal! Print error and closedown
  218287. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218288. Process::terminate();
  218289. return;
  218290. }
  218291. initThreadCalled = true;
  218292. }
  218293. LinuxErrorHandling::installXErrorHandlers();
  218294. LinuxErrorHandling::installKeyboardBreakHandler();
  218295. }
  218296. // Create the internal message queue
  218297. InternalMessageQueue::getInstance();
  218298. // Try to connect to a display
  218299. String displayName (getenv ("DISPLAY"));
  218300. if (displayName.isEmpty())
  218301. displayName = ":0.0";
  218302. display = XOpenDisplay (displayName.toCString());
  218303. if (display != 0) // This is not fatal! we can run headless.
  218304. {
  218305. // Create a context to store user data associated with Windows we create in WindowDriver
  218306. windowHandleXContext = XUniqueContext();
  218307. // We're only interested in client messages for this window, which are always sent
  218308. XSetWindowAttributes swa;
  218309. swa.event_mask = NoEventMask;
  218310. // Create our message window (this will never be mapped)
  218311. const int screen = DefaultScreen (display);
  218312. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218313. 0, 0, 1, 1, 0, 0, InputOnly,
  218314. DefaultVisual (display, screen),
  218315. CWEventMask, &swa);
  218316. }
  218317. }
  218318. void MessageManager::doPlatformSpecificShutdown()
  218319. {
  218320. InternalMessageQueue::deleteInstance();
  218321. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218322. {
  218323. XDestroyWindow (display, juce_messageWindowHandle);
  218324. XCloseDisplay (display);
  218325. juce_messageWindowHandle = 0;
  218326. display = 0;
  218327. LinuxErrorHandling::removeXErrorHandlers();
  218328. }
  218329. }
  218330. bool juce_postMessageToSystemQueue (Message* message)
  218331. {
  218332. if (LinuxErrorHandling::errorOccurred)
  218333. return false;
  218334. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218335. return true;
  218336. }
  218337. void MessageManager::broadcastMessage (const String& value)
  218338. {
  218339. /* TODO */
  218340. }
  218341. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218342. {
  218343. if (LinuxErrorHandling::errorOccurred)
  218344. return 0;
  218345. if (isThisTheMessageThread())
  218346. return func (parameter);
  218347. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  218348. messageCallContext.func = func;
  218349. messageCallContext.parameter = parameter;
  218350. InternalMessageQueue::getInstanceWithoutCreating()
  218351. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  218352. 0, 0, &messageCallContext));
  218353. // Wait for it to complete before continuing
  218354. messageCallContext.event.wait();
  218355. return messageCallContext.result;
  218356. }
  218357. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218358. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218359. {
  218360. while (! LinuxErrorHandling::errorOccurred)
  218361. {
  218362. if (LinuxErrorHandling::keyboardBreakOccurred)
  218363. {
  218364. LinuxErrorHandling::errorOccurred = true;
  218365. if (JUCEApplication::isStandaloneApp())
  218366. Process::terminate();
  218367. break;
  218368. }
  218369. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218370. return true;
  218371. if (returnIfNoPendingMessages)
  218372. break;
  218373. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218374. }
  218375. return false;
  218376. }
  218377. #endif
  218378. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218379. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218380. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218381. // compiled on its own).
  218382. #if JUCE_INCLUDED_FILE
  218383. class FreeTypeFontFace
  218384. {
  218385. public:
  218386. enum FontStyle
  218387. {
  218388. Plain = 0,
  218389. Bold = 1,
  218390. Italic = 2
  218391. };
  218392. FreeTypeFontFace (const String& familyName)
  218393. : hasSerif (false),
  218394. monospaced (false)
  218395. {
  218396. family = familyName;
  218397. }
  218398. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218399. {
  218400. if (names [(int) style].fileName.isEmpty())
  218401. {
  218402. names [(int) style].fileName = name;
  218403. names [(int) style].faceIndex = faceIndex;
  218404. }
  218405. }
  218406. const String& getFamilyName() const throw() { return family; }
  218407. const String& getFileName (const int style, int& faceIndex) const throw()
  218408. {
  218409. faceIndex = names[style].faceIndex;
  218410. return names[style].fileName;
  218411. }
  218412. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218413. bool getMonospaced() const throw() { return monospaced; }
  218414. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218415. bool getSerif() const throw() { return hasSerif; }
  218416. private:
  218417. String family;
  218418. struct FontNameIndex
  218419. {
  218420. String fileName;
  218421. int faceIndex;
  218422. };
  218423. FontNameIndex names[4];
  218424. bool hasSerif, monospaced;
  218425. };
  218426. class FreeTypeInterface : public DeletedAtShutdown
  218427. {
  218428. public:
  218429. FreeTypeInterface()
  218430. : ftLib (0),
  218431. lastFace (0),
  218432. lastBold (false),
  218433. lastItalic (false)
  218434. {
  218435. if (FT_Init_FreeType (&ftLib) != 0)
  218436. {
  218437. ftLib = 0;
  218438. DBG ("Failed to initialize FreeType");
  218439. }
  218440. StringArray fontDirs;
  218441. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218442. fontDirs.removeEmptyStrings (true);
  218443. if (fontDirs.size() == 0)
  218444. {
  218445. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218446. if (fontsInfo != 0)
  218447. {
  218448. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218449. {
  218450. fontDirs.add (e->getAllSubText().trim());
  218451. }
  218452. }
  218453. }
  218454. if (fontDirs.size() == 0)
  218455. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218456. for (int i = 0; i < fontDirs.size(); ++i)
  218457. enumerateFaces (fontDirs[i]);
  218458. }
  218459. ~FreeTypeInterface()
  218460. {
  218461. if (lastFace != 0)
  218462. FT_Done_Face (lastFace);
  218463. if (ftLib != 0)
  218464. FT_Done_FreeType (ftLib);
  218465. clearSingletonInstance();
  218466. }
  218467. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218468. {
  218469. for (int i = 0; i < faces.size(); i++)
  218470. if (faces[i]->getFamilyName() == familyName)
  218471. return faces[i];
  218472. if (! create)
  218473. return 0;
  218474. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218475. faces.add (newFace);
  218476. return newFace;
  218477. }
  218478. // Enumerate all font faces available in a given directory
  218479. void enumerateFaces (const String& path)
  218480. {
  218481. File dirPath (path);
  218482. if (path.isEmpty() || ! dirPath.isDirectory())
  218483. return;
  218484. DirectoryIterator di (dirPath, true);
  218485. while (di.next())
  218486. {
  218487. File possible (di.getFile());
  218488. if (possible.hasFileExtension ("ttf")
  218489. || possible.hasFileExtension ("pfb")
  218490. || possible.hasFileExtension ("pcf"))
  218491. {
  218492. FT_Face face;
  218493. int faceIndex = 0;
  218494. int numFaces = 0;
  218495. do
  218496. {
  218497. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218498. faceIndex, &face) == 0)
  218499. {
  218500. if (faceIndex == 0)
  218501. numFaces = face->num_faces;
  218502. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218503. {
  218504. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218505. int style = (int) FreeTypeFontFace::Plain;
  218506. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218507. style |= (int) FreeTypeFontFace::Bold;
  218508. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218509. style |= (int) FreeTypeFontFace::Italic;
  218510. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218511. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218512. // Surely there must be a better way to do this?
  218513. const String name (face->family_name);
  218514. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218515. || name.containsIgnoreCase ("Verdana")
  218516. || name.containsIgnoreCase ("Arial")));
  218517. }
  218518. FT_Done_Face (face);
  218519. }
  218520. ++faceIndex;
  218521. }
  218522. while (faceIndex < numFaces);
  218523. }
  218524. }
  218525. }
  218526. // Create a FreeType face object for a given font
  218527. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218528. {
  218529. FT_Face face = 0;
  218530. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218531. {
  218532. face = lastFace;
  218533. }
  218534. else
  218535. {
  218536. if (lastFace != 0)
  218537. {
  218538. FT_Done_Face (lastFace);
  218539. lastFace = 0;
  218540. }
  218541. lastFontName = fontName;
  218542. lastBold = bold;
  218543. lastItalic = italic;
  218544. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218545. if (ftFace != 0)
  218546. {
  218547. int style = (int) FreeTypeFontFace::Plain;
  218548. if (bold)
  218549. style |= (int) FreeTypeFontFace::Bold;
  218550. if (italic)
  218551. style |= (int) FreeTypeFontFace::Italic;
  218552. int faceIndex;
  218553. String fileName (ftFace->getFileName (style, faceIndex));
  218554. if (fileName.isEmpty())
  218555. {
  218556. style ^= (int) FreeTypeFontFace::Bold;
  218557. fileName = ftFace->getFileName (style, faceIndex);
  218558. if (fileName.isEmpty())
  218559. {
  218560. style ^= (int) FreeTypeFontFace::Bold;
  218561. style ^= (int) FreeTypeFontFace::Italic;
  218562. fileName = ftFace->getFileName (style, faceIndex);
  218563. if (! fileName.length())
  218564. {
  218565. style ^= (int) FreeTypeFontFace::Bold;
  218566. fileName = ftFace->getFileName (style, faceIndex);
  218567. }
  218568. }
  218569. }
  218570. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218571. {
  218572. face = lastFace;
  218573. // If there isn't a unicode charmap then select the first one.
  218574. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218575. FT_Set_Charmap (face, face->charmaps[0]);
  218576. }
  218577. }
  218578. }
  218579. return face;
  218580. }
  218581. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218582. {
  218583. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218584. const float height = (float) (face->ascender - face->descender);
  218585. const float scaleX = 1.0f / height;
  218586. const float scaleY = -1.0f / height;
  218587. Path destShape;
  218588. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218589. || face->glyph->format != ft_glyph_format_outline)
  218590. {
  218591. return false;
  218592. }
  218593. const FT_Outline* const outline = &face->glyph->outline;
  218594. const short* const contours = outline->contours;
  218595. const char* const tags = outline->tags;
  218596. FT_Vector* const points = outline->points;
  218597. for (int c = 0; c < outline->n_contours; c++)
  218598. {
  218599. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218600. const int endPoint = contours[c];
  218601. for (int p = startPoint; p <= endPoint; p++)
  218602. {
  218603. const float x = scaleX * points[p].x;
  218604. const float y = scaleY * points[p].y;
  218605. if (p == startPoint)
  218606. {
  218607. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218608. {
  218609. float x2 = scaleX * points [endPoint].x;
  218610. float y2 = scaleY * points [endPoint].y;
  218611. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218612. {
  218613. x2 = (x + x2) * 0.5f;
  218614. y2 = (y + y2) * 0.5f;
  218615. }
  218616. destShape.startNewSubPath (x2, y2);
  218617. }
  218618. else
  218619. {
  218620. destShape.startNewSubPath (x, y);
  218621. }
  218622. }
  218623. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218624. {
  218625. if (p != startPoint)
  218626. destShape.lineTo (x, y);
  218627. }
  218628. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218629. {
  218630. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218631. float x2 = scaleX * points [nextIndex].x;
  218632. float y2 = scaleY * points [nextIndex].y;
  218633. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218634. {
  218635. x2 = (x + x2) * 0.5f;
  218636. y2 = (y + y2) * 0.5f;
  218637. }
  218638. else
  218639. {
  218640. ++p;
  218641. }
  218642. destShape.quadraticTo (x, y, x2, y2);
  218643. }
  218644. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218645. {
  218646. if (p >= endPoint)
  218647. return false;
  218648. const int next1 = p + 1;
  218649. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218650. const float x2 = scaleX * points [next1].x;
  218651. const float y2 = scaleY * points [next1].y;
  218652. const float x3 = scaleX * points [next2].x;
  218653. const float y3 = scaleY * points [next2].y;
  218654. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218655. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218656. return false;
  218657. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218658. p += 2;
  218659. }
  218660. }
  218661. destShape.closeSubPath();
  218662. }
  218663. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218664. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218665. addKerning (face, dest, character, glyphIndex);
  218666. return true;
  218667. }
  218668. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218669. {
  218670. const float height = (float) (face->ascender - face->descender);
  218671. uint32 rightGlyphIndex;
  218672. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218673. while (rightGlyphIndex != 0)
  218674. {
  218675. FT_Vector kerning;
  218676. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218677. {
  218678. if (kerning.x != 0)
  218679. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218680. }
  218681. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218682. }
  218683. }
  218684. // Add a glyph to a font
  218685. bool addGlyphToFont (const uint32 character, const String& fontName,
  218686. bool bold, bool italic, CustomTypeface& dest)
  218687. {
  218688. FT_Face face = createFT_Face (fontName, bold, italic);
  218689. return face != 0 && addGlyph (face, dest, character);
  218690. }
  218691. void getFamilyNames (StringArray& familyNames) const
  218692. {
  218693. for (int i = 0; i < faces.size(); i++)
  218694. familyNames.add (faces[i]->getFamilyName());
  218695. }
  218696. void getMonospacedNames (StringArray& monoSpaced) const
  218697. {
  218698. for (int i = 0; i < faces.size(); i++)
  218699. if (faces[i]->getMonospaced())
  218700. monoSpaced.add (faces[i]->getFamilyName());
  218701. }
  218702. void getSerifNames (StringArray& serif) const
  218703. {
  218704. for (int i = 0; i < faces.size(); i++)
  218705. if (faces[i]->getSerif())
  218706. serif.add (faces[i]->getFamilyName());
  218707. }
  218708. void getSansSerifNames (StringArray& sansSerif) const
  218709. {
  218710. for (int i = 0; i < faces.size(); i++)
  218711. if (! faces[i]->getSerif())
  218712. sansSerif.add (faces[i]->getFamilyName());
  218713. }
  218714. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218715. private:
  218716. FT_Library ftLib;
  218717. FT_Face lastFace;
  218718. String lastFontName;
  218719. bool lastBold, lastItalic;
  218720. OwnedArray<FreeTypeFontFace> faces;
  218721. };
  218722. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218723. class FreetypeTypeface : public CustomTypeface
  218724. {
  218725. public:
  218726. FreetypeTypeface (const Font& font)
  218727. {
  218728. FT_Face face = FreeTypeInterface::getInstance()
  218729. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218730. if (face == 0)
  218731. {
  218732. #if JUCE_DEBUG
  218733. String msg ("Failed to create typeface: ");
  218734. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218735. DBG (msg);
  218736. #endif
  218737. }
  218738. else
  218739. {
  218740. setCharacteristics (font.getTypefaceName(),
  218741. face->ascender / (float) (face->ascender - face->descender),
  218742. font.isBold(), font.isItalic(),
  218743. L' ');
  218744. }
  218745. }
  218746. bool loadGlyphIfPossible (juce_wchar character)
  218747. {
  218748. return FreeTypeInterface::getInstance()
  218749. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218750. }
  218751. };
  218752. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218753. {
  218754. return new FreetypeTypeface (font);
  218755. }
  218756. const StringArray Font::findAllTypefaceNames()
  218757. {
  218758. StringArray s;
  218759. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218760. s.sort (true);
  218761. return s;
  218762. }
  218763. namespace
  218764. {
  218765. const String pickBestFont (const StringArray& names,
  218766. const char* const choicesString)
  218767. {
  218768. StringArray choices;
  218769. choices.addTokens (String (choicesString), ",", String::empty);
  218770. choices.trim();
  218771. choices.removeEmptyStrings();
  218772. int i, j;
  218773. for (j = 0; j < choices.size(); ++j)
  218774. if (names.contains (choices[j], true))
  218775. return choices[j];
  218776. for (j = 0; j < choices.size(); ++j)
  218777. for (i = 0; i < names.size(); i++)
  218778. if (names[i].startsWithIgnoreCase (choices[j]))
  218779. return names[i];
  218780. for (j = 0; j < choices.size(); ++j)
  218781. for (i = 0; i < names.size(); i++)
  218782. if (names[i].containsIgnoreCase (choices[j]))
  218783. return names[i];
  218784. return names[0];
  218785. }
  218786. const String linux_getDefaultSansSerifFontName()
  218787. {
  218788. StringArray allFonts;
  218789. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218790. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218791. }
  218792. const String linux_getDefaultSerifFontName()
  218793. {
  218794. StringArray allFonts;
  218795. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218796. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218797. }
  218798. const String linux_getDefaultMonospacedFontName()
  218799. {
  218800. StringArray allFonts;
  218801. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218802. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218803. }
  218804. }
  218805. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  218806. {
  218807. defaultSans = linux_getDefaultSansSerifFontName();
  218808. defaultSerif = linux_getDefaultSerifFontName();
  218809. defaultFixed = linux_getDefaultMonospacedFontName();
  218810. }
  218811. #endif
  218812. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218813. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218814. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218815. // compiled on its own).
  218816. #if JUCE_INCLUDED_FILE
  218817. // These are defined in juce_linux_Messaging.cpp
  218818. extern Display* display;
  218819. extern XContext windowHandleXContext;
  218820. namespace Atoms
  218821. {
  218822. enum ProtocolItems
  218823. {
  218824. TAKE_FOCUS = 0,
  218825. DELETE_WINDOW = 1,
  218826. PING = 2
  218827. };
  218828. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218829. ActiveWin, Pid, WindowType, WindowState,
  218830. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218831. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218832. XdndActionDescription, XdndActionCopy,
  218833. allowedActions[5],
  218834. allowedMimeTypes[2];
  218835. const unsigned long DndVersion = 3;
  218836. static void initialiseAtoms()
  218837. {
  218838. static bool atomsInitialised = false;
  218839. if (! atomsInitialised)
  218840. {
  218841. atomsInitialised = true;
  218842. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218843. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218844. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218845. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218846. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218847. State = XInternAtom (display, "WM_STATE", True);
  218848. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218849. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218850. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218851. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218852. XdndAware = XInternAtom (display, "XdndAware", False);
  218853. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218854. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218855. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218856. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218857. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218858. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218859. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218860. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218861. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218862. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218863. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218864. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218865. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218866. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218867. allowedActions[1] = XdndActionCopy;
  218868. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218869. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218870. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218871. }
  218872. }
  218873. }
  218874. namespace Keys
  218875. {
  218876. enum MouseButtons
  218877. {
  218878. NoButton = 0,
  218879. LeftButton = 1,
  218880. MiddleButton = 2,
  218881. RightButton = 3,
  218882. WheelUp = 4,
  218883. WheelDown = 5
  218884. };
  218885. static int AltMask = 0;
  218886. static int NumLockMask = 0;
  218887. static bool numLock = false;
  218888. static bool capsLock = false;
  218889. static char keyStates [32];
  218890. static const int extendedKeyModifier = 0x10000000;
  218891. }
  218892. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218893. {
  218894. int keysym;
  218895. if (keyCode & Keys::extendedKeyModifier)
  218896. {
  218897. keysym = 0xff00 | (keyCode & 0xff);
  218898. }
  218899. else
  218900. {
  218901. keysym = keyCode;
  218902. if (keysym == (XK_Tab & 0xff)
  218903. || keysym == (XK_Return & 0xff)
  218904. || keysym == (XK_Escape & 0xff)
  218905. || keysym == (XK_BackSpace & 0xff))
  218906. {
  218907. keysym |= 0xff00;
  218908. }
  218909. }
  218910. ScopedXLock xlock;
  218911. const int keycode = XKeysymToKeycode (display, keysym);
  218912. const int keybyte = keycode >> 3;
  218913. const int keybit = (1 << (keycode & 7));
  218914. return (Keys::keyStates [keybyte] & keybit) != 0;
  218915. }
  218916. #if JUCE_USE_XSHM
  218917. namespace XSHMHelpers
  218918. {
  218919. static int trappedErrorCode = 0;
  218920. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218921. {
  218922. trappedErrorCode = err->error_code;
  218923. return 0;
  218924. }
  218925. static bool isShmAvailable() throw()
  218926. {
  218927. static bool isChecked = false;
  218928. static bool isAvailable = false;
  218929. if (! isChecked)
  218930. {
  218931. isChecked = true;
  218932. int major, minor;
  218933. Bool pixmaps;
  218934. ScopedXLock xlock;
  218935. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218936. {
  218937. trappedErrorCode = 0;
  218938. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218939. XShmSegmentInfo segmentInfo;
  218940. zerostruct (segmentInfo);
  218941. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218942. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218943. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218944. xImage->bytes_per_line * xImage->height,
  218945. IPC_CREAT | 0777)) >= 0)
  218946. {
  218947. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218948. if (segmentInfo.shmaddr != (void*) -1)
  218949. {
  218950. segmentInfo.readOnly = False;
  218951. xImage->data = segmentInfo.shmaddr;
  218952. XSync (display, False);
  218953. if (XShmAttach (display, &segmentInfo) != 0)
  218954. {
  218955. XSync (display, False);
  218956. XShmDetach (display, &segmentInfo);
  218957. isAvailable = true;
  218958. }
  218959. }
  218960. XFlush (display);
  218961. XDestroyImage (xImage);
  218962. shmdt (segmentInfo.shmaddr);
  218963. }
  218964. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218965. XSetErrorHandler (oldHandler);
  218966. if (trappedErrorCode != 0)
  218967. isAvailable = false;
  218968. }
  218969. }
  218970. return isAvailable;
  218971. }
  218972. }
  218973. #endif
  218974. #if JUCE_USE_XRENDER
  218975. namespace XRender
  218976. {
  218977. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218978. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218979. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218980. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218981. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218982. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218983. static tXRenderFindFormat xRenderFindFormat = 0;
  218984. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218985. static bool isAvailable()
  218986. {
  218987. static bool hasLoaded = false;
  218988. if (! hasLoaded)
  218989. {
  218990. ScopedXLock xlock;
  218991. hasLoaded = true;
  218992. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218993. if (h != 0)
  218994. {
  218995. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218996. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218997. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218998. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218999. }
  219000. if (xRenderQueryVersion != 0
  219001. && xRenderFindStandardFormat != 0
  219002. && xRenderFindFormat != 0
  219003. && xRenderFindVisualFormat != 0)
  219004. {
  219005. int major, minor;
  219006. if (xRenderQueryVersion (display, &major, &minor))
  219007. return true;
  219008. }
  219009. xRenderQueryVersion = 0;
  219010. }
  219011. return xRenderQueryVersion != 0;
  219012. }
  219013. static XRenderPictFormat* findPictureFormat()
  219014. {
  219015. ScopedXLock xlock;
  219016. XRenderPictFormat* pictFormat = 0;
  219017. if (isAvailable())
  219018. {
  219019. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219020. if (pictFormat == 0)
  219021. {
  219022. XRenderPictFormat desiredFormat;
  219023. desiredFormat.type = PictTypeDirect;
  219024. desiredFormat.depth = 32;
  219025. desiredFormat.direct.alphaMask = 0xff;
  219026. desiredFormat.direct.redMask = 0xff;
  219027. desiredFormat.direct.greenMask = 0xff;
  219028. desiredFormat.direct.blueMask = 0xff;
  219029. desiredFormat.direct.alpha = 24;
  219030. desiredFormat.direct.red = 16;
  219031. desiredFormat.direct.green = 8;
  219032. desiredFormat.direct.blue = 0;
  219033. pictFormat = xRenderFindFormat (display,
  219034. PictFormatType | PictFormatDepth
  219035. | PictFormatRedMask | PictFormatRed
  219036. | PictFormatGreenMask | PictFormatGreen
  219037. | PictFormatBlueMask | PictFormatBlue
  219038. | PictFormatAlphaMask | PictFormatAlpha,
  219039. &desiredFormat,
  219040. 0);
  219041. }
  219042. }
  219043. return pictFormat;
  219044. }
  219045. }
  219046. #endif
  219047. namespace Visuals
  219048. {
  219049. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219050. {
  219051. ScopedXLock xlock;
  219052. Visual* visual = 0;
  219053. int numVisuals = 0;
  219054. long desiredMask = VisualNoMask;
  219055. XVisualInfo desiredVisual;
  219056. desiredVisual.screen = DefaultScreen (display);
  219057. desiredVisual.depth = desiredDepth;
  219058. desiredMask = VisualScreenMask | VisualDepthMask;
  219059. if (desiredDepth == 32)
  219060. {
  219061. desiredVisual.c_class = TrueColor;
  219062. desiredVisual.red_mask = 0x00FF0000;
  219063. desiredVisual.green_mask = 0x0000FF00;
  219064. desiredVisual.blue_mask = 0x000000FF;
  219065. desiredVisual.bits_per_rgb = 8;
  219066. desiredMask |= VisualClassMask;
  219067. desiredMask |= VisualRedMaskMask;
  219068. desiredMask |= VisualGreenMaskMask;
  219069. desiredMask |= VisualBlueMaskMask;
  219070. desiredMask |= VisualBitsPerRGBMask;
  219071. }
  219072. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219073. desiredMask,
  219074. &desiredVisual,
  219075. &numVisuals);
  219076. if (xvinfos != 0)
  219077. {
  219078. for (int i = 0; i < numVisuals; i++)
  219079. {
  219080. if (xvinfos[i].depth == desiredDepth)
  219081. {
  219082. visual = xvinfos[i].visual;
  219083. break;
  219084. }
  219085. }
  219086. XFree (xvinfos);
  219087. }
  219088. return visual;
  219089. }
  219090. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219091. {
  219092. Visual* visual = 0;
  219093. if (desiredDepth == 32)
  219094. {
  219095. #if JUCE_USE_XSHM
  219096. if (XSHMHelpers::isShmAvailable())
  219097. {
  219098. #if JUCE_USE_XRENDER
  219099. if (XRender::isAvailable())
  219100. {
  219101. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219102. if (pictFormat != 0)
  219103. {
  219104. int numVisuals = 0;
  219105. XVisualInfo desiredVisual;
  219106. desiredVisual.screen = DefaultScreen (display);
  219107. desiredVisual.depth = 32;
  219108. desiredVisual.bits_per_rgb = 8;
  219109. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219110. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219111. &desiredVisual, &numVisuals);
  219112. if (xvinfos != 0)
  219113. {
  219114. for (int i = 0; i < numVisuals; ++i)
  219115. {
  219116. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219117. if (pictVisualFormat != 0
  219118. && pictVisualFormat->type == PictTypeDirect
  219119. && pictVisualFormat->direct.alphaMask)
  219120. {
  219121. visual = xvinfos[i].visual;
  219122. matchedDepth = 32;
  219123. break;
  219124. }
  219125. }
  219126. XFree (xvinfos);
  219127. }
  219128. }
  219129. }
  219130. #endif
  219131. if (visual == 0)
  219132. {
  219133. visual = findVisualWithDepth (32);
  219134. if (visual != 0)
  219135. matchedDepth = 32;
  219136. }
  219137. }
  219138. #endif
  219139. }
  219140. if (visual == 0 && desiredDepth >= 24)
  219141. {
  219142. visual = findVisualWithDepth (24);
  219143. if (visual != 0)
  219144. matchedDepth = 24;
  219145. }
  219146. if (visual == 0 && desiredDepth >= 16)
  219147. {
  219148. visual = findVisualWithDepth (16);
  219149. if (visual != 0)
  219150. matchedDepth = 16;
  219151. }
  219152. return visual;
  219153. }
  219154. }
  219155. class XBitmapImage : public Image::SharedImage
  219156. {
  219157. public:
  219158. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219159. const bool clearImage, const int imageDepth_, Visual* visual)
  219160. : Image::SharedImage (format_, w, h),
  219161. imageDepth (imageDepth_),
  219162. gc (None)
  219163. {
  219164. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219165. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219166. lineStride = ((w * pixelStride + 3) & ~3);
  219167. ScopedXLock xlock;
  219168. #if JUCE_USE_XSHM
  219169. usingXShm = false;
  219170. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219171. {
  219172. zerostruct (segmentInfo);
  219173. segmentInfo.shmid = -1;
  219174. segmentInfo.shmaddr = (char *) -1;
  219175. segmentInfo.readOnly = False;
  219176. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219177. if (xImage != 0)
  219178. {
  219179. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219180. xImage->bytes_per_line * xImage->height,
  219181. IPC_CREAT | 0777)) >= 0)
  219182. {
  219183. if (segmentInfo.shmid != -1)
  219184. {
  219185. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219186. if (segmentInfo.shmaddr != (void*) -1)
  219187. {
  219188. segmentInfo.readOnly = False;
  219189. xImage->data = segmentInfo.shmaddr;
  219190. imageData = (uint8*) segmentInfo.shmaddr;
  219191. if (XShmAttach (display, &segmentInfo) != 0)
  219192. usingXShm = true;
  219193. else
  219194. jassertfalse;
  219195. }
  219196. else
  219197. {
  219198. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219199. }
  219200. }
  219201. }
  219202. }
  219203. }
  219204. if (! usingXShm)
  219205. #endif
  219206. {
  219207. imageDataAllocated.malloc (lineStride * h);
  219208. imageData = imageDataAllocated;
  219209. if (format_ == Image::ARGB && clearImage)
  219210. zeromem (imageData, h * lineStride);
  219211. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219212. xImage->width = w;
  219213. xImage->height = h;
  219214. xImage->xoffset = 0;
  219215. xImage->format = ZPixmap;
  219216. xImage->data = (char*) imageData;
  219217. xImage->byte_order = ImageByteOrder (display);
  219218. xImage->bitmap_unit = BitmapUnit (display);
  219219. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219220. xImage->bitmap_pad = 32;
  219221. xImage->depth = pixelStride * 8;
  219222. xImage->bytes_per_line = lineStride;
  219223. xImage->bits_per_pixel = pixelStride * 8;
  219224. xImage->red_mask = 0x00FF0000;
  219225. xImage->green_mask = 0x0000FF00;
  219226. xImage->blue_mask = 0x000000FF;
  219227. if (imageDepth == 16)
  219228. {
  219229. const int pixelStride = 2;
  219230. const int lineStride = ((w * pixelStride + 3) & ~3);
  219231. imageData16Bit.malloc (lineStride * h);
  219232. xImage->data = imageData16Bit;
  219233. xImage->bitmap_pad = 16;
  219234. xImage->depth = pixelStride * 8;
  219235. xImage->bytes_per_line = lineStride;
  219236. xImage->bits_per_pixel = pixelStride * 8;
  219237. xImage->red_mask = visual->red_mask;
  219238. xImage->green_mask = visual->green_mask;
  219239. xImage->blue_mask = visual->blue_mask;
  219240. }
  219241. if (! XInitImage (xImage))
  219242. jassertfalse;
  219243. }
  219244. }
  219245. ~XBitmapImage()
  219246. {
  219247. ScopedXLock xlock;
  219248. if (gc != None)
  219249. XFreeGC (display, gc);
  219250. #if JUCE_USE_XSHM
  219251. if (usingXShm)
  219252. {
  219253. XShmDetach (display, &segmentInfo);
  219254. XFlush (display);
  219255. XDestroyImage (xImage);
  219256. shmdt (segmentInfo.shmaddr);
  219257. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219258. }
  219259. else
  219260. #endif
  219261. {
  219262. xImage->data = 0;
  219263. XDestroyImage (xImage);
  219264. }
  219265. }
  219266. Image::ImageType getType() const { return Image::NativeImage; }
  219267. LowLevelGraphicsContext* createLowLevelContext()
  219268. {
  219269. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219270. }
  219271. SharedImage* clone()
  219272. {
  219273. jassertfalse;
  219274. return 0;
  219275. }
  219276. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219277. {
  219278. ScopedXLock xlock;
  219279. if (gc == None)
  219280. {
  219281. XGCValues gcvalues;
  219282. gcvalues.foreground = None;
  219283. gcvalues.background = None;
  219284. gcvalues.function = GXcopy;
  219285. gcvalues.plane_mask = AllPlanes;
  219286. gcvalues.clip_mask = None;
  219287. gcvalues.graphics_exposures = False;
  219288. gc = XCreateGC (display, window,
  219289. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219290. &gcvalues);
  219291. }
  219292. if (imageDepth == 16)
  219293. {
  219294. const uint32 rMask = xImage->red_mask;
  219295. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219296. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219297. const uint32 gMask = xImage->green_mask;
  219298. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219299. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219300. const uint32 bMask = xImage->blue_mask;
  219301. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219302. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219303. const Image::BitmapData srcData (Image (this), false);
  219304. for (int y = sy; y < sy + dh; ++y)
  219305. {
  219306. const uint8* p = srcData.getPixelPointer (sx, y);
  219307. for (int x = sx; x < sx + dw; ++x)
  219308. {
  219309. const PixelRGB* const pixel = (const PixelRGB*) p;
  219310. p += srcData.pixelStride;
  219311. XPutPixel (xImage, x, y,
  219312. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219313. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219314. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219315. }
  219316. }
  219317. }
  219318. // blit results to screen.
  219319. #if JUCE_USE_XSHM
  219320. if (usingXShm)
  219321. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219322. else
  219323. #endif
  219324. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219325. }
  219326. private:
  219327. XImage* xImage;
  219328. const int imageDepth;
  219329. HeapBlock <uint8> imageDataAllocated;
  219330. HeapBlock <char> imageData16Bit;
  219331. GC gc;
  219332. #if JUCE_USE_XSHM
  219333. XShmSegmentInfo segmentInfo;
  219334. bool usingXShm;
  219335. #endif
  219336. static int getShiftNeeded (const uint32 mask) throw()
  219337. {
  219338. for (int i = 32; --i >= 0;)
  219339. if (((mask >> i) & 1) != 0)
  219340. return i - 7;
  219341. jassertfalse;
  219342. return 0;
  219343. }
  219344. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219345. };
  219346. namespace PixmapHelpers
  219347. {
  219348. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219349. {
  219350. ScopedXLock xlock;
  219351. const int width = image.getWidth();
  219352. const int height = image.getHeight();
  219353. HeapBlock <uint32> colour (width * height);
  219354. int index = 0;
  219355. for (int y = 0; y < height; ++y)
  219356. for (int x = 0; x < width; ++x)
  219357. colour[index++] = image.getPixelAt (x, y).getARGB();
  219358. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219359. 0, reinterpret_cast<char*> (colour.getData()),
  219360. width, height, 32, 0);
  219361. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219362. width, height, 24);
  219363. GC gc = XCreateGC (display, pixmap, 0, 0);
  219364. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219365. XFreeGC (display, gc);
  219366. return pixmap;
  219367. }
  219368. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219369. {
  219370. ScopedXLock xlock;
  219371. const int width = image.getWidth();
  219372. const int height = image.getHeight();
  219373. const int stride = (width + 7) >> 3;
  219374. HeapBlock <char> mask;
  219375. mask.calloc (stride * height);
  219376. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219377. for (int y = 0; y < height; ++y)
  219378. {
  219379. for (int x = 0; x < width; ++x)
  219380. {
  219381. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219382. const int offset = y * stride + (x >> 3);
  219383. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219384. mask[offset] |= bit;
  219385. }
  219386. }
  219387. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219388. mask.getData(), width, height, 1, 0, 1);
  219389. }
  219390. }
  219391. class LinuxComponentPeer : public ComponentPeer
  219392. {
  219393. public:
  219394. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219395. : ComponentPeer (component, windowStyleFlags),
  219396. windowH (0),
  219397. parentWindow (0),
  219398. wx (0),
  219399. wy (0),
  219400. ww (0),
  219401. wh (0),
  219402. fullScreen (false),
  219403. mapped (false),
  219404. visual (0),
  219405. depth (0)
  219406. {
  219407. // it's dangerous to create a window on a thread other than the message thread..
  219408. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219409. repainter = new LinuxRepaintManager (this);
  219410. createWindow();
  219411. setTitle (component->getName());
  219412. }
  219413. ~LinuxComponentPeer()
  219414. {
  219415. // it's dangerous to delete a window on a thread other than the message thread..
  219416. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219417. deleteIconPixmaps();
  219418. destroyWindow();
  219419. windowH = 0;
  219420. }
  219421. void* getNativeHandle() const
  219422. {
  219423. return (void*) windowH;
  219424. }
  219425. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219426. {
  219427. XPointer peer = 0;
  219428. ScopedXLock xlock;
  219429. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219430. {
  219431. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219432. peer = 0;
  219433. }
  219434. return (LinuxComponentPeer*) peer;
  219435. }
  219436. void setVisible (bool shouldBeVisible)
  219437. {
  219438. ScopedXLock xlock;
  219439. if (shouldBeVisible)
  219440. XMapWindow (display, windowH);
  219441. else
  219442. XUnmapWindow (display, windowH);
  219443. }
  219444. void setTitle (const String& title)
  219445. {
  219446. XTextProperty nameProperty;
  219447. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219448. ScopedXLock xlock;
  219449. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219450. {
  219451. XSetWMName (display, windowH, &nameProperty);
  219452. XSetWMIconName (display, windowH, &nameProperty);
  219453. XFree (nameProperty.value);
  219454. }
  219455. }
  219456. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219457. {
  219458. fullScreen = isNowFullScreen;
  219459. if (windowH != 0)
  219460. {
  219461. WeakReference<Component> deletionChecker (component);
  219462. wx = x;
  219463. wy = y;
  219464. ww = jmax (1, w);
  219465. wh = jmax (1, h);
  219466. ScopedXLock xlock;
  219467. // Make sure the Window manager does what we want
  219468. XSizeHints* hints = XAllocSizeHints();
  219469. hints->flags = USSize | USPosition;
  219470. hints->width = ww;
  219471. hints->height = wh;
  219472. hints->x = wx;
  219473. hints->y = wy;
  219474. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219475. {
  219476. hints->min_width = hints->max_width = hints->width;
  219477. hints->min_height = hints->max_height = hints->height;
  219478. hints->flags |= PMinSize | PMaxSize;
  219479. }
  219480. XSetWMNormalHints (display, windowH, hints);
  219481. XFree (hints);
  219482. XMoveResizeWindow (display, windowH,
  219483. wx - windowBorder.getLeft(),
  219484. wy - windowBorder.getTop(), ww, wh);
  219485. if (deletionChecker != 0)
  219486. {
  219487. updateBorderSize();
  219488. handleMovedOrResized();
  219489. }
  219490. }
  219491. }
  219492. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219493. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219494. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219495. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219496. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219497. {
  219498. return relativePosition + getScreenPosition();
  219499. }
  219500. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219501. {
  219502. return screenPosition - getScreenPosition();
  219503. }
  219504. void setAlpha (float newAlpha)
  219505. {
  219506. //xxx todo!
  219507. }
  219508. void setMinimised (bool shouldBeMinimised)
  219509. {
  219510. if (shouldBeMinimised)
  219511. {
  219512. Window root = RootWindow (display, DefaultScreen (display));
  219513. XClientMessageEvent clientMsg;
  219514. clientMsg.display = display;
  219515. clientMsg.window = windowH;
  219516. clientMsg.type = ClientMessage;
  219517. clientMsg.format = 32;
  219518. clientMsg.message_type = Atoms::ChangeState;
  219519. clientMsg.data.l[0] = IconicState;
  219520. ScopedXLock xlock;
  219521. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219522. }
  219523. else
  219524. {
  219525. setVisible (true);
  219526. }
  219527. }
  219528. bool isMinimised() const
  219529. {
  219530. bool minimised = false;
  219531. unsigned char* stateProp;
  219532. unsigned long nitems, bytesLeft;
  219533. Atom actualType;
  219534. int actualFormat;
  219535. ScopedXLock xlock;
  219536. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219537. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219538. &stateProp) == Success
  219539. && actualType == Atoms::State
  219540. && actualFormat == 32
  219541. && nitems > 0)
  219542. {
  219543. if (((unsigned long*) stateProp)[0] == IconicState)
  219544. minimised = true;
  219545. XFree (stateProp);
  219546. }
  219547. return minimised;
  219548. }
  219549. void setFullScreen (const bool shouldBeFullScreen)
  219550. {
  219551. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219552. setMinimised (false);
  219553. if (fullScreen != shouldBeFullScreen)
  219554. {
  219555. if (shouldBeFullScreen)
  219556. r = Desktop::getInstance().getMainMonitorArea();
  219557. if (! r.isEmpty())
  219558. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219559. getComponent()->repaint();
  219560. }
  219561. }
  219562. bool isFullScreen() const
  219563. {
  219564. return fullScreen;
  219565. }
  219566. bool isChildWindowOf (Window possibleParent) const
  219567. {
  219568. Window* windowList = 0;
  219569. uint32 windowListSize = 0;
  219570. Window parent, root;
  219571. ScopedXLock xlock;
  219572. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219573. {
  219574. if (windowList != 0)
  219575. XFree (windowList);
  219576. return parent == possibleParent;
  219577. }
  219578. return false;
  219579. }
  219580. bool isFrontWindow() const
  219581. {
  219582. Window* windowList = 0;
  219583. uint32 windowListSize = 0;
  219584. bool result = false;
  219585. ScopedXLock xlock;
  219586. Window parent, root = RootWindow (display, DefaultScreen (display));
  219587. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219588. {
  219589. for (int i = windowListSize; --i >= 0;)
  219590. {
  219591. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219592. if (peer != 0)
  219593. {
  219594. result = (peer == this);
  219595. break;
  219596. }
  219597. }
  219598. }
  219599. if (windowList != 0)
  219600. XFree (windowList);
  219601. return result;
  219602. }
  219603. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219604. {
  219605. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219606. return false;
  219607. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219608. {
  219609. Component* const c = Desktop::getInstance().getComponent (i);
  219610. if (c == getComponent())
  219611. break;
  219612. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219613. return false;
  219614. }
  219615. if (trueIfInAChildWindow)
  219616. return true;
  219617. ::Window root, child;
  219618. unsigned int bw, depth;
  219619. int wx, wy, w, h;
  219620. ScopedXLock xlock;
  219621. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219622. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219623. &bw, &depth))
  219624. {
  219625. return false;
  219626. }
  219627. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219628. return false;
  219629. return child == None;
  219630. }
  219631. const BorderSize getFrameSize() const
  219632. {
  219633. return BorderSize();
  219634. }
  219635. bool setAlwaysOnTop (bool alwaysOnTop)
  219636. {
  219637. return false;
  219638. }
  219639. void toFront (bool makeActive)
  219640. {
  219641. if (makeActive)
  219642. {
  219643. setVisible (true);
  219644. grabFocus();
  219645. }
  219646. XEvent ev;
  219647. ev.xclient.type = ClientMessage;
  219648. ev.xclient.serial = 0;
  219649. ev.xclient.send_event = True;
  219650. ev.xclient.message_type = Atoms::ActiveWin;
  219651. ev.xclient.window = windowH;
  219652. ev.xclient.format = 32;
  219653. ev.xclient.data.l[0] = 2;
  219654. ev.xclient.data.l[1] = CurrentTime;
  219655. ev.xclient.data.l[2] = 0;
  219656. ev.xclient.data.l[3] = 0;
  219657. ev.xclient.data.l[4] = 0;
  219658. {
  219659. ScopedXLock xlock;
  219660. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219661. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219662. XWindowAttributes attr;
  219663. XGetWindowAttributes (display, windowH, &attr);
  219664. if (component->isAlwaysOnTop())
  219665. XRaiseWindow (display, windowH);
  219666. XSync (display, False);
  219667. }
  219668. handleBroughtToFront();
  219669. }
  219670. void toBehind (ComponentPeer* other)
  219671. {
  219672. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219673. jassert (otherPeer != 0); // wrong type of window?
  219674. if (otherPeer != 0)
  219675. {
  219676. setMinimised (false);
  219677. Window newStack[] = { otherPeer->windowH, windowH };
  219678. ScopedXLock xlock;
  219679. XRestackWindows (display, newStack, 2);
  219680. }
  219681. }
  219682. bool isFocused() const
  219683. {
  219684. int revert = 0;
  219685. Window focusedWindow = 0;
  219686. ScopedXLock xlock;
  219687. XGetInputFocus (display, &focusedWindow, &revert);
  219688. return focusedWindow == windowH;
  219689. }
  219690. void grabFocus()
  219691. {
  219692. XWindowAttributes atts;
  219693. ScopedXLock xlock;
  219694. if (windowH != 0
  219695. && XGetWindowAttributes (display, windowH, &atts)
  219696. && atts.map_state == IsViewable
  219697. && ! isFocused())
  219698. {
  219699. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219700. isActiveApplication = true;
  219701. }
  219702. }
  219703. void textInputRequired (const Point<int>&)
  219704. {
  219705. }
  219706. void repaint (const Rectangle<int>& area)
  219707. {
  219708. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219709. }
  219710. void performAnyPendingRepaintsNow()
  219711. {
  219712. repainter->performAnyPendingRepaintsNow();
  219713. }
  219714. void setIcon (const Image& newIcon)
  219715. {
  219716. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219717. HeapBlock <unsigned long> data (dataSize);
  219718. int index = 0;
  219719. data[index++] = newIcon.getWidth();
  219720. data[index++] = newIcon.getHeight();
  219721. for (int y = 0; y < newIcon.getHeight(); ++y)
  219722. for (int x = 0; x < newIcon.getWidth(); ++x)
  219723. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219724. ScopedXLock xlock;
  219725. XChangeProperty (display, windowH,
  219726. XInternAtom (display, "_NET_WM_ICON", False),
  219727. XA_CARDINAL, 32, PropModeReplace,
  219728. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219729. deleteIconPixmaps();
  219730. XWMHints* wmHints = XGetWMHints (display, windowH);
  219731. if (wmHints == 0)
  219732. wmHints = XAllocWMHints();
  219733. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219734. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  219735. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  219736. XSetWMHints (display, windowH, wmHints);
  219737. XFree (wmHints);
  219738. XSync (display, False);
  219739. }
  219740. void deleteIconPixmaps()
  219741. {
  219742. ScopedXLock xlock;
  219743. XWMHints* wmHints = XGetWMHints (display, windowH);
  219744. if (wmHints != 0)
  219745. {
  219746. if ((wmHints->flags & IconPixmapHint) != 0)
  219747. {
  219748. wmHints->flags &= ~IconPixmapHint;
  219749. XFreePixmap (display, wmHints->icon_pixmap);
  219750. }
  219751. if ((wmHints->flags & IconMaskHint) != 0)
  219752. {
  219753. wmHints->flags &= ~IconMaskHint;
  219754. XFreePixmap (display, wmHints->icon_mask);
  219755. }
  219756. XSetWMHints (display, windowH, wmHints);
  219757. XFree (wmHints);
  219758. }
  219759. }
  219760. void handleWindowMessage (XEvent* event)
  219761. {
  219762. switch (event->xany.type)
  219763. {
  219764. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  219765. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  219766. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  219767. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  219768. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  219769. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  219770. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  219771. case FocusIn: handleFocusInEvent(); break;
  219772. case FocusOut: handleFocusOutEvent(); break;
  219773. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  219774. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  219775. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  219776. case SelectionNotify: handleDragAndDropSelection (event); break;
  219777. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  219778. case ReparentNotify: handleReparentNotifyEvent(); break;
  219779. case GravityNotify: handleGravityNotify(); break;
  219780. case CirculateNotify:
  219781. case CreateNotify:
  219782. case DestroyNotify:
  219783. // Think we can ignore these
  219784. break;
  219785. case MapNotify:
  219786. mapped = true;
  219787. handleBroughtToFront();
  219788. break;
  219789. case UnmapNotify:
  219790. mapped = false;
  219791. break;
  219792. case SelectionClear:
  219793. case SelectionRequest:
  219794. break;
  219795. default:
  219796. #if JUCE_USE_XSHM
  219797. {
  219798. ScopedXLock xlock;
  219799. if (event->xany.type == XShmGetEventBase (display))
  219800. repainter->notifyPaintCompleted();
  219801. }
  219802. #endif
  219803. break;
  219804. }
  219805. }
  219806. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  219807. {
  219808. char utf8 [64] = { 0 };
  219809. juce_wchar unicodeChar = 0;
  219810. int keyCode = 0;
  219811. bool keyDownChange = false;
  219812. KeySym sym;
  219813. {
  219814. ScopedXLock xlock;
  219815. updateKeyStates (keyEvent->keycode, true);
  219816. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219817. ::setlocale (LC_ALL, "");
  219818. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219819. ::setlocale (LC_ALL, oldLocale);
  219820. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219821. keyCode = (int) unicodeChar;
  219822. if (keyCode < 0x20)
  219823. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219824. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219825. }
  219826. const ModifierKeys oldMods (currentModifiers);
  219827. bool keyPressed = false;
  219828. if ((sym & 0xff00) == 0xff00)
  219829. {
  219830. switch (sym) // Translate keypad
  219831. {
  219832. case XK_KP_Divide: keyCode = XK_slash; break;
  219833. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  219834. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  219835. case XK_KP_Add: keyCode = XK_plus; break;
  219836. case XK_KP_Enter: keyCode = XK_Return; break;
  219837. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  219838. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  219839. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  219840. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  219841. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  219842. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  219843. case XK_KP_5: keyCode = XK_5; break;
  219844. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  219845. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  219846. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  219847. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  219848. default: break;
  219849. }
  219850. switch (sym)
  219851. {
  219852. case XK_Left:
  219853. case XK_Right:
  219854. case XK_Up:
  219855. case XK_Down:
  219856. case XK_Page_Up:
  219857. case XK_Page_Down:
  219858. case XK_End:
  219859. case XK_Home:
  219860. case XK_Delete:
  219861. case XK_Insert:
  219862. keyPressed = true;
  219863. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219864. break;
  219865. case XK_Tab:
  219866. case XK_Return:
  219867. case XK_Escape:
  219868. case XK_BackSpace:
  219869. keyPressed = true;
  219870. keyCode &= 0xff;
  219871. break;
  219872. default:
  219873. if (sym >= XK_F1 && sym <= XK_F16)
  219874. {
  219875. keyPressed = true;
  219876. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219877. }
  219878. break;
  219879. }
  219880. }
  219881. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219882. keyPressed = true;
  219883. if (oldMods != currentModifiers)
  219884. handleModifierKeysChange();
  219885. if (keyDownChange)
  219886. handleKeyUpOrDown (true);
  219887. if (keyPressed)
  219888. handleKeyPress (keyCode, unicodeChar);
  219889. }
  219890. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  219891. {
  219892. updateKeyStates (keyEvent->keycode, false);
  219893. KeySym sym;
  219894. {
  219895. ScopedXLock xlock;
  219896. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219897. }
  219898. const ModifierKeys oldMods (currentModifiers);
  219899. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219900. if (oldMods != currentModifiers)
  219901. handleModifierKeysChange();
  219902. if (keyDownChange)
  219903. handleKeyUpOrDown (false);
  219904. }
  219905. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  219906. {
  219907. updateKeyModifiers (buttonPressEvent->state);
  219908. bool buttonMsg = false;
  219909. const int map = pointerMap [buttonPressEvent->button - Button1];
  219910. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219911. {
  219912. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219913. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219914. }
  219915. if (map == Keys::LeftButton)
  219916. {
  219917. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219918. buttonMsg = true;
  219919. }
  219920. else if (map == Keys::RightButton)
  219921. {
  219922. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219923. buttonMsg = true;
  219924. }
  219925. else if (map == Keys::MiddleButton)
  219926. {
  219927. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219928. buttonMsg = true;
  219929. }
  219930. if (buttonMsg)
  219931. {
  219932. toFront (true);
  219933. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219934. getEventTime (buttonPressEvent->time));
  219935. }
  219936. clearLastMousePos();
  219937. }
  219938. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  219939. {
  219940. updateKeyModifiers (buttonRelEvent->state);
  219941. const int map = pointerMap [buttonRelEvent->button - Button1];
  219942. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219943. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219944. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219945. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219946. getEventTime (buttonRelEvent->time));
  219947. clearLastMousePos();
  219948. }
  219949. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  219950. {
  219951. updateKeyModifiers (movedEvent->state);
  219952. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  219953. if (lastMousePos != mousePos)
  219954. {
  219955. lastMousePos = mousePos;
  219956. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219957. {
  219958. Window wRoot = 0, wParent = 0;
  219959. {
  219960. ScopedXLock xlock;
  219961. unsigned int numChildren;
  219962. Window* wChild = 0;
  219963. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219964. }
  219965. if (wParent != 0
  219966. && wParent != windowH
  219967. && wParent != wRoot)
  219968. {
  219969. parentWindow = wParent;
  219970. updateBounds();
  219971. }
  219972. else
  219973. {
  219974. parentWindow = 0;
  219975. }
  219976. }
  219977. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219978. }
  219979. }
  219980. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  219981. {
  219982. clearLastMousePos();
  219983. if (! currentModifiers.isAnyMouseButtonDown())
  219984. {
  219985. updateKeyModifiers (enterEvent->state);
  219986. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219987. }
  219988. }
  219989. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  219990. {
  219991. // Suppress the normal leave if we've got a pointer grab, or if
  219992. // it's a bogus one caused by clicking a mouse button when running
  219993. // in a Window manager
  219994. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219995. || leaveEvent->mode == NotifyUngrab)
  219996. {
  219997. updateKeyModifiers (leaveEvent->state);
  219998. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219999. }
  220000. }
  220001. void handleFocusInEvent()
  220002. {
  220003. isActiveApplication = true;
  220004. if (isFocused())
  220005. handleFocusGain();
  220006. }
  220007. void handleFocusOutEvent()
  220008. {
  220009. isActiveApplication = false;
  220010. if (! isFocused())
  220011. handleFocusLoss();
  220012. }
  220013. void handleExposeEvent (XExposeEvent* exposeEvent)
  220014. {
  220015. // Batch together all pending expose events
  220016. XEvent nextEvent;
  220017. ScopedXLock xlock;
  220018. if (exposeEvent->window != windowH)
  220019. {
  220020. Window child;
  220021. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220022. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220023. &child);
  220024. }
  220025. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220026. exposeEvent->width, exposeEvent->height));
  220027. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220028. {
  220029. XPeekEvent (display, (XEvent*) &nextEvent);
  220030. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  220031. break;
  220032. XNextEvent (display, (XEvent*) &nextEvent);
  220033. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220034. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220035. nextExposeEvent->width, nextExposeEvent->height));
  220036. }
  220037. }
  220038. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  220039. {
  220040. updateBounds();
  220041. updateBorderSize();
  220042. handleMovedOrResized();
  220043. // if the native title bar is dragged, need to tell any active menus, etc.
  220044. if ((styleFlags & windowHasTitleBar) != 0
  220045. && component->isCurrentlyBlockedByAnotherModalComponent())
  220046. {
  220047. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220048. if (currentModalComp != 0)
  220049. currentModalComp->inputAttemptWhenModal();
  220050. }
  220051. if (confEvent->window == windowH
  220052. && confEvent->above != 0
  220053. && isFrontWindow())
  220054. {
  220055. handleBroughtToFront();
  220056. }
  220057. }
  220058. void handleReparentNotifyEvent()
  220059. {
  220060. parentWindow = 0;
  220061. Window wRoot = 0;
  220062. Window* wChild = 0;
  220063. unsigned int numChildren;
  220064. {
  220065. ScopedXLock xlock;
  220066. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220067. }
  220068. if (parentWindow == windowH || parentWindow == wRoot)
  220069. parentWindow = 0;
  220070. handleGravityNotify();
  220071. }
  220072. void handleGravityNotify()
  220073. {
  220074. updateBounds();
  220075. updateBorderSize();
  220076. handleMovedOrResized();
  220077. }
  220078. void handleMappingNotify (XMappingEvent* const mappingEvent)
  220079. {
  220080. if (mappingEvent->request != MappingPointer)
  220081. {
  220082. // Deal with modifier/keyboard mapping
  220083. ScopedXLock xlock;
  220084. XRefreshKeyboardMapping (mappingEvent);
  220085. updateModifierMappings();
  220086. }
  220087. }
  220088. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  220089. {
  220090. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220091. {
  220092. const Atom atom = (Atom) clientMsg->data.l[0];
  220093. if (atom == Atoms::ProtocolList [Atoms::PING])
  220094. {
  220095. Window root = RootWindow (display, DefaultScreen (display));
  220096. clientMsg->window = root;
  220097. XSendEvent (display, root, False, NoEventMask, event);
  220098. XFlush (display);
  220099. }
  220100. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220101. {
  220102. XWindowAttributes atts;
  220103. ScopedXLock xlock;
  220104. if (clientMsg->window != 0
  220105. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220106. {
  220107. if (atts.map_state == IsViewable)
  220108. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220109. }
  220110. }
  220111. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220112. {
  220113. handleUserClosingWindow();
  220114. }
  220115. }
  220116. else if (clientMsg->message_type == Atoms::XdndEnter)
  220117. {
  220118. handleDragAndDropEnter (clientMsg);
  220119. }
  220120. else if (clientMsg->message_type == Atoms::XdndLeave)
  220121. {
  220122. resetDragAndDrop();
  220123. }
  220124. else if (clientMsg->message_type == Atoms::XdndPosition)
  220125. {
  220126. handleDragAndDropPosition (clientMsg);
  220127. }
  220128. else if (clientMsg->message_type == Atoms::XdndDrop)
  220129. {
  220130. handleDragAndDropDrop (clientMsg);
  220131. }
  220132. else if (clientMsg->message_type == Atoms::XdndStatus)
  220133. {
  220134. handleDragAndDropStatus (clientMsg);
  220135. }
  220136. else if (clientMsg->message_type == Atoms::XdndFinished)
  220137. {
  220138. resetDragAndDrop();
  220139. }
  220140. }
  220141. void showMouseCursor (Cursor cursor) throw()
  220142. {
  220143. ScopedXLock xlock;
  220144. XDefineCursor (display, windowH, cursor);
  220145. }
  220146. void setTaskBarIcon (const Image& image)
  220147. {
  220148. ScopedXLock xlock;
  220149. taskbarImage = image;
  220150. Screen* const screen = XDefaultScreenOfDisplay (display);
  220151. const int screenNumber = XScreenNumberOfScreen (screen);
  220152. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220153. screenAtom << screenNumber;
  220154. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220155. XGrabServer (display);
  220156. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220157. if (managerWin != None)
  220158. XSelectInput (display, managerWin, StructureNotifyMask);
  220159. XUngrabServer (display);
  220160. XFlush (display);
  220161. if (managerWin != None)
  220162. {
  220163. XEvent ev;
  220164. zerostruct (ev);
  220165. ev.xclient.type = ClientMessage;
  220166. ev.xclient.window = managerWin;
  220167. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220168. ev.xclient.format = 32;
  220169. ev.xclient.data.l[0] = CurrentTime;
  220170. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220171. ev.xclient.data.l[2] = windowH;
  220172. ev.xclient.data.l[3] = 0;
  220173. ev.xclient.data.l[4] = 0;
  220174. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220175. XSync (display, False);
  220176. }
  220177. // For older KDE's ...
  220178. long atomData = 1;
  220179. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220180. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220181. // For more recent KDE's...
  220182. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220183. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220184. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220185. XSizeHints* hints = XAllocSizeHints();
  220186. hints->flags = PMinSize;
  220187. hints->min_width = 22;
  220188. hints->min_height = 22;
  220189. XSetWMNormalHints (display, windowH, hints);
  220190. XFree (hints);
  220191. }
  220192. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220193. bool dontRepaint;
  220194. static ModifierKeys currentModifiers;
  220195. static bool isActiveApplication;
  220196. private:
  220197. class LinuxRepaintManager : public Timer
  220198. {
  220199. public:
  220200. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220201. : peer (peer_),
  220202. lastTimeImageUsed (0)
  220203. {
  220204. #if JUCE_USE_XSHM
  220205. shmCompletedDrawing = true;
  220206. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220207. if (useARGBImagesForRendering)
  220208. {
  220209. ScopedXLock xlock;
  220210. XShmSegmentInfo segmentinfo;
  220211. XImage* const testImage
  220212. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220213. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220214. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220215. XDestroyImage (testImage);
  220216. }
  220217. #endif
  220218. }
  220219. void timerCallback()
  220220. {
  220221. #if JUCE_USE_XSHM
  220222. if (! shmCompletedDrawing)
  220223. return;
  220224. #endif
  220225. if (! regionsNeedingRepaint.isEmpty())
  220226. {
  220227. stopTimer();
  220228. performAnyPendingRepaintsNow();
  220229. }
  220230. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220231. {
  220232. stopTimer();
  220233. image = Image::null;
  220234. }
  220235. }
  220236. void repaint (const Rectangle<int>& area)
  220237. {
  220238. if (! isTimerRunning())
  220239. startTimer (repaintTimerPeriod);
  220240. regionsNeedingRepaint.add (area);
  220241. }
  220242. void performAnyPendingRepaintsNow()
  220243. {
  220244. #if JUCE_USE_XSHM
  220245. if (! shmCompletedDrawing)
  220246. {
  220247. startTimer (repaintTimerPeriod);
  220248. return;
  220249. }
  220250. #endif
  220251. peer->clearMaskedRegion();
  220252. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220253. regionsNeedingRepaint.clear();
  220254. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220255. if (! totalArea.isEmpty())
  220256. {
  220257. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220258. || image.getHeight() < totalArea.getHeight())
  220259. {
  220260. #if JUCE_USE_XSHM
  220261. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220262. : Image::RGB,
  220263. #else
  220264. image = Image (new XBitmapImage (Image::RGB,
  220265. #endif
  220266. (totalArea.getWidth() + 31) & ~31,
  220267. (totalArea.getHeight() + 31) & ~31,
  220268. false, peer->depth, peer->visual));
  220269. }
  220270. startTimer (repaintTimerPeriod);
  220271. RectangleList adjustedList (originalRepaintRegion);
  220272. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220273. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220274. if (peer->depth == 32)
  220275. {
  220276. RectangleList::Iterator i (originalRepaintRegion);
  220277. while (i.next())
  220278. image.clear (*i.getRectangle() - totalArea.getPosition());
  220279. }
  220280. peer->handlePaint (context);
  220281. if (! peer->maskedRegion.isEmpty())
  220282. originalRepaintRegion.subtract (peer->maskedRegion);
  220283. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220284. {
  220285. #if JUCE_USE_XSHM
  220286. shmCompletedDrawing = false;
  220287. #endif
  220288. const Rectangle<int>& r = *i.getRectangle();
  220289. static_cast<XBitmapImage*> (image.getSharedImage())
  220290. ->blitToWindow (peer->windowH,
  220291. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220292. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220293. }
  220294. }
  220295. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220296. startTimer (repaintTimerPeriod);
  220297. }
  220298. #if JUCE_USE_XSHM
  220299. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220300. #endif
  220301. private:
  220302. enum { repaintTimerPeriod = 1000 / 100 };
  220303. LinuxComponentPeer* const peer;
  220304. Image image;
  220305. uint32 lastTimeImageUsed;
  220306. RectangleList regionsNeedingRepaint;
  220307. #if JUCE_USE_XSHM
  220308. bool useARGBImagesForRendering, shmCompletedDrawing;
  220309. #endif
  220310. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220311. };
  220312. ScopedPointer <LinuxRepaintManager> repainter;
  220313. friend class LinuxRepaintManager;
  220314. Window windowH, parentWindow;
  220315. int wx, wy, ww, wh;
  220316. Image taskbarImage;
  220317. bool fullScreen, mapped;
  220318. Visual* visual;
  220319. int depth;
  220320. BorderSize windowBorder;
  220321. struct MotifWmHints
  220322. {
  220323. unsigned long flags;
  220324. unsigned long functions;
  220325. unsigned long decorations;
  220326. long input_mode;
  220327. unsigned long status;
  220328. };
  220329. static void updateKeyStates (const int keycode, const bool press) throw()
  220330. {
  220331. const int keybyte = keycode >> 3;
  220332. const int keybit = (1 << (keycode & 7));
  220333. if (press)
  220334. Keys::keyStates [keybyte] |= keybit;
  220335. else
  220336. Keys::keyStates [keybyte] &= ~keybit;
  220337. }
  220338. static void updateKeyModifiers (const int status) throw()
  220339. {
  220340. int keyMods = 0;
  220341. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220342. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220343. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220344. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220345. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220346. Keys::capsLock = ((status & LockMask) != 0);
  220347. }
  220348. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220349. {
  220350. int modifier = 0;
  220351. bool isModifier = true;
  220352. switch (sym)
  220353. {
  220354. case XK_Shift_L:
  220355. case XK_Shift_R:
  220356. modifier = ModifierKeys::shiftModifier;
  220357. break;
  220358. case XK_Control_L:
  220359. case XK_Control_R:
  220360. modifier = ModifierKeys::ctrlModifier;
  220361. break;
  220362. case XK_Alt_L:
  220363. case XK_Alt_R:
  220364. modifier = ModifierKeys::altModifier;
  220365. break;
  220366. case XK_Num_Lock:
  220367. if (press)
  220368. Keys::numLock = ! Keys::numLock;
  220369. break;
  220370. case XK_Caps_Lock:
  220371. if (press)
  220372. Keys::capsLock = ! Keys::capsLock;
  220373. break;
  220374. case XK_Scroll_Lock:
  220375. break;
  220376. default:
  220377. isModifier = false;
  220378. break;
  220379. }
  220380. if (modifier != 0)
  220381. {
  220382. if (press)
  220383. currentModifiers = currentModifiers.withFlags (modifier);
  220384. else
  220385. currentModifiers = currentModifiers.withoutFlags (modifier);
  220386. }
  220387. return isModifier;
  220388. }
  220389. // Alt and Num lock are not defined by standard X
  220390. // modifier constants: check what they're mapped to
  220391. static void updateModifierMappings() throw()
  220392. {
  220393. ScopedXLock xlock;
  220394. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220395. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220396. Keys::AltMask = 0;
  220397. Keys::NumLockMask = 0;
  220398. XModifierKeymap* mapping = XGetModifierMapping (display);
  220399. if (mapping)
  220400. {
  220401. for (int i = 0; i < 8; i++)
  220402. {
  220403. if (mapping->modifiermap [i << 1] == altLeftCode)
  220404. Keys::AltMask = 1 << i;
  220405. else if (mapping->modifiermap [i << 1] == numLockCode)
  220406. Keys::NumLockMask = 1 << i;
  220407. }
  220408. XFreeModifiermap (mapping);
  220409. }
  220410. }
  220411. void removeWindowDecorations (Window wndH)
  220412. {
  220413. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220414. if (hints != None)
  220415. {
  220416. MotifWmHints motifHints;
  220417. zerostruct (motifHints);
  220418. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220419. motifHints.decorations = 0;
  220420. ScopedXLock xlock;
  220421. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220422. (unsigned char*) &motifHints, 4);
  220423. }
  220424. hints = XInternAtom (display, "_WIN_HINTS", True);
  220425. if (hints != None)
  220426. {
  220427. long gnomeHints = 0;
  220428. ScopedXLock xlock;
  220429. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220430. (unsigned char*) &gnomeHints, 1);
  220431. }
  220432. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220433. if (hints != None)
  220434. {
  220435. long kwmHints = 2; /*KDE_tinyDecoration*/
  220436. ScopedXLock xlock;
  220437. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220438. (unsigned char*) &kwmHints, 1);
  220439. }
  220440. }
  220441. void addWindowButtons (Window wndH)
  220442. {
  220443. ScopedXLock xlock;
  220444. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220445. if (hints != None)
  220446. {
  220447. MotifWmHints motifHints;
  220448. zerostruct (motifHints);
  220449. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220450. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220451. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220452. if ((styleFlags & windowHasCloseButton) != 0)
  220453. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220454. if ((styleFlags & windowHasMinimiseButton) != 0)
  220455. {
  220456. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220457. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220458. }
  220459. if ((styleFlags & windowHasMaximiseButton) != 0)
  220460. {
  220461. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220462. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220463. }
  220464. if ((styleFlags & windowIsResizable) != 0)
  220465. {
  220466. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220467. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220468. }
  220469. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220470. }
  220471. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220472. if (hints != None)
  220473. {
  220474. int netHints [6];
  220475. int num = 0;
  220476. if ((styleFlags & windowIsResizable) != 0)
  220477. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220478. if ((styleFlags & windowHasMaximiseButton) != 0)
  220479. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220480. if ((styleFlags & windowHasMinimiseButton) != 0)
  220481. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220482. if ((styleFlags & windowHasCloseButton) != 0)
  220483. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220484. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220485. }
  220486. }
  220487. void setWindowType()
  220488. {
  220489. int netHints [2];
  220490. int numHints = 0;
  220491. if ((styleFlags & windowIsTemporary) != 0
  220492. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220493. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220494. else
  220495. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220496. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220497. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220498. (unsigned char*) &netHints, numHints);
  220499. numHints = 0;
  220500. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220501. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220502. if (component->isAlwaysOnTop())
  220503. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220504. if (numHints > 0)
  220505. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220506. (unsigned char*) &netHints, numHints);
  220507. }
  220508. void createWindow()
  220509. {
  220510. ScopedXLock xlock;
  220511. Atoms::initialiseAtoms();
  220512. resetDragAndDrop();
  220513. // Get defaults for various properties
  220514. const int screen = DefaultScreen (display);
  220515. Window root = RootWindow (display, screen);
  220516. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220517. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220518. if (visual == 0)
  220519. {
  220520. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220521. Process::terminate();
  220522. }
  220523. // Create and install a colormap suitable fr our visual
  220524. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220525. XInstallColormap (display, colormap);
  220526. // Set up the window attributes
  220527. XSetWindowAttributes swa;
  220528. swa.border_pixel = 0;
  220529. swa.background_pixmap = None;
  220530. swa.colormap = colormap;
  220531. swa.event_mask = getAllEventsMask();
  220532. windowH = XCreateWindow (display, root,
  220533. 0, 0, 1, 1,
  220534. 0, depth, InputOutput, visual,
  220535. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220536. &swa);
  220537. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220538. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220539. GrabModeAsync, GrabModeAsync, None, None);
  220540. // Set the window context to identify the window handle object
  220541. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220542. {
  220543. // Failed
  220544. jassertfalse;
  220545. Logger::outputDebugString ("Failed to create context information for window.\n");
  220546. XDestroyWindow (display, windowH);
  220547. windowH = 0;
  220548. return;
  220549. }
  220550. // Set window manager hints
  220551. XWMHints* wmHints = XAllocWMHints();
  220552. wmHints->flags = InputHint | StateHint;
  220553. wmHints->input = True; // Locally active input model
  220554. wmHints->initial_state = NormalState;
  220555. XSetWMHints (display, windowH, wmHints);
  220556. XFree (wmHints);
  220557. // Set the window type
  220558. setWindowType();
  220559. // Define decoration
  220560. if ((styleFlags & windowHasTitleBar) == 0)
  220561. removeWindowDecorations (windowH);
  220562. else
  220563. addWindowButtons (windowH);
  220564. setTitle (getComponent()->getName());
  220565. // Associate the PID, allowing to be shut down when something goes wrong
  220566. unsigned long pid = getpid();
  220567. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220568. (unsigned char*) &pid, 1);
  220569. // Set window manager protocols
  220570. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220571. (unsigned char*) Atoms::ProtocolList, 2);
  220572. // Set drag and drop flags
  220573. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220574. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220575. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220576. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220577. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220578. (const unsigned char*) "", 0);
  220579. unsigned long dndVersion = Atoms::DndVersion;
  220580. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220581. (const unsigned char*) &dndVersion, 1);
  220582. // Initialise the pointer and keyboard mapping
  220583. // This is not the same as the logical pointer mapping the X server uses:
  220584. // we don't mess with this.
  220585. static bool mappingInitialised = false;
  220586. if (! mappingInitialised)
  220587. {
  220588. mappingInitialised = true;
  220589. const int numButtons = XGetPointerMapping (display, 0, 0);
  220590. if (numButtons == 2)
  220591. {
  220592. pointerMap[0] = Keys::LeftButton;
  220593. pointerMap[1] = Keys::RightButton;
  220594. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220595. }
  220596. else if (numButtons >= 3)
  220597. {
  220598. pointerMap[0] = Keys::LeftButton;
  220599. pointerMap[1] = Keys::MiddleButton;
  220600. pointerMap[2] = Keys::RightButton;
  220601. if (numButtons >= 5)
  220602. {
  220603. pointerMap[3] = Keys::WheelUp;
  220604. pointerMap[4] = Keys::WheelDown;
  220605. }
  220606. }
  220607. updateModifierMappings();
  220608. }
  220609. }
  220610. void destroyWindow()
  220611. {
  220612. ScopedXLock xlock;
  220613. XPointer handlePointer;
  220614. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220615. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220616. XDestroyWindow (display, windowH);
  220617. // Wait for it to complete and then remove any events for this
  220618. // window from the event queue.
  220619. XSync (display, false);
  220620. XEvent event;
  220621. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220622. {}
  220623. }
  220624. static int getAllEventsMask() throw()
  220625. {
  220626. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220627. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220628. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220629. }
  220630. static int64 getEventTime (::Time t)
  220631. {
  220632. static int64 eventTimeOffset = 0x12345678;
  220633. const int64 thisMessageTime = t;
  220634. if (eventTimeOffset == 0x12345678)
  220635. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220636. return eventTimeOffset + thisMessageTime;
  220637. }
  220638. void updateBorderSize()
  220639. {
  220640. if ((styleFlags & windowHasTitleBar) == 0)
  220641. {
  220642. windowBorder = BorderSize (0);
  220643. }
  220644. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220645. {
  220646. ScopedXLock xlock;
  220647. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220648. if (hints != None)
  220649. {
  220650. unsigned char* data = 0;
  220651. unsigned long nitems, bytesLeft;
  220652. Atom actualType;
  220653. int actualFormat;
  220654. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220655. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220656. &data) == Success)
  220657. {
  220658. const unsigned long* const sizes = (const unsigned long*) data;
  220659. if (actualFormat == 32)
  220660. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  220661. (int) sizes[3], (int) sizes[1]);
  220662. XFree (data);
  220663. }
  220664. }
  220665. }
  220666. }
  220667. void updateBounds()
  220668. {
  220669. jassert (windowH != 0);
  220670. if (windowH != 0)
  220671. {
  220672. Window root, child;
  220673. unsigned int bw, depth;
  220674. ScopedXLock xlock;
  220675. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220676. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220677. &bw, &depth))
  220678. {
  220679. wx = wy = ww = wh = 0;
  220680. }
  220681. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220682. {
  220683. wx = wy = 0;
  220684. }
  220685. }
  220686. }
  220687. void resetDragAndDrop()
  220688. {
  220689. dragAndDropFiles.clear();
  220690. lastDropPos = Point<int> (-1, -1);
  220691. dragAndDropCurrentMimeType = 0;
  220692. dragAndDropSourceWindow = 0;
  220693. srcMimeTypeAtomList.clear();
  220694. }
  220695. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220696. {
  220697. msg.type = ClientMessage;
  220698. msg.display = display;
  220699. msg.window = dragAndDropSourceWindow;
  220700. msg.format = 32;
  220701. msg.data.l[0] = windowH;
  220702. ScopedXLock xlock;
  220703. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220704. }
  220705. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220706. {
  220707. XClientMessageEvent msg;
  220708. zerostruct (msg);
  220709. msg.message_type = Atoms::XdndStatus;
  220710. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220711. msg.data.l[4] = dropAction;
  220712. sendDragAndDropMessage (msg);
  220713. }
  220714. void sendDragAndDropLeave()
  220715. {
  220716. XClientMessageEvent msg;
  220717. zerostruct (msg);
  220718. msg.message_type = Atoms::XdndLeave;
  220719. sendDragAndDropMessage (msg);
  220720. }
  220721. void sendDragAndDropFinish()
  220722. {
  220723. XClientMessageEvent msg;
  220724. zerostruct (msg);
  220725. msg.message_type = Atoms::XdndFinished;
  220726. sendDragAndDropMessage (msg);
  220727. }
  220728. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220729. {
  220730. if ((clientMsg->data.l[1] & 1) == 0)
  220731. {
  220732. sendDragAndDropLeave();
  220733. if (dragAndDropFiles.size() > 0)
  220734. handleFileDragExit (dragAndDropFiles);
  220735. dragAndDropFiles.clear();
  220736. }
  220737. }
  220738. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220739. {
  220740. if (dragAndDropSourceWindow == 0)
  220741. return;
  220742. dragAndDropSourceWindow = clientMsg->data.l[0];
  220743. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220744. (int) clientMsg->data.l[2] & 0xffff);
  220745. dropPos -= getScreenPosition();
  220746. if (lastDropPos != dropPos)
  220747. {
  220748. lastDropPos = dropPos;
  220749. dragAndDropTimestamp = clientMsg->data.l[3];
  220750. Atom targetAction = Atoms::XdndActionCopy;
  220751. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220752. {
  220753. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220754. {
  220755. targetAction = Atoms::allowedActions[i];
  220756. break;
  220757. }
  220758. }
  220759. sendDragAndDropStatus (true, targetAction);
  220760. if (dragAndDropFiles.size() == 0)
  220761. updateDraggedFileList (clientMsg);
  220762. if (dragAndDropFiles.size() > 0)
  220763. handleFileDragMove (dragAndDropFiles, dropPos);
  220764. }
  220765. }
  220766. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220767. {
  220768. if (dragAndDropFiles.size() == 0)
  220769. updateDraggedFileList (clientMsg);
  220770. const StringArray files (dragAndDropFiles);
  220771. const Point<int> lastPos (lastDropPos);
  220772. sendDragAndDropFinish();
  220773. resetDragAndDrop();
  220774. if (files.size() > 0)
  220775. handleFileDragDrop (files, lastPos);
  220776. }
  220777. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220778. {
  220779. dragAndDropFiles.clear();
  220780. srcMimeTypeAtomList.clear();
  220781. dragAndDropCurrentMimeType = 0;
  220782. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220783. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220784. {
  220785. dragAndDropSourceWindow = 0;
  220786. return;
  220787. }
  220788. dragAndDropSourceWindow = clientMsg->data.l[0];
  220789. if ((clientMsg->data.l[1] & 1) != 0)
  220790. {
  220791. Atom actual;
  220792. int format;
  220793. unsigned long count = 0, remaining = 0;
  220794. unsigned char* data = 0;
  220795. ScopedXLock xlock;
  220796. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220797. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220798. &count, &remaining, &data);
  220799. if (data != 0)
  220800. {
  220801. if (actual == XA_ATOM && format == 32 && count != 0)
  220802. {
  220803. const unsigned long* const types = (const unsigned long*) data;
  220804. for (unsigned int i = 0; i < count; ++i)
  220805. if (types[i] != None)
  220806. srcMimeTypeAtomList.add (types[i]);
  220807. }
  220808. XFree (data);
  220809. }
  220810. }
  220811. if (srcMimeTypeAtomList.size() == 0)
  220812. {
  220813. for (int i = 2; i < 5; ++i)
  220814. if (clientMsg->data.l[i] != None)
  220815. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220816. if (srcMimeTypeAtomList.size() == 0)
  220817. {
  220818. dragAndDropSourceWindow = 0;
  220819. return;
  220820. }
  220821. }
  220822. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220823. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220824. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220825. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220826. handleDragAndDropPosition (clientMsg);
  220827. }
  220828. void handleDragAndDropSelection (const XEvent* const evt)
  220829. {
  220830. dragAndDropFiles.clear();
  220831. if (evt->xselection.property != 0)
  220832. {
  220833. StringArray lines;
  220834. {
  220835. MemoryBlock dropData;
  220836. for (;;)
  220837. {
  220838. Atom actual;
  220839. uint8* data = 0;
  220840. unsigned long count = 0, remaining = 0;
  220841. int format = 0;
  220842. ScopedXLock xlock;
  220843. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220844. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220845. &format, &count, &remaining, &data) == Success)
  220846. {
  220847. dropData.append (data, count * format / 8);
  220848. XFree (data);
  220849. if (remaining == 0)
  220850. break;
  220851. }
  220852. else
  220853. {
  220854. XFree (data);
  220855. break;
  220856. }
  220857. }
  220858. lines.addLines (dropData.toString());
  220859. }
  220860. for (int i = 0; i < lines.size(); ++i)
  220861. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220862. dragAndDropFiles.trim();
  220863. dragAndDropFiles.removeEmptyStrings();
  220864. }
  220865. }
  220866. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220867. {
  220868. dragAndDropFiles.clear();
  220869. if (dragAndDropSourceWindow != None
  220870. && dragAndDropCurrentMimeType != 0)
  220871. {
  220872. dragAndDropTimestamp = clientMsg->data.l[2];
  220873. ScopedXLock xlock;
  220874. XConvertSelection (display,
  220875. Atoms::XdndSelection,
  220876. dragAndDropCurrentMimeType,
  220877. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220878. windowH,
  220879. dragAndDropTimestamp);
  220880. }
  220881. }
  220882. StringArray dragAndDropFiles;
  220883. int dragAndDropTimestamp;
  220884. Point<int> lastDropPos;
  220885. Atom dragAndDropCurrentMimeType;
  220886. Window dragAndDropSourceWindow;
  220887. Array <Atom> srcMimeTypeAtomList;
  220888. static int pointerMap[5];
  220889. static Point<int> lastMousePos;
  220890. static void clearLastMousePos() throw()
  220891. {
  220892. lastMousePos = Point<int> (0x100000, 0x100000);
  220893. }
  220894. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  220895. };
  220896. ModifierKeys LinuxComponentPeer::currentModifiers;
  220897. bool LinuxComponentPeer::isActiveApplication = false;
  220898. int LinuxComponentPeer::pointerMap[5];
  220899. Point<int> LinuxComponentPeer::lastMousePos;
  220900. bool Process::isForegroundProcess()
  220901. {
  220902. return LinuxComponentPeer::isActiveApplication;
  220903. }
  220904. void ModifierKeys::updateCurrentModifiers() throw()
  220905. {
  220906. currentModifiers = LinuxComponentPeer::currentModifiers;
  220907. }
  220908. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220909. {
  220910. Window root, child;
  220911. int x, y, winx, winy;
  220912. unsigned int mask;
  220913. int mouseMods = 0;
  220914. ScopedXLock xlock;
  220915. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220916. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220917. {
  220918. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220919. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220920. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220921. }
  220922. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220923. return LinuxComponentPeer::currentModifiers;
  220924. }
  220925. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220926. {
  220927. if (enableOrDisable)
  220928. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220929. }
  220930. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220931. {
  220932. return new LinuxComponentPeer (this, styleFlags);
  220933. }
  220934. // (this callback is hooked up in the messaging code)
  220935. void juce_windowMessageReceive (XEvent* event)
  220936. {
  220937. if (event->xany.window != None)
  220938. {
  220939. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220940. if (ComponentPeer::isValidPeer (peer))
  220941. peer->handleWindowMessage (event);
  220942. }
  220943. else
  220944. {
  220945. switch (event->xany.type)
  220946. {
  220947. case KeymapNotify:
  220948. {
  220949. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220950. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220951. break;
  220952. }
  220953. default:
  220954. break;
  220955. }
  220956. }
  220957. }
  220958. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220959. {
  220960. if (display == 0)
  220961. return;
  220962. #if JUCE_USE_XINERAMA
  220963. int major_opcode, first_event, first_error;
  220964. ScopedXLock xlock;
  220965. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220966. {
  220967. typedef Bool (*tXineramaIsActive) (Display*);
  220968. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220969. static tXineramaIsActive xXineramaIsActive = 0;
  220970. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220971. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220972. {
  220973. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220974. if (h == 0)
  220975. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220976. if (h != 0)
  220977. {
  220978. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220979. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220980. }
  220981. }
  220982. if (xXineramaIsActive != 0
  220983. && xXineramaQueryScreens != 0
  220984. && xXineramaIsActive (display))
  220985. {
  220986. int numMonitors = 0;
  220987. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220988. if (screens != 0)
  220989. {
  220990. for (int i = numMonitors; --i >= 0;)
  220991. {
  220992. int index = screens[i].screen_number;
  220993. if (index >= 0)
  220994. {
  220995. while (monitorCoords.size() < index)
  220996. monitorCoords.add (Rectangle<int>());
  220997. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220998. screens[i].y_org,
  220999. screens[i].width,
  221000. screens[i].height));
  221001. }
  221002. }
  221003. XFree (screens);
  221004. }
  221005. }
  221006. }
  221007. if (monitorCoords.size() == 0)
  221008. #endif
  221009. {
  221010. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221011. if (hints != None)
  221012. {
  221013. const int numMonitors = ScreenCount (display);
  221014. for (int i = 0; i < numMonitors; ++i)
  221015. {
  221016. Window root = RootWindow (display, i);
  221017. unsigned long nitems, bytesLeft;
  221018. Atom actualType;
  221019. int actualFormat;
  221020. unsigned char* data = 0;
  221021. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221022. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221023. &data) == Success)
  221024. {
  221025. const long* const position = (const long*) data;
  221026. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221027. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221028. position[2], position[3]));
  221029. XFree (data);
  221030. }
  221031. }
  221032. }
  221033. if (monitorCoords.size() == 0)
  221034. {
  221035. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221036. DisplayHeight (display, DefaultScreen (display))));
  221037. }
  221038. }
  221039. }
  221040. void Desktop::createMouseInputSources()
  221041. {
  221042. mouseSources.add (new MouseInputSource (0, true));
  221043. }
  221044. bool Desktop::canUseSemiTransparentWindows() throw()
  221045. {
  221046. int matchedDepth = 0;
  221047. const int desiredDepth = 32;
  221048. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221049. && (matchedDepth == desiredDepth);
  221050. }
  221051. const Point<int> MouseInputSource::getCurrentMousePosition()
  221052. {
  221053. Window root, child;
  221054. int x, y, winx, winy;
  221055. unsigned int mask;
  221056. ScopedXLock xlock;
  221057. if (XQueryPointer (display,
  221058. RootWindow (display, DefaultScreen (display)),
  221059. &root, &child,
  221060. &x, &y, &winx, &winy, &mask) == False)
  221061. {
  221062. // Pointer not on the default screen
  221063. x = y = -1;
  221064. }
  221065. return Point<int> (x, y);
  221066. }
  221067. void Desktop::setMousePosition (const Point<int>& newPosition)
  221068. {
  221069. ScopedXLock xlock;
  221070. Window root = RootWindow (display, DefaultScreen (display));
  221071. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221072. }
  221073. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  221074. {
  221075. return upright;
  221076. }
  221077. static bool screenSaverAllowed = true;
  221078. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221079. {
  221080. if (screenSaverAllowed != isEnabled)
  221081. {
  221082. screenSaverAllowed = isEnabled;
  221083. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221084. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221085. if (xScreenSaverSuspend == 0)
  221086. {
  221087. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221088. if (h != 0)
  221089. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221090. }
  221091. ScopedXLock xlock;
  221092. if (xScreenSaverSuspend != 0)
  221093. xScreenSaverSuspend (display, ! isEnabled);
  221094. }
  221095. }
  221096. bool Desktop::isScreenSaverEnabled()
  221097. {
  221098. return screenSaverAllowed;
  221099. }
  221100. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221101. {
  221102. ScopedXLock xlock;
  221103. const unsigned int imageW = image.getWidth();
  221104. const unsigned int imageH = image.getHeight();
  221105. #if JUCE_USE_XCURSOR
  221106. {
  221107. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221108. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221109. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221110. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221111. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221112. static tXcursorImageCreate xXcursorImageCreate = 0;
  221113. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221114. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221115. static bool hasBeenLoaded = false;
  221116. if (! hasBeenLoaded)
  221117. {
  221118. hasBeenLoaded = true;
  221119. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221120. if (h != 0)
  221121. {
  221122. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221123. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221124. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221125. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221126. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221127. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221128. || ! xXcursorSupportsARGB (display))
  221129. xXcursorSupportsARGB = 0;
  221130. }
  221131. }
  221132. if (xXcursorSupportsARGB != 0)
  221133. {
  221134. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221135. if (xcImage != 0)
  221136. {
  221137. xcImage->xhot = hotspotX;
  221138. xcImage->yhot = hotspotY;
  221139. XcursorPixel* dest = xcImage->pixels;
  221140. for (int y = 0; y < (int) imageH; ++y)
  221141. for (int x = 0; x < (int) imageW; ++x)
  221142. *dest++ = image.getPixelAt (x, y).getARGB();
  221143. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221144. xXcursorImageDestroy (xcImage);
  221145. if (result != 0)
  221146. return result;
  221147. }
  221148. }
  221149. }
  221150. #endif
  221151. Window root = RootWindow (display, DefaultScreen (display));
  221152. unsigned int cursorW, cursorH;
  221153. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221154. return 0;
  221155. Image im (Image::ARGB, cursorW, cursorH, true);
  221156. {
  221157. Graphics g (im);
  221158. if (imageW > cursorW || imageH > cursorH)
  221159. {
  221160. hotspotX = (hotspotX * cursorW) / imageW;
  221161. hotspotY = (hotspotY * cursorH) / imageH;
  221162. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221163. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221164. false);
  221165. }
  221166. else
  221167. {
  221168. g.drawImageAt (image, 0, 0);
  221169. }
  221170. }
  221171. const int stride = (cursorW + 7) >> 3;
  221172. HeapBlock <char> maskPlane, sourcePlane;
  221173. maskPlane.calloc (stride * cursorH);
  221174. sourcePlane.calloc (stride * cursorH);
  221175. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221176. for (int y = cursorH; --y >= 0;)
  221177. {
  221178. for (int x = cursorW; --x >= 0;)
  221179. {
  221180. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221181. const int offset = y * stride + (x >> 3);
  221182. const Colour c (im.getPixelAt (x, y));
  221183. if (c.getAlpha() >= 128)
  221184. maskPlane[offset] |= mask;
  221185. if (c.getBrightness() >= 0.5f)
  221186. sourcePlane[offset] |= mask;
  221187. }
  221188. }
  221189. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221190. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221191. XColor white, black;
  221192. black.red = black.green = black.blue = 0;
  221193. white.red = white.green = white.blue = 0xffff;
  221194. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221195. XFreePixmap (display, sourcePixmap);
  221196. XFreePixmap (display, maskPixmap);
  221197. return result;
  221198. }
  221199. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221200. {
  221201. ScopedXLock xlock;
  221202. if (cursorHandle != 0)
  221203. XFreeCursor (display, (Cursor) cursorHandle);
  221204. }
  221205. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221206. {
  221207. unsigned int shape;
  221208. switch (type)
  221209. {
  221210. case NormalCursor: return None; // Use parent cursor
  221211. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221212. case WaitCursor: shape = XC_watch; break;
  221213. case IBeamCursor: shape = XC_xterm; break;
  221214. case PointingHandCursor: shape = XC_hand2; break;
  221215. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221216. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221217. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221218. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221219. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221220. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221221. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221222. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221223. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221224. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221225. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221226. case CrosshairCursor: shape = XC_crosshair; break;
  221227. case DraggingHandCursor:
  221228. {
  221229. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221230. 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,
  221231. 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 };
  221232. const int dragHandDataSize = 99;
  221233. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221234. }
  221235. case CopyingCursor:
  221236. {
  221237. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221238. 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,
  221239. 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,
  221240. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221241. const int copyCursorSize = 119;
  221242. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221243. }
  221244. default:
  221245. jassertfalse;
  221246. return None;
  221247. }
  221248. ScopedXLock xlock;
  221249. return (void*) XCreateFontCursor (display, shape);
  221250. }
  221251. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221252. {
  221253. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221254. if (lp != 0)
  221255. lp->showMouseCursor ((Cursor) getHandle());
  221256. }
  221257. void MouseCursor::showInAllWindows() const
  221258. {
  221259. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221260. showInWindow (ComponentPeer::getPeer (i));
  221261. }
  221262. const Image juce_createIconForFile (const File& file)
  221263. {
  221264. return Image::null;
  221265. }
  221266. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221267. {
  221268. return createSoftwareImage (format, width, height, clearImage);
  221269. }
  221270. #if JUCE_OPENGL
  221271. class WindowedGLContext : public OpenGLContext
  221272. {
  221273. public:
  221274. WindowedGLContext (Component* const component,
  221275. const OpenGLPixelFormat& pixelFormat_,
  221276. GLXContext sharedContext)
  221277. : renderContext (0),
  221278. embeddedWindow (0),
  221279. pixelFormat (pixelFormat_),
  221280. swapInterval (0)
  221281. {
  221282. jassert (component != 0);
  221283. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221284. if (peer == 0)
  221285. return;
  221286. ScopedXLock xlock;
  221287. XSync (display, False);
  221288. GLint attribs [64];
  221289. int n = 0;
  221290. attribs[n++] = GLX_RGBA;
  221291. attribs[n++] = GLX_DOUBLEBUFFER;
  221292. attribs[n++] = GLX_RED_SIZE;
  221293. attribs[n++] = pixelFormat.redBits;
  221294. attribs[n++] = GLX_GREEN_SIZE;
  221295. attribs[n++] = pixelFormat.greenBits;
  221296. attribs[n++] = GLX_BLUE_SIZE;
  221297. attribs[n++] = pixelFormat.blueBits;
  221298. attribs[n++] = GLX_ALPHA_SIZE;
  221299. attribs[n++] = pixelFormat.alphaBits;
  221300. attribs[n++] = GLX_DEPTH_SIZE;
  221301. attribs[n++] = pixelFormat.depthBufferBits;
  221302. attribs[n++] = GLX_STENCIL_SIZE;
  221303. attribs[n++] = pixelFormat.stencilBufferBits;
  221304. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221305. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221306. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221307. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221308. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221309. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221310. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221311. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221312. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221313. attribs[n++] = None;
  221314. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221315. if (bestVisual == 0)
  221316. return;
  221317. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221318. Window windowH = (Window) peer->getNativeHandle();
  221319. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221320. XSetWindowAttributes swa;
  221321. swa.colormap = colourMap;
  221322. swa.border_pixel = 0;
  221323. swa.event_mask = ExposureMask | StructureNotifyMask;
  221324. embeddedWindow = XCreateWindow (display, windowH,
  221325. 0, 0, 1, 1, 0,
  221326. bestVisual->depth,
  221327. InputOutput,
  221328. bestVisual->visual,
  221329. CWBorderPixel | CWColormap | CWEventMask,
  221330. &swa);
  221331. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221332. XMapWindow (display, embeddedWindow);
  221333. XFreeColormap (display, colourMap);
  221334. XFree (bestVisual);
  221335. XSync (display, False);
  221336. }
  221337. ~WindowedGLContext()
  221338. {
  221339. ScopedXLock xlock;
  221340. deleteContext();
  221341. XUnmapWindow (display, embeddedWindow);
  221342. XDestroyWindow (display, embeddedWindow);
  221343. }
  221344. void deleteContext()
  221345. {
  221346. makeInactive();
  221347. if (renderContext != 0)
  221348. {
  221349. ScopedXLock xlock;
  221350. glXDestroyContext (display, renderContext);
  221351. renderContext = 0;
  221352. }
  221353. }
  221354. bool makeActive() const throw()
  221355. {
  221356. jassert (renderContext != 0);
  221357. ScopedXLock xlock;
  221358. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221359. && XSync (display, False);
  221360. }
  221361. bool makeInactive() const throw()
  221362. {
  221363. ScopedXLock xlock;
  221364. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221365. }
  221366. bool isActive() const throw()
  221367. {
  221368. ScopedXLock xlock;
  221369. return glXGetCurrentContext() == renderContext;
  221370. }
  221371. const OpenGLPixelFormat getPixelFormat() const
  221372. {
  221373. return pixelFormat;
  221374. }
  221375. void* getRawContext() const throw()
  221376. {
  221377. return renderContext;
  221378. }
  221379. void updateWindowPosition (int x, int y, int w, int h, int)
  221380. {
  221381. ScopedXLock xlock;
  221382. XMoveResizeWindow (display, embeddedWindow,
  221383. x, y, jmax (1, w), jmax (1, h));
  221384. }
  221385. void swapBuffers()
  221386. {
  221387. ScopedXLock xlock;
  221388. glXSwapBuffers (display, embeddedWindow);
  221389. }
  221390. bool setSwapInterval (const int numFramesPerSwap)
  221391. {
  221392. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221393. if (GLXSwapIntervalSGI != 0)
  221394. {
  221395. swapInterval = numFramesPerSwap;
  221396. GLXSwapIntervalSGI (numFramesPerSwap);
  221397. return true;
  221398. }
  221399. return false;
  221400. }
  221401. int getSwapInterval() const
  221402. {
  221403. return swapInterval;
  221404. }
  221405. void repaint()
  221406. {
  221407. }
  221408. GLXContext renderContext;
  221409. private:
  221410. Window embeddedWindow;
  221411. OpenGLPixelFormat pixelFormat;
  221412. int swapInterval;
  221413. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221414. };
  221415. OpenGLContext* OpenGLComponent::createContext()
  221416. {
  221417. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221418. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221419. return (c->renderContext != 0) ? c.release() : 0;
  221420. }
  221421. void juce_glViewport (const int w, const int h)
  221422. {
  221423. glViewport (0, 0, w, h);
  221424. }
  221425. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221426. OwnedArray <OpenGLPixelFormat>& results)
  221427. {
  221428. results.add (new OpenGLPixelFormat()); // xxx
  221429. }
  221430. #endif
  221431. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221432. {
  221433. jassertfalse; // not implemented!
  221434. return false;
  221435. }
  221436. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221437. {
  221438. jassertfalse; // not implemented!
  221439. return false;
  221440. }
  221441. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221442. {
  221443. if (! isOnDesktop ())
  221444. addToDesktop (0);
  221445. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221446. if (wp != 0)
  221447. {
  221448. wp->setTaskBarIcon (newImage);
  221449. setVisible (true);
  221450. toFront (false);
  221451. repaint();
  221452. }
  221453. }
  221454. void SystemTrayIconComponent::paint (Graphics& g)
  221455. {
  221456. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221457. if (wp != 0)
  221458. {
  221459. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221460. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221461. false);
  221462. }
  221463. }
  221464. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221465. {
  221466. // xxx not yet implemented!
  221467. }
  221468. void PlatformUtilities::beep()
  221469. {
  221470. std::cout << "\a" << std::flush;
  221471. }
  221472. bool AlertWindow::showNativeDialogBox (const String& title,
  221473. const String& bodyText,
  221474. bool isOkCancel)
  221475. {
  221476. // use a non-native one for the time being..
  221477. if (isOkCancel)
  221478. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221479. else
  221480. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221481. return true;
  221482. }
  221483. const int KeyPress::spaceKey = XK_space & 0xff;
  221484. const int KeyPress::returnKey = XK_Return & 0xff;
  221485. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221486. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221487. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221488. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221489. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221490. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221491. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221492. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221493. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221494. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221495. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221496. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221497. const int KeyPress::tabKey = XK_Tab & 0xff;
  221498. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221499. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221500. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221501. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221502. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221503. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221504. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221505. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221506. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221507. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221508. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221509. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221510. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221511. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221512. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221513. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221514. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221515. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221516. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221517. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221518. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221519. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221520. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221521. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221522. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221523. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221524. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221525. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221526. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221527. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221528. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221529. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221530. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221531. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221532. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221533. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221534. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221535. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221536. #endif
  221537. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221538. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221539. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221540. // compiled on its own).
  221541. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221542. namespace
  221543. {
  221544. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221545. {
  221546. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221547. snd_pcm_hw_params_t* hwParams;
  221548. snd_pcm_hw_params_alloca (&hwParams);
  221549. for (int i = 0; ratesToTry[i] != 0; ++i)
  221550. {
  221551. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221552. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221553. {
  221554. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221555. }
  221556. }
  221557. }
  221558. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221559. {
  221560. snd_pcm_hw_params_t *params;
  221561. snd_pcm_hw_params_alloca (&params);
  221562. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221563. {
  221564. snd_pcm_hw_params_get_channels_min (params, minChans);
  221565. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221566. }
  221567. }
  221568. void getDeviceProperties (const String& deviceID,
  221569. unsigned int& minChansOut,
  221570. unsigned int& maxChansOut,
  221571. unsigned int& minChansIn,
  221572. unsigned int& maxChansIn,
  221573. Array <int>& rates)
  221574. {
  221575. if (deviceID.isEmpty())
  221576. return;
  221577. snd_ctl_t* handle;
  221578. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221579. {
  221580. snd_pcm_info_t* info;
  221581. snd_pcm_info_alloca (&info);
  221582. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221583. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221584. snd_pcm_info_set_subdevice (info, 0);
  221585. if (snd_ctl_pcm_info (handle, info) >= 0)
  221586. {
  221587. snd_pcm_t* pcmHandle;
  221588. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221589. {
  221590. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221591. getDeviceSampleRates (pcmHandle, rates);
  221592. snd_pcm_close (pcmHandle);
  221593. }
  221594. }
  221595. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221596. if (snd_ctl_pcm_info (handle, info) >= 0)
  221597. {
  221598. snd_pcm_t* pcmHandle;
  221599. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221600. {
  221601. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221602. if (rates.size() == 0)
  221603. getDeviceSampleRates (pcmHandle, rates);
  221604. snd_pcm_close (pcmHandle);
  221605. }
  221606. }
  221607. snd_ctl_close (handle);
  221608. }
  221609. }
  221610. }
  221611. class ALSADevice
  221612. {
  221613. public:
  221614. ALSADevice (const String& deviceID, bool forInput)
  221615. : handle (0),
  221616. bitDepth (16),
  221617. numChannelsRunning (0),
  221618. latency (0),
  221619. isInput (forInput),
  221620. isInterleaved (true)
  221621. {
  221622. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221623. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221624. SND_PCM_ASYNC));
  221625. }
  221626. ~ALSADevice()
  221627. {
  221628. if (handle != 0)
  221629. snd_pcm_close (handle);
  221630. }
  221631. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221632. {
  221633. if (handle == 0)
  221634. return false;
  221635. snd_pcm_hw_params_t* hwParams;
  221636. snd_pcm_hw_params_alloca (&hwParams);
  221637. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221638. return false;
  221639. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221640. isInterleaved = false;
  221641. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221642. isInterleaved = true;
  221643. else
  221644. {
  221645. jassertfalse;
  221646. return false;
  221647. }
  221648. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221649. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221650. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221651. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221652. SND_PCM_FORMAT_S32_BE, 32,
  221653. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221654. SND_PCM_FORMAT_S24_3BE, 24,
  221655. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221656. SND_PCM_FORMAT_S16_BE, 16 };
  221657. bitDepth = 0;
  221658. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221659. {
  221660. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221661. {
  221662. bitDepth = formatsToTry [i + 1] & 255;
  221663. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221664. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221665. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221666. break;
  221667. }
  221668. }
  221669. if (bitDepth == 0)
  221670. {
  221671. error = "device doesn't support a compatible PCM format";
  221672. DBG ("ALSA error: " + error + "\n");
  221673. return false;
  221674. }
  221675. int dir = 0;
  221676. unsigned int periods = 4;
  221677. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221678. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221679. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221680. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221681. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221682. || failed (snd_pcm_hw_params (handle, hwParams)))
  221683. {
  221684. return false;
  221685. }
  221686. snd_pcm_uframes_t frames = 0;
  221687. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  221688. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  221689. latency = 0;
  221690. else
  221691. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  221692. snd_pcm_sw_params_t* swParams;
  221693. snd_pcm_sw_params_alloca (&swParams);
  221694. snd_pcm_uframes_t boundary;
  221695. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221696. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221697. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221698. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221699. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221700. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221701. || failed (snd_pcm_sw_params (handle, swParams)))
  221702. {
  221703. return false;
  221704. }
  221705. #if 0
  221706. // enable this to dump the config of the devices that get opened
  221707. snd_output_t* out;
  221708. snd_output_stdio_attach (&out, stderr, 0);
  221709. snd_pcm_hw_params_dump (hwParams, out);
  221710. snd_pcm_sw_params_dump (swParams, out);
  221711. #endif
  221712. numChannelsRunning = numChannels;
  221713. return true;
  221714. }
  221715. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221716. {
  221717. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221718. float** const data = outputChannelBuffer.getArrayOfChannels();
  221719. snd_pcm_sframes_t numDone = 0;
  221720. if (isInterleaved)
  221721. {
  221722. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221723. for (int i = 0; i < numChannelsRunning; ++i)
  221724. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  221725. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  221726. }
  221727. else
  221728. {
  221729. for (int i = 0; i < numChannelsRunning; ++i)
  221730. converter->convertSamples (data[i], data[i], numSamples);
  221731. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  221732. }
  221733. if (failed (numDone))
  221734. {
  221735. if (numDone == -EPIPE)
  221736. {
  221737. if (failed (snd_pcm_prepare (handle)))
  221738. return false;
  221739. }
  221740. else if (numDone != -ESTRPIPE)
  221741. return false;
  221742. }
  221743. return true;
  221744. }
  221745. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221746. {
  221747. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221748. float** const data = inputChannelBuffer.getArrayOfChannels();
  221749. if (isInterleaved)
  221750. {
  221751. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221752. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  221753. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  221754. if (failed (num))
  221755. {
  221756. if (num == -EPIPE)
  221757. {
  221758. if (failed (snd_pcm_prepare (handle)))
  221759. return false;
  221760. }
  221761. else if (num != -ESTRPIPE)
  221762. return false;
  221763. }
  221764. for (int i = 0; i < numChannelsRunning; ++i)
  221765. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  221766. }
  221767. else
  221768. {
  221769. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221770. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221771. return false;
  221772. for (int i = 0; i < numChannelsRunning; ++i)
  221773. converter->convertSamples (data[i], data[i], numSamples);
  221774. }
  221775. return true;
  221776. }
  221777. snd_pcm_t* handle;
  221778. String error;
  221779. int bitDepth, numChannelsRunning, latency;
  221780. private:
  221781. const bool isInput;
  221782. bool isInterleaved;
  221783. MemoryBlock scratch;
  221784. ScopedPointer<AudioData::Converter> converter;
  221785. template <class SampleType>
  221786. struct ConverterHelper
  221787. {
  221788. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  221789. {
  221790. if (forInput)
  221791. {
  221792. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  221793. if (isLittleEndian)
  221794. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221795. else
  221796. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221797. }
  221798. else
  221799. {
  221800. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  221801. if (isLittleEndian)
  221802. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221803. else
  221804. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221805. }
  221806. }
  221807. };
  221808. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  221809. {
  221810. switch (bitDepth)
  221811. {
  221812. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221813. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221814. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  221815. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221816. default: jassertfalse; break; // unsupported format!
  221817. }
  221818. return 0;
  221819. }
  221820. bool failed (const int errorNum)
  221821. {
  221822. if (errorNum >= 0)
  221823. return false;
  221824. error = snd_strerror (errorNum);
  221825. DBG ("ALSA error: " + error + "\n");
  221826. return true;
  221827. }
  221828. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  221829. };
  221830. class ALSAThread : public Thread
  221831. {
  221832. public:
  221833. ALSAThread (const String& inputId_,
  221834. const String& outputId_)
  221835. : Thread ("Juce ALSA"),
  221836. sampleRate (0),
  221837. bufferSize (0),
  221838. outputLatency (0),
  221839. inputLatency (0),
  221840. callback (0),
  221841. inputId (inputId_),
  221842. outputId (outputId_),
  221843. numCallbacks (0),
  221844. inputChannelBuffer (1, 1),
  221845. outputChannelBuffer (1, 1)
  221846. {
  221847. initialiseRatesAndChannels();
  221848. }
  221849. ~ALSAThread()
  221850. {
  221851. close();
  221852. }
  221853. void open (BigInteger inputChannels,
  221854. BigInteger outputChannels,
  221855. const double sampleRate_,
  221856. const int bufferSize_)
  221857. {
  221858. close();
  221859. error = String::empty;
  221860. sampleRate = sampleRate_;
  221861. bufferSize = bufferSize_;
  221862. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221863. inputChannelBuffer.clear();
  221864. inputChannelDataForCallback.clear();
  221865. currentInputChans.clear();
  221866. if (inputChannels.getHighestBit() >= 0)
  221867. {
  221868. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221869. {
  221870. if (inputChannels[i])
  221871. {
  221872. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221873. currentInputChans.setBit (i);
  221874. }
  221875. }
  221876. }
  221877. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221878. outputChannelBuffer.clear();
  221879. outputChannelDataForCallback.clear();
  221880. currentOutputChans.clear();
  221881. if (outputChannels.getHighestBit() >= 0)
  221882. {
  221883. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221884. {
  221885. if (outputChannels[i])
  221886. {
  221887. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221888. currentOutputChans.setBit (i);
  221889. }
  221890. }
  221891. }
  221892. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221893. {
  221894. outputDevice = new ALSADevice (outputId, false);
  221895. if (outputDevice->error.isNotEmpty())
  221896. {
  221897. error = outputDevice->error;
  221898. outputDevice = 0;
  221899. return;
  221900. }
  221901. currentOutputChans.setRange (0, minChansOut, true);
  221902. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221903. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221904. bufferSize))
  221905. {
  221906. error = outputDevice->error;
  221907. outputDevice = 0;
  221908. return;
  221909. }
  221910. outputLatency = outputDevice->latency;
  221911. }
  221912. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221913. {
  221914. inputDevice = new ALSADevice (inputId, true);
  221915. if (inputDevice->error.isNotEmpty())
  221916. {
  221917. error = inputDevice->error;
  221918. inputDevice = 0;
  221919. return;
  221920. }
  221921. currentInputChans.setRange (0, minChansIn, true);
  221922. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221923. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221924. bufferSize))
  221925. {
  221926. error = inputDevice->error;
  221927. inputDevice = 0;
  221928. return;
  221929. }
  221930. inputLatency = inputDevice->latency;
  221931. }
  221932. if (outputDevice == 0 && inputDevice == 0)
  221933. {
  221934. error = "no channels";
  221935. return;
  221936. }
  221937. if (outputDevice != 0 && inputDevice != 0)
  221938. {
  221939. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221940. }
  221941. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221942. return;
  221943. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221944. return;
  221945. startThread (9);
  221946. int count = 1000;
  221947. while (numCallbacks == 0)
  221948. {
  221949. sleep (5);
  221950. if (--count < 0 || ! isThreadRunning())
  221951. {
  221952. error = "device didn't start";
  221953. break;
  221954. }
  221955. }
  221956. }
  221957. void close()
  221958. {
  221959. stopThread (6000);
  221960. inputDevice = 0;
  221961. outputDevice = 0;
  221962. inputChannelBuffer.setSize (1, 1);
  221963. outputChannelBuffer.setSize (1, 1);
  221964. numCallbacks = 0;
  221965. }
  221966. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221967. {
  221968. const ScopedLock sl (callbackLock);
  221969. callback = newCallback;
  221970. }
  221971. void run()
  221972. {
  221973. while (! threadShouldExit())
  221974. {
  221975. if (inputDevice != 0)
  221976. {
  221977. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  221978. {
  221979. DBG ("ALSA: read failure");
  221980. break;
  221981. }
  221982. }
  221983. if (threadShouldExit())
  221984. break;
  221985. {
  221986. const ScopedLock sl (callbackLock);
  221987. ++numCallbacks;
  221988. if (callback != 0)
  221989. {
  221990. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221991. inputChannelDataForCallback.size(),
  221992. outputChannelDataForCallback.getRawDataPointer(),
  221993. outputChannelDataForCallback.size(),
  221994. bufferSize);
  221995. }
  221996. else
  221997. {
  221998. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221999. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222000. }
  222001. }
  222002. if (outputDevice != 0)
  222003. {
  222004. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222005. if (threadShouldExit())
  222006. break;
  222007. failed (snd_pcm_avail_update (outputDevice->handle));
  222008. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222009. {
  222010. DBG ("ALSA: write failure");
  222011. break;
  222012. }
  222013. }
  222014. }
  222015. }
  222016. int getBitDepth() const throw()
  222017. {
  222018. if (outputDevice != 0)
  222019. return outputDevice->bitDepth;
  222020. if (inputDevice != 0)
  222021. return inputDevice->bitDepth;
  222022. return 16;
  222023. }
  222024. String error;
  222025. double sampleRate;
  222026. int bufferSize, outputLatency, inputLatency;
  222027. BigInteger currentInputChans, currentOutputChans;
  222028. Array <int> sampleRates;
  222029. StringArray channelNamesOut, channelNamesIn;
  222030. AudioIODeviceCallback* callback;
  222031. private:
  222032. const String inputId, outputId;
  222033. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222034. int numCallbacks;
  222035. CriticalSection callbackLock;
  222036. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222037. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222038. unsigned int minChansOut, maxChansOut;
  222039. unsigned int minChansIn, maxChansIn;
  222040. bool failed (const int errorNum)
  222041. {
  222042. if (errorNum >= 0)
  222043. return false;
  222044. error = snd_strerror (errorNum);
  222045. DBG ("ALSA error: " + error + "\n");
  222046. return true;
  222047. }
  222048. void initialiseRatesAndChannels()
  222049. {
  222050. sampleRates.clear();
  222051. channelNamesOut.clear();
  222052. channelNamesIn.clear();
  222053. minChansOut = 0;
  222054. maxChansOut = 0;
  222055. minChansIn = 0;
  222056. maxChansIn = 0;
  222057. unsigned int dummy = 0;
  222058. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222059. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222060. unsigned int i;
  222061. for (i = 0; i < maxChansOut; ++i)
  222062. channelNamesOut.add ("channel " + String ((int) i + 1));
  222063. for (i = 0; i < maxChansIn; ++i)
  222064. channelNamesIn.add ("channel " + String ((int) i + 1));
  222065. }
  222066. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  222067. };
  222068. class ALSAAudioIODevice : public AudioIODevice
  222069. {
  222070. public:
  222071. ALSAAudioIODevice (const String& deviceName,
  222072. const String& inputId_,
  222073. const String& outputId_)
  222074. : AudioIODevice (deviceName, "ALSA"),
  222075. inputId (inputId_),
  222076. outputId (outputId_),
  222077. isOpen_ (false),
  222078. isStarted (false),
  222079. internal (inputId_, outputId_)
  222080. {
  222081. }
  222082. ~ALSAAudioIODevice()
  222083. {
  222084. }
  222085. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222086. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222087. int getNumSampleRates() { return internal.sampleRates.size(); }
  222088. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222089. int getDefaultBufferSize() { return 512; }
  222090. int getNumBufferSizesAvailable() { return 50; }
  222091. int getBufferSizeSamples (int index)
  222092. {
  222093. int n = 16;
  222094. for (int i = 0; i < index; ++i)
  222095. n += n < 64 ? 16
  222096. : (n < 512 ? 32
  222097. : (n < 1024 ? 64
  222098. : (n < 2048 ? 128 : 256)));
  222099. return n;
  222100. }
  222101. const String open (const BigInteger& inputChannels,
  222102. const BigInteger& outputChannels,
  222103. double sampleRate,
  222104. int bufferSizeSamples)
  222105. {
  222106. close();
  222107. if (bufferSizeSamples <= 0)
  222108. bufferSizeSamples = getDefaultBufferSize();
  222109. if (sampleRate <= 0)
  222110. {
  222111. for (int i = 0; i < getNumSampleRates(); ++i)
  222112. {
  222113. if (getSampleRate (i) >= 44100)
  222114. {
  222115. sampleRate = getSampleRate (i);
  222116. break;
  222117. }
  222118. }
  222119. }
  222120. internal.open (inputChannels, outputChannels,
  222121. sampleRate, bufferSizeSamples);
  222122. isOpen_ = internal.error.isEmpty();
  222123. return internal.error;
  222124. }
  222125. void close()
  222126. {
  222127. stop();
  222128. internal.close();
  222129. isOpen_ = false;
  222130. }
  222131. bool isOpen() { return isOpen_; }
  222132. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222133. const String getLastError() { return internal.error; }
  222134. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222135. double getCurrentSampleRate() { return internal.sampleRate; }
  222136. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222137. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222138. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222139. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222140. int getInputLatencyInSamples() { return internal.inputLatency; }
  222141. void start (AudioIODeviceCallback* callback)
  222142. {
  222143. if (! isOpen_)
  222144. callback = 0;
  222145. if (callback != 0)
  222146. callback->audioDeviceAboutToStart (this);
  222147. internal.setCallback (callback);
  222148. isStarted = (callback != 0);
  222149. }
  222150. void stop()
  222151. {
  222152. AudioIODeviceCallback* const oldCallback = internal.callback;
  222153. start (0);
  222154. if (oldCallback != 0)
  222155. oldCallback->audioDeviceStopped();
  222156. }
  222157. String inputId, outputId;
  222158. private:
  222159. bool isOpen_, isStarted;
  222160. ALSAThread internal;
  222161. };
  222162. class ALSAAudioIODeviceType : public AudioIODeviceType
  222163. {
  222164. public:
  222165. ALSAAudioIODeviceType()
  222166. : AudioIODeviceType ("ALSA"),
  222167. hasScanned (false)
  222168. {
  222169. }
  222170. ~ALSAAudioIODeviceType()
  222171. {
  222172. }
  222173. void scanForDevices()
  222174. {
  222175. if (hasScanned)
  222176. return;
  222177. hasScanned = true;
  222178. inputNames.clear();
  222179. inputIds.clear();
  222180. outputNames.clear();
  222181. outputIds.clear();
  222182. /* void** hints = 0;
  222183. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222184. {
  222185. for (void** hint = hints; *hint != 0; ++hint)
  222186. {
  222187. const String name (getHint (*hint, "NAME"));
  222188. if (name.isNotEmpty())
  222189. {
  222190. const String ioid (getHint (*hint, "IOID"));
  222191. String desc (getHint (*hint, "DESC"));
  222192. if (desc.isEmpty())
  222193. desc = name;
  222194. desc = desc.replaceCharacters ("\n\r", " ");
  222195. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222196. if (ioid.isEmpty() || ioid == "Input")
  222197. {
  222198. inputNames.add (desc);
  222199. inputIds.add (name);
  222200. }
  222201. if (ioid.isEmpty() || ioid == "Output")
  222202. {
  222203. outputNames.add (desc);
  222204. outputIds.add (name);
  222205. }
  222206. }
  222207. }
  222208. snd_device_name_free_hint (hints);
  222209. }
  222210. */
  222211. snd_ctl_t* handle = 0;
  222212. snd_ctl_card_info_t* info = 0;
  222213. snd_ctl_card_info_alloca (&info);
  222214. int cardNum = -1;
  222215. while (outputIds.size() + inputIds.size() <= 32)
  222216. {
  222217. snd_card_next (&cardNum);
  222218. if (cardNum < 0)
  222219. break;
  222220. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222221. {
  222222. if (snd_ctl_card_info (handle, info) >= 0)
  222223. {
  222224. String cardId (snd_ctl_card_info_get_id (info));
  222225. if (cardId.removeCharacters ("0123456789").isEmpty())
  222226. cardId = String (cardNum);
  222227. int device = -1;
  222228. for (;;)
  222229. {
  222230. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222231. break;
  222232. String id, name;
  222233. id << "hw:" << cardId << ',' << device;
  222234. bool isInput, isOutput;
  222235. if (testDevice (id, isInput, isOutput))
  222236. {
  222237. name << snd_ctl_card_info_get_name (info);
  222238. if (name.isEmpty())
  222239. name = id;
  222240. if (isInput)
  222241. {
  222242. inputNames.add (name);
  222243. inputIds.add (id);
  222244. }
  222245. if (isOutput)
  222246. {
  222247. outputNames.add (name);
  222248. outputIds.add (id);
  222249. }
  222250. }
  222251. }
  222252. }
  222253. snd_ctl_close (handle);
  222254. }
  222255. }
  222256. inputNames.appendNumbersToDuplicates (false, true);
  222257. outputNames.appendNumbersToDuplicates (false, true);
  222258. }
  222259. const StringArray getDeviceNames (bool wantInputNames) const
  222260. {
  222261. jassert (hasScanned); // need to call scanForDevices() before doing this
  222262. return wantInputNames ? inputNames : outputNames;
  222263. }
  222264. int getDefaultDeviceIndex (bool forInput) const
  222265. {
  222266. jassert (hasScanned); // need to call scanForDevices() before doing this
  222267. return 0;
  222268. }
  222269. bool hasSeparateInputsAndOutputs() const { return true; }
  222270. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222271. {
  222272. jassert (hasScanned); // need to call scanForDevices() before doing this
  222273. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222274. if (d == 0)
  222275. return -1;
  222276. return asInput ? inputIds.indexOf (d->inputId)
  222277. : outputIds.indexOf (d->outputId);
  222278. }
  222279. AudioIODevice* createDevice (const String& outputDeviceName,
  222280. const String& inputDeviceName)
  222281. {
  222282. jassert (hasScanned); // need to call scanForDevices() before doing this
  222283. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222284. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222285. String deviceName (outputIndex >= 0 ? outputDeviceName
  222286. : inputDeviceName);
  222287. if (inputIndex >= 0 || outputIndex >= 0)
  222288. return new ALSAAudioIODevice (deviceName,
  222289. inputIds [inputIndex],
  222290. outputIds [outputIndex]);
  222291. return 0;
  222292. }
  222293. private:
  222294. StringArray inputNames, outputNames, inputIds, outputIds;
  222295. bool hasScanned;
  222296. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222297. {
  222298. unsigned int minChansOut = 0, maxChansOut = 0;
  222299. unsigned int minChansIn = 0, maxChansIn = 0;
  222300. Array <int> rates;
  222301. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222302. DBG ("ALSA device: " + id
  222303. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222304. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222305. + " rates=" + String (rates.size()));
  222306. isInput = maxChansIn > 0;
  222307. isOutput = maxChansOut > 0;
  222308. return (isInput || isOutput) && rates.size() > 0;
  222309. }
  222310. /*static const String getHint (void* hint, const char* type)
  222311. {
  222312. char* const n = snd_device_name_get_hint (hint, type);
  222313. const String s ((const char*) n);
  222314. free (n);
  222315. return s;
  222316. }*/
  222317. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222318. };
  222319. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222320. {
  222321. return new ALSAAudioIODeviceType();
  222322. }
  222323. #endif
  222324. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222325. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222326. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222327. // compiled on its own).
  222328. #ifdef JUCE_INCLUDED_FILE
  222329. #if JUCE_JACK
  222330. static void* juce_libjack_handle = 0;
  222331. void* juce_load_jack_function (const char* const name)
  222332. {
  222333. if (juce_libjack_handle == 0)
  222334. return 0;
  222335. return dlsym (juce_libjack_handle, name);
  222336. }
  222337. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222338. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222339. return_type fn_name argument_types { \
  222340. static fn_name##_ptr_t fn = 0; \
  222341. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222342. if (fn) return (*fn)arguments; \
  222343. else return 0; \
  222344. }
  222345. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222346. typedef void (*fn_name##_ptr_t)argument_types; \
  222347. void fn_name argument_types { \
  222348. static fn_name##_ptr_t fn = 0; \
  222349. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222350. if (fn) (*fn)arguments; \
  222351. }
  222352. 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));
  222353. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222354. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222355. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222356. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222357. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222358. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222359. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222360. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222361. 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));
  222362. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222363. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222364. 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));
  222365. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222366. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222367. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222368. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222369. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222370. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222371. #if JUCE_DEBUG
  222372. #define JACK_LOGGING_ENABLED 1
  222373. #endif
  222374. #if JACK_LOGGING_ENABLED
  222375. namespace
  222376. {
  222377. void jack_Log (const String& s)
  222378. {
  222379. std::cerr << s << std::endl;
  222380. }
  222381. void dumpJackErrorMessage (const jack_status_t status)
  222382. {
  222383. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222384. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222385. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222386. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222387. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222388. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222389. }
  222390. }
  222391. #else
  222392. #define dumpJackErrorMessage(a) {}
  222393. #define jack_Log(...) {}
  222394. #endif
  222395. #ifndef JUCE_JACK_CLIENT_NAME
  222396. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222397. #endif
  222398. class JackAudioIODevice : public AudioIODevice
  222399. {
  222400. public:
  222401. JackAudioIODevice (const String& deviceName,
  222402. const String& inputId_,
  222403. const String& outputId_)
  222404. : AudioIODevice (deviceName, "JACK"),
  222405. inputId (inputId_),
  222406. outputId (outputId_),
  222407. isOpen_ (false),
  222408. callback (0),
  222409. totalNumberOfInputChannels (0),
  222410. totalNumberOfOutputChannels (0)
  222411. {
  222412. jassert (deviceName.isNotEmpty());
  222413. jack_status_t status;
  222414. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222415. if (client == 0)
  222416. {
  222417. dumpJackErrorMessage (status);
  222418. }
  222419. else
  222420. {
  222421. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222422. // open input ports
  222423. const StringArray inputChannels (getInputChannelNames());
  222424. for (int i = 0; i < inputChannels.size(); i++)
  222425. {
  222426. String inputName;
  222427. inputName << "in_" << ++totalNumberOfInputChannels;
  222428. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222429. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222430. }
  222431. // open output ports
  222432. const StringArray outputChannels (getOutputChannelNames());
  222433. for (int i = 0; i < outputChannels.size (); i++)
  222434. {
  222435. String outputName;
  222436. outputName << "out_" << ++totalNumberOfOutputChannels;
  222437. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222438. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222439. }
  222440. inChans.calloc (totalNumberOfInputChannels + 2);
  222441. outChans.calloc (totalNumberOfOutputChannels + 2);
  222442. }
  222443. }
  222444. ~JackAudioIODevice()
  222445. {
  222446. close();
  222447. if (client != 0)
  222448. {
  222449. JUCE_NAMESPACE::jack_client_close (client);
  222450. client = 0;
  222451. }
  222452. }
  222453. const StringArray getChannelNames (bool forInput) const
  222454. {
  222455. StringArray names;
  222456. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222457. forInput ? JackPortIsInput : JackPortIsOutput);
  222458. if (ports != 0)
  222459. {
  222460. int j = 0;
  222461. while (ports[j] != 0)
  222462. {
  222463. const String portName (ports [j++]);
  222464. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222465. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222466. }
  222467. free (ports);
  222468. }
  222469. return names;
  222470. }
  222471. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222472. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222473. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222474. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222475. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222476. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222477. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222478. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222479. double sampleRate, int bufferSizeSamples)
  222480. {
  222481. if (client == 0)
  222482. {
  222483. lastError = "No JACK client running";
  222484. return lastError;
  222485. }
  222486. lastError = String::empty;
  222487. close();
  222488. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222489. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222490. JUCE_NAMESPACE::jack_activate (client);
  222491. isOpen_ = true;
  222492. if (! inputChannels.isZero())
  222493. {
  222494. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222495. if (ports != 0)
  222496. {
  222497. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222498. for (int i = 0; i < numInputChannels; ++i)
  222499. {
  222500. const String portName (ports[i]);
  222501. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222502. {
  222503. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222504. if (error != 0)
  222505. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222506. }
  222507. }
  222508. free (ports);
  222509. }
  222510. }
  222511. if (! outputChannels.isZero())
  222512. {
  222513. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222514. if (ports != 0)
  222515. {
  222516. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222517. for (int i = 0; i < numOutputChannels; ++i)
  222518. {
  222519. const String portName (ports[i]);
  222520. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222521. {
  222522. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222523. if (error != 0)
  222524. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222525. }
  222526. }
  222527. free (ports);
  222528. }
  222529. }
  222530. return lastError;
  222531. }
  222532. void close()
  222533. {
  222534. stop();
  222535. if (client != 0)
  222536. {
  222537. JUCE_NAMESPACE::jack_deactivate (client);
  222538. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222539. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222540. }
  222541. isOpen_ = false;
  222542. }
  222543. void start (AudioIODeviceCallback* newCallback)
  222544. {
  222545. if (isOpen_ && newCallback != callback)
  222546. {
  222547. if (newCallback != 0)
  222548. newCallback->audioDeviceAboutToStart (this);
  222549. AudioIODeviceCallback* const oldCallback = callback;
  222550. {
  222551. const ScopedLock sl (callbackLock);
  222552. callback = newCallback;
  222553. }
  222554. if (oldCallback != 0)
  222555. oldCallback->audioDeviceStopped();
  222556. }
  222557. }
  222558. void stop()
  222559. {
  222560. start (0);
  222561. }
  222562. bool isOpen() { return isOpen_; }
  222563. bool isPlaying() { return callback != 0; }
  222564. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222565. double getCurrentSampleRate() { return getSampleRate (0); }
  222566. int getCurrentBitDepth() { return 32; }
  222567. const String getLastError() { return lastError; }
  222568. const BigInteger getActiveOutputChannels() const
  222569. {
  222570. BigInteger outputBits;
  222571. for (int i = 0; i < outputPorts.size(); i++)
  222572. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222573. outputBits.setBit (i);
  222574. return outputBits;
  222575. }
  222576. const BigInteger getActiveInputChannels() const
  222577. {
  222578. BigInteger inputBits;
  222579. for (int i = 0; i < inputPorts.size(); i++)
  222580. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222581. inputBits.setBit (i);
  222582. return inputBits;
  222583. }
  222584. int getOutputLatencyInSamples()
  222585. {
  222586. int latency = 0;
  222587. for (int i = 0; i < outputPorts.size(); i++)
  222588. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222589. return latency;
  222590. }
  222591. int getInputLatencyInSamples()
  222592. {
  222593. int latency = 0;
  222594. for (int i = 0; i < inputPorts.size(); i++)
  222595. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222596. return latency;
  222597. }
  222598. String inputId, outputId;
  222599. private:
  222600. void process (const int numSamples)
  222601. {
  222602. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222603. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222604. {
  222605. jack_default_audio_sample_t* in
  222606. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222607. if (in != 0)
  222608. inChans [numActiveInChans++] = (float*) in;
  222609. }
  222610. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222611. {
  222612. jack_default_audio_sample_t* out
  222613. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222614. if (out != 0)
  222615. outChans [numActiveOutChans++] = (float*) out;
  222616. }
  222617. const ScopedLock sl (callbackLock);
  222618. if (callback != 0)
  222619. {
  222620. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222621. outChans, numActiveOutChans, numSamples);
  222622. }
  222623. else
  222624. {
  222625. for (i = 0; i < numActiveOutChans; ++i)
  222626. zeromem (outChans[i], sizeof (float) * numSamples);
  222627. }
  222628. }
  222629. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222630. {
  222631. if (callbackArgument != 0)
  222632. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222633. return 0;
  222634. }
  222635. static void threadInitCallback (void* callbackArgument)
  222636. {
  222637. jack_Log ("JackAudioIODevice::initialise");
  222638. }
  222639. static void shutdownCallback (void* callbackArgument)
  222640. {
  222641. jack_Log ("JackAudioIODevice::shutdown");
  222642. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222643. if (device != 0)
  222644. {
  222645. device->client = 0;
  222646. device->close();
  222647. }
  222648. }
  222649. static void errorCallback (const char* msg)
  222650. {
  222651. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222652. }
  222653. bool isOpen_;
  222654. jack_client_t* client;
  222655. String lastError;
  222656. AudioIODeviceCallback* callback;
  222657. CriticalSection callbackLock;
  222658. HeapBlock <float*> inChans, outChans;
  222659. int totalNumberOfInputChannels;
  222660. int totalNumberOfOutputChannels;
  222661. Array<void*> inputPorts, outputPorts;
  222662. };
  222663. class JackAudioIODeviceType : public AudioIODeviceType
  222664. {
  222665. public:
  222666. JackAudioIODeviceType()
  222667. : AudioIODeviceType ("JACK"),
  222668. hasScanned (false)
  222669. {
  222670. }
  222671. ~JackAudioIODeviceType()
  222672. {
  222673. }
  222674. void scanForDevices()
  222675. {
  222676. hasScanned = true;
  222677. inputNames.clear();
  222678. inputIds.clear();
  222679. outputNames.clear();
  222680. outputIds.clear();
  222681. if (juce_libjack_handle == 0)
  222682. {
  222683. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222684. if (juce_libjack_handle == 0)
  222685. return;
  222686. }
  222687. // open a dummy client
  222688. jack_status_t status;
  222689. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222690. if (client == 0)
  222691. {
  222692. dumpJackErrorMessage (status);
  222693. }
  222694. else
  222695. {
  222696. // scan for output devices
  222697. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222698. if (ports != 0)
  222699. {
  222700. int j = 0;
  222701. while (ports[j] != 0)
  222702. {
  222703. String clientName (ports[j]);
  222704. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222705. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222706. && ! inputNames.contains (clientName))
  222707. {
  222708. inputNames.add (clientName);
  222709. inputIds.add (ports [j]);
  222710. }
  222711. ++j;
  222712. }
  222713. free (ports);
  222714. }
  222715. // scan for input devices
  222716. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222717. if (ports != 0)
  222718. {
  222719. int j = 0;
  222720. while (ports[j] != 0)
  222721. {
  222722. String clientName (ports[j]);
  222723. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222724. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222725. && ! outputNames.contains (clientName))
  222726. {
  222727. outputNames.add (clientName);
  222728. outputIds.add (ports [j]);
  222729. }
  222730. ++j;
  222731. }
  222732. free (ports);
  222733. }
  222734. JUCE_NAMESPACE::jack_client_close (client);
  222735. }
  222736. }
  222737. const StringArray getDeviceNames (bool wantInputNames) const
  222738. {
  222739. jassert (hasScanned); // need to call scanForDevices() before doing this
  222740. return wantInputNames ? inputNames : outputNames;
  222741. }
  222742. int getDefaultDeviceIndex (bool forInput) const
  222743. {
  222744. jassert (hasScanned); // need to call scanForDevices() before doing this
  222745. return 0;
  222746. }
  222747. bool hasSeparateInputsAndOutputs() const { return true; }
  222748. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222749. {
  222750. jassert (hasScanned); // need to call scanForDevices() before doing this
  222751. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222752. if (d == 0)
  222753. return -1;
  222754. return asInput ? inputIds.indexOf (d->inputId)
  222755. : outputIds.indexOf (d->outputId);
  222756. }
  222757. AudioIODevice* createDevice (const String& outputDeviceName,
  222758. const String& inputDeviceName)
  222759. {
  222760. jassert (hasScanned); // need to call scanForDevices() before doing this
  222761. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222762. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222763. if (inputIndex >= 0 || outputIndex >= 0)
  222764. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222765. : inputDeviceName,
  222766. inputIds [inputIndex],
  222767. outputIds [outputIndex]);
  222768. return 0;
  222769. }
  222770. private:
  222771. StringArray inputNames, outputNames, inputIds, outputIds;
  222772. bool hasScanned;
  222773. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  222774. };
  222775. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222776. {
  222777. return new JackAudioIODeviceType();
  222778. }
  222779. #else // if JACK is turned off..
  222780. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222781. #endif
  222782. #endif
  222783. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222784. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222785. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222786. // compiled on its own).
  222787. #if JUCE_INCLUDED_FILE
  222788. #if JUCE_ALSA
  222789. namespace
  222790. {
  222791. snd_seq_t* iterateMidiDevices (const bool forInput,
  222792. StringArray& deviceNamesFound,
  222793. const int deviceIndexToOpen)
  222794. {
  222795. snd_seq_t* returnedHandle = 0;
  222796. snd_seq_t* seqHandle;
  222797. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222798. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222799. {
  222800. snd_seq_system_info_t* systemInfo;
  222801. snd_seq_client_info_t* clientInfo;
  222802. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222803. {
  222804. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222805. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222806. {
  222807. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222808. while (--numClients >= 0 && returnedHandle == 0)
  222809. {
  222810. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222811. {
  222812. snd_seq_port_info_t* portInfo;
  222813. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222814. {
  222815. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222816. const int client = snd_seq_client_info_get_client (clientInfo);
  222817. snd_seq_port_info_set_client (portInfo, client);
  222818. snd_seq_port_info_set_port (portInfo, -1);
  222819. while (--numPorts >= 0)
  222820. {
  222821. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222822. && (snd_seq_port_info_get_capability (portInfo)
  222823. & (forInput ? SND_SEQ_PORT_CAP_READ
  222824. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222825. {
  222826. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222827. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222828. {
  222829. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222830. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222831. if (sourcePort != -1)
  222832. {
  222833. snd_seq_set_client_name (seqHandle,
  222834. forInput ? "Juce Midi Input"
  222835. : "Juce Midi Output");
  222836. const int portId
  222837. = snd_seq_create_simple_port (seqHandle,
  222838. forInput ? "Juce Midi In Port"
  222839. : "Juce Midi Out Port",
  222840. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222841. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222842. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222843. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222844. returnedHandle = seqHandle;
  222845. }
  222846. }
  222847. }
  222848. }
  222849. snd_seq_port_info_free (portInfo);
  222850. }
  222851. }
  222852. }
  222853. snd_seq_client_info_free (clientInfo);
  222854. }
  222855. snd_seq_system_info_free (systemInfo);
  222856. }
  222857. if (returnedHandle == 0)
  222858. snd_seq_close (seqHandle);
  222859. }
  222860. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222861. return returnedHandle;
  222862. }
  222863. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  222864. {
  222865. snd_seq_t* seqHandle = 0;
  222866. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222867. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222868. {
  222869. snd_seq_set_client_name (seqHandle,
  222870. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222871. const int portId
  222872. = snd_seq_create_simple_port (seqHandle,
  222873. forInput ? "in"
  222874. : "out",
  222875. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222876. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222877. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222878. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222879. if (portId < 0)
  222880. {
  222881. snd_seq_close (seqHandle);
  222882. seqHandle = 0;
  222883. }
  222884. }
  222885. return seqHandle;
  222886. }
  222887. }
  222888. class MidiOutputDevice
  222889. {
  222890. public:
  222891. MidiOutputDevice (MidiOutput* const midiOutput_,
  222892. snd_seq_t* const seqHandle_)
  222893. :
  222894. midiOutput (midiOutput_),
  222895. seqHandle (seqHandle_),
  222896. maxEventSize (16 * 1024)
  222897. {
  222898. jassert (seqHandle != 0 && midiOutput != 0);
  222899. snd_midi_event_new (maxEventSize, &midiParser);
  222900. }
  222901. ~MidiOutputDevice()
  222902. {
  222903. snd_midi_event_free (midiParser);
  222904. snd_seq_close (seqHandle);
  222905. }
  222906. void sendMessageNow (const MidiMessage& message)
  222907. {
  222908. if (message.getRawDataSize() > maxEventSize)
  222909. {
  222910. maxEventSize = message.getRawDataSize();
  222911. snd_midi_event_free (midiParser);
  222912. snd_midi_event_new (maxEventSize, &midiParser);
  222913. }
  222914. snd_seq_event_t event;
  222915. snd_seq_ev_clear (&event);
  222916. snd_midi_event_encode (midiParser,
  222917. message.getRawData(),
  222918. message.getRawDataSize(),
  222919. &event);
  222920. snd_midi_event_reset_encode (midiParser);
  222921. snd_seq_ev_set_source (&event, 0);
  222922. snd_seq_ev_set_subs (&event);
  222923. snd_seq_ev_set_direct (&event);
  222924. snd_seq_event_output (seqHandle, &event);
  222925. snd_seq_drain_output (seqHandle);
  222926. }
  222927. private:
  222928. MidiOutput* const midiOutput;
  222929. snd_seq_t* const seqHandle;
  222930. snd_midi_event_t* midiParser;
  222931. int maxEventSize;
  222932. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  222933. };
  222934. const StringArray MidiOutput::getDevices()
  222935. {
  222936. StringArray devices;
  222937. iterateMidiDevices (false, devices, -1);
  222938. return devices;
  222939. }
  222940. int MidiOutput::getDefaultDeviceIndex()
  222941. {
  222942. return 0;
  222943. }
  222944. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222945. {
  222946. MidiOutput* newDevice = 0;
  222947. StringArray devices;
  222948. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  222949. if (handle != 0)
  222950. {
  222951. newDevice = new MidiOutput();
  222952. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222953. }
  222954. return newDevice;
  222955. }
  222956. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222957. {
  222958. MidiOutput* newDevice = 0;
  222959. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  222960. if (handle != 0)
  222961. {
  222962. newDevice = new MidiOutput();
  222963. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222964. }
  222965. return newDevice;
  222966. }
  222967. MidiOutput::~MidiOutput()
  222968. {
  222969. delete static_cast <MidiOutputDevice*> (internal);
  222970. }
  222971. void MidiOutput::reset()
  222972. {
  222973. }
  222974. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222975. {
  222976. return false;
  222977. }
  222978. void MidiOutput::setVolume (float leftVol, float rightVol)
  222979. {
  222980. }
  222981. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222982. {
  222983. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  222984. }
  222985. class MidiInputThread : public Thread
  222986. {
  222987. public:
  222988. MidiInputThread (MidiInput* const midiInput_,
  222989. snd_seq_t* const seqHandle_,
  222990. MidiInputCallback* const callback_)
  222991. : Thread ("Juce MIDI Input"),
  222992. midiInput (midiInput_),
  222993. seqHandle (seqHandle_),
  222994. callback (callback_)
  222995. {
  222996. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222997. }
  222998. ~MidiInputThread()
  222999. {
  223000. snd_seq_close (seqHandle);
  223001. }
  223002. void run()
  223003. {
  223004. const int maxEventSize = 16 * 1024;
  223005. snd_midi_event_t* midiParser;
  223006. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223007. {
  223008. HeapBlock <uint8> buffer (maxEventSize);
  223009. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223010. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223011. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223012. while (! threadShouldExit())
  223013. {
  223014. if (poll (pfd, numPfds, 500) > 0)
  223015. {
  223016. snd_seq_event_t* inputEvent = 0;
  223017. snd_seq_nonblock (seqHandle, 1);
  223018. do
  223019. {
  223020. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223021. {
  223022. // xxx what about SYSEXes that are too big for the buffer?
  223023. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223024. snd_midi_event_reset_decode (midiParser);
  223025. if (numBytes > 0)
  223026. {
  223027. const MidiMessage message ((const uint8*) buffer,
  223028. numBytes,
  223029. Time::getMillisecondCounter() * 0.001);
  223030. callback->handleIncomingMidiMessage (midiInput, message);
  223031. }
  223032. snd_seq_free_event (inputEvent);
  223033. }
  223034. }
  223035. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223036. snd_seq_free_event (inputEvent);
  223037. }
  223038. }
  223039. snd_midi_event_free (midiParser);
  223040. }
  223041. };
  223042. private:
  223043. MidiInput* const midiInput;
  223044. snd_seq_t* const seqHandle;
  223045. MidiInputCallback* const callback;
  223046. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  223047. };
  223048. MidiInput::MidiInput (const String& name_)
  223049. : name (name_),
  223050. internal (0)
  223051. {
  223052. }
  223053. MidiInput::~MidiInput()
  223054. {
  223055. stop();
  223056. delete static_cast <MidiInputThread*> (internal);
  223057. }
  223058. void MidiInput::start()
  223059. {
  223060. static_cast <MidiInputThread*> (internal)->startThread();
  223061. }
  223062. void MidiInput::stop()
  223063. {
  223064. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223065. }
  223066. int MidiInput::getDefaultDeviceIndex()
  223067. {
  223068. return 0;
  223069. }
  223070. const StringArray MidiInput::getDevices()
  223071. {
  223072. StringArray devices;
  223073. iterateMidiDevices (true, devices, -1);
  223074. return devices;
  223075. }
  223076. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223077. {
  223078. MidiInput* newDevice = 0;
  223079. StringArray devices;
  223080. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223081. if (handle != 0)
  223082. {
  223083. newDevice = new MidiInput (devices [deviceIndex]);
  223084. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223085. }
  223086. return newDevice;
  223087. }
  223088. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223089. {
  223090. MidiInput* newDevice = 0;
  223091. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223092. if (handle != 0)
  223093. {
  223094. newDevice = new MidiInput (deviceName);
  223095. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223096. }
  223097. return newDevice;
  223098. }
  223099. #else
  223100. // (These are just stub functions if ALSA is unavailable...)
  223101. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223102. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223103. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223104. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223105. MidiOutput::~MidiOutput() {}
  223106. void MidiOutput::reset() {}
  223107. bool MidiOutput::getVolume (float&, float&) { return false; }
  223108. void MidiOutput::setVolume (float, float) {}
  223109. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223110. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223111. MidiInput::~MidiInput() {}
  223112. void MidiInput::start() {}
  223113. void MidiInput::stop() {}
  223114. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223115. const StringArray MidiInput::getDevices() { return StringArray(); }
  223116. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223117. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223118. #endif
  223119. #endif
  223120. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223121. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223122. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223123. // compiled on its own).
  223124. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223125. AudioCDReader::AudioCDReader()
  223126. : AudioFormatReader (0, "CD Audio")
  223127. {
  223128. }
  223129. const StringArray AudioCDReader::getAvailableCDNames()
  223130. {
  223131. StringArray names;
  223132. return names;
  223133. }
  223134. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223135. {
  223136. return 0;
  223137. }
  223138. AudioCDReader::~AudioCDReader()
  223139. {
  223140. }
  223141. void AudioCDReader::refreshTrackLengths()
  223142. {
  223143. }
  223144. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223145. int64 startSampleInFile, int numSamples)
  223146. {
  223147. return false;
  223148. }
  223149. bool AudioCDReader::isCDStillPresent() const
  223150. {
  223151. return false;
  223152. }
  223153. bool AudioCDReader::isTrackAudio (int trackNum) const
  223154. {
  223155. return false;
  223156. }
  223157. void AudioCDReader::enableIndexScanning (bool b)
  223158. {
  223159. }
  223160. int AudioCDReader::getLastIndex() const
  223161. {
  223162. return 0;
  223163. }
  223164. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223165. {
  223166. return Array<int>();
  223167. }
  223168. #endif
  223169. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223170. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223171. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223172. // compiled on its own).
  223173. #if JUCE_INCLUDED_FILE
  223174. void FileChooser::showPlatformDialog (Array<File>& results,
  223175. const String& title,
  223176. const File& file,
  223177. const String& filters,
  223178. bool isDirectory,
  223179. bool selectsFiles,
  223180. bool isSave,
  223181. bool warnAboutOverwritingExistingFiles,
  223182. bool selectMultipleFiles,
  223183. FilePreviewComponent* previewComponent)
  223184. {
  223185. const String separator (":");
  223186. String command ("zenity --file-selection");
  223187. if (title.isNotEmpty())
  223188. command << " --title=\"" << title << "\"";
  223189. if (file != File::nonexistent)
  223190. command << " --filename=\"" << file.getFullPathName () << "\"";
  223191. if (isDirectory)
  223192. command << " --directory";
  223193. if (isSave)
  223194. command << " --save";
  223195. if (selectMultipleFiles)
  223196. command << " --multiple --separator=\"" << separator << "\"";
  223197. command << " 2>&1";
  223198. MemoryOutputStream result;
  223199. int status = -1;
  223200. FILE* stream = popen (command.toUTF8(), "r");
  223201. if (stream != 0)
  223202. {
  223203. for (;;)
  223204. {
  223205. char buffer [1024];
  223206. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223207. if (bytesRead <= 0)
  223208. break;
  223209. result.write (buffer, bytesRead);
  223210. }
  223211. status = pclose (stream);
  223212. }
  223213. if (status == 0)
  223214. {
  223215. StringArray tokens;
  223216. if (selectMultipleFiles)
  223217. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223218. else
  223219. tokens.add (result.toUTF8());
  223220. for (int i = 0; i < tokens.size(); i++)
  223221. results.add (File (tokens[i]));
  223222. return;
  223223. }
  223224. //xxx ain't got one!
  223225. jassertfalse;
  223226. }
  223227. #endif
  223228. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223229. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223230. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223231. // compiled on its own).
  223232. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223233. /*
  223234. Sorry.. This class isn't implemented on Linux!
  223235. */
  223236. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223237. : browser (0),
  223238. blankPageShown (false),
  223239. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223240. {
  223241. setOpaque (true);
  223242. }
  223243. WebBrowserComponent::~WebBrowserComponent()
  223244. {
  223245. }
  223246. void WebBrowserComponent::goToURL (const String& url,
  223247. const StringArray* headers,
  223248. const MemoryBlock* postData)
  223249. {
  223250. lastURL = url;
  223251. lastHeaders.clear();
  223252. if (headers != 0)
  223253. lastHeaders = *headers;
  223254. lastPostData.setSize (0);
  223255. if (postData != 0)
  223256. lastPostData = *postData;
  223257. blankPageShown = false;
  223258. }
  223259. void WebBrowserComponent::stop()
  223260. {
  223261. }
  223262. void WebBrowserComponent::goBack()
  223263. {
  223264. lastURL = String::empty;
  223265. blankPageShown = false;
  223266. }
  223267. void WebBrowserComponent::goForward()
  223268. {
  223269. lastURL = String::empty;
  223270. }
  223271. void WebBrowserComponent::refresh()
  223272. {
  223273. }
  223274. void WebBrowserComponent::paint (Graphics& g)
  223275. {
  223276. g.fillAll (Colours::white);
  223277. }
  223278. void WebBrowserComponent::checkWindowAssociation()
  223279. {
  223280. }
  223281. void WebBrowserComponent::reloadLastURL()
  223282. {
  223283. if (lastURL.isNotEmpty())
  223284. {
  223285. goToURL (lastURL, &lastHeaders, &lastPostData);
  223286. lastURL = String::empty;
  223287. }
  223288. }
  223289. void WebBrowserComponent::parentHierarchyChanged()
  223290. {
  223291. checkWindowAssociation();
  223292. }
  223293. void WebBrowserComponent::resized()
  223294. {
  223295. }
  223296. void WebBrowserComponent::visibilityChanged()
  223297. {
  223298. checkWindowAssociation();
  223299. }
  223300. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223301. {
  223302. return true;
  223303. }
  223304. #endif
  223305. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223306. #endif
  223307. END_JUCE_NAMESPACE
  223308. #endif
  223309. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223310. #endif
  223311. #if JUCE_MAC || JUCE_IPHONE
  223312. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223313. /*
  223314. This file wraps together all the mac-specific code, so that
  223315. we can include all the native headers just once, and compile all our
  223316. platform-specific stuff in one big lump, keeping it out of the way of
  223317. the rest of the codebase.
  223318. */
  223319. #if JUCE_MAC || JUCE_IOS
  223320. #undef JUCE_BUILD_NATIVE
  223321. #define JUCE_BUILD_NATIVE 1
  223322. BEGIN_JUCE_NAMESPACE
  223323. #undef Point
  223324. namespace
  223325. {
  223326. template <class RectType>
  223327. const Rectangle<int> convertToRectInt (const RectType& r)
  223328. {
  223329. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223330. }
  223331. template <class RectType>
  223332. const Rectangle<float> convertToRectFloat (const RectType& r)
  223333. {
  223334. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223335. }
  223336. template <class RectType>
  223337. CGRect convertToCGRect (const RectType& r)
  223338. {
  223339. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223340. }
  223341. }
  223342. class MessageQueue
  223343. {
  223344. public:
  223345. MessageQueue()
  223346. {
  223347. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223348. runLoop = CFRunLoopGetMain();
  223349. #else
  223350. runLoop = CFRunLoopGetCurrent();
  223351. #endif
  223352. CFRunLoopSourceContext sourceContext;
  223353. zerostruct (sourceContext);
  223354. sourceContext.info = this;
  223355. sourceContext.perform = runLoopSourceCallback;
  223356. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223357. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223358. }
  223359. ~MessageQueue()
  223360. {
  223361. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223362. CFRunLoopSourceInvalidate (runLoopSource);
  223363. CFRelease (runLoopSource);
  223364. }
  223365. void post (Message* const message)
  223366. {
  223367. messages.add (message);
  223368. CFRunLoopSourceSignal (runLoopSource);
  223369. CFRunLoopWakeUp (runLoop);
  223370. }
  223371. private:
  223372. ReferenceCountedArray <Message, CriticalSection> messages;
  223373. CriticalSection lock;
  223374. CFRunLoopRef runLoop;
  223375. CFRunLoopSourceRef runLoopSource;
  223376. bool deliverNextMessage()
  223377. {
  223378. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223379. if (nextMessage == 0)
  223380. return false;
  223381. const ScopedAutoReleasePool pool;
  223382. MessageManager::getInstance()->deliverMessage (nextMessage);
  223383. return true;
  223384. }
  223385. void runLoopCallback()
  223386. {
  223387. for (int i = 4; --i >= 0;)
  223388. if (! deliverNextMessage())
  223389. return;
  223390. CFRunLoopSourceSignal (runLoopSource);
  223391. CFRunLoopWakeUp (runLoop);
  223392. }
  223393. static void runLoopSourceCallback (void* info)
  223394. {
  223395. static_cast <MessageQueue*> (info)->runLoopCallback();
  223396. }
  223397. };
  223398. #define JUCE_INCLUDED_FILE 1
  223399. // Now include the actual code files..
  223400. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223401. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223402. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223403. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223404. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223405. actually calling into a similarly named class in the other module's address space.
  223406. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223407. have unique names, and should avoid this problem.
  223408. If you're using the amalgamated version, you can just set this macro to something unique before
  223409. you include juce_amalgamated.cpp.
  223410. */
  223411. #ifndef JUCE_ObjCExtraSuffix
  223412. #define JUCE_ObjCExtraSuffix 3
  223413. #endif
  223414. #ifndef DOXYGEN
  223415. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223416. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223417. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223418. #endif
  223419. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223420. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223421. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223422. // compiled on its own).
  223423. #if JUCE_INCLUDED_FILE
  223424. namespace
  223425. {
  223426. const String nsStringToJuce (NSString* s)
  223427. {
  223428. return String::fromUTF8 ([s UTF8String]);
  223429. }
  223430. NSString* juceStringToNS (const String& s)
  223431. {
  223432. return [NSString stringWithUTF8String: s.toUTF8()];
  223433. }
  223434. const String convertUTF16ToString (const UniChar* utf16)
  223435. {
  223436. String s;
  223437. while (*utf16 != 0)
  223438. s += (juce_wchar) *utf16++;
  223439. return s;
  223440. }
  223441. }
  223442. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223443. {
  223444. String result;
  223445. if (cfString != 0)
  223446. {
  223447. CFRange range = { 0, CFStringGetLength (cfString) };
  223448. HeapBlock <UniChar> u (range.length + 1);
  223449. CFStringGetCharacters (cfString, range, u);
  223450. u[range.length] = 0;
  223451. result = convertUTF16ToString (u);
  223452. }
  223453. return result;
  223454. }
  223455. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223456. {
  223457. const int len = s.length();
  223458. HeapBlock <UniChar> temp (len + 2);
  223459. for (int i = 0; i <= len; ++i)
  223460. temp[i] = s[i];
  223461. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223462. }
  223463. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223464. {
  223465. #if JUCE_IOS
  223466. const ScopedAutoReleasePool pool;
  223467. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223468. #else
  223469. UnicodeMapping map;
  223470. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223471. kUnicodeNoSubset,
  223472. kTextEncodingDefaultFormat);
  223473. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223474. kUnicodeCanonicalCompVariant,
  223475. kTextEncodingDefaultFormat);
  223476. map.mappingVersion = kUnicodeUseLatestMapping;
  223477. UnicodeToTextInfo conversionInfo = 0;
  223478. String result;
  223479. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223480. {
  223481. const int len = s.length();
  223482. HeapBlock <UniChar> tempIn, tempOut;
  223483. tempIn.calloc (len + 2);
  223484. tempOut.calloc (len + 2);
  223485. for (int i = 0; i <= len; ++i)
  223486. tempIn[i] = s[i];
  223487. ByteCount bytesRead = 0;
  223488. ByteCount outputBufferSize = 0;
  223489. if (ConvertFromUnicodeToText (conversionInfo,
  223490. len * sizeof (UniChar), tempIn,
  223491. kUnicodeDefaultDirectionMask,
  223492. 0, 0, 0, 0,
  223493. len * sizeof (UniChar), &bytesRead,
  223494. &outputBufferSize, tempOut) == noErr)
  223495. {
  223496. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223497. juce_wchar* t = result;
  223498. unsigned int i;
  223499. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  223500. t[i] = (juce_wchar) tempOut[i];
  223501. t[i] = 0;
  223502. }
  223503. DisposeUnicodeToTextInfo (&conversionInfo);
  223504. }
  223505. return result;
  223506. #endif
  223507. }
  223508. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223509. void SystemClipboard::copyTextToClipboard (const String& text)
  223510. {
  223511. #if JUCE_IOS
  223512. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223513. forPasteboardType: @"public.text"];
  223514. #else
  223515. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223516. owner: nil];
  223517. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223518. forType: NSStringPboardType];
  223519. #endif
  223520. }
  223521. const String SystemClipboard::getTextFromClipboard()
  223522. {
  223523. #if JUCE_IOS
  223524. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223525. #else
  223526. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223527. #endif
  223528. return text == 0 ? String::empty
  223529. : nsStringToJuce (text);
  223530. }
  223531. #endif
  223532. #endif
  223533. /*** End of inlined file: juce_mac_Strings.mm ***/
  223534. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223535. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223536. // compiled on its own).
  223537. #if JUCE_INCLUDED_FILE
  223538. namespace SystemStatsHelpers
  223539. {
  223540. static int64 highResTimerFrequency = 0;
  223541. static double highResTimerToMillisecRatio = 0;
  223542. #if JUCE_INTEL
  223543. static void juce_getCpuVendor (char* const v) throw()
  223544. {
  223545. int vendor[4];
  223546. zerostruct (vendor);
  223547. int dummy = 0;
  223548. asm ("mov %%ebx, %%esi \n\t"
  223549. "cpuid \n\t"
  223550. "xchg %%esi, %%ebx"
  223551. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  223552. memcpy (v, vendor, 16);
  223553. }
  223554. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  223555. {
  223556. unsigned int cpu = 0;
  223557. unsigned int ext = 0;
  223558. unsigned int family = 0;
  223559. unsigned int dummy = 0;
  223560. asm ("mov %%ebx, %%esi \n\t"
  223561. "cpuid \n\t"
  223562. "xchg %%esi, %%ebx"
  223563. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  223564. familyModel = family;
  223565. extFeatures = ext;
  223566. return cpu;
  223567. }
  223568. #endif
  223569. }
  223570. void SystemStats::initialiseStats()
  223571. {
  223572. using namespace SystemStatsHelpers;
  223573. static bool initialised = false;
  223574. if (! initialised)
  223575. {
  223576. initialised = true;
  223577. #if JUCE_MAC
  223578. [NSApplication sharedApplication];
  223579. #endif
  223580. #if JUCE_INTEL
  223581. unsigned int familyModel, extFeatures;
  223582. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  223583. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223584. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223585. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223586. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223587. #else
  223588. cpuFlags.hasMMX = false;
  223589. cpuFlags.hasSSE = false;
  223590. cpuFlags.hasSSE2 = false;
  223591. cpuFlags.has3DNow = false;
  223592. #endif
  223593. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223594. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223595. #else
  223596. cpuFlags.numCpus = (int) MPProcessors();
  223597. #endif
  223598. mach_timebase_info_data_t timebase;
  223599. (void) mach_timebase_info (&timebase);
  223600. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223601. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223602. String s (SystemStats::getJUCEVersion());
  223603. rlimit lim;
  223604. getrlimit (RLIMIT_NOFILE, &lim);
  223605. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223606. setrlimit (RLIMIT_NOFILE, &lim);
  223607. }
  223608. }
  223609. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223610. {
  223611. return MacOSX;
  223612. }
  223613. const String SystemStats::getOperatingSystemName()
  223614. {
  223615. return "Mac OS X";
  223616. }
  223617. #if ! JUCE_IOS
  223618. int PlatformUtilities::getOSXMinorVersionNumber()
  223619. {
  223620. SInt32 versionMinor = 0;
  223621. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223622. (void) err;
  223623. jassert (err == noErr);
  223624. return (int) versionMinor;
  223625. }
  223626. #endif
  223627. bool SystemStats::isOperatingSystem64Bit()
  223628. {
  223629. #if JUCE_IOS
  223630. return false;
  223631. #elif JUCE_64BIT
  223632. return true;
  223633. #else
  223634. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223635. #endif
  223636. }
  223637. int SystemStats::getMemorySizeInMegabytes()
  223638. {
  223639. uint64 mem = 0;
  223640. size_t memSize = sizeof (mem);
  223641. int mib[] = { CTL_HW, HW_MEMSIZE };
  223642. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223643. return (int) (mem / (1024 * 1024));
  223644. }
  223645. const String SystemStats::getCpuVendor()
  223646. {
  223647. #if JUCE_INTEL
  223648. char v [16];
  223649. SystemStatsHelpers::juce_getCpuVendor (v);
  223650. return String (v, 16);
  223651. #else
  223652. return String::empty;
  223653. #endif
  223654. }
  223655. int SystemStats::getCpuSpeedInMegaherz()
  223656. {
  223657. uint64 speedHz = 0;
  223658. size_t speedSize = sizeof (speedHz);
  223659. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223660. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223661. #if JUCE_BIG_ENDIAN
  223662. if (speedSize == 4)
  223663. speedHz >>= 32;
  223664. #endif
  223665. return (int) (speedHz / 1000000);
  223666. }
  223667. const String SystemStats::getLogonName()
  223668. {
  223669. return nsStringToJuce (NSUserName());
  223670. }
  223671. const String SystemStats::getFullUserName()
  223672. {
  223673. return nsStringToJuce (NSFullUserName());
  223674. }
  223675. uint32 juce_millisecondsSinceStartup() throw()
  223676. {
  223677. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223678. }
  223679. double Time::getMillisecondCounterHiRes() throw()
  223680. {
  223681. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223682. }
  223683. int64 Time::getHighResolutionTicks() throw()
  223684. {
  223685. return (int64) mach_absolute_time();
  223686. }
  223687. int64 Time::getHighResolutionTicksPerSecond() throw()
  223688. {
  223689. return SystemStatsHelpers::highResTimerFrequency;
  223690. }
  223691. bool Time::setSystemTimeToThisTime() const
  223692. {
  223693. jassertfalse;
  223694. return false;
  223695. }
  223696. int SystemStats::getPageSize()
  223697. {
  223698. return (int) NSPageSize();
  223699. }
  223700. void PlatformUtilities::fpuReset()
  223701. {
  223702. }
  223703. #endif
  223704. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223705. /*** Start of inlined file: juce_mac_Network.mm ***/
  223706. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223707. // compiled on its own).
  223708. #if JUCE_INCLUDED_FILE
  223709. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  223710. {
  223711. ifaddrs* addrs = 0;
  223712. if (getifaddrs (&addrs) == 0)
  223713. {
  223714. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  223715. {
  223716. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223717. if (sto->ss_family == AF_LINK)
  223718. {
  223719. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223720. #ifndef IFT_ETHER
  223721. #define IFT_ETHER 6
  223722. #endif
  223723. if (sadd->sdl_type == IFT_ETHER)
  223724. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  223725. }
  223726. }
  223727. freeifaddrs (addrs);
  223728. }
  223729. }
  223730. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223731. const String& emailSubject,
  223732. const String& bodyText,
  223733. const StringArray& filesToAttach)
  223734. {
  223735. #if JUCE_IOS
  223736. //xxx probably need to use MFMailComposeViewController
  223737. jassertfalse;
  223738. return false;
  223739. #else
  223740. const ScopedAutoReleasePool pool;
  223741. String script;
  223742. script << "tell application \"Mail\"\r\n"
  223743. "set newMessage to make new outgoing message with properties {subject:\""
  223744. << emailSubject.replace ("\"", "\\\"")
  223745. << "\", content:\""
  223746. << bodyText.replace ("\"", "\\\"")
  223747. << "\" & return & return}\r\n"
  223748. "tell newMessage\r\n"
  223749. "set visible to true\r\n"
  223750. "set sender to \"sdfsdfsdfewf\"\r\n"
  223751. "make new to recipient at end of to recipients with properties {address:\""
  223752. << targetEmailAddress
  223753. << "\"}\r\n";
  223754. for (int i = 0; i < filesToAttach.size(); ++i)
  223755. {
  223756. script << "tell content\r\n"
  223757. "make new attachment with properties {file name:\""
  223758. << filesToAttach[i].replace ("\"", "\\\"")
  223759. << "\"} at after the last paragraph\r\n"
  223760. "end tell\r\n";
  223761. }
  223762. script << "end tell\r\n"
  223763. "end tell\r\n";
  223764. NSAppleScript* s = [[NSAppleScript alloc]
  223765. initWithSource: juceStringToNS (script)];
  223766. NSDictionary* error = 0;
  223767. const bool ok = [s executeAndReturnError: &error] != nil;
  223768. [s release];
  223769. return ok;
  223770. #endif
  223771. }
  223772. END_JUCE_NAMESPACE
  223773. using namespace JUCE_NAMESPACE;
  223774. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223775. @interface JuceURLConnection : NSObject
  223776. {
  223777. @public
  223778. NSURLRequest* request;
  223779. NSURLConnection* connection;
  223780. NSMutableData* data;
  223781. Thread* runLoopThread;
  223782. bool initialised, hasFailed, hasFinished;
  223783. int position;
  223784. int64 contentLength;
  223785. NSDictionary* headers;
  223786. NSLock* dataLock;
  223787. }
  223788. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223789. - (void) dealloc;
  223790. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223791. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223792. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223793. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223794. - (BOOL) isOpen;
  223795. - (int) read: (char*) dest numBytes: (int) num;
  223796. - (int) readPosition;
  223797. - (void) stop;
  223798. - (void) createConnection;
  223799. @end
  223800. class JuceURLConnectionMessageThread : public Thread
  223801. {
  223802. public:
  223803. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223804. : Thread ("http connection"),
  223805. owner (owner_)
  223806. {
  223807. }
  223808. ~JuceURLConnectionMessageThread()
  223809. {
  223810. stopThread (10000);
  223811. }
  223812. void run()
  223813. {
  223814. [owner createConnection];
  223815. while (! threadShouldExit())
  223816. {
  223817. const ScopedAutoReleasePool pool;
  223818. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223819. }
  223820. }
  223821. private:
  223822. JuceURLConnection* owner;
  223823. };
  223824. @implementation JuceURLConnection
  223825. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223826. withCallback: (URL::OpenStreamProgressCallback*) callback
  223827. withContext: (void*) context;
  223828. {
  223829. [super init];
  223830. request = req;
  223831. [request retain];
  223832. data = [[NSMutableData data] retain];
  223833. dataLock = [[NSLock alloc] init];
  223834. connection = 0;
  223835. initialised = false;
  223836. hasFailed = false;
  223837. hasFinished = false;
  223838. contentLength = -1;
  223839. headers = 0;
  223840. runLoopThread = new JuceURLConnectionMessageThread (self);
  223841. runLoopThread->startThread();
  223842. while (runLoopThread->isThreadRunning() && ! initialised)
  223843. {
  223844. if (callback != 0)
  223845. callback (context, -1, (int) [[request HTTPBody] length]);
  223846. Thread::sleep (1);
  223847. }
  223848. return self;
  223849. }
  223850. - (void) dealloc
  223851. {
  223852. [self stop];
  223853. deleteAndZero (runLoopThread);
  223854. [connection release];
  223855. [data release];
  223856. [dataLock release];
  223857. [request release];
  223858. [headers release];
  223859. [super dealloc];
  223860. }
  223861. - (void) createConnection
  223862. {
  223863. NSUInteger oldRetainCount = [self retainCount];
  223864. connection = [[NSURLConnection alloc] initWithRequest: request
  223865. delegate: self];
  223866. if (oldRetainCount == [self retainCount])
  223867. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223868. if (connection == nil)
  223869. runLoopThread->signalThreadShouldExit();
  223870. }
  223871. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223872. {
  223873. (void) conn;
  223874. [dataLock lock];
  223875. [data setLength: 0];
  223876. [dataLock unlock];
  223877. initialised = true;
  223878. contentLength = [response expectedContentLength];
  223879. [headers release];
  223880. headers = 0;
  223881. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223882. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223883. }
  223884. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223885. {
  223886. (void) conn;
  223887. DBG (nsStringToJuce ([error description]));
  223888. hasFailed = true;
  223889. initialised = true;
  223890. if (runLoopThread != 0)
  223891. runLoopThread->signalThreadShouldExit();
  223892. }
  223893. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223894. {
  223895. (void) conn;
  223896. [dataLock lock];
  223897. [data appendData: newData];
  223898. [dataLock unlock];
  223899. initialised = true;
  223900. }
  223901. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223902. {
  223903. (void) conn;
  223904. hasFinished = true;
  223905. initialised = true;
  223906. if (runLoopThread != 0)
  223907. runLoopThread->signalThreadShouldExit();
  223908. }
  223909. - (BOOL) isOpen
  223910. {
  223911. return connection != 0 && ! hasFailed;
  223912. }
  223913. - (int) readPosition
  223914. {
  223915. return position;
  223916. }
  223917. - (int) read: (char*) dest numBytes: (int) numNeeded
  223918. {
  223919. int numDone = 0;
  223920. while (numNeeded > 0)
  223921. {
  223922. int available = jmin (numNeeded, (int) [data length]);
  223923. if (available > 0)
  223924. {
  223925. [dataLock lock];
  223926. [data getBytes: dest length: available];
  223927. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223928. [dataLock unlock];
  223929. numDone += available;
  223930. numNeeded -= available;
  223931. dest += available;
  223932. }
  223933. else
  223934. {
  223935. if (hasFailed || hasFinished)
  223936. break;
  223937. Thread::sleep (1);
  223938. }
  223939. }
  223940. position += numDone;
  223941. return numDone;
  223942. }
  223943. - (void) stop
  223944. {
  223945. [connection cancel];
  223946. if (runLoopThread != 0)
  223947. runLoopThread->stopThread (10000);
  223948. }
  223949. @end
  223950. BEGIN_JUCE_NAMESPACE
  223951. class WebInputStream : public InputStream
  223952. {
  223953. public:
  223954. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  223955. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223956. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  223957. : connection (nil),
  223958. address (address_), headers (headers_), postData (postData_), position (0),
  223959. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  223960. {
  223961. JUCE_AUTORELEASEPOOL
  223962. connection = createConnection (progressCallback, progressCallbackContext);
  223963. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  223964. {
  223965. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  223966. NSString* key;
  223967. while ((key = [enumerator nextObject]) != nil)
  223968. responseHeaders->set (nsStringToJuce (key),
  223969. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  223970. }
  223971. }
  223972. ~WebInputStream()
  223973. {
  223974. close();
  223975. }
  223976. bool isError() const { return connection == nil; }
  223977. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  223978. bool isExhausted() { return finished; }
  223979. int64 getPosition() { return position; }
  223980. int read (void* buffer, int bytesToRead)
  223981. {
  223982. if (finished || isError())
  223983. {
  223984. return 0;
  223985. }
  223986. else
  223987. {
  223988. JUCE_AUTORELEASEPOOL
  223989. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  223990. position += bytesRead;
  223991. if (bytesRead == 0)
  223992. finished = true;
  223993. return bytesRead;
  223994. }
  223995. }
  223996. bool setPosition (int64 wantedPos)
  223997. {
  223998. if (wantedPos != position)
  223999. {
  224000. finished = false;
  224001. if (wantedPos < position)
  224002. {
  224003. close();
  224004. position = 0;
  224005. connection = createConnection (0, 0);
  224006. }
  224007. skipNextBytes (wantedPos - position);
  224008. }
  224009. return true;
  224010. }
  224011. private:
  224012. JuceURLConnection* connection;
  224013. String address, headers;
  224014. MemoryBlock postData;
  224015. int64 position;
  224016. bool finished;
  224017. const bool isPost;
  224018. const int timeOutMs;
  224019. void close()
  224020. {
  224021. [connection stop];
  224022. [connection release];
  224023. connection = nil;
  224024. }
  224025. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  224026. void* progressCallbackContext)
  224027. {
  224028. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  224029. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224030. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224031. if (req == nil)
  224032. return 0;
  224033. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224034. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224035. StringArray headerLines;
  224036. headerLines.addLines (headers);
  224037. headerLines.removeEmptyStrings (true);
  224038. for (int i = 0; i < headerLines.size(); ++i)
  224039. {
  224040. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224041. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224042. if (key.isNotEmpty() && value.isNotEmpty())
  224043. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224044. }
  224045. if (isPost && postData.getSize() > 0)
  224046. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224047. length: postData.getSize()]];
  224048. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224049. withCallback: progressCallback
  224050. withContext: progressCallbackContext];
  224051. if ([s isOpen])
  224052. return s;
  224053. [s release];
  224054. return 0;
  224055. }
  224056. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  224057. };
  224058. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  224059. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224060. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  224061. {
  224062. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  224063. progressCallback, progressCallbackContext,
  224064. headers, timeOutMs, responseHeaders));
  224065. return wi->isError() ? 0 : wi.release();
  224066. }
  224067. #endif
  224068. /*** End of inlined file: juce_mac_Network.mm ***/
  224069. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224070. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224071. // compiled on its own).
  224072. #if JUCE_INCLUDED_FILE
  224073. struct NamedPipeInternal
  224074. {
  224075. String pipeInName, pipeOutName;
  224076. int pipeIn, pipeOut;
  224077. bool volatile createdPipe, blocked, stopReadOperation;
  224078. static void signalHandler (int) {}
  224079. };
  224080. void NamedPipe::cancelPendingReads()
  224081. {
  224082. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224083. {
  224084. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224085. intern->stopReadOperation = true;
  224086. char buffer [1] = { 0 };
  224087. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224088. (void) bytesWritten;
  224089. int timeout = 2000;
  224090. while (intern->blocked && --timeout >= 0)
  224091. Thread::sleep (2);
  224092. intern->stopReadOperation = false;
  224093. }
  224094. }
  224095. void NamedPipe::close()
  224096. {
  224097. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224098. if (intern != 0)
  224099. {
  224100. internal = 0;
  224101. if (intern->pipeIn != -1)
  224102. ::close (intern->pipeIn);
  224103. if (intern->pipeOut != -1)
  224104. ::close (intern->pipeOut);
  224105. if (intern->createdPipe)
  224106. {
  224107. unlink (intern->pipeInName.toUTF8());
  224108. unlink (intern->pipeOutName.toUTF8());
  224109. }
  224110. delete intern;
  224111. }
  224112. }
  224113. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224114. {
  224115. close();
  224116. NamedPipeInternal* const intern = new NamedPipeInternal();
  224117. internal = intern;
  224118. intern->createdPipe = createPipe;
  224119. intern->blocked = false;
  224120. intern->stopReadOperation = false;
  224121. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224122. siginterrupt (SIGPIPE, 1);
  224123. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224124. intern->pipeInName = pipePath + "_in";
  224125. intern->pipeOutName = pipePath + "_out";
  224126. intern->pipeIn = -1;
  224127. intern->pipeOut = -1;
  224128. if (createPipe)
  224129. {
  224130. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224131. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224132. {
  224133. delete intern;
  224134. internal = 0;
  224135. return false;
  224136. }
  224137. }
  224138. return true;
  224139. }
  224140. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224141. {
  224142. int bytesRead = -1;
  224143. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224144. if (intern != 0)
  224145. {
  224146. intern->blocked = true;
  224147. if (intern->pipeIn == -1)
  224148. {
  224149. if (intern->createdPipe)
  224150. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224151. else
  224152. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224153. if (intern->pipeIn == -1)
  224154. {
  224155. intern->blocked = false;
  224156. return -1;
  224157. }
  224158. }
  224159. bytesRead = 0;
  224160. char* p = static_cast<char*> (destBuffer);
  224161. while (bytesRead < maxBytesToRead)
  224162. {
  224163. const int bytesThisTime = maxBytesToRead - bytesRead;
  224164. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224165. if (numRead <= 0 || intern->stopReadOperation)
  224166. {
  224167. bytesRead = -1;
  224168. break;
  224169. }
  224170. bytesRead += numRead;
  224171. p += bytesRead;
  224172. }
  224173. intern->blocked = false;
  224174. }
  224175. return bytesRead;
  224176. }
  224177. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224178. {
  224179. int bytesWritten = -1;
  224180. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224181. if (intern != 0)
  224182. {
  224183. if (intern->pipeOut == -1)
  224184. {
  224185. if (intern->createdPipe)
  224186. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224187. else
  224188. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224189. if (intern->pipeOut == -1)
  224190. {
  224191. return -1;
  224192. }
  224193. }
  224194. const char* p = static_cast<const char*> (sourceBuffer);
  224195. bytesWritten = 0;
  224196. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224197. while (bytesWritten < numBytesToWrite
  224198. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224199. {
  224200. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224201. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224202. if (numWritten <= 0)
  224203. {
  224204. bytesWritten = -1;
  224205. break;
  224206. }
  224207. bytesWritten += numWritten;
  224208. p += bytesWritten;
  224209. }
  224210. }
  224211. return bytesWritten;
  224212. }
  224213. #endif
  224214. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224215. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224216. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224217. // compiled on its own).
  224218. #if JUCE_INCLUDED_FILE
  224219. /*
  224220. Note that a lot of methods that you'd expect to find in this file actually
  224221. live in juce_posix_SharedCode.h!
  224222. */
  224223. bool Process::isForegroundProcess()
  224224. {
  224225. #if JUCE_MAC
  224226. return [NSApp isActive];
  224227. #else
  224228. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224229. #endif
  224230. }
  224231. void Process::raisePrivilege()
  224232. {
  224233. jassertfalse;
  224234. }
  224235. void Process::lowerPrivilege()
  224236. {
  224237. jassertfalse;
  224238. }
  224239. void Process::terminate()
  224240. {
  224241. exit (0);
  224242. }
  224243. void Process::setPriority (ProcessPriority)
  224244. {
  224245. // xxx
  224246. }
  224247. #endif
  224248. /*** End of inlined file: juce_mac_Threads.mm ***/
  224249. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224250. /*
  224251. This file contains posix routines that are common to both the Linux and Mac builds.
  224252. It gets included directly in the cpp files for these platforms.
  224253. */
  224254. CriticalSection::CriticalSection() throw()
  224255. {
  224256. pthread_mutexattr_t atts;
  224257. pthread_mutexattr_init (&atts);
  224258. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224259. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224260. pthread_mutex_init (&internal, &atts);
  224261. }
  224262. CriticalSection::~CriticalSection() throw()
  224263. {
  224264. pthread_mutex_destroy (&internal);
  224265. }
  224266. void CriticalSection::enter() const throw()
  224267. {
  224268. pthread_mutex_lock (&internal);
  224269. }
  224270. bool CriticalSection::tryEnter() const throw()
  224271. {
  224272. return pthread_mutex_trylock (&internal) == 0;
  224273. }
  224274. void CriticalSection::exit() const throw()
  224275. {
  224276. pthread_mutex_unlock (&internal);
  224277. }
  224278. class WaitableEventImpl
  224279. {
  224280. public:
  224281. WaitableEventImpl (const bool manualReset_)
  224282. : triggered (false),
  224283. manualReset (manualReset_)
  224284. {
  224285. pthread_cond_init (&condition, 0);
  224286. pthread_mutexattr_t atts;
  224287. pthread_mutexattr_init (&atts);
  224288. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224289. pthread_mutex_init (&mutex, &atts);
  224290. }
  224291. ~WaitableEventImpl()
  224292. {
  224293. pthread_cond_destroy (&condition);
  224294. pthread_mutex_destroy (&mutex);
  224295. }
  224296. bool wait (const int timeOutMillisecs) throw()
  224297. {
  224298. pthread_mutex_lock (&mutex);
  224299. if (! triggered)
  224300. {
  224301. if (timeOutMillisecs < 0)
  224302. {
  224303. do
  224304. {
  224305. pthread_cond_wait (&condition, &mutex);
  224306. }
  224307. while (! triggered);
  224308. }
  224309. else
  224310. {
  224311. struct timeval now;
  224312. gettimeofday (&now, 0);
  224313. struct timespec time;
  224314. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224315. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224316. if (time.tv_nsec >= 1000000000)
  224317. {
  224318. time.tv_nsec -= 1000000000;
  224319. time.tv_sec++;
  224320. }
  224321. do
  224322. {
  224323. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224324. {
  224325. pthread_mutex_unlock (&mutex);
  224326. return false;
  224327. }
  224328. }
  224329. while (! triggered);
  224330. }
  224331. }
  224332. if (! manualReset)
  224333. triggered = false;
  224334. pthread_mutex_unlock (&mutex);
  224335. return true;
  224336. }
  224337. void signal() throw()
  224338. {
  224339. pthread_mutex_lock (&mutex);
  224340. triggered = true;
  224341. pthread_cond_broadcast (&condition);
  224342. pthread_mutex_unlock (&mutex);
  224343. }
  224344. void reset() throw()
  224345. {
  224346. pthread_mutex_lock (&mutex);
  224347. triggered = false;
  224348. pthread_mutex_unlock (&mutex);
  224349. }
  224350. private:
  224351. pthread_cond_t condition;
  224352. pthread_mutex_t mutex;
  224353. bool triggered;
  224354. const bool manualReset;
  224355. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224356. };
  224357. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224358. : internal (new WaitableEventImpl (manualReset))
  224359. {
  224360. }
  224361. WaitableEvent::~WaitableEvent() throw()
  224362. {
  224363. delete static_cast <WaitableEventImpl*> (internal);
  224364. }
  224365. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224366. {
  224367. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224368. }
  224369. void WaitableEvent::signal() const throw()
  224370. {
  224371. static_cast <WaitableEventImpl*> (internal)->signal();
  224372. }
  224373. void WaitableEvent::reset() const throw()
  224374. {
  224375. static_cast <WaitableEventImpl*> (internal)->reset();
  224376. }
  224377. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224378. {
  224379. struct timespec time;
  224380. time.tv_sec = millisecs / 1000;
  224381. time.tv_nsec = (millisecs % 1000) * 1000000;
  224382. nanosleep (&time, 0);
  224383. }
  224384. const juce_wchar File::separator = '/';
  224385. const String File::separatorString ("/");
  224386. const File File::getCurrentWorkingDirectory()
  224387. {
  224388. HeapBlock<char> heapBuffer;
  224389. char localBuffer [1024];
  224390. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224391. int bufferSize = 4096;
  224392. while (cwd == 0 && errno == ERANGE)
  224393. {
  224394. heapBuffer.malloc (bufferSize);
  224395. cwd = getcwd (heapBuffer, bufferSize - 1);
  224396. bufferSize += 1024;
  224397. }
  224398. return File (String::fromUTF8 (cwd));
  224399. }
  224400. bool File::setAsCurrentWorkingDirectory() const
  224401. {
  224402. return chdir (getFullPathName().toUTF8()) == 0;
  224403. }
  224404. namespace
  224405. {
  224406. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224407. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224408. #else
  224409. typedef struct stat juce_statStruct;
  224410. #endif
  224411. bool juce_stat (const String& fileName, juce_statStruct& info)
  224412. {
  224413. return fileName.isNotEmpty()
  224414. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224415. && (stat64 (fileName.toUTF8(), &info) == 0);
  224416. #else
  224417. && (stat (fileName.toUTF8(), &info) == 0);
  224418. #endif
  224419. }
  224420. // if this file doesn't exist, find a parent of it that does..
  224421. bool juce_doStatFS (File f, struct statfs& result)
  224422. {
  224423. for (int i = 5; --i >= 0;)
  224424. {
  224425. if (f.exists())
  224426. break;
  224427. f = f.getParentDirectory();
  224428. }
  224429. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224430. }
  224431. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224432. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224433. {
  224434. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224435. {
  224436. juce_statStruct info;
  224437. const bool statOk = juce_stat (path, info);
  224438. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224439. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224440. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224441. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224442. }
  224443. if (isReadOnly != 0)
  224444. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224445. }
  224446. }
  224447. bool File::isDirectory() const
  224448. {
  224449. juce_statStruct info;
  224450. return fullPath.isEmpty()
  224451. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224452. }
  224453. bool File::exists() const
  224454. {
  224455. juce_statStruct info;
  224456. return fullPath.isNotEmpty()
  224457. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224458. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224459. #else
  224460. && (lstat (fullPath.toUTF8(), &info) == 0);
  224461. #endif
  224462. }
  224463. bool File::existsAsFile() const
  224464. {
  224465. return exists() && ! isDirectory();
  224466. }
  224467. int64 File::getSize() const
  224468. {
  224469. juce_statStruct info;
  224470. return juce_stat (fullPath, info) ? info.st_size : 0;
  224471. }
  224472. bool File::hasWriteAccess() const
  224473. {
  224474. if (exists())
  224475. return access (fullPath.toUTF8(), W_OK) == 0;
  224476. if ((! isDirectory()) && fullPath.containsChar (separator))
  224477. return getParentDirectory().hasWriteAccess();
  224478. return false;
  224479. }
  224480. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224481. {
  224482. juce_statStruct info;
  224483. if (! juce_stat (fullPath, info))
  224484. return false;
  224485. info.st_mode &= 0777; // Just permissions
  224486. if (shouldBeReadOnly)
  224487. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224488. else
  224489. // Give everybody write permission?
  224490. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224491. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224492. }
  224493. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224494. {
  224495. modificationTime = 0;
  224496. accessTime = 0;
  224497. creationTime = 0;
  224498. juce_statStruct info;
  224499. if (juce_stat (fullPath, info))
  224500. {
  224501. modificationTime = (int64) info.st_mtime * 1000;
  224502. accessTime = (int64) info.st_atime * 1000;
  224503. creationTime = (int64) info.st_ctime * 1000;
  224504. }
  224505. }
  224506. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224507. {
  224508. struct utimbuf times;
  224509. times.actime = (time_t) (accessTime / 1000);
  224510. times.modtime = (time_t) (modificationTime / 1000);
  224511. return utime (fullPath.toUTF8(), &times) == 0;
  224512. }
  224513. bool File::deleteFile() const
  224514. {
  224515. if (! exists())
  224516. return true;
  224517. else if (isDirectory())
  224518. return rmdir (fullPath.toUTF8()) == 0;
  224519. else
  224520. return remove (fullPath.toUTF8()) == 0;
  224521. }
  224522. bool File::moveInternal (const File& dest) const
  224523. {
  224524. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224525. return true;
  224526. if (hasWriteAccess() && copyInternal (dest))
  224527. {
  224528. if (deleteFile())
  224529. return true;
  224530. dest.deleteFile();
  224531. }
  224532. return false;
  224533. }
  224534. void File::createDirectoryInternal (const String& fileName) const
  224535. {
  224536. mkdir (fileName.toUTF8(), 0777);
  224537. }
  224538. int64 juce_fileSetPosition (void* handle, int64 pos)
  224539. {
  224540. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224541. return pos;
  224542. return -1;
  224543. }
  224544. void FileInputStream::openHandle()
  224545. {
  224546. totalSize = file.getSize();
  224547. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224548. if (f != -1)
  224549. fileHandle = (void*) f;
  224550. }
  224551. void FileInputStream::closeHandle()
  224552. {
  224553. if (fileHandle != 0)
  224554. {
  224555. close ((int) (pointer_sized_int) fileHandle);
  224556. fileHandle = 0;
  224557. }
  224558. }
  224559. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224560. {
  224561. if (fileHandle != 0)
  224562. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224563. return 0;
  224564. }
  224565. void FileOutputStream::openHandle()
  224566. {
  224567. if (file.exists())
  224568. {
  224569. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224570. if (f != -1)
  224571. {
  224572. currentPosition = lseek (f, 0, SEEK_END);
  224573. if (currentPosition >= 0)
  224574. fileHandle = (void*) f;
  224575. else
  224576. close (f);
  224577. }
  224578. }
  224579. else
  224580. {
  224581. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224582. if (f != -1)
  224583. fileHandle = (void*) f;
  224584. }
  224585. }
  224586. void FileOutputStream::closeHandle()
  224587. {
  224588. if (fileHandle != 0)
  224589. {
  224590. close ((int) (pointer_sized_int) fileHandle);
  224591. fileHandle = 0;
  224592. }
  224593. }
  224594. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224595. {
  224596. if (fileHandle != 0)
  224597. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224598. return 0;
  224599. }
  224600. void FileOutputStream::flushInternal()
  224601. {
  224602. if (fileHandle != 0)
  224603. fsync ((int) (pointer_sized_int) fileHandle);
  224604. }
  224605. const File juce_getExecutableFile()
  224606. {
  224607. Dl_info exeInfo;
  224608. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  224609. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224610. }
  224611. int64 File::getBytesFreeOnVolume() const
  224612. {
  224613. struct statfs buf;
  224614. if (juce_doStatFS (*this, buf))
  224615. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224616. return 0;
  224617. }
  224618. int64 File::getVolumeTotalSize() const
  224619. {
  224620. struct statfs buf;
  224621. if (juce_doStatFS (*this, buf))
  224622. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224623. return 0;
  224624. }
  224625. const String File::getVolumeLabel() const
  224626. {
  224627. #if JUCE_MAC
  224628. struct VolAttrBuf
  224629. {
  224630. u_int32_t length;
  224631. attrreference_t mountPointRef;
  224632. char mountPointSpace [MAXPATHLEN];
  224633. } attrBuf;
  224634. struct attrlist attrList;
  224635. zerostruct (attrList);
  224636. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224637. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224638. File f (*this);
  224639. for (;;)
  224640. {
  224641. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224642. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224643. (int) attrBuf.mountPointRef.attr_length);
  224644. const File parent (f.getParentDirectory());
  224645. if (f == parent)
  224646. break;
  224647. f = parent;
  224648. }
  224649. #endif
  224650. return String::empty;
  224651. }
  224652. int File::getVolumeSerialNumber() const
  224653. {
  224654. return 0; // xxx
  224655. }
  224656. void juce_runSystemCommand (const String& command)
  224657. {
  224658. int result = system (command.toUTF8());
  224659. (void) result;
  224660. }
  224661. const String juce_getOutputFromCommand (const String& command)
  224662. {
  224663. // slight bodge here, as we just pipe the output into a temp file and read it...
  224664. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224665. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224666. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224667. String result (tempFile.loadFileAsString());
  224668. tempFile.deleteFile();
  224669. return result;
  224670. }
  224671. class InterProcessLock::Pimpl
  224672. {
  224673. public:
  224674. Pimpl (const String& name, const int timeOutMillisecs)
  224675. : handle (0), refCount (1)
  224676. {
  224677. #if JUCE_MAC
  224678. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224679. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224680. #else
  224681. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224682. #endif
  224683. temp.create();
  224684. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224685. if (handle != 0)
  224686. {
  224687. struct flock fl;
  224688. zerostruct (fl);
  224689. fl.l_whence = SEEK_SET;
  224690. fl.l_type = F_WRLCK;
  224691. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224692. for (;;)
  224693. {
  224694. const int result = fcntl (handle, F_SETLK, &fl);
  224695. if (result >= 0)
  224696. return;
  224697. if (errno != EINTR)
  224698. {
  224699. if (timeOutMillisecs == 0
  224700. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224701. break;
  224702. Thread::sleep (10);
  224703. }
  224704. }
  224705. }
  224706. closeFile();
  224707. }
  224708. ~Pimpl()
  224709. {
  224710. closeFile();
  224711. }
  224712. void closeFile()
  224713. {
  224714. if (handle != 0)
  224715. {
  224716. struct flock fl;
  224717. zerostruct (fl);
  224718. fl.l_whence = SEEK_SET;
  224719. fl.l_type = F_UNLCK;
  224720. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224721. {}
  224722. close (handle);
  224723. handle = 0;
  224724. }
  224725. }
  224726. int handle, refCount;
  224727. };
  224728. InterProcessLock::InterProcessLock (const String& name_)
  224729. : name (name_)
  224730. {
  224731. }
  224732. InterProcessLock::~InterProcessLock()
  224733. {
  224734. }
  224735. bool InterProcessLock::enter (const int timeOutMillisecs)
  224736. {
  224737. const ScopedLock sl (lock);
  224738. if (pimpl == 0)
  224739. {
  224740. pimpl = new Pimpl (name, timeOutMillisecs);
  224741. if (pimpl->handle == 0)
  224742. pimpl = 0;
  224743. }
  224744. else
  224745. {
  224746. pimpl->refCount++;
  224747. }
  224748. return pimpl != 0;
  224749. }
  224750. void InterProcessLock::exit()
  224751. {
  224752. const ScopedLock sl (lock);
  224753. // Trying to release the lock too many times!
  224754. jassert (pimpl != 0);
  224755. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224756. pimpl = 0;
  224757. }
  224758. void JUCE_API juce_threadEntryPoint (void*);
  224759. void* threadEntryProc (void* userData)
  224760. {
  224761. JUCE_AUTORELEASEPOOL
  224762. juce_threadEntryPoint (userData);
  224763. return 0;
  224764. }
  224765. void Thread::launchThread()
  224766. {
  224767. threadHandle_ = 0;
  224768. pthread_t handle = 0;
  224769. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  224770. {
  224771. pthread_detach (handle);
  224772. threadHandle_ = (void*) handle;
  224773. threadId_ = (ThreadID) threadHandle_;
  224774. }
  224775. }
  224776. void Thread::closeThreadHandle()
  224777. {
  224778. threadId_ = 0;
  224779. threadHandle_ = 0;
  224780. }
  224781. void Thread::killThread()
  224782. {
  224783. if (threadHandle_ != 0)
  224784. pthread_cancel ((pthread_t) threadHandle_);
  224785. }
  224786. void Thread::setCurrentThreadName (const String& /*name*/)
  224787. {
  224788. }
  224789. bool Thread::setThreadPriority (void* handle, int priority)
  224790. {
  224791. struct sched_param param;
  224792. int policy;
  224793. priority = jlimit (0, 10, priority);
  224794. if (handle == 0)
  224795. handle = (void*) pthread_self();
  224796. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  224797. return false;
  224798. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  224799. const int minPriority = sched_get_priority_min (policy);
  224800. const int maxPriority = sched_get_priority_max (policy);
  224801. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  224802. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  224803. }
  224804. Thread::ThreadID Thread::getCurrentThreadId()
  224805. {
  224806. return (ThreadID) pthread_self();
  224807. }
  224808. void Thread::yield()
  224809. {
  224810. sched_yield();
  224811. }
  224812. /* Remove this macro if you're having problems compiling the cpu affinity
  224813. calls (the API for these has changed about quite a bit in various Linux
  224814. versions, and a lot of distros seem to ship with obsolete versions)
  224815. */
  224816. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  224817. #define SUPPORT_AFFINITIES 1
  224818. #endif
  224819. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  224820. {
  224821. #if SUPPORT_AFFINITIES
  224822. cpu_set_t affinity;
  224823. CPU_ZERO (&affinity);
  224824. for (int i = 0; i < 32; ++i)
  224825. if ((affinityMask & (1 << i)) != 0)
  224826. CPU_SET (i, &affinity);
  224827. /*
  224828. N.B. If this line causes a compile error, then you've probably not got the latest
  224829. version of glibc installed.
  224830. If you don't want to update your copy of glibc and don't care about cpu affinities,
  224831. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  224832. */
  224833. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  224834. sched_yield();
  224835. #else
  224836. /* affinities aren't supported because either the appropriate header files weren't found,
  224837. or the SUPPORT_AFFINITIES macro was turned off
  224838. */
  224839. jassertfalse;
  224840. #endif
  224841. }
  224842. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224843. /*** Start of inlined file: juce_mac_Files.mm ***/
  224844. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224845. // compiled on its own).
  224846. #if JUCE_INCLUDED_FILE
  224847. /*
  224848. Note that a lot of methods that you'd expect to find in this file actually
  224849. live in juce_posix_SharedCode.h!
  224850. */
  224851. bool File::copyInternal (const File& dest) const
  224852. {
  224853. const ScopedAutoReleasePool pool;
  224854. NSFileManager* fm = [NSFileManager defaultManager];
  224855. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224856. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224857. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224858. toPath: juceStringToNS (dest.getFullPathName())
  224859. error: nil];
  224860. #else
  224861. && [fm copyPath: juceStringToNS (fullPath)
  224862. toPath: juceStringToNS (dest.getFullPathName())
  224863. handler: nil];
  224864. #endif
  224865. }
  224866. void File::findFileSystemRoots (Array<File>& destArray)
  224867. {
  224868. destArray.add (File ("/"));
  224869. }
  224870. namespace FileHelpers
  224871. {
  224872. bool isFileOnDriveType (const File& f, const char* const* types)
  224873. {
  224874. struct statfs buf;
  224875. if (juce_doStatFS (f, buf))
  224876. {
  224877. const String type (buf.f_fstypename);
  224878. while (*types != 0)
  224879. if (type.equalsIgnoreCase (*types++))
  224880. return true;
  224881. }
  224882. return false;
  224883. }
  224884. bool isHiddenFile (const String& path)
  224885. {
  224886. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  224887. const ScopedAutoReleasePool pool;
  224888. NSNumber* hidden = nil;
  224889. NSError* err = nil;
  224890. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  224891. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  224892. && [hidden boolValue];
  224893. #else
  224894. #if JUCE_IOS
  224895. return File (path).getFileName().startsWithChar ('.');
  224896. #else
  224897. FSRef ref;
  224898. LSItemInfoRecord info;
  224899. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  224900. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  224901. && (info.flags & kLSItemInfoIsInvisible) != 0;
  224902. #endif
  224903. #endif
  224904. }
  224905. #if JUCE_IOS
  224906. const String getIOSSystemLocation (NSSearchPathDirectory type)
  224907. {
  224908. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  224909. objectAtIndex: 0]);
  224910. }
  224911. #endif
  224912. bool launchExecutable (const String& pathAndArguments)
  224913. {
  224914. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224915. const int cpid = fork();
  224916. if (cpid == 0)
  224917. {
  224918. // Child process
  224919. if (execve (argv[0], (char**) argv, 0) < 0)
  224920. exit (0);
  224921. }
  224922. else
  224923. {
  224924. if (cpid < 0)
  224925. return false;
  224926. }
  224927. return true;
  224928. }
  224929. }
  224930. bool File::isOnCDRomDrive() const
  224931. {
  224932. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224933. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  224934. }
  224935. bool File::isOnHardDisk() const
  224936. {
  224937. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224938. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  224939. }
  224940. bool File::isOnRemovableDrive() const
  224941. {
  224942. #if JUCE_IOS
  224943. return false; // xxx is this possible?
  224944. #else
  224945. const ScopedAutoReleasePool pool;
  224946. BOOL removable = false;
  224947. [[NSWorkspace sharedWorkspace]
  224948. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224949. isRemovable: &removable
  224950. isWritable: nil
  224951. isUnmountable: nil
  224952. description: nil
  224953. type: nil];
  224954. return removable;
  224955. #endif
  224956. }
  224957. bool File::isHidden() const
  224958. {
  224959. return FileHelpers::isHiddenFile (getFullPathName());
  224960. }
  224961. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224962. const File File::getSpecialLocation (const SpecialLocationType type)
  224963. {
  224964. const ScopedAutoReleasePool pool;
  224965. String resultPath;
  224966. switch (type)
  224967. {
  224968. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  224969. #if JUCE_IOS
  224970. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  224971. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  224972. case tempDirectory:
  224973. {
  224974. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  224975. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  224976. tmp.createDirectory();
  224977. return tmp.getFullPathName();
  224978. }
  224979. #else
  224980. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  224981. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  224982. case tempDirectory:
  224983. {
  224984. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224985. tmp.createDirectory();
  224986. return tmp.getFullPathName();
  224987. }
  224988. #endif
  224989. case userMusicDirectory: resultPath = "~/Music"; break;
  224990. case userMoviesDirectory: resultPath = "~/Movies"; break;
  224991. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  224992. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  224993. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  224994. case invokedExecutableFile:
  224995. if (juce_Argv0 != 0)
  224996. return File (String::fromUTF8 (juce_Argv0));
  224997. // deliberate fall-through...
  224998. case currentExecutableFile:
  224999. return juce_getExecutableFile();
  225000. case currentApplicationFile:
  225001. {
  225002. const File exe (juce_getExecutableFile());
  225003. const File parent (exe.getParentDirectory());
  225004. #if JUCE_IOS
  225005. return parent;
  225006. #else
  225007. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225008. ? parent.getParentDirectory().getParentDirectory()
  225009. : exe;
  225010. #endif
  225011. }
  225012. case hostApplicationPath:
  225013. {
  225014. unsigned int size = 8192;
  225015. HeapBlock<char> buffer;
  225016. buffer.calloc (size + 8);
  225017. _NSGetExecutablePath (buffer.getData(), &size);
  225018. return String::fromUTF8 (buffer, size);
  225019. }
  225020. default:
  225021. jassertfalse; // unknown type?
  225022. break;
  225023. }
  225024. if (resultPath.isNotEmpty())
  225025. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225026. return File::nonexistent;
  225027. }
  225028. const String File::getVersion() const
  225029. {
  225030. const ScopedAutoReleasePool pool;
  225031. String result;
  225032. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225033. if (bundle != 0)
  225034. {
  225035. NSDictionary* info = [bundle infoDictionary];
  225036. if (info != 0)
  225037. {
  225038. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225039. if (name != nil)
  225040. result = nsStringToJuce (name);
  225041. }
  225042. }
  225043. return result;
  225044. }
  225045. const File File::getLinkedTarget() const
  225046. {
  225047. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225048. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225049. #else
  225050. // (the cast here avoids a deprecation warning)
  225051. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225052. #endif
  225053. if (dest != nil)
  225054. return File (nsStringToJuce (dest));
  225055. return *this;
  225056. }
  225057. bool File::moveToTrash() const
  225058. {
  225059. if (! exists())
  225060. return true;
  225061. #if JUCE_IOS
  225062. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225063. #else
  225064. const ScopedAutoReleasePool pool;
  225065. NSString* p = juceStringToNS (getFullPathName());
  225066. return [[NSWorkspace sharedWorkspace]
  225067. performFileOperation: NSWorkspaceRecycleOperation
  225068. source: [p stringByDeletingLastPathComponent]
  225069. destination: @""
  225070. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225071. tag: nil ];
  225072. #endif
  225073. }
  225074. class DirectoryIterator::NativeIterator::Pimpl
  225075. {
  225076. public:
  225077. Pimpl (const File& directory, const String& wildCard_)
  225078. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225079. wildCard (wildCard_),
  225080. enumerator (0)
  225081. {
  225082. const ScopedAutoReleasePool pool;
  225083. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225084. wildcardUTF8 = wildCard.toUTF8();
  225085. }
  225086. ~Pimpl()
  225087. {
  225088. [enumerator release];
  225089. }
  225090. bool next (String& filenameFound,
  225091. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225092. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225093. {
  225094. const ScopedAutoReleasePool pool;
  225095. for (;;)
  225096. {
  225097. NSString* file;
  225098. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225099. return false;
  225100. [enumerator skipDescendents];
  225101. filenameFound = nsStringToJuce (file);
  225102. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225103. continue;
  225104. const String path (parentDir + filenameFound);
  225105. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  225106. if (isHidden != 0)
  225107. *isHidden = FileHelpers::isHiddenFile (path);
  225108. return true;
  225109. }
  225110. }
  225111. private:
  225112. String parentDir, wildCard;
  225113. const char* wildcardUTF8;
  225114. NSDirectoryEnumerator* enumerator;
  225115. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  225116. };
  225117. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225118. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225119. {
  225120. }
  225121. DirectoryIterator::NativeIterator::~NativeIterator()
  225122. {
  225123. }
  225124. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225125. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225126. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225127. {
  225128. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225129. }
  225130. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225131. {
  225132. #if JUCE_IOS
  225133. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225134. #else
  225135. const ScopedAutoReleasePool pool;
  225136. if (parameters.isEmpty())
  225137. {
  225138. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225139. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225140. }
  225141. bool ok = false;
  225142. if (PlatformUtilities::isBundle (fileName))
  225143. {
  225144. NSMutableArray* urls = [NSMutableArray array];
  225145. StringArray docs;
  225146. docs.addTokens (parameters, true);
  225147. for (int i = 0; i < docs.size(); ++i)
  225148. [urls addObject: juceStringToNS (docs[i])];
  225149. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225150. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225151. options: 0
  225152. additionalEventParamDescriptor: nil
  225153. launchIdentifiers: nil];
  225154. }
  225155. else if (File (fileName).exists())
  225156. {
  225157. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  225158. }
  225159. return ok;
  225160. #endif
  225161. }
  225162. void File::revealToUser() const
  225163. {
  225164. #if ! JUCE_IOS
  225165. if (exists())
  225166. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225167. else if (getParentDirectory().exists())
  225168. getParentDirectory().revealToUser();
  225169. #endif
  225170. }
  225171. #if ! JUCE_IOS
  225172. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225173. {
  225174. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225175. }
  225176. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225177. {
  225178. char path [2048];
  225179. zerostruct (path);
  225180. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225181. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225182. return String::empty;
  225183. }
  225184. #endif
  225185. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225186. {
  225187. const ScopedAutoReleasePool pool;
  225188. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225189. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225190. #else
  225191. // (the cast here avoids a deprecation warning)
  225192. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225193. #endif
  225194. return [fileDict fileHFSTypeCode];
  225195. }
  225196. bool PlatformUtilities::isBundle (const String& filename)
  225197. {
  225198. #if JUCE_IOS
  225199. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225200. #else
  225201. const ScopedAutoReleasePool pool;
  225202. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225203. #endif
  225204. }
  225205. #endif
  225206. /*** End of inlined file: juce_mac_Files.mm ***/
  225207. #if JUCE_IOS
  225208. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225209. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225210. // compiled on its own).
  225211. #if JUCE_INCLUDED_FILE
  225212. END_JUCE_NAMESPACE
  225213. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225214. {
  225215. }
  225216. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225217. - (void) applicationWillTerminate: (UIApplication*) application;
  225218. @end
  225219. @implementation JuceAppStartupDelegate
  225220. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225221. {
  225222. initialiseJuce_GUI();
  225223. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225224. exit (0);
  225225. }
  225226. - (void) applicationWillTerminate: (UIApplication*) application
  225227. {
  225228. JUCEApplication::appWillTerminateByForce();
  225229. }
  225230. @end
  225231. BEGIN_JUCE_NAMESPACE
  225232. int juce_iOSMain (int argc, const char* argv[])
  225233. {
  225234. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225235. }
  225236. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225237. {
  225238. pool = [[NSAutoreleasePool alloc] init];
  225239. }
  225240. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225241. {
  225242. [((NSAutoreleasePool*) pool) release];
  225243. }
  225244. void PlatformUtilities::beep()
  225245. {
  225246. //xxx
  225247. //AudioServicesPlaySystemSound ();
  225248. }
  225249. void PlatformUtilities::addItemToDock (const File& file)
  225250. {
  225251. }
  225252. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225253. END_JUCE_NAMESPACE
  225254. @interface JuceAlertBoxDelegate : NSObject
  225255. {
  225256. @public
  225257. bool clickedOk;
  225258. }
  225259. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225260. @end
  225261. @implementation JuceAlertBoxDelegate
  225262. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225263. {
  225264. clickedOk = (buttonIndex == 0);
  225265. alertView.hidden = true;
  225266. }
  225267. @end
  225268. BEGIN_JUCE_NAMESPACE
  225269. // (This function is used directly by other bits of code)
  225270. bool juce_iPhoneShowModalAlert (const String& title,
  225271. const String& bodyText,
  225272. NSString* okButtonText,
  225273. NSString* cancelButtonText)
  225274. {
  225275. const ScopedAutoReleasePool pool;
  225276. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225277. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225278. message: juceStringToNS (bodyText)
  225279. delegate: callback
  225280. cancelButtonTitle: okButtonText
  225281. otherButtonTitles: cancelButtonText, nil];
  225282. [alert retain];
  225283. [alert show];
  225284. while (! alert.hidden && alert.superview != nil)
  225285. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225286. const bool result = callback->clickedOk;
  225287. [alert release];
  225288. [callback release];
  225289. return result;
  225290. }
  225291. bool AlertWindow::showNativeDialogBox (const String& title,
  225292. const String& bodyText,
  225293. bool isOkCancel)
  225294. {
  225295. return juce_iPhoneShowModalAlert (title, bodyText,
  225296. @"OK",
  225297. isOkCancel ? @"Cancel" : nil);
  225298. }
  225299. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225300. {
  225301. jassertfalse; // no such thing on the iphone!
  225302. return false;
  225303. }
  225304. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225305. {
  225306. jassertfalse; // no such thing on the iphone!
  225307. return false;
  225308. }
  225309. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225310. {
  225311. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225312. }
  225313. bool Desktop::isScreenSaverEnabled()
  225314. {
  225315. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225316. }
  225317. #endif
  225318. #endif
  225319. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225320. #else
  225321. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225322. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225323. // compiled on its own).
  225324. #if JUCE_INCLUDED_FILE
  225325. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225326. {
  225327. pool = [[NSAutoreleasePool alloc] init];
  225328. }
  225329. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225330. {
  225331. [((NSAutoreleasePool*) pool) release];
  225332. }
  225333. void PlatformUtilities::beep()
  225334. {
  225335. NSBeep();
  225336. }
  225337. void PlatformUtilities::addItemToDock (const File& file)
  225338. {
  225339. // check that it's not already there...
  225340. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225341. .containsIgnoreCase (file.getFullPathName()))
  225342. {
  225343. 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>"
  225344. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225345. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225346. }
  225347. }
  225348. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225349. bool AlertWindow::showNativeDialogBox (const String& title,
  225350. const String& bodyText,
  225351. bool isOkCancel)
  225352. {
  225353. const ScopedAutoReleasePool pool;
  225354. return NSRunAlertPanel (juceStringToNS (title),
  225355. juceStringToNS (bodyText),
  225356. @"Ok",
  225357. isOkCancel ? @"Cancel" : nil,
  225358. nil) == NSAlertDefaultReturn;
  225359. }
  225360. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225361. {
  225362. if (files.size() == 0)
  225363. return false;
  225364. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225365. if (draggingSource == 0)
  225366. {
  225367. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225368. return false;
  225369. }
  225370. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225371. if (sourceComp == 0)
  225372. {
  225373. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225374. return false;
  225375. }
  225376. const ScopedAutoReleasePool pool;
  225377. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225378. if (view == 0)
  225379. return false;
  225380. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225381. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225382. owner: nil];
  225383. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225384. for (int i = 0; i < files.size(); ++i)
  225385. [filesArray addObject: juceStringToNS (files[i])];
  225386. [pboard setPropertyList: filesArray
  225387. forType: NSFilenamesPboardType];
  225388. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225389. fromView: nil];
  225390. dragPosition.x -= 16;
  225391. dragPosition.y -= 16;
  225392. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225393. at: dragPosition
  225394. offset: NSMakeSize (0, 0)
  225395. event: [[view window] currentEvent]
  225396. pasteboard: pboard
  225397. source: view
  225398. slideBack: YES];
  225399. return true;
  225400. }
  225401. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225402. {
  225403. jassertfalse; // not implemented!
  225404. return false;
  225405. }
  225406. bool Desktop::canUseSemiTransparentWindows() throw()
  225407. {
  225408. return true;
  225409. }
  225410. const Point<int> MouseInputSource::getCurrentMousePosition()
  225411. {
  225412. const ScopedAutoReleasePool pool;
  225413. const NSPoint p ([NSEvent mouseLocation]);
  225414. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225415. }
  225416. void Desktop::setMousePosition (const Point<int>& newPosition)
  225417. {
  225418. // this rubbish needs to be done around the warp call, to avoid causing a
  225419. // bizarre glitch..
  225420. CGAssociateMouseAndMouseCursorPosition (false);
  225421. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225422. CGAssociateMouseAndMouseCursorPosition (true);
  225423. }
  225424. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225425. {
  225426. return upright;
  225427. }
  225428. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225429. class ScreenSaverDefeater : public Timer,
  225430. public DeletedAtShutdown
  225431. {
  225432. public:
  225433. ScreenSaverDefeater()
  225434. {
  225435. startTimer (10000);
  225436. timerCallback();
  225437. }
  225438. ~ScreenSaverDefeater() {}
  225439. void timerCallback()
  225440. {
  225441. if (Process::isForegroundProcess())
  225442. UpdateSystemActivity (UsrActivity);
  225443. }
  225444. };
  225445. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225446. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225447. {
  225448. if (isEnabled)
  225449. deleteAndZero (screenSaverDefeater);
  225450. else if (screenSaverDefeater == 0)
  225451. screenSaverDefeater = new ScreenSaverDefeater();
  225452. }
  225453. bool Desktop::isScreenSaverEnabled()
  225454. {
  225455. return screenSaverDefeater == 0;
  225456. }
  225457. #else
  225458. static IOPMAssertionID screenSaverDisablerID = 0;
  225459. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225460. {
  225461. if (isEnabled)
  225462. {
  225463. if (screenSaverDisablerID != 0)
  225464. {
  225465. IOPMAssertionRelease (screenSaverDisablerID);
  225466. screenSaverDisablerID = 0;
  225467. }
  225468. }
  225469. else
  225470. {
  225471. if (screenSaverDisablerID == 0)
  225472. {
  225473. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225474. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225475. CFSTR ("Juce"), &screenSaverDisablerID);
  225476. #else
  225477. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225478. &screenSaverDisablerID);
  225479. #endif
  225480. }
  225481. }
  225482. }
  225483. bool Desktop::isScreenSaverEnabled()
  225484. {
  225485. return screenSaverDisablerID == 0;
  225486. }
  225487. #endif
  225488. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225489. {
  225490. const ScopedAutoReleasePool pool;
  225491. monitorCoords.clear();
  225492. NSArray* screens = [NSScreen screens];
  225493. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225494. for (unsigned int i = 0; i < [screens count]; ++i)
  225495. {
  225496. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225497. NSRect r = clipToWorkArea ? [s visibleFrame]
  225498. : [s frame];
  225499. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225500. monitorCoords.add (convertToRectInt (r));
  225501. }
  225502. jassert (monitorCoords.size() > 0);
  225503. }
  225504. #endif
  225505. #endif
  225506. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225507. #endif
  225508. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225509. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225510. // compiled on its own).
  225511. #if JUCE_INCLUDED_FILE
  225512. void Logger::outputDebugString (const String& text)
  225513. {
  225514. std::cerr << text << std::endl;
  225515. }
  225516. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225517. {
  225518. static char testResult = 0;
  225519. if (testResult == 0)
  225520. {
  225521. struct kinfo_proc info;
  225522. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225523. size_t sz = sizeof (info);
  225524. sysctl (m, 4, &info, &sz, 0, 0);
  225525. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225526. }
  225527. return testResult > 0;
  225528. }
  225529. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225530. {
  225531. return juce_isRunningUnderDebugger();
  225532. }
  225533. #endif
  225534. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225535. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225536. #if JUCE_IOS
  225537. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225538. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225539. // compiled on its own).
  225540. #if JUCE_INCLUDED_FILE
  225541. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225542. #define SUPPORT_10_4_FONTS 1
  225543. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225544. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225545. #define SUPPORT_ONLY_10_4_FONTS 1
  225546. #endif
  225547. END_JUCE_NAMESPACE
  225548. @interface NSFont (PrivateHack)
  225549. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225550. @end
  225551. BEGIN_JUCE_NAMESPACE
  225552. #endif
  225553. class MacTypeface : public Typeface
  225554. {
  225555. public:
  225556. MacTypeface (const Font& font)
  225557. : Typeface (font.getTypefaceName())
  225558. {
  225559. const ScopedAutoReleasePool pool;
  225560. renderingTransform = CGAffineTransformIdentity;
  225561. bool needsItalicTransform = false;
  225562. #if JUCE_IOS
  225563. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225564. if (font.isItalic() || font.isBold())
  225565. {
  225566. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225567. for (NSString* i in familyFonts)
  225568. {
  225569. const String fn (nsStringToJuce (i));
  225570. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225571. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225572. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225573. || afterDash.containsIgnoreCase ("italic")
  225574. || fn.endsWithIgnoreCase ("oblique")
  225575. || fn.endsWithIgnoreCase ("italic");
  225576. if (probablyBold == font.isBold()
  225577. && probablyItalic == font.isItalic())
  225578. {
  225579. fontName = i;
  225580. needsItalicTransform = false;
  225581. break;
  225582. }
  225583. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225584. {
  225585. fontName = i;
  225586. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225587. }
  225588. }
  225589. if (needsItalicTransform)
  225590. renderingTransform.c = 0.15f;
  225591. }
  225592. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225593. const int ascender = abs (CGFontGetAscent (fontRef));
  225594. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225595. ascent = ascender / totalHeight;
  225596. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225597. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225598. #else
  225599. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225600. if (font.isItalic())
  225601. {
  225602. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225603. toHaveTrait: NSItalicFontMask];
  225604. if (newFont == nsFont)
  225605. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225606. nsFont = newFont;
  225607. }
  225608. if (font.isBold())
  225609. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225610. [nsFont retain];
  225611. ascent = std::abs ((float) [nsFont ascender]);
  225612. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225613. ascent /= totalSize;
  225614. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225615. if (needsItalicTransform)
  225616. {
  225617. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225618. renderingTransform.c = 0.15f;
  225619. }
  225620. #if SUPPORT_ONLY_10_4_FONTS
  225621. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225622. if (atsFont == 0)
  225623. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225624. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225625. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225626. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225627. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225628. #else
  225629. #if SUPPORT_10_4_FONTS
  225630. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225631. {
  225632. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225633. if (atsFont == 0)
  225634. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225635. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225636. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225637. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225638. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225639. }
  225640. else
  225641. #endif
  225642. {
  225643. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225644. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225645. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225646. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225647. }
  225648. #endif
  225649. #endif
  225650. }
  225651. ~MacTypeface()
  225652. {
  225653. #if ! JUCE_IOS
  225654. [nsFont release];
  225655. #endif
  225656. if (fontRef != 0)
  225657. CGFontRelease (fontRef);
  225658. }
  225659. float getAscent() const
  225660. {
  225661. return ascent;
  225662. }
  225663. float getDescent() const
  225664. {
  225665. return 1.0f - ascent;
  225666. }
  225667. float getStringWidth (const String& text)
  225668. {
  225669. if (fontRef == 0 || text.isEmpty())
  225670. return 0;
  225671. const int length = text.length();
  225672. HeapBlock <CGGlyph> glyphs;
  225673. createGlyphsForString (text, length, glyphs);
  225674. float x = 0;
  225675. #if SUPPORT_ONLY_10_4_FONTS
  225676. HeapBlock <NSSize> advances (length);
  225677. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225678. for (int i = 0; i < length; ++i)
  225679. x += advances[i].width;
  225680. #else
  225681. #if SUPPORT_10_4_FONTS
  225682. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225683. {
  225684. HeapBlock <NSSize> advances (length);
  225685. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225686. for (int i = 0; i < length; ++i)
  225687. x += advances[i].width;
  225688. }
  225689. else
  225690. #endif
  225691. {
  225692. HeapBlock <int> advances (length);
  225693. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225694. for (int i = 0; i < length; ++i)
  225695. x += advances[i];
  225696. }
  225697. #endif
  225698. return x * unitsToHeightScaleFactor;
  225699. }
  225700. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225701. {
  225702. xOffsets.add (0);
  225703. if (fontRef == 0 || text.isEmpty())
  225704. return;
  225705. const int length = text.length();
  225706. HeapBlock <CGGlyph> glyphs;
  225707. createGlyphsForString (text, length, glyphs);
  225708. #if SUPPORT_ONLY_10_4_FONTS
  225709. HeapBlock <NSSize> advances (length);
  225710. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225711. int x = 0;
  225712. for (int i = 0; i < length; ++i)
  225713. {
  225714. x += advances[i].width;
  225715. xOffsets.add (x * unitsToHeightScaleFactor);
  225716. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225717. }
  225718. #else
  225719. #if SUPPORT_10_4_FONTS
  225720. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225721. {
  225722. HeapBlock <NSSize> advances (length);
  225723. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225724. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225725. float x = 0;
  225726. for (int i = 0; i < length; ++i)
  225727. {
  225728. x += advances[i].width;
  225729. xOffsets.add (x * unitsToHeightScaleFactor);
  225730. resultGlyphs.add (nsGlyphs[i]);
  225731. }
  225732. }
  225733. else
  225734. #endif
  225735. {
  225736. HeapBlock <int> advances (length);
  225737. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225738. {
  225739. int x = 0;
  225740. for (int i = 0; i < length; ++i)
  225741. {
  225742. x += advances [i];
  225743. xOffsets.add (x * unitsToHeightScaleFactor);
  225744. resultGlyphs.add (glyphs[i]);
  225745. }
  225746. }
  225747. }
  225748. #endif
  225749. }
  225750. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225751. {
  225752. #if JUCE_IOS
  225753. return false;
  225754. #else
  225755. if (nsFont == 0)
  225756. return false;
  225757. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225758. jassert (path.isEmpty());
  225759. const ScopedAutoReleasePool pool;
  225760. NSBezierPath* bez = [NSBezierPath bezierPath];
  225761. [bez moveToPoint: NSMakePoint (0, 0)];
  225762. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225763. inFont: nsFont];
  225764. for (int i = 0; i < [bez elementCount]; ++i)
  225765. {
  225766. NSPoint p[3];
  225767. switch ([bez elementAtIndex: i associatedPoints: p])
  225768. {
  225769. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  225770. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  225771. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  225772. (float) p[1].x, (float) -p[1].y,
  225773. (float) p[2].x, (float) -p[2].y); break;
  225774. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  225775. default: jassertfalse; break;
  225776. }
  225777. }
  225778. path.applyTransform (pathTransform);
  225779. return true;
  225780. #endif
  225781. }
  225782. CGFontRef fontRef;
  225783. float fontHeightToCGSizeFactor;
  225784. CGAffineTransform renderingTransform;
  225785. private:
  225786. float ascent, unitsToHeightScaleFactor;
  225787. #if JUCE_IOS
  225788. #else
  225789. NSFont* nsFont;
  225790. AffineTransform pathTransform;
  225791. #endif
  225792. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  225793. {
  225794. #if SUPPORT_10_4_FONTS
  225795. #if ! SUPPORT_ONLY_10_4_FONTS
  225796. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225797. #endif
  225798. {
  225799. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225800. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225801. for (int i = 0; i < length; ++i)
  225802. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  225803. return;
  225804. }
  225805. #endif
  225806. #if ! SUPPORT_ONLY_10_4_FONTS
  225807. if (charToGlyphMapper == 0)
  225808. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225809. glyphs.malloc (length);
  225810. for (int i = 0; i < length; ++i)
  225811. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  225812. #endif
  225813. }
  225814. #if ! SUPPORT_ONLY_10_4_FONTS
  225815. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225816. class CharToGlyphMapper
  225817. {
  225818. public:
  225819. CharToGlyphMapper (CGFontRef fontRef)
  225820. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225821. idRangeOffset (0), glyphIndexes (0)
  225822. {
  225823. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225824. if (cmapTable != 0)
  225825. {
  225826. const int numSubtables = getValue16 (cmapTable, 2);
  225827. for (int i = 0; i < numSubtables; ++i)
  225828. {
  225829. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225830. {
  225831. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225832. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225833. {
  225834. const int length = getValue16 (cmapTable, offset + 2);
  225835. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225836. segCount = segCountX2 / 2;
  225837. const int endCodeOffset = offset + 14;
  225838. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225839. const int idDeltaOffset = startCodeOffset + segCountX2;
  225840. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225841. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225842. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225843. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225844. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225845. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225846. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225847. }
  225848. break;
  225849. }
  225850. }
  225851. CFRelease (cmapTable);
  225852. }
  225853. }
  225854. ~CharToGlyphMapper()
  225855. {
  225856. if (endCode != 0)
  225857. {
  225858. CFRelease (endCode);
  225859. CFRelease (startCode);
  225860. CFRelease (idDelta);
  225861. CFRelease (idRangeOffset);
  225862. CFRelease (glyphIndexes);
  225863. }
  225864. }
  225865. int getGlyphForCharacter (const juce_wchar c) const
  225866. {
  225867. for (int i = 0; i < segCount; ++i)
  225868. {
  225869. if (getValue16 (endCode, i * 2) >= c)
  225870. {
  225871. const int start = getValue16 (startCode, i * 2);
  225872. if (start > c)
  225873. break;
  225874. const int delta = getValue16 (idDelta, i * 2);
  225875. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225876. if (rangeOffset == 0)
  225877. return delta + c;
  225878. else
  225879. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225880. }
  225881. }
  225882. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225883. return jmax (-1, (int) c - 29);
  225884. }
  225885. private:
  225886. int segCount;
  225887. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225888. static uint16 getValue16 (CFDataRef data, const int index)
  225889. {
  225890. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225891. }
  225892. static uint32 getValue32 (CFDataRef data, const int index)
  225893. {
  225894. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225895. }
  225896. };
  225897. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225898. #endif
  225899. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  225900. };
  225901. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225902. {
  225903. return new MacTypeface (font);
  225904. }
  225905. const StringArray Font::findAllTypefaceNames()
  225906. {
  225907. StringArray names;
  225908. const ScopedAutoReleasePool pool;
  225909. #if JUCE_IOS
  225910. NSArray* fonts = [UIFont familyNames];
  225911. #else
  225912. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225913. #endif
  225914. for (unsigned int i = 0; i < [fonts count]; ++i)
  225915. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225916. names.sort (true);
  225917. return names;
  225918. }
  225919. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  225920. {
  225921. #if JUCE_IOS
  225922. defaultSans = "Helvetica";
  225923. defaultSerif = "Times New Roman";
  225924. defaultFixed = "Courier New";
  225925. #else
  225926. defaultSans = "Lucida Grande";
  225927. defaultSerif = "Times New Roman";
  225928. defaultFixed = "Monaco";
  225929. #endif
  225930. defaultFallback = "Arial Unicode MS";
  225931. }
  225932. #endif
  225933. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225934. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225935. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225936. // compiled on its own).
  225937. #if JUCE_INCLUDED_FILE
  225938. class CoreGraphicsImage : public Image::SharedImage
  225939. {
  225940. public:
  225941. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225942. : Image::SharedImage (format_, width_, height_)
  225943. {
  225944. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225945. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225946. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225947. imageData = imageDataAllocated;
  225948. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225949. : CGColorSpaceCreateDeviceRGB();
  225950. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225951. colourSpace, getCGImageFlags (format_));
  225952. CGColorSpaceRelease (colourSpace);
  225953. }
  225954. ~CoreGraphicsImage()
  225955. {
  225956. CGContextRelease (context);
  225957. }
  225958. Image::ImageType getType() const { return Image::NativeImage; }
  225959. LowLevelGraphicsContext* createLowLevelContext();
  225960. SharedImage* clone()
  225961. {
  225962. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225963. memcpy (im->imageData, imageData, lineStride * height);
  225964. return im;
  225965. }
  225966. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  225967. {
  225968. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225969. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225970. {
  225971. return CGBitmapContextCreateImage (nativeImage->context);
  225972. }
  225973. else
  225974. {
  225975. const Image::BitmapData srcData (juceImage, false);
  225976. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225977. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225978. 8, srcData.pixelStride * 8, srcData.lineStride,
  225979. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225980. 0, true, kCGRenderingIntentDefault);
  225981. CGDataProviderRelease (provider);
  225982. return imageRef;
  225983. }
  225984. }
  225985. #if JUCE_MAC
  225986. static NSImage* createNSImage (const Image& image)
  225987. {
  225988. const ScopedAutoReleasePool pool;
  225989. NSImage* im = [[NSImage alloc] init];
  225990. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225991. [im lockFocus];
  225992. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225993. CGImageRef imageRef = createImage (image, false, colourSpace);
  225994. CGColorSpaceRelease (colourSpace);
  225995. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225996. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225997. CGImageRelease (imageRef);
  225998. [im unlockFocus];
  225999. return im;
  226000. }
  226001. #endif
  226002. CGContextRef context;
  226003. HeapBlock<uint8> imageDataAllocated;
  226004. private:
  226005. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226006. {
  226007. #if JUCE_BIG_ENDIAN
  226008. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226009. #else
  226010. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226011. #endif
  226012. }
  226013. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  226014. };
  226015. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226016. {
  226017. #if USE_COREGRAPHICS_RENDERING
  226018. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226019. #else
  226020. return createSoftwareImage (format, width, height, clearImage);
  226021. #endif
  226022. }
  226023. class CoreGraphicsContext : public LowLevelGraphicsContext
  226024. {
  226025. public:
  226026. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226027. : context (context_),
  226028. flipHeight (flipHeight_),
  226029. lastClipRectIsValid (false),
  226030. state (new SavedState()),
  226031. numGradientLookupEntries (0)
  226032. {
  226033. CGContextRetain (context);
  226034. CGContextSaveGState(context);
  226035. CGContextSetShouldSmoothFonts (context, true);
  226036. CGContextSetShouldAntialias (context, true);
  226037. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226038. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226039. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226040. gradientCallbacks.version = 0;
  226041. gradientCallbacks.evaluate = gradientCallback;
  226042. gradientCallbacks.releaseInfo = 0;
  226043. setFont (Font());
  226044. }
  226045. ~CoreGraphicsContext()
  226046. {
  226047. CGContextRestoreGState (context);
  226048. CGContextRelease (context);
  226049. CGColorSpaceRelease (rgbColourSpace);
  226050. CGColorSpaceRelease (greyColourSpace);
  226051. }
  226052. bool isVectorDevice() const { return false; }
  226053. void setOrigin (int x, int y)
  226054. {
  226055. CGContextTranslateCTM (context, x, -y);
  226056. if (lastClipRectIsValid)
  226057. lastClipRect.translate (-x, -y);
  226058. }
  226059. void addTransform (const AffineTransform& transform)
  226060. {
  226061. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  226062. .translated (0, flipHeight)
  226063. .followedBy (transform)
  226064. .translated (0, -flipHeight)
  226065. .scaled (1.0f, -1.0f));
  226066. lastClipRectIsValid = false;
  226067. }
  226068. float getScaleFactor()
  226069. {
  226070. CGAffineTransform t = CGContextGetCTM (context);
  226071. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  226072. }
  226073. bool clipToRectangle (const Rectangle<int>& r)
  226074. {
  226075. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226076. if (lastClipRectIsValid)
  226077. {
  226078. // This is actually incorrect, because the actual clip region may be complex, and
  226079. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226080. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226081. // when calculating the resultant clip bounds, and makes the same mistake!
  226082. lastClipRect = lastClipRect.getIntersection (r);
  226083. return ! lastClipRect.isEmpty();
  226084. }
  226085. return ! isClipEmpty();
  226086. }
  226087. bool clipToRectangleList (const RectangleList& clipRegion)
  226088. {
  226089. if (clipRegion.isEmpty())
  226090. {
  226091. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226092. lastClipRectIsValid = true;
  226093. lastClipRect = Rectangle<int>();
  226094. return false;
  226095. }
  226096. else
  226097. {
  226098. const int numRects = clipRegion.getNumRectangles();
  226099. HeapBlock <CGRect> rects (numRects);
  226100. for (int i = 0; i < numRects; ++i)
  226101. {
  226102. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226103. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226104. }
  226105. CGContextClipToRects (context, rects, numRects);
  226106. lastClipRectIsValid = false;
  226107. return ! isClipEmpty();
  226108. }
  226109. }
  226110. void excludeClipRectangle (const Rectangle<int>& r)
  226111. {
  226112. RectangleList remaining (getClipBounds());
  226113. remaining.subtract (r);
  226114. clipToRectangleList (remaining);
  226115. lastClipRectIsValid = false;
  226116. }
  226117. void clipToPath (const Path& path, const AffineTransform& transform)
  226118. {
  226119. createPath (path, transform);
  226120. CGContextClip (context);
  226121. lastClipRectIsValid = false;
  226122. }
  226123. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226124. {
  226125. if (! transform.isSingularity())
  226126. {
  226127. Image singleChannelImage (sourceImage);
  226128. if (sourceImage.getFormat() != Image::SingleChannel)
  226129. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226130. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226131. flip();
  226132. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226133. applyTransform (t);
  226134. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226135. CGContextClipToMask (context, r, image);
  226136. applyTransform (t.inverted());
  226137. flip();
  226138. CGImageRelease (image);
  226139. lastClipRectIsValid = false;
  226140. }
  226141. }
  226142. bool clipRegionIntersects (const Rectangle<int>& r)
  226143. {
  226144. return getClipBounds().intersects (r);
  226145. }
  226146. const Rectangle<int> getClipBounds() const
  226147. {
  226148. if (! lastClipRectIsValid)
  226149. {
  226150. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226151. lastClipRectIsValid = true;
  226152. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226153. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226154. roundToInt (bounds.size.width),
  226155. roundToInt (bounds.size.height));
  226156. }
  226157. return lastClipRect;
  226158. }
  226159. bool isClipEmpty() const
  226160. {
  226161. return getClipBounds().isEmpty();
  226162. }
  226163. void saveState()
  226164. {
  226165. CGContextSaveGState (context);
  226166. stateStack.add (new SavedState (*state));
  226167. }
  226168. void restoreState()
  226169. {
  226170. CGContextRestoreGState (context);
  226171. SavedState* const top = stateStack.getLast();
  226172. if (top != 0)
  226173. {
  226174. state = top;
  226175. stateStack.removeLast (1, false);
  226176. lastClipRectIsValid = false;
  226177. }
  226178. else
  226179. {
  226180. jassertfalse; // trying to pop with an empty stack!
  226181. }
  226182. }
  226183. void beginTransparencyLayer (float opacity)
  226184. {
  226185. saveState();
  226186. CGContextSetAlpha (context, opacity);
  226187. CGContextBeginTransparencyLayer (context, 0);
  226188. }
  226189. void endTransparencyLayer()
  226190. {
  226191. CGContextEndTransparencyLayer (context);
  226192. restoreState();
  226193. }
  226194. void setFill (const FillType& fillType)
  226195. {
  226196. state->fillType = fillType;
  226197. if (fillType.isColour())
  226198. {
  226199. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226200. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226201. CGContextSetAlpha (context, 1.0f);
  226202. }
  226203. }
  226204. void setOpacity (float newOpacity)
  226205. {
  226206. state->fillType.setOpacity (newOpacity);
  226207. setFill (state->fillType);
  226208. }
  226209. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226210. {
  226211. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226212. ? kCGInterpolationLow
  226213. : kCGInterpolationHigh);
  226214. }
  226215. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226216. {
  226217. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226218. }
  226219. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226220. {
  226221. if (replaceExistingContents)
  226222. {
  226223. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226224. CGContextClearRect (context, cgRect);
  226225. #else
  226226. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226227. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226228. CGContextClearRect (context, cgRect);
  226229. else
  226230. #endif
  226231. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226232. #endif
  226233. fillCGRect (cgRect, false);
  226234. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226235. }
  226236. else
  226237. {
  226238. if (state->fillType.isColour())
  226239. {
  226240. CGContextFillRect (context, cgRect);
  226241. }
  226242. else if (state->fillType.isGradient())
  226243. {
  226244. CGContextSaveGState (context);
  226245. CGContextClipToRect (context, cgRect);
  226246. drawGradient();
  226247. CGContextRestoreGState (context);
  226248. }
  226249. else
  226250. {
  226251. CGContextSaveGState (context);
  226252. CGContextClipToRect (context, cgRect);
  226253. drawImage (state->fillType.image, state->fillType.transform, true);
  226254. CGContextRestoreGState (context);
  226255. }
  226256. }
  226257. }
  226258. void fillPath (const Path& path, const AffineTransform& transform)
  226259. {
  226260. CGContextSaveGState (context);
  226261. if (state->fillType.isColour())
  226262. {
  226263. flip();
  226264. applyTransform (transform);
  226265. createPath (path);
  226266. if (path.isUsingNonZeroWinding())
  226267. CGContextFillPath (context);
  226268. else
  226269. CGContextEOFillPath (context);
  226270. }
  226271. else
  226272. {
  226273. createPath (path, transform);
  226274. if (path.isUsingNonZeroWinding())
  226275. CGContextClip (context);
  226276. else
  226277. CGContextEOClip (context);
  226278. if (state->fillType.isGradient())
  226279. drawGradient();
  226280. else
  226281. drawImage (state->fillType.image, state->fillType.transform, true);
  226282. }
  226283. CGContextRestoreGState (context);
  226284. }
  226285. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226286. {
  226287. const int iw = sourceImage.getWidth();
  226288. const int ih = sourceImage.getHeight();
  226289. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226290. CGContextSaveGState (context);
  226291. CGContextSetAlpha (context, state->fillType.getOpacity());
  226292. flip();
  226293. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226294. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226295. if (fillEntireClipAsTiles)
  226296. {
  226297. #if JUCE_IOS
  226298. CGContextDrawTiledImage (context, imageRect, image);
  226299. #else
  226300. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226301. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226302. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226303. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226304. CGContextDrawTiledImage (context, imageRect, image);
  226305. else
  226306. #endif
  226307. {
  226308. // Fallback to manually doing a tiled fill on 10.4
  226309. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226310. int x = 0, y = 0;
  226311. while (x > clip.origin.x) x -= iw;
  226312. while (y > clip.origin.y) y -= ih;
  226313. const int right = (int) (clip.origin.x + clip.size.width);
  226314. const int bottom = (int) (clip.origin.y + clip.size.height);
  226315. while (y < bottom)
  226316. {
  226317. for (int x2 = x; x2 < right; x2 += iw)
  226318. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226319. y += ih;
  226320. }
  226321. }
  226322. #endif
  226323. }
  226324. else
  226325. {
  226326. CGContextDrawImage (context, imageRect, image);
  226327. }
  226328. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226329. CGContextRestoreGState (context);
  226330. }
  226331. void drawLine (const Line<float>& line)
  226332. {
  226333. if (state->fillType.isColour())
  226334. {
  226335. CGContextSetLineCap (context, kCGLineCapSquare);
  226336. CGContextSetLineWidth (context, 1.0f);
  226337. CGContextSetRGBStrokeColor (context,
  226338. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226339. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226340. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226341. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226342. CGContextStrokeLineSegments (context, cgLine, 1);
  226343. }
  226344. else
  226345. {
  226346. Path p;
  226347. p.addLineSegment (line, 1.0f);
  226348. fillPath (p, AffineTransform::identity);
  226349. }
  226350. }
  226351. void drawVerticalLine (const int x, float top, float bottom)
  226352. {
  226353. if (state->fillType.isColour())
  226354. {
  226355. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226356. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226357. #else
  226358. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226359. // the x co-ord slightly to trick it..
  226360. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226361. #endif
  226362. }
  226363. else
  226364. {
  226365. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226366. }
  226367. }
  226368. void drawHorizontalLine (const int y, float left, float right)
  226369. {
  226370. if (state->fillType.isColour())
  226371. {
  226372. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226373. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226374. #else
  226375. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226376. // the x co-ord slightly to trick it..
  226377. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226378. #endif
  226379. }
  226380. else
  226381. {
  226382. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226383. }
  226384. }
  226385. void setFont (const Font& newFont)
  226386. {
  226387. if (state->font != newFont)
  226388. {
  226389. state->fontRef = 0;
  226390. state->font = newFont;
  226391. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226392. if (mf != 0)
  226393. {
  226394. state->fontRef = mf->fontRef;
  226395. CGContextSetFont (context, state->fontRef);
  226396. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226397. state->fontTransform = mf->renderingTransform;
  226398. state->fontTransform.a *= state->font.getHorizontalScale();
  226399. CGContextSetTextMatrix (context, state->fontTransform);
  226400. }
  226401. }
  226402. }
  226403. const Font getFont()
  226404. {
  226405. return state->font;
  226406. }
  226407. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226408. {
  226409. if (state->fontRef != 0 && state->fillType.isColour())
  226410. {
  226411. if (transform.isOnlyTranslation())
  226412. {
  226413. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226414. CGGlyph g = glyphNumber;
  226415. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226416. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226417. }
  226418. else
  226419. {
  226420. CGContextSaveGState (context);
  226421. flip();
  226422. applyTransform (transform);
  226423. CGAffineTransform t = state->fontTransform;
  226424. t.d = -t.d;
  226425. CGContextSetTextMatrix (context, t);
  226426. CGGlyph g = glyphNumber;
  226427. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226428. CGContextRestoreGState (context);
  226429. }
  226430. }
  226431. else
  226432. {
  226433. Path p;
  226434. Font& f = state->font;
  226435. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226436. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226437. .followedBy (transform));
  226438. }
  226439. }
  226440. private:
  226441. CGContextRef context;
  226442. const CGFloat flipHeight;
  226443. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226444. CGFunctionCallbacks gradientCallbacks;
  226445. mutable Rectangle<int> lastClipRect;
  226446. mutable bool lastClipRectIsValid;
  226447. struct SavedState
  226448. {
  226449. SavedState()
  226450. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226451. {
  226452. }
  226453. SavedState (const SavedState& other)
  226454. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226455. fontTransform (other.fontTransform)
  226456. {
  226457. }
  226458. FillType fillType;
  226459. Font font;
  226460. CGFontRef fontRef;
  226461. CGAffineTransform fontTransform;
  226462. };
  226463. ScopedPointer <SavedState> state;
  226464. OwnedArray <SavedState> stateStack;
  226465. HeapBlock <PixelARGB> gradientLookupTable;
  226466. int numGradientLookupEntries;
  226467. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226468. {
  226469. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226470. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226471. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226472. colour.unpremultiply();
  226473. outData[0] = colour.getRed() / 255.0f;
  226474. outData[1] = colour.getGreen() / 255.0f;
  226475. outData[2] = colour.getBlue() / 255.0f;
  226476. outData[3] = colour.getAlpha() / 255.0f;
  226477. }
  226478. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226479. {
  226480. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  226481. --numGradientLookupEntries;
  226482. CGShadingRef result = 0;
  226483. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226484. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226485. if (gradient.isRadial)
  226486. {
  226487. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226488. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226489. function, true, true);
  226490. }
  226491. else
  226492. {
  226493. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226494. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226495. function, true, true);
  226496. }
  226497. CGFunctionRelease (function);
  226498. return result;
  226499. }
  226500. void drawGradient()
  226501. {
  226502. flip();
  226503. applyTransform (state->fillType.transform);
  226504. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226505. // you draw a gradient with high quality interp enabled).
  226506. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226507. CGContextSetAlpha (context, state->fillType.getOpacity());
  226508. CGContextDrawShading (context, shading);
  226509. CGShadingRelease (shading);
  226510. }
  226511. void createPath (const Path& path) const
  226512. {
  226513. CGContextBeginPath (context);
  226514. Path::Iterator i (path);
  226515. while (i.next())
  226516. {
  226517. switch (i.elementType)
  226518. {
  226519. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226520. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226521. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226522. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226523. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226524. default: jassertfalse; break;
  226525. }
  226526. }
  226527. }
  226528. void createPath (const Path& path, const AffineTransform& transform) const
  226529. {
  226530. CGContextBeginPath (context);
  226531. Path::Iterator i (path);
  226532. while (i.next())
  226533. {
  226534. switch (i.elementType)
  226535. {
  226536. case Path::Iterator::startNewSubPath:
  226537. transform.transformPoint (i.x1, i.y1);
  226538. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226539. break;
  226540. case Path::Iterator::lineTo:
  226541. transform.transformPoint (i.x1, i.y1);
  226542. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226543. break;
  226544. case Path::Iterator::quadraticTo:
  226545. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226546. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226547. break;
  226548. case Path::Iterator::cubicTo:
  226549. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226550. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226551. break;
  226552. case Path::Iterator::closePath:
  226553. CGContextClosePath (context); break;
  226554. default:
  226555. jassertfalse;
  226556. break;
  226557. }
  226558. }
  226559. }
  226560. void flip() const
  226561. {
  226562. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226563. }
  226564. void applyTransform (const AffineTransform& transform) const
  226565. {
  226566. CGAffineTransform t;
  226567. t.a = transform.mat00;
  226568. t.b = transform.mat10;
  226569. t.c = transform.mat01;
  226570. t.d = transform.mat11;
  226571. t.tx = transform.mat02;
  226572. t.ty = transform.mat12;
  226573. CGContextConcatCTM (context, t);
  226574. }
  226575. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226576. };
  226577. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226578. {
  226579. return new CoreGraphicsContext (context, height);
  226580. }
  226581. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226582. const Image juce_loadWithCoreImage (InputStream& input)
  226583. {
  226584. MemoryBlock data;
  226585. input.readIntoMemoryBlock (data, -1);
  226586. #if JUCE_IOS
  226587. JUCE_AUTORELEASEPOOL
  226588. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226589. length: data.getSize()
  226590. freeWhenDone: NO]];
  226591. if (image != nil)
  226592. {
  226593. CGImageRef loadedImage = image.CGImage;
  226594. #else
  226595. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226596. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226597. CGDataProviderRelease (provider);
  226598. if (imageSource != 0)
  226599. {
  226600. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226601. CFRelease (imageSource);
  226602. #endif
  226603. if (loadedImage != 0)
  226604. {
  226605. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226606. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226607. && alphaInfo != kCGImageAlphaNoneSkipLast
  226608. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226609. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226610. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226611. hasAlphaChan, Image::NativeImage);
  226612. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226613. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226614. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226615. CGContextFlush (cgImage->context);
  226616. #if ! JUCE_IOS
  226617. CFRelease (loadedImage);
  226618. #endif
  226619. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226620. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226621. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226622. return image;
  226623. }
  226624. }
  226625. return Image::null;
  226626. }
  226627. #endif
  226628. #endif
  226629. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226630. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226631. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226632. // compiled on its own).
  226633. #if JUCE_INCLUDED_FILE
  226634. class UIViewComponentPeer;
  226635. END_JUCE_NAMESPACE
  226636. #define JuceUIView MakeObjCClassName(JuceUIView)
  226637. @interface JuceUIView : UIView <UITextViewDelegate>
  226638. {
  226639. @public
  226640. UIViewComponentPeer* owner;
  226641. UITextView* hiddenTextView;
  226642. }
  226643. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  226644. - (void) dealloc;
  226645. - (void) drawRect: (CGRect) r;
  226646. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  226647. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  226648. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  226649. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  226650. - (BOOL) becomeFirstResponder;
  226651. - (BOOL) resignFirstResponder;
  226652. - (BOOL) canBecomeFirstResponder;
  226653. - (void) asyncRepaint: (id) rect;
  226654. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  226655. @end
  226656. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  226657. @interface JuceUIViewController : UIViewController
  226658. {
  226659. }
  226660. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  226661. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  226662. @end
  226663. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  226664. @interface JuceUIWindow : UIWindow
  226665. {
  226666. @private
  226667. UIViewComponentPeer* owner;
  226668. bool isZooming;
  226669. }
  226670. - (void) setOwner: (UIViewComponentPeer*) owner;
  226671. - (void) becomeKeyWindow;
  226672. @end
  226673. BEGIN_JUCE_NAMESPACE
  226674. class UIViewComponentPeer : public ComponentPeer,
  226675. public FocusChangeListener
  226676. {
  226677. public:
  226678. UIViewComponentPeer (Component* const component,
  226679. const int windowStyleFlags,
  226680. UIView* viewToAttachTo);
  226681. ~UIViewComponentPeer();
  226682. void* getNativeHandle() const;
  226683. void setVisible (bool shouldBeVisible);
  226684. void setTitle (const String& title);
  226685. void setPosition (int x, int y);
  226686. void setSize (int w, int h);
  226687. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  226688. const Rectangle<int> getBounds() const;
  226689. const Rectangle<int> getBounds (const bool global) const;
  226690. const Point<int> getScreenPosition() const;
  226691. const Point<int> localToGlobal (const Point<int>& relativePosition);
  226692. const Point<int> globalToLocal (const Point<int>& screenPosition);
  226693. void setAlpha (float newAlpha);
  226694. void setMinimised (bool shouldBeMinimised);
  226695. bool isMinimised() const;
  226696. void setFullScreen (bool shouldBeFullScreen);
  226697. bool isFullScreen() const;
  226698. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226699. const BorderSize getFrameSize() const;
  226700. bool setAlwaysOnTop (bool alwaysOnTop);
  226701. void toFront (bool makeActiveWindow);
  226702. void toBehind (ComponentPeer* other);
  226703. void setIcon (const Image& newIcon);
  226704. virtual void drawRect (CGRect r);
  226705. virtual bool canBecomeKeyWindow();
  226706. virtual bool windowShouldClose();
  226707. virtual void redirectMovedOrResized();
  226708. virtual CGRect constrainRect (CGRect r);
  226709. virtual void viewFocusGain();
  226710. virtual void viewFocusLoss();
  226711. bool isFocused() const;
  226712. void grabFocus();
  226713. void textInputRequired (const Point<int>& position);
  226714. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  226715. void updateHiddenTextContent (TextInputTarget* target);
  226716. void globalFocusChanged (Component*);
  226717. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  226718. virtual void displayRotated();
  226719. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  226720. void repaint (const Rectangle<int>& area);
  226721. void performAnyPendingRepaintsNow();
  226722. UIWindow* window;
  226723. JuceUIView* view;
  226724. JuceUIViewController* controller;
  226725. bool isSharedWindow, fullScreen, insideDrawRect;
  226726. static ModifierKeys currentModifiers;
  226727. static int64 getMouseTime (UIEvent* e)
  226728. {
  226729. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  226730. + (int64) ([e timestamp] * 1000.0);
  226731. }
  226732. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  226733. {
  226734. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226735. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226736. {
  226737. case UIInterfaceOrientationPortrait:
  226738. return r;
  226739. case UIInterfaceOrientationPortraitUpsideDown:
  226740. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226741. r.getWidth(), r.getHeight());
  226742. case UIInterfaceOrientationLandscapeLeft:
  226743. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  226744. r.getHeight(), r.getWidth());
  226745. case UIInterfaceOrientationLandscapeRight:
  226746. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  226747. r.getHeight(), r.getWidth());
  226748. default: jassertfalse; // unknown orientation!
  226749. }
  226750. return r;
  226751. }
  226752. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  226753. {
  226754. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226755. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226756. {
  226757. case UIInterfaceOrientationPortrait:
  226758. return r;
  226759. case UIInterfaceOrientationPortraitUpsideDown:
  226760. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226761. r.getWidth(), r.getHeight());
  226762. case UIInterfaceOrientationLandscapeLeft:
  226763. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  226764. r.getHeight(), r.getWidth());
  226765. case UIInterfaceOrientationLandscapeRight:
  226766. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  226767. r.getHeight(), r.getWidth());
  226768. default: jassertfalse; // unknown orientation!
  226769. }
  226770. return r;
  226771. }
  226772. Array <UITouch*> currentTouches;
  226773. private:
  226774. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  226775. };
  226776. END_JUCE_NAMESPACE
  226777. @implementation JuceUIViewController
  226778. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  226779. {
  226780. JuceUIView* juceView = (JuceUIView*) [self view];
  226781. jassert (juceView != 0 && juceView->owner != 0);
  226782. return juceView->owner->shouldRotate (interfaceOrientation);
  226783. }
  226784. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  226785. {
  226786. JuceUIView* juceView = (JuceUIView*) [self view];
  226787. jassert (juceView != 0 && juceView->owner != 0);
  226788. juceView->owner->displayRotated();
  226789. }
  226790. @end
  226791. @implementation JuceUIView
  226792. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  226793. withFrame: (CGRect) frame
  226794. {
  226795. [super initWithFrame: frame];
  226796. owner = owner_;
  226797. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  226798. [self addSubview: hiddenTextView];
  226799. hiddenTextView.delegate = self;
  226800. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  226801. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  226802. return self;
  226803. }
  226804. - (void) dealloc
  226805. {
  226806. [hiddenTextView removeFromSuperview];
  226807. [hiddenTextView release];
  226808. [super dealloc];
  226809. }
  226810. - (void) drawRect: (CGRect) r
  226811. {
  226812. if (owner != 0)
  226813. owner->drawRect (r);
  226814. }
  226815. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  226816. {
  226817. return false;
  226818. }
  226819. ModifierKeys UIViewComponentPeer::currentModifiers;
  226820. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  226821. {
  226822. return UIViewComponentPeer::currentModifiers;
  226823. }
  226824. void ModifierKeys::updateCurrentModifiers() throw()
  226825. {
  226826. currentModifiers = UIViewComponentPeer::currentModifiers;
  226827. }
  226828. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  226829. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  226830. {
  226831. if (owner != 0)
  226832. owner->handleTouches (event, true, false, false);
  226833. }
  226834. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  226835. {
  226836. if (owner != 0)
  226837. owner->handleTouches (event, false, false, false);
  226838. }
  226839. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  226840. {
  226841. if (owner != 0)
  226842. owner->handleTouches (event, false, true, false);
  226843. }
  226844. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  226845. {
  226846. if (owner != 0)
  226847. owner->handleTouches (event, false, true, true);
  226848. [self touchesEnded: touches withEvent: event];
  226849. }
  226850. - (BOOL) becomeFirstResponder
  226851. {
  226852. if (owner != 0)
  226853. owner->viewFocusGain();
  226854. return true;
  226855. }
  226856. - (BOOL) resignFirstResponder
  226857. {
  226858. if (owner != 0)
  226859. owner->viewFocusLoss();
  226860. return true;
  226861. }
  226862. - (BOOL) canBecomeFirstResponder
  226863. {
  226864. return owner != 0 && owner->canBecomeKeyWindow();
  226865. }
  226866. - (void) asyncRepaint: (id) rect
  226867. {
  226868. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226869. [self setNeedsDisplayInRect: *r];
  226870. }
  226871. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  226872. {
  226873. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226874. nsStringToJuce (text));
  226875. }
  226876. @end
  226877. @implementation JuceUIWindow
  226878. - (void) setOwner: (UIViewComponentPeer*) owner_
  226879. {
  226880. owner = owner_;
  226881. isZooming = false;
  226882. }
  226883. - (void) becomeKeyWindow
  226884. {
  226885. [super becomeKeyWindow];
  226886. if (owner != 0)
  226887. owner->grabFocus();
  226888. }
  226889. @end
  226890. BEGIN_JUCE_NAMESPACE
  226891. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226892. const int windowStyleFlags,
  226893. UIView* viewToAttachTo)
  226894. : ComponentPeer (component, windowStyleFlags),
  226895. window (0),
  226896. view (0), controller (0),
  226897. isSharedWindow (viewToAttachTo != 0),
  226898. fullScreen (false),
  226899. insideDrawRect (false)
  226900. {
  226901. CGRect r = convertToCGRect (component->getLocalBounds());
  226902. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226903. if (isSharedWindow)
  226904. {
  226905. window = [viewToAttachTo window];
  226906. [viewToAttachTo addSubview: view];
  226907. setVisible (component->isVisible());
  226908. }
  226909. else
  226910. {
  226911. controller = [[JuceUIViewController alloc] init];
  226912. controller.view = view;
  226913. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  226914. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226915. window = [[JuceUIWindow alloc] init];
  226916. window.frame = r;
  226917. window.opaque = component->isOpaque();
  226918. view.opaque = component->isOpaque();
  226919. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226920. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226921. [((JuceUIWindow*) window) setOwner: this];
  226922. if (component->isAlwaysOnTop())
  226923. window.windowLevel = UIWindowLevelAlert;
  226924. [window addSubview: view];
  226925. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226926. view.hidden = ! component->isVisible();
  226927. window.hidden = ! component->isVisible();
  226928. view.multipleTouchEnabled = YES;
  226929. }
  226930. setTitle (component->getName());
  226931. Desktop::getInstance().addFocusChangeListener (this);
  226932. }
  226933. UIViewComponentPeer::~UIViewComponentPeer()
  226934. {
  226935. Desktop::getInstance().removeFocusChangeListener (this);
  226936. view->owner = 0;
  226937. [view removeFromSuperview];
  226938. [view release];
  226939. [controller release];
  226940. if (! isSharedWindow)
  226941. {
  226942. [((JuceUIWindow*) window) setOwner: 0];
  226943. [window release];
  226944. }
  226945. }
  226946. void* UIViewComponentPeer::getNativeHandle() const
  226947. {
  226948. return view;
  226949. }
  226950. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226951. {
  226952. view.hidden = ! shouldBeVisible;
  226953. if (! isSharedWindow)
  226954. window.hidden = ! shouldBeVisible;
  226955. }
  226956. void UIViewComponentPeer::setTitle (const String& title)
  226957. {
  226958. // xxx is this possible?
  226959. }
  226960. void UIViewComponentPeer::setPosition (int x, int y)
  226961. {
  226962. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226963. }
  226964. void UIViewComponentPeer::setSize (int w, int h)
  226965. {
  226966. setBounds (component->getX(), component->getY(), w, h, false);
  226967. }
  226968. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226969. {
  226970. fullScreen = isNowFullScreen;
  226971. w = jmax (0, w);
  226972. h = jmax (0, h);
  226973. if (isSharedWindow)
  226974. {
  226975. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  226976. if ([view frame].size.width != r.size.width
  226977. || [view frame].size.height != r.size.height)
  226978. [view setNeedsDisplay];
  226979. view.frame = r;
  226980. }
  226981. else
  226982. {
  226983. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  226984. window.frame = convertToCGRect (bounds);
  226985. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  226986. handleMovedOrResized();
  226987. }
  226988. }
  226989. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226990. {
  226991. CGRect r = [view frame];
  226992. if (global && [view window] != 0)
  226993. {
  226994. r = [view convertRect: r toView: nil];
  226995. CGRect wr = [[view window] frame];
  226996. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  226997. r.origin.x = windowBounds.getX();
  226998. r.origin.y = windowBounds.getY();
  226999. }
  227000. return convertToRectInt (r);
  227001. }
  227002. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227003. {
  227004. return getBounds (! isSharedWindow);
  227005. }
  227006. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227007. {
  227008. return getBounds (true).getPosition();
  227009. }
  227010. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  227011. {
  227012. return relativePosition + getScreenPosition();
  227013. }
  227014. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  227015. {
  227016. return screenPosition - getScreenPosition();
  227017. }
  227018. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227019. {
  227020. if (constrainer != 0)
  227021. {
  227022. CGRect current = [window frame];
  227023. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227024. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227025. Rectangle<int> pos (convertToRectInt (r));
  227026. Rectangle<int> original (convertToRectInt (current));
  227027. constrainer->checkBounds (pos, original,
  227028. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227029. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227030. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227031. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227032. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227033. r.origin.x = pos.getX();
  227034. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227035. r.size.width = pos.getWidth();
  227036. r.size.height = pos.getHeight();
  227037. }
  227038. return r;
  227039. }
  227040. void UIViewComponentPeer::setAlpha (float newAlpha)
  227041. {
  227042. [[view window] setAlpha: (CGFloat) newAlpha];
  227043. }
  227044. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227045. {
  227046. }
  227047. bool UIViewComponentPeer::isMinimised() const
  227048. {
  227049. return false;
  227050. }
  227051. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227052. {
  227053. if (! isSharedWindow)
  227054. {
  227055. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227056. : lastNonFullscreenBounds);
  227057. if ((! shouldBeFullScreen) && r.isEmpty())
  227058. r = getBounds();
  227059. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227060. if (! r.isEmpty())
  227061. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227062. component->repaint();
  227063. }
  227064. }
  227065. bool UIViewComponentPeer::isFullScreen() const
  227066. {
  227067. return fullScreen;
  227068. }
  227069. namespace
  227070. {
  227071. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227072. {
  227073. switch (interfaceOrientation)
  227074. {
  227075. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227076. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227077. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227078. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227079. default: jassertfalse; // unknown orientation!
  227080. }
  227081. return Desktop::upright;
  227082. }
  227083. }
  227084. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227085. {
  227086. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227087. }
  227088. void UIViewComponentPeer::displayRotated()
  227089. {
  227090. const Rectangle<int> oldArea (component->getBounds());
  227091. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227092. Desktop::getInstance().refreshMonitorSizes();
  227093. if (fullScreen)
  227094. {
  227095. fullScreen = false;
  227096. setFullScreen (true);
  227097. }
  227098. else
  227099. {
  227100. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227101. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227102. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227103. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227104. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227105. setBounds ((int) (l * newDesktop.getWidth()),
  227106. (int) (t * newDesktop.getHeight()),
  227107. (int) ((r - l) * newDesktop.getWidth()),
  227108. (int) ((b - t) * newDesktop.getHeight()),
  227109. false);
  227110. }
  227111. }
  227112. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227113. {
  227114. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  227115. && isPositiveAndBelow (position.getY(), component->getHeight())))
  227116. return false;
  227117. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227118. withEvent: nil];
  227119. if (trueIfInAChildWindow)
  227120. return v != nil;
  227121. return v == view;
  227122. }
  227123. const BorderSize UIViewComponentPeer::getFrameSize() const
  227124. {
  227125. return BorderSize();
  227126. }
  227127. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227128. {
  227129. if (! isSharedWindow)
  227130. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227131. return true;
  227132. }
  227133. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227134. {
  227135. if (isSharedWindow)
  227136. [[view superview] bringSubviewToFront: view];
  227137. if (window != 0 && component->isVisible())
  227138. [window makeKeyAndVisible];
  227139. }
  227140. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227141. {
  227142. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227143. jassert (otherPeer != 0); // wrong type of window?
  227144. if (otherPeer != 0)
  227145. {
  227146. if (isSharedWindow)
  227147. {
  227148. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227149. }
  227150. else
  227151. {
  227152. jassertfalse; // don't know how to do this
  227153. }
  227154. }
  227155. }
  227156. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227157. {
  227158. // to do..
  227159. }
  227160. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227161. {
  227162. NSArray* touches = [[event touchesForView: view] allObjects];
  227163. for (unsigned int i = 0; i < [touches count]; ++i)
  227164. {
  227165. UITouch* touch = [touches objectAtIndex: i];
  227166. CGPoint p = [touch locationInView: view];
  227167. const Point<int> pos ((int) p.x, (int) p.y);
  227168. juce_lastMousePos = pos + getScreenPosition();
  227169. const int64 time = getMouseTime (event);
  227170. int touchIndex = currentTouches.indexOf (touch);
  227171. if (touchIndex < 0)
  227172. {
  227173. touchIndex = currentTouches.size();
  227174. currentTouches.add (touch);
  227175. }
  227176. if (isDown)
  227177. {
  227178. currentModifiers = currentModifiers.withoutMouseButtons();
  227179. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227180. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227181. }
  227182. else if (isUp)
  227183. {
  227184. currentModifiers = currentModifiers.withoutMouseButtons();
  227185. currentTouches.remove (touchIndex);
  227186. }
  227187. if (isCancel)
  227188. currentTouches.clear();
  227189. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227190. }
  227191. }
  227192. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227193. void UIViewComponentPeer::viewFocusGain()
  227194. {
  227195. if (currentlyFocusedPeer != this)
  227196. {
  227197. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227198. currentlyFocusedPeer->handleFocusLoss();
  227199. currentlyFocusedPeer = this;
  227200. handleFocusGain();
  227201. }
  227202. }
  227203. void UIViewComponentPeer::viewFocusLoss()
  227204. {
  227205. if (currentlyFocusedPeer == this)
  227206. {
  227207. currentlyFocusedPeer = 0;
  227208. handleFocusLoss();
  227209. }
  227210. }
  227211. void juce_HandleProcessFocusChange()
  227212. {
  227213. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227214. {
  227215. if (Process::isForegroundProcess())
  227216. {
  227217. currentlyFocusedPeer->handleFocusGain();
  227218. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227219. }
  227220. else
  227221. {
  227222. currentlyFocusedPeer->handleFocusLoss();
  227223. // turn kiosk mode off if we lose focus..
  227224. Desktop::getInstance().setKioskModeComponent (0);
  227225. }
  227226. }
  227227. }
  227228. bool UIViewComponentPeer::isFocused() const
  227229. {
  227230. return isSharedWindow ? this == currentlyFocusedPeer
  227231. : (window != 0 && [window isKeyWindow]);
  227232. }
  227233. void UIViewComponentPeer::grabFocus()
  227234. {
  227235. if (window != 0)
  227236. {
  227237. [window makeKeyWindow];
  227238. viewFocusGain();
  227239. }
  227240. }
  227241. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227242. {
  227243. }
  227244. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227245. {
  227246. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227247. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227248. }
  227249. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227250. {
  227251. TextInputTarget* const target = findCurrentTextInputTarget();
  227252. if (target != 0)
  227253. {
  227254. const Range<int> currentSelection (target->getHighlightedRegion());
  227255. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227256. if (currentSelection.isEmpty())
  227257. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227258. target->insertTextAtCaret (text);
  227259. updateHiddenTextContent (target);
  227260. }
  227261. return NO;
  227262. }
  227263. void UIViewComponentPeer::globalFocusChanged (Component*)
  227264. {
  227265. TextInputTarget* const target = findCurrentTextInputTarget();
  227266. if (target != 0)
  227267. {
  227268. Component* comp = dynamic_cast<Component*> (target);
  227269. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227270. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227271. updateHiddenTextContent (target);
  227272. [view->hiddenTextView becomeFirstResponder];
  227273. }
  227274. else
  227275. {
  227276. [view->hiddenTextView resignFirstResponder];
  227277. }
  227278. }
  227279. void UIViewComponentPeer::drawRect (CGRect r)
  227280. {
  227281. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227282. return;
  227283. CGContextRef cg = UIGraphicsGetCurrentContext();
  227284. if (! component->isOpaque())
  227285. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227286. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227287. CoreGraphicsContext g (cg, view.bounds.size.height);
  227288. insideDrawRect = true;
  227289. handlePaint (g);
  227290. insideDrawRect = false;
  227291. }
  227292. bool UIViewComponentPeer::canBecomeKeyWindow()
  227293. {
  227294. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227295. }
  227296. bool UIViewComponentPeer::windowShouldClose()
  227297. {
  227298. if (! isValidPeer (this))
  227299. return YES;
  227300. handleUserClosingWindow();
  227301. return NO;
  227302. }
  227303. void UIViewComponentPeer::redirectMovedOrResized()
  227304. {
  227305. handleMovedOrResized();
  227306. }
  227307. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227308. {
  227309. }
  227310. class AsyncRepaintMessage : public CallbackMessage
  227311. {
  227312. public:
  227313. UIViewComponentPeer* const peer;
  227314. const Rectangle<int> rect;
  227315. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227316. : peer (peer_), rect (rect_)
  227317. {
  227318. }
  227319. void messageCallback()
  227320. {
  227321. if (ComponentPeer::isValidPeer (peer))
  227322. peer->repaint (rect);
  227323. }
  227324. };
  227325. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227326. {
  227327. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227328. {
  227329. (new AsyncRepaintMessage (this, area))->post();
  227330. }
  227331. else
  227332. {
  227333. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227334. }
  227335. }
  227336. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227337. {
  227338. }
  227339. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227340. {
  227341. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227342. }
  227343. const Image juce_createIconForFile (const File& file)
  227344. {
  227345. return Image::null;
  227346. }
  227347. void Desktop::createMouseInputSources()
  227348. {
  227349. for (int i = 0; i < 10; ++i)
  227350. mouseSources.add (new MouseInputSource (i, false));
  227351. }
  227352. bool Desktop::canUseSemiTransparentWindows() throw()
  227353. {
  227354. return true;
  227355. }
  227356. const Point<int> MouseInputSource::getCurrentMousePosition()
  227357. {
  227358. return juce_lastMousePos;
  227359. }
  227360. void Desktop::setMousePosition (const Point<int>&)
  227361. {
  227362. }
  227363. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227364. {
  227365. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227366. }
  227367. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227368. {
  227369. const ScopedAutoReleasePool pool;
  227370. monitorCoords.clear();
  227371. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227372. : [[UIScreen mainScreen] bounds];
  227373. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227374. }
  227375. const int KeyPress::spaceKey = ' ';
  227376. const int KeyPress::returnKey = 0x0d;
  227377. const int KeyPress::escapeKey = 0x1b;
  227378. const int KeyPress::backspaceKey = 0x7f;
  227379. const int KeyPress::leftKey = 0x1000;
  227380. const int KeyPress::rightKey = 0x1001;
  227381. const int KeyPress::upKey = 0x1002;
  227382. const int KeyPress::downKey = 0x1003;
  227383. const int KeyPress::pageUpKey = 0x1004;
  227384. const int KeyPress::pageDownKey = 0x1005;
  227385. const int KeyPress::endKey = 0x1006;
  227386. const int KeyPress::homeKey = 0x1007;
  227387. const int KeyPress::deleteKey = 0x1008;
  227388. const int KeyPress::insertKey = -1;
  227389. const int KeyPress::tabKey = 9;
  227390. const int KeyPress::F1Key = 0x2001;
  227391. const int KeyPress::F2Key = 0x2002;
  227392. const int KeyPress::F3Key = 0x2003;
  227393. const int KeyPress::F4Key = 0x2004;
  227394. const int KeyPress::F5Key = 0x2005;
  227395. const int KeyPress::F6Key = 0x2006;
  227396. const int KeyPress::F7Key = 0x2007;
  227397. const int KeyPress::F8Key = 0x2008;
  227398. const int KeyPress::F9Key = 0x2009;
  227399. const int KeyPress::F10Key = 0x200a;
  227400. const int KeyPress::F11Key = 0x200b;
  227401. const int KeyPress::F12Key = 0x200c;
  227402. const int KeyPress::F13Key = 0x200d;
  227403. const int KeyPress::F14Key = 0x200e;
  227404. const int KeyPress::F15Key = 0x200f;
  227405. const int KeyPress::F16Key = 0x2010;
  227406. const int KeyPress::numberPad0 = 0x30020;
  227407. const int KeyPress::numberPad1 = 0x30021;
  227408. const int KeyPress::numberPad2 = 0x30022;
  227409. const int KeyPress::numberPad3 = 0x30023;
  227410. const int KeyPress::numberPad4 = 0x30024;
  227411. const int KeyPress::numberPad5 = 0x30025;
  227412. const int KeyPress::numberPad6 = 0x30026;
  227413. const int KeyPress::numberPad7 = 0x30027;
  227414. const int KeyPress::numberPad8 = 0x30028;
  227415. const int KeyPress::numberPad9 = 0x30029;
  227416. const int KeyPress::numberPadAdd = 0x3002a;
  227417. const int KeyPress::numberPadSubtract = 0x3002b;
  227418. const int KeyPress::numberPadMultiply = 0x3002c;
  227419. const int KeyPress::numberPadDivide = 0x3002d;
  227420. const int KeyPress::numberPadSeparator = 0x3002e;
  227421. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227422. const int KeyPress::numberPadEquals = 0x30030;
  227423. const int KeyPress::numberPadDelete = 0x30031;
  227424. const int KeyPress::playKey = 0x30000;
  227425. const int KeyPress::stopKey = 0x30001;
  227426. const int KeyPress::fastForwardKey = 0x30002;
  227427. const int KeyPress::rewindKey = 0x30003;
  227428. #endif
  227429. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227430. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227431. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227432. // compiled on its own).
  227433. #if JUCE_INCLUDED_FILE
  227434. struct CallbackMessagePayload
  227435. {
  227436. MessageCallbackFunction* function;
  227437. void* parameter;
  227438. void* volatile result;
  227439. bool volatile hasBeenExecuted;
  227440. };
  227441. END_JUCE_NAMESPACE
  227442. @interface JuceCustomMessageHandler : NSObject
  227443. {
  227444. }
  227445. - (void) performCallback: (id) info;
  227446. @end
  227447. @implementation JuceCustomMessageHandler
  227448. - (void) performCallback: (id) info
  227449. {
  227450. if ([info isKindOfClass: [NSData class]])
  227451. {
  227452. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227453. if (pl != 0)
  227454. {
  227455. pl->result = (*pl->function) (pl->parameter);
  227456. pl->hasBeenExecuted = true;
  227457. }
  227458. }
  227459. else
  227460. {
  227461. jassertfalse; // should never get here!
  227462. }
  227463. }
  227464. @end
  227465. BEGIN_JUCE_NAMESPACE
  227466. void MessageManager::runDispatchLoop()
  227467. {
  227468. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227469. runDispatchLoopUntil (-1);
  227470. }
  227471. void MessageManager::stopDispatchLoop()
  227472. {
  227473. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227474. exit (0); // iPhone apps get no mercy..
  227475. }
  227476. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227477. {
  227478. const ScopedAutoReleasePool pool;
  227479. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227480. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227481. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227482. while (! quitMessagePosted)
  227483. {
  227484. const ScopedAutoReleasePool pool;
  227485. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227486. beforeDate: endDate];
  227487. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227488. break;
  227489. }
  227490. return ! quitMessagePosted;
  227491. }
  227492. struct MessageDispatchSystem
  227493. {
  227494. MessageDispatchSystem()
  227495. : juceCustomMessageHandler (0)
  227496. {
  227497. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227498. }
  227499. ~MessageDispatchSystem()
  227500. {
  227501. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227502. [juceCustomMessageHandler release];
  227503. }
  227504. JuceCustomMessageHandler* juceCustomMessageHandler;
  227505. MessageQueue messageQueue;
  227506. };
  227507. static MessageDispatchSystem* dispatcher = 0;
  227508. void MessageManager::doPlatformSpecificInitialisation()
  227509. {
  227510. if (dispatcher == 0)
  227511. dispatcher = new MessageDispatchSystem();
  227512. }
  227513. void MessageManager::doPlatformSpecificShutdown()
  227514. {
  227515. deleteAndZero (dispatcher);
  227516. }
  227517. bool juce_postMessageToSystemQueue (Message* message)
  227518. {
  227519. if (dispatcher != 0)
  227520. dispatcher->messageQueue.post (message);
  227521. return true;
  227522. }
  227523. void MessageManager::broadcastMessage (const String& value)
  227524. {
  227525. }
  227526. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227527. {
  227528. if (isThisTheMessageThread())
  227529. {
  227530. return (*callback) (data);
  227531. }
  227532. else
  227533. {
  227534. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227535. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227536. // deadlock because the message manager is blocked from running, so can never
  227537. // call your function..
  227538. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227539. const ScopedAutoReleasePool pool;
  227540. CallbackMessagePayload cmp;
  227541. cmp.function = callback;
  227542. cmp.parameter = data;
  227543. cmp.result = 0;
  227544. cmp.hasBeenExecuted = false;
  227545. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227546. withObject: [NSData dataWithBytesNoCopy: &cmp
  227547. length: sizeof (cmp)
  227548. freeWhenDone: NO]
  227549. waitUntilDone: YES];
  227550. return cmp.result;
  227551. }
  227552. }
  227553. #endif
  227554. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  227555. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227556. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227557. // compiled on its own).
  227558. #if JUCE_INCLUDED_FILE
  227559. #if JUCE_MAC
  227560. END_JUCE_NAMESPACE
  227561. using namespace JUCE_NAMESPACE;
  227562. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227563. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227564. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227565. #else
  227566. @interface JuceFileChooserDelegate : NSObject
  227567. #endif
  227568. {
  227569. StringArray* filters;
  227570. }
  227571. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227572. - (void) dealloc;
  227573. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227574. @end
  227575. @implementation JuceFileChooserDelegate
  227576. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227577. {
  227578. [super init];
  227579. filters = filters_;
  227580. return self;
  227581. }
  227582. - (void) dealloc
  227583. {
  227584. delete filters;
  227585. [super dealloc];
  227586. }
  227587. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227588. {
  227589. (void) sender;
  227590. const File f (nsStringToJuce (filename));
  227591. for (int i = filters->size(); --i >= 0;)
  227592. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227593. return true;
  227594. return f.isDirectory();
  227595. }
  227596. @end
  227597. BEGIN_JUCE_NAMESPACE
  227598. void FileChooser::showPlatformDialog (Array<File>& results,
  227599. const String& title,
  227600. const File& currentFileOrDirectory,
  227601. const String& filter,
  227602. bool selectsDirectory,
  227603. bool selectsFiles,
  227604. bool isSaveDialogue,
  227605. bool warnAboutOverwritingExistingFiles,
  227606. bool selectMultipleFiles,
  227607. FilePreviewComponent* extraInfoComponent)
  227608. {
  227609. const ScopedAutoReleasePool pool;
  227610. StringArray* filters = new StringArray();
  227611. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227612. filters->trim();
  227613. filters->removeEmptyStrings();
  227614. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227615. [delegate autorelease];
  227616. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227617. : [NSOpenPanel openPanel];
  227618. [panel setTitle: juceStringToNS (title)];
  227619. if (! isSaveDialogue)
  227620. {
  227621. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227622. [openPanel setCanChooseDirectories: selectsDirectory];
  227623. [openPanel setCanChooseFiles: selectsFiles];
  227624. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227625. }
  227626. [panel setDelegate: delegate];
  227627. if (isSaveDialogue || selectsDirectory)
  227628. [panel setCanCreateDirectories: YES];
  227629. String directory, filename;
  227630. if (currentFileOrDirectory.isDirectory())
  227631. {
  227632. directory = currentFileOrDirectory.getFullPathName();
  227633. }
  227634. else
  227635. {
  227636. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227637. filename = currentFileOrDirectory.getFileName();
  227638. }
  227639. if ([panel runModalForDirectory: juceStringToNS (directory)
  227640. file: juceStringToNS (filename)]
  227641. == NSOKButton)
  227642. {
  227643. if (isSaveDialogue)
  227644. {
  227645. results.add (File (nsStringToJuce ([panel filename])));
  227646. }
  227647. else
  227648. {
  227649. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227650. NSArray* urls = [openPanel filenames];
  227651. for (unsigned int i = 0; i < [urls count]; ++i)
  227652. {
  227653. NSString* f = [urls objectAtIndex: i];
  227654. results.add (File (nsStringToJuce (f)));
  227655. }
  227656. }
  227657. }
  227658. [panel setDelegate: nil];
  227659. }
  227660. #else
  227661. void FileChooser::showPlatformDialog (Array<File>& results,
  227662. const String& title,
  227663. const File& currentFileOrDirectory,
  227664. const String& filter,
  227665. bool selectsDirectory,
  227666. bool selectsFiles,
  227667. bool isSaveDialogue,
  227668. bool warnAboutOverwritingExistingFiles,
  227669. bool selectMultipleFiles,
  227670. FilePreviewComponent* extraInfoComponent)
  227671. {
  227672. const ScopedAutoReleasePool pool;
  227673. jassertfalse; //xxx to do
  227674. }
  227675. #endif
  227676. #endif
  227677. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  227678. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  227679. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227680. // compiled on its own).
  227681. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  227682. #if JUCE_MAC
  227683. END_JUCE_NAMESPACE
  227684. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  227685. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  227686. {
  227687. CriticalSection* contextLock;
  227688. bool needsUpdate;
  227689. }
  227690. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  227691. - (bool) makeActive;
  227692. - (void) makeInactive;
  227693. - (void) reshape;
  227694. @end
  227695. @implementation ThreadSafeNSOpenGLView
  227696. - (id) initWithFrame: (NSRect) frameRect
  227697. pixelFormat: (NSOpenGLPixelFormat*) format
  227698. {
  227699. contextLock = new CriticalSection();
  227700. self = [super initWithFrame: frameRect pixelFormat: format];
  227701. if (self != nil)
  227702. [[NSNotificationCenter defaultCenter] addObserver: self
  227703. selector: @selector (_surfaceNeedsUpdate:)
  227704. name: NSViewGlobalFrameDidChangeNotification
  227705. object: self];
  227706. return self;
  227707. }
  227708. - (void) dealloc
  227709. {
  227710. [[NSNotificationCenter defaultCenter] removeObserver: self];
  227711. delete contextLock;
  227712. [super dealloc];
  227713. }
  227714. - (bool) makeActive
  227715. {
  227716. const ScopedLock sl (*contextLock);
  227717. if ([self openGLContext] == 0)
  227718. return false;
  227719. [[self openGLContext] makeCurrentContext];
  227720. if (needsUpdate)
  227721. {
  227722. [super update];
  227723. needsUpdate = false;
  227724. }
  227725. return true;
  227726. }
  227727. - (void) makeInactive
  227728. {
  227729. const ScopedLock sl (*contextLock);
  227730. [NSOpenGLContext clearCurrentContext];
  227731. }
  227732. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  227733. {
  227734. const ScopedLock sl (*contextLock);
  227735. needsUpdate = true;
  227736. }
  227737. - (void) update
  227738. {
  227739. const ScopedLock sl (*contextLock);
  227740. needsUpdate = true;
  227741. }
  227742. - (void) reshape
  227743. {
  227744. const ScopedLock sl (*contextLock);
  227745. needsUpdate = true;
  227746. }
  227747. @end
  227748. BEGIN_JUCE_NAMESPACE
  227749. class WindowedGLContext : public OpenGLContext
  227750. {
  227751. public:
  227752. WindowedGLContext (Component* const component,
  227753. const OpenGLPixelFormat& pixelFormat_,
  227754. NSOpenGLContext* sharedContext)
  227755. : renderContext (0),
  227756. pixelFormat (pixelFormat_)
  227757. {
  227758. jassert (component != 0);
  227759. NSOpenGLPixelFormatAttribute attribs [64];
  227760. int n = 0;
  227761. attribs[n++] = NSOpenGLPFADoubleBuffer;
  227762. attribs[n++] = NSOpenGLPFAAccelerated;
  227763. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  227764. attribs[n++] = NSOpenGLPFAColorSize;
  227765. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  227766. pixelFormat.greenBits,
  227767. pixelFormat.blueBits);
  227768. attribs[n++] = NSOpenGLPFAAlphaSize;
  227769. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  227770. attribs[n++] = NSOpenGLPFADepthSize;
  227771. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  227772. attribs[n++] = NSOpenGLPFAStencilSize;
  227773. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  227774. attribs[n++] = NSOpenGLPFAAccumSize;
  227775. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  227776. pixelFormat.accumulationBufferGreenBits,
  227777. pixelFormat.accumulationBufferBlueBits,
  227778. pixelFormat.accumulationBufferAlphaBits);
  227779. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  227780. attribs[n++] = NSOpenGLPFASampleBuffers;
  227781. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  227782. attribs[n++] = NSOpenGLPFAClosestPolicy;
  227783. attribs[n++] = NSOpenGLPFANoRecovery;
  227784. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  227785. NSOpenGLPixelFormat* format
  227786. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  227787. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227788. pixelFormat: format];
  227789. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  227790. shareContext: sharedContext] autorelease];
  227791. const GLint swapInterval = 1;
  227792. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  227793. [view setOpenGLContext: renderContext];
  227794. [format release];
  227795. viewHolder = new NSViewComponentInternal (view, component);
  227796. }
  227797. ~WindowedGLContext()
  227798. {
  227799. deleteContext();
  227800. viewHolder = 0;
  227801. }
  227802. void deleteContext()
  227803. {
  227804. makeInactive();
  227805. [renderContext clearDrawable];
  227806. [renderContext setView: nil];
  227807. [view setOpenGLContext: nil];
  227808. renderContext = nil;
  227809. }
  227810. bool makeActive() const throw()
  227811. {
  227812. jassert (renderContext != 0);
  227813. if ([renderContext view] != view)
  227814. [renderContext setView: view];
  227815. [view makeActive];
  227816. return isActive();
  227817. }
  227818. bool makeInactive() const throw()
  227819. {
  227820. [view makeInactive];
  227821. return true;
  227822. }
  227823. bool isActive() const throw()
  227824. {
  227825. return [NSOpenGLContext currentContext] == renderContext;
  227826. }
  227827. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227828. void* getRawContext() const throw() { return renderContext; }
  227829. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227830. {
  227831. }
  227832. void swapBuffers()
  227833. {
  227834. [renderContext flushBuffer];
  227835. }
  227836. bool setSwapInterval (const int numFramesPerSwap)
  227837. {
  227838. [renderContext setValues: (const GLint*) &numFramesPerSwap
  227839. forParameter: NSOpenGLCPSwapInterval];
  227840. return true;
  227841. }
  227842. int getSwapInterval() const
  227843. {
  227844. GLint numFrames = 0;
  227845. [renderContext getValues: &numFrames
  227846. forParameter: NSOpenGLCPSwapInterval];
  227847. return numFrames;
  227848. }
  227849. void repaint()
  227850. {
  227851. // we need to invalidate the juce view that holds this gl view, to make it
  227852. // cause a repaint callback
  227853. NSView* v = (NSView*) viewHolder->view;
  227854. NSRect r = [v frame];
  227855. // bit of a bodge here.. if we only invalidate the area of the gl component,
  227856. // it's completely covered by the NSOpenGLView, so the OS throws away the
  227857. // repaint message, thus never causing our paint() callback, and never repainting
  227858. // the comp. So invalidating just a little bit around the edge helps..
  227859. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  227860. }
  227861. void* getNativeWindowHandle() const { return viewHolder->view; }
  227862. NSOpenGLContext* renderContext;
  227863. ThreadSafeNSOpenGLView* view;
  227864. private:
  227865. OpenGLPixelFormat pixelFormat;
  227866. ScopedPointer <NSViewComponentInternal> viewHolder;
  227867. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  227868. };
  227869. OpenGLContext* OpenGLComponent::createContext()
  227870. {
  227871. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  227872. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227873. return (c->renderContext != 0) ? c.release() : 0;
  227874. }
  227875. void* OpenGLComponent::getNativeWindowHandle() const
  227876. {
  227877. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227878. : 0;
  227879. }
  227880. void juce_glViewport (const int w, const int h)
  227881. {
  227882. glViewport (0, 0, w, h);
  227883. }
  227884. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227885. OwnedArray <OpenGLPixelFormat>& results)
  227886. {
  227887. /* GLint attribs [64];
  227888. int n = 0;
  227889. attribs[n++] = AGL_RGBA;
  227890. attribs[n++] = AGL_DOUBLEBUFFER;
  227891. attribs[n++] = AGL_ACCELERATED;
  227892. attribs[n++] = AGL_NO_RECOVERY;
  227893. attribs[n++] = AGL_NONE;
  227894. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227895. while (p != 0)
  227896. {
  227897. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227898. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227899. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227900. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227901. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227902. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227903. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227904. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227905. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227906. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227907. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227908. results.add (pf);
  227909. p = aglNextPixelFormat (p);
  227910. }*/
  227911. //jassertfalse // can't see how you do this in cocoa!
  227912. }
  227913. #else
  227914. END_JUCE_NAMESPACE
  227915. @interface JuceGLView : UIView
  227916. {
  227917. }
  227918. + (Class) layerClass;
  227919. @end
  227920. @implementation JuceGLView
  227921. + (Class) layerClass
  227922. {
  227923. return [CAEAGLLayer class];
  227924. }
  227925. @end
  227926. BEGIN_JUCE_NAMESPACE
  227927. class GLESContext : public OpenGLContext
  227928. {
  227929. public:
  227930. GLESContext (UIViewComponentPeer* peer,
  227931. Component* const component_,
  227932. const OpenGLPixelFormat& pixelFormat_,
  227933. const GLESContext* const sharedContext,
  227934. NSUInteger apiType)
  227935. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227936. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227937. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227938. {
  227939. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227940. view.opaque = YES;
  227941. view.hidden = NO;
  227942. view.backgroundColor = [UIColor blackColor];
  227943. view.userInteractionEnabled = NO;
  227944. glLayer = (CAEAGLLayer*) [view layer];
  227945. [peer->view addSubview: view];
  227946. if (sharedContext != 0)
  227947. context = [[EAGLContext alloc] initWithAPI: apiType
  227948. sharegroup: [sharedContext->context sharegroup]];
  227949. else
  227950. context = [[EAGLContext alloc] initWithAPI: apiType];
  227951. createGLBuffers();
  227952. }
  227953. ~GLESContext()
  227954. {
  227955. deleteContext();
  227956. [view removeFromSuperview];
  227957. [view release];
  227958. freeGLBuffers();
  227959. }
  227960. void deleteContext()
  227961. {
  227962. makeInactive();
  227963. [context release];
  227964. context = nil;
  227965. }
  227966. bool makeActive() const throw()
  227967. {
  227968. jassert (context != 0);
  227969. [EAGLContext setCurrentContext: context];
  227970. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227971. return true;
  227972. }
  227973. void swapBuffers()
  227974. {
  227975. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227976. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227977. }
  227978. bool makeInactive() const throw()
  227979. {
  227980. return [EAGLContext setCurrentContext: nil];
  227981. }
  227982. bool isActive() const throw()
  227983. {
  227984. return [EAGLContext currentContext] == context;
  227985. }
  227986. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227987. void* getRawContext() const throw() { return glLayer; }
  227988. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227989. {
  227990. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  227991. if (lastWidth != w || lastHeight != h)
  227992. {
  227993. lastWidth = w;
  227994. lastHeight = h;
  227995. freeGLBuffers();
  227996. createGLBuffers();
  227997. }
  227998. }
  227999. bool setSwapInterval (const int numFramesPerSwap)
  228000. {
  228001. numFrames = numFramesPerSwap;
  228002. return true;
  228003. }
  228004. int getSwapInterval() const
  228005. {
  228006. return numFrames;
  228007. }
  228008. void repaint()
  228009. {
  228010. }
  228011. void createGLBuffers()
  228012. {
  228013. makeActive();
  228014. glGenFramebuffersOES (1, &frameBufferHandle);
  228015. glGenRenderbuffersOES (1, &colorBufferHandle);
  228016. glGenRenderbuffersOES (1, &depthBufferHandle);
  228017. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228018. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228019. GLint width, height;
  228020. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228021. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228022. if (useDepthBuffer)
  228023. {
  228024. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228025. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228026. }
  228027. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228028. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228029. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228030. if (useDepthBuffer)
  228031. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228032. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228033. }
  228034. void freeGLBuffers()
  228035. {
  228036. if (frameBufferHandle != 0)
  228037. {
  228038. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228039. frameBufferHandle = 0;
  228040. }
  228041. if (colorBufferHandle != 0)
  228042. {
  228043. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228044. colorBufferHandle = 0;
  228045. }
  228046. if (depthBufferHandle != 0)
  228047. {
  228048. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228049. depthBufferHandle = 0;
  228050. }
  228051. }
  228052. private:
  228053. WeakReference<Component> component;
  228054. OpenGLPixelFormat pixelFormat;
  228055. JuceGLView* view;
  228056. CAEAGLLayer* glLayer;
  228057. EAGLContext* context;
  228058. bool useDepthBuffer;
  228059. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228060. int numFrames;
  228061. int lastWidth, lastHeight;
  228062. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  228063. };
  228064. OpenGLContext* OpenGLComponent::createContext()
  228065. {
  228066. ScopedAutoReleasePool pool;
  228067. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228068. if (peer != 0)
  228069. return new GLESContext (peer, this, preferredPixelFormat,
  228070. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228071. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228072. return 0;
  228073. }
  228074. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228075. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228076. {
  228077. }
  228078. void juce_glViewport (const int w, const int h)
  228079. {
  228080. glViewport (0, 0, w, h);
  228081. }
  228082. #endif
  228083. #endif
  228084. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228085. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228086. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228087. // compiled on its own).
  228088. #if JUCE_INCLUDED_FILE
  228089. #if JUCE_MAC
  228090. namespace MouseCursorHelpers
  228091. {
  228092. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228093. {
  228094. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228095. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228096. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228097. [im release];
  228098. return c;
  228099. }
  228100. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228101. {
  228102. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228103. BufferedInputStream buf (fileStream, 4096);
  228104. PNGImageFormat pngFormat;
  228105. Image im (pngFormat.decodeImage (buf));
  228106. if (im.isValid())
  228107. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228108. jassertfalse;
  228109. return 0;
  228110. }
  228111. }
  228112. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228113. {
  228114. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228115. }
  228116. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228117. {
  228118. const ScopedAutoReleasePool pool;
  228119. NSCursor* c = 0;
  228120. switch (type)
  228121. {
  228122. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228123. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228124. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228125. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228126. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228127. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228128. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228129. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228130. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228131. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228132. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228133. case UpDownResizeCursor:
  228134. case TopEdgeResizeCursor:
  228135. case BottomEdgeResizeCursor:
  228136. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228137. case TopLeftCornerResizeCursor:
  228138. case BottomRightCornerResizeCursor:
  228139. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228140. case TopRightCornerResizeCursor:
  228141. case BottomLeftCornerResizeCursor:
  228142. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228143. case UpDownLeftRightResizeCursor:
  228144. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228145. default:
  228146. jassertfalse;
  228147. break;
  228148. }
  228149. [c retain];
  228150. return c;
  228151. }
  228152. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228153. {
  228154. [((NSCursor*) cursorHandle) release];
  228155. }
  228156. void MouseCursor::showInAllWindows() const
  228157. {
  228158. showInWindow (0);
  228159. }
  228160. void MouseCursor::showInWindow (ComponentPeer*) const
  228161. {
  228162. NSCursor* c = (NSCursor*) getHandle();
  228163. if (c == 0)
  228164. c = [NSCursor arrowCursor];
  228165. [c set];
  228166. }
  228167. #else
  228168. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228169. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228170. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228171. void MouseCursor::showInAllWindows() const {}
  228172. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228173. #endif
  228174. #endif
  228175. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228176. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228177. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228178. // compiled on its own).
  228179. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228180. #if JUCE_MAC
  228181. END_JUCE_NAMESPACE
  228182. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228183. @interface DownloadClickDetector : NSObject
  228184. {
  228185. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228186. }
  228187. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228188. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228189. request: (NSURLRequest*) request
  228190. frame: (WebFrame*) frame
  228191. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228192. @end
  228193. @implementation DownloadClickDetector
  228194. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228195. {
  228196. [super init];
  228197. ownerComponent = ownerComponent_;
  228198. return self;
  228199. }
  228200. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228201. request: (NSURLRequest*) request
  228202. frame: (WebFrame*) frame
  228203. decisionListener: (id <WebPolicyDecisionListener>) listener
  228204. {
  228205. (void) sender;
  228206. (void) request;
  228207. (void) frame;
  228208. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228209. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228210. [listener use];
  228211. else
  228212. [listener ignore];
  228213. }
  228214. @end
  228215. BEGIN_JUCE_NAMESPACE
  228216. class WebBrowserComponentInternal : public NSViewComponent
  228217. {
  228218. public:
  228219. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228220. {
  228221. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228222. frameName: @""
  228223. groupName: @""];
  228224. setView (webView);
  228225. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228226. [webView setPolicyDelegate: clickListener];
  228227. }
  228228. ~WebBrowserComponentInternal()
  228229. {
  228230. [webView setPolicyDelegate: nil];
  228231. [clickListener release];
  228232. setView (0);
  228233. }
  228234. void goToURL (const String& url,
  228235. const StringArray* headers,
  228236. const MemoryBlock* postData)
  228237. {
  228238. NSMutableURLRequest* r
  228239. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228240. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228241. timeoutInterval: 30.0];
  228242. if (postData != 0 && postData->getSize() > 0)
  228243. {
  228244. [r setHTTPMethod: @"POST"];
  228245. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228246. length: postData->getSize()]];
  228247. }
  228248. if (headers != 0)
  228249. {
  228250. for (int i = 0; i < headers->size(); ++i)
  228251. {
  228252. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228253. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228254. [r setValue: juceStringToNS (headerValue)
  228255. forHTTPHeaderField: juceStringToNS (headerName)];
  228256. }
  228257. }
  228258. stop();
  228259. [[webView mainFrame] loadRequest: r];
  228260. }
  228261. void goBack()
  228262. {
  228263. [webView goBack];
  228264. }
  228265. void goForward()
  228266. {
  228267. [webView goForward];
  228268. }
  228269. void stop()
  228270. {
  228271. [webView stopLoading: nil];
  228272. }
  228273. void refresh()
  228274. {
  228275. [webView reload: nil];
  228276. }
  228277. void mouseMove (const MouseEvent&)
  228278. {
  228279. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228280. // them work is to push them via this non-public method..
  228281. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228282. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228283. }
  228284. private:
  228285. WebView* webView;
  228286. DownloadClickDetector* clickListener;
  228287. };
  228288. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228289. : browser (0),
  228290. blankPageShown (false),
  228291. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228292. {
  228293. setOpaque (true);
  228294. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228295. }
  228296. WebBrowserComponent::~WebBrowserComponent()
  228297. {
  228298. deleteAndZero (browser);
  228299. }
  228300. void WebBrowserComponent::goToURL (const String& url,
  228301. const StringArray* headers,
  228302. const MemoryBlock* postData)
  228303. {
  228304. lastURL = url;
  228305. lastHeaders.clear();
  228306. if (headers != 0)
  228307. lastHeaders = *headers;
  228308. lastPostData.setSize (0);
  228309. if (postData != 0)
  228310. lastPostData = *postData;
  228311. blankPageShown = false;
  228312. browser->goToURL (url, headers, postData);
  228313. }
  228314. void WebBrowserComponent::stop()
  228315. {
  228316. browser->stop();
  228317. }
  228318. void WebBrowserComponent::goBack()
  228319. {
  228320. lastURL = String::empty;
  228321. blankPageShown = false;
  228322. browser->goBack();
  228323. }
  228324. void WebBrowserComponent::goForward()
  228325. {
  228326. lastURL = String::empty;
  228327. browser->goForward();
  228328. }
  228329. void WebBrowserComponent::refresh()
  228330. {
  228331. browser->refresh();
  228332. }
  228333. void WebBrowserComponent::paint (Graphics&)
  228334. {
  228335. }
  228336. void WebBrowserComponent::checkWindowAssociation()
  228337. {
  228338. if (isShowing())
  228339. {
  228340. if (blankPageShown)
  228341. goBack();
  228342. }
  228343. else
  228344. {
  228345. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228346. {
  228347. // when the component becomes invisible, some stuff like flash
  228348. // carries on playing audio, so we need to force it onto a blank
  228349. // page to avoid this, (and send it back when it's made visible again).
  228350. blankPageShown = true;
  228351. browser->goToURL ("about:blank", 0, 0);
  228352. }
  228353. }
  228354. }
  228355. void WebBrowserComponent::reloadLastURL()
  228356. {
  228357. if (lastURL.isNotEmpty())
  228358. {
  228359. goToURL (lastURL, &lastHeaders, &lastPostData);
  228360. lastURL = String::empty;
  228361. }
  228362. }
  228363. void WebBrowserComponent::parentHierarchyChanged()
  228364. {
  228365. checkWindowAssociation();
  228366. }
  228367. void WebBrowserComponent::resized()
  228368. {
  228369. browser->setSize (getWidth(), getHeight());
  228370. }
  228371. void WebBrowserComponent::visibilityChanged()
  228372. {
  228373. checkWindowAssociation();
  228374. }
  228375. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228376. {
  228377. return true;
  228378. }
  228379. #else
  228380. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228381. {
  228382. }
  228383. WebBrowserComponent::~WebBrowserComponent()
  228384. {
  228385. }
  228386. void WebBrowserComponent::goToURL (const String& url,
  228387. const StringArray* headers,
  228388. const MemoryBlock* postData)
  228389. {
  228390. }
  228391. void WebBrowserComponent::stop()
  228392. {
  228393. }
  228394. void WebBrowserComponent::goBack()
  228395. {
  228396. }
  228397. void WebBrowserComponent::goForward()
  228398. {
  228399. }
  228400. void WebBrowserComponent::refresh()
  228401. {
  228402. }
  228403. void WebBrowserComponent::paint (Graphics& g)
  228404. {
  228405. }
  228406. void WebBrowserComponent::checkWindowAssociation()
  228407. {
  228408. }
  228409. void WebBrowserComponent::reloadLastURL()
  228410. {
  228411. }
  228412. void WebBrowserComponent::parentHierarchyChanged()
  228413. {
  228414. }
  228415. void WebBrowserComponent::resized()
  228416. {
  228417. }
  228418. void WebBrowserComponent::visibilityChanged()
  228419. {
  228420. }
  228421. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228422. {
  228423. return true;
  228424. }
  228425. #endif
  228426. #endif
  228427. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228428. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228429. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228430. // compiled on its own).
  228431. #if JUCE_INCLUDED_FILE
  228432. class IPhoneAudioIODevice : public AudioIODevice
  228433. {
  228434. public:
  228435. IPhoneAudioIODevice (const String& deviceName)
  228436. : AudioIODevice (deviceName, "Audio"),
  228437. actualBufferSize (0),
  228438. isRunning (false),
  228439. audioUnit (0),
  228440. callback (0),
  228441. floatData (1, 2)
  228442. {
  228443. numInputChannels = 2;
  228444. numOutputChannels = 2;
  228445. preferredBufferSize = 0;
  228446. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228447. updateDeviceInfo();
  228448. }
  228449. ~IPhoneAudioIODevice()
  228450. {
  228451. close();
  228452. }
  228453. const StringArray getOutputChannelNames()
  228454. {
  228455. StringArray s;
  228456. s.add ("Left");
  228457. s.add ("Right");
  228458. return s;
  228459. }
  228460. const StringArray getInputChannelNames()
  228461. {
  228462. StringArray s;
  228463. if (audioInputIsAvailable)
  228464. {
  228465. s.add ("Left");
  228466. s.add ("Right");
  228467. }
  228468. return s;
  228469. }
  228470. int getNumSampleRates()
  228471. {
  228472. return 1;
  228473. }
  228474. double getSampleRate (int index)
  228475. {
  228476. return sampleRate;
  228477. }
  228478. int getNumBufferSizesAvailable()
  228479. {
  228480. return 1;
  228481. }
  228482. int getBufferSizeSamples (int index)
  228483. {
  228484. return getDefaultBufferSize();
  228485. }
  228486. int getDefaultBufferSize()
  228487. {
  228488. return 1024;
  228489. }
  228490. const String open (const BigInteger& inputChannels,
  228491. const BigInteger& outputChannels,
  228492. double sampleRate,
  228493. int bufferSize)
  228494. {
  228495. close();
  228496. lastError = String::empty;
  228497. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228498. // xxx set up channel mapping
  228499. activeOutputChans = outputChannels;
  228500. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228501. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228502. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228503. activeInputChans = inputChannels;
  228504. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228505. numInputChannels = activeInputChans.countNumberOfSetBits();
  228506. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228507. AudioSessionSetActive (true);
  228508. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228509. : kAudioSessionCategory_MediaPlayback;
  228510. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228511. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228512. fixAudioRouteIfSetToReceiver();
  228513. updateDeviceInfo();
  228514. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228515. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228516. actualBufferSize = preferredBufferSize;
  228517. prepareFloatBuffers();
  228518. isRunning = true;
  228519. propertyChanged (0, 0, 0); // creates and starts the AU
  228520. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228521. return lastError;
  228522. }
  228523. void close()
  228524. {
  228525. if (isRunning)
  228526. {
  228527. isRunning = false;
  228528. AudioSessionSetActive (false);
  228529. if (audioUnit != 0)
  228530. {
  228531. AudioComponentInstanceDispose (audioUnit);
  228532. audioUnit = 0;
  228533. }
  228534. }
  228535. }
  228536. bool isOpen()
  228537. {
  228538. return isRunning;
  228539. }
  228540. int getCurrentBufferSizeSamples()
  228541. {
  228542. return actualBufferSize;
  228543. }
  228544. double getCurrentSampleRate()
  228545. {
  228546. return sampleRate;
  228547. }
  228548. int getCurrentBitDepth()
  228549. {
  228550. return 16;
  228551. }
  228552. const BigInteger getActiveOutputChannels() const
  228553. {
  228554. return activeOutputChans;
  228555. }
  228556. const BigInteger getActiveInputChannels() const
  228557. {
  228558. return activeInputChans;
  228559. }
  228560. int getOutputLatencyInSamples()
  228561. {
  228562. return 0; //xxx
  228563. }
  228564. int getInputLatencyInSamples()
  228565. {
  228566. return 0; //xxx
  228567. }
  228568. void start (AudioIODeviceCallback* callback_)
  228569. {
  228570. if (isRunning && callback != callback_)
  228571. {
  228572. if (callback_ != 0)
  228573. callback_->audioDeviceAboutToStart (this);
  228574. const ScopedLock sl (callbackLock);
  228575. callback = callback_;
  228576. }
  228577. }
  228578. void stop()
  228579. {
  228580. if (isRunning)
  228581. {
  228582. AudioIODeviceCallback* lastCallback;
  228583. {
  228584. const ScopedLock sl (callbackLock);
  228585. lastCallback = callback;
  228586. callback = 0;
  228587. }
  228588. if (lastCallback != 0)
  228589. lastCallback->audioDeviceStopped();
  228590. }
  228591. }
  228592. bool isPlaying()
  228593. {
  228594. return isRunning && callback != 0;
  228595. }
  228596. const String getLastError()
  228597. {
  228598. return lastError;
  228599. }
  228600. private:
  228601. CriticalSection callbackLock;
  228602. Float64 sampleRate;
  228603. int numInputChannels, numOutputChannels;
  228604. int preferredBufferSize;
  228605. int actualBufferSize;
  228606. bool isRunning;
  228607. String lastError;
  228608. AudioStreamBasicDescription format;
  228609. AudioUnit audioUnit;
  228610. UInt32 audioInputIsAvailable;
  228611. AudioIODeviceCallback* callback;
  228612. BigInteger activeOutputChans, activeInputChans;
  228613. AudioSampleBuffer floatData;
  228614. float* inputChannels[3];
  228615. float* outputChannels[3];
  228616. bool monoInputChannelNumber, monoOutputChannelNumber;
  228617. void prepareFloatBuffers()
  228618. {
  228619. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228620. zerostruct (inputChannels);
  228621. zerostruct (outputChannels);
  228622. for (int i = 0; i < numInputChannels; ++i)
  228623. inputChannels[i] = floatData.getSampleData (i);
  228624. for (int i = 0; i < numOutputChannels; ++i)
  228625. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228626. }
  228627. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228628. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228629. {
  228630. OSStatus err = noErr;
  228631. if (audioInputIsAvailable)
  228632. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  228633. const ScopedLock sl (callbackLock);
  228634. if (callback != 0)
  228635. {
  228636. if (audioInputIsAvailable && numInputChannels > 0)
  228637. {
  228638. short* shortData = (short*) ioData->mBuffers[0].mData;
  228639. if (numInputChannels >= 2)
  228640. {
  228641. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228642. {
  228643. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228644. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  228645. }
  228646. }
  228647. else
  228648. {
  228649. if (monoInputChannelNumber > 0)
  228650. ++shortData;
  228651. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228652. {
  228653. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228654. ++shortData;
  228655. }
  228656. }
  228657. }
  228658. else
  228659. {
  228660. for (int i = numInputChannels; --i >= 0;)
  228661. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  228662. }
  228663. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  228664. outputChannels, numOutputChannels,
  228665. (int) inNumberFrames);
  228666. short* shortData = (short*) ioData->mBuffers[0].mData;
  228667. int n = 0;
  228668. if (numOutputChannels >= 2)
  228669. {
  228670. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228671. {
  228672. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  228673. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  228674. }
  228675. }
  228676. else if (numOutputChannels == 1)
  228677. {
  228678. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228679. {
  228680. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  228681. shortData [n++] = s;
  228682. shortData [n++] = s;
  228683. }
  228684. }
  228685. else
  228686. {
  228687. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228688. }
  228689. }
  228690. else
  228691. {
  228692. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228693. }
  228694. return err;
  228695. }
  228696. void updateDeviceInfo()
  228697. {
  228698. UInt32 size = sizeof (sampleRate);
  228699. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  228700. size = sizeof (audioInputIsAvailable);
  228701. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  228702. }
  228703. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228704. {
  228705. if (! isRunning)
  228706. return;
  228707. if (inPropertyValue != 0)
  228708. {
  228709. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  228710. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  228711. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  228712. SInt32 routeChangeReason;
  228713. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  228714. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  228715. fixAudioRouteIfSetToReceiver();
  228716. }
  228717. updateDeviceInfo();
  228718. createAudioUnit();
  228719. AudioSessionSetActive (true);
  228720. if (audioUnit != 0)
  228721. {
  228722. UInt32 formatSize = sizeof (format);
  228723. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  228724. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228725. UInt32 bufferDurationSize = sizeof (bufferDuration);
  228726. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  228727. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  228728. AudioOutputUnitStart (audioUnit);
  228729. }
  228730. }
  228731. void interruptionListener (UInt32 inInterruption)
  228732. {
  228733. /*if (inInterruption == kAudioSessionBeginInterruption)
  228734. {
  228735. isRunning = false;
  228736. AudioOutputUnitStop (audioUnit);
  228737. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  228738. "This could have been interrupted by another application or by unplugging a headset",
  228739. @"Resume",
  228740. @"Cancel"))
  228741. {
  228742. isRunning = true;
  228743. propertyChanged (0, 0, 0);
  228744. }
  228745. }*/
  228746. if (inInterruption == kAudioSessionEndInterruption)
  228747. {
  228748. isRunning = true;
  228749. AudioSessionSetActive (true);
  228750. AudioOutputUnitStart (audioUnit);
  228751. }
  228752. }
  228753. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228754. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228755. {
  228756. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  228757. }
  228758. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228759. {
  228760. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  228761. }
  228762. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  228763. {
  228764. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  228765. }
  228766. void resetFormat (const int numChannels)
  228767. {
  228768. memset (&format, 0, sizeof (format));
  228769. format.mFormatID = kAudioFormatLinearPCM;
  228770. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  228771. format.mBitsPerChannel = 8 * sizeof (short);
  228772. format.mChannelsPerFrame = 2;
  228773. format.mFramesPerPacket = 1;
  228774. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  228775. }
  228776. bool createAudioUnit()
  228777. {
  228778. if (audioUnit != 0)
  228779. {
  228780. AudioComponentInstanceDispose (audioUnit);
  228781. audioUnit = 0;
  228782. }
  228783. resetFormat (2);
  228784. AudioComponentDescription desc;
  228785. desc.componentType = kAudioUnitType_Output;
  228786. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  228787. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  228788. desc.componentFlags = 0;
  228789. desc.componentFlagsMask = 0;
  228790. AudioComponent comp = AudioComponentFindNext (0, &desc);
  228791. AudioComponentInstanceNew (comp, &audioUnit);
  228792. if (audioUnit == 0)
  228793. return false;
  228794. const UInt32 one = 1;
  228795. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  228796. AudioChannelLayout layout;
  228797. layout.mChannelBitmap = 0;
  228798. layout.mNumberChannelDescriptions = 0;
  228799. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  228800. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  228801. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  228802. AURenderCallbackStruct inputProc;
  228803. inputProc.inputProc = processStatic;
  228804. inputProc.inputProcRefCon = this;
  228805. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  228806. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  228807. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  228808. AudioUnitInitialize (audioUnit);
  228809. return true;
  228810. }
  228811. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  228812. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  228813. static void fixAudioRouteIfSetToReceiver()
  228814. {
  228815. CFStringRef audioRoute = 0;
  228816. UInt32 propertySize = sizeof (audioRoute);
  228817. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  228818. {
  228819. NSString* route = (NSString*) audioRoute;
  228820. //DBG ("audio route: " + nsStringToJuce (route));
  228821. if ([route hasPrefix: @"Receiver"])
  228822. {
  228823. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  228824. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  228825. }
  228826. CFRelease (audioRoute);
  228827. }
  228828. }
  228829. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  228830. };
  228831. class IPhoneAudioIODeviceType : public AudioIODeviceType
  228832. {
  228833. public:
  228834. IPhoneAudioIODeviceType()
  228835. : AudioIODeviceType ("iPhone Audio")
  228836. {
  228837. }
  228838. void scanForDevices()
  228839. {
  228840. }
  228841. const StringArray getDeviceNames (bool wantInputNames) const
  228842. {
  228843. StringArray s;
  228844. s.add ("iPhone Audio");
  228845. return s;
  228846. }
  228847. int getDefaultDeviceIndex (bool forInput) const
  228848. {
  228849. return 0;
  228850. }
  228851. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  228852. {
  228853. return device != 0 ? 0 : -1;
  228854. }
  228855. bool hasSeparateInputsAndOutputs() const { return false; }
  228856. AudioIODevice* createDevice (const String& outputDeviceName,
  228857. const String& inputDeviceName)
  228858. {
  228859. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  228860. {
  228861. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  228862. : inputDeviceName);
  228863. }
  228864. return 0;
  228865. }
  228866. private:
  228867. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  228868. };
  228869. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228870. {
  228871. return new IPhoneAudioIODeviceType();
  228872. }
  228873. #endif
  228874. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  228875. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228876. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228877. // compiled on its own).
  228878. #if JUCE_INCLUDED_FILE
  228879. #if JUCE_MAC
  228880. namespace CoreMidiHelpers
  228881. {
  228882. bool logError (const OSStatus err, const int lineNum)
  228883. {
  228884. if (err == noErr)
  228885. return true;
  228886. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228887. jassertfalse;
  228888. return false;
  228889. }
  228890. #undef CHECK_ERROR
  228891. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  228892. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228893. {
  228894. String result;
  228895. CFStringRef str = 0;
  228896. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228897. if (str != 0)
  228898. {
  228899. result = PlatformUtilities::cfStringToJuceString (str);
  228900. CFRelease (str);
  228901. str = 0;
  228902. }
  228903. MIDIEntityRef entity = 0;
  228904. MIDIEndpointGetEntity (endpoint, &entity);
  228905. if (entity == 0)
  228906. return result; // probably virtual
  228907. if (result.isEmpty())
  228908. {
  228909. // endpoint name has zero length - try the entity
  228910. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228911. if (str != 0)
  228912. {
  228913. result += PlatformUtilities::cfStringToJuceString (str);
  228914. CFRelease (str);
  228915. str = 0;
  228916. }
  228917. }
  228918. // now consider the device's name
  228919. MIDIDeviceRef device = 0;
  228920. MIDIEntityGetDevice (entity, &device);
  228921. if (device == 0)
  228922. return result;
  228923. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228924. if (str != 0)
  228925. {
  228926. const String s (PlatformUtilities::cfStringToJuceString (str));
  228927. CFRelease (str);
  228928. // if an external device has only one entity, throw away
  228929. // the endpoint name and just use the device name
  228930. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228931. {
  228932. result = s;
  228933. }
  228934. else if (! result.startsWithIgnoreCase (s))
  228935. {
  228936. // prepend the device name to the entity name
  228937. result = (s + " " + result).trimEnd();
  228938. }
  228939. }
  228940. return result;
  228941. }
  228942. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228943. {
  228944. String result;
  228945. // Does the endpoint have connections?
  228946. CFDataRef connections = 0;
  228947. int numConnections = 0;
  228948. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228949. if (connections != 0)
  228950. {
  228951. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228952. if (numConnections > 0)
  228953. {
  228954. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228955. for (int i = 0; i < numConnections; ++i, ++pid)
  228956. {
  228957. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228958. MIDIObjectRef connObject;
  228959. MIDIObjectType connObjectType;
  228960. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228961. if (err == noErr)
  228962. {
  228963. String s;
  228964. if (connObjectType == kMIDIObjectType_ExternalSource
  228965. || connObjectType == kMIDIObjectType_ExternalDestination)
  228966. {
  228967. // Connected to an external device's endpoint (10.3 and later).
  228968. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228969. }
  228970. else
  228971. {
  228972. // Connected to an external device (10.2) (or something else, catch-all)
  228973. CFStringRef str = 0;
  228974. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228975. if (str != 0)
  228976. {
  228977. s = PlatformUtilities::cfStringToJuceString (str);
  228978. CFRelease (str);
  228979. }
  228980. }
  228981. if (s.isNotEmpty())
  228982. {
  228983. if (result.isNotEmpty())
  228984. result += ", ";
  228985. result += s;
  228986. }
  228987. }
  228988. }
  228989. }
  228990. CFRelease (connections);
  228991. }
  228992. if (result.isNotEmpty())
  228993. return result;
  228994. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228995. return getEndpointName (endpoint, false);
  228996. }
  228997. MIDIClientRef getGlobalMidiClient()
  228998. {
  228999. static MIDIClientRef globalMidiClient = 0;
  229000. if (globalMidiClient == 0)
  229001. {
  229002. String name ("JUCE");
  229003. if (JUCEApplication::getInstance() != 0)
  229004. name = JUCEApplication::getInstance()->getApplicationName();
  229005. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229006. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229007. CFRelease (appName);
  229008. }
  229009. return globalMidiClient;
  229010. }
  229011. class MidiPortAndEndpoint
  229012. {
  229013. public:
  229014. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229015. : port (port_), endPoint (endPoint_)
  229016. {
  229017. }
  229018. ~MidiPortAndEndpoint()
  229019. {
  229020. if (port != 0)
  229021. MIDIPortDispose (port);
  229022. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229023. MIDIEndpointDispose (endPoint);
  229024. }
  229025. void send (const MIDIPacketList* const packets)
  229026. {
  229027. if (port != 0)
  229028. MIDISend (port, endPoint, packets);
  229029. else
  229030. MIDIReceived (endPoint, packets);
  229031. }
  229032. MIDIPortRef port;
  229033. MIDIEndpointRef endPoint;
  229034. };
  229035. class MidiPortAndCallback;
  229036. CriticalSection callbackLock;
  229037. Array<MidiPortAndCallback*> activeCallbacks;
  229038. class MidiPortAndCallback
  229039. {
  229040. public:
  229041. MidiPortAndCallback (MidiInputCallback& callback_)
  229042. : input (0), active (false), callback (callback_), concatenator (2048)
  229043. {
  229044. }
  229045. ~MidiPortAndCallback()
  229046. {
  229047. active = false;
  229048. {
  229049. const ScopedLock sl (callbackLock);
  229050. activeCallbacks.removeValue (this);
  229051. }
  229052. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229053. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229054. }
  229055. void handlePackets (const MIDIPacketList* const pktlist)
  229056. {
  229057. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229058. const ScopedLock sl (callbackLock);
  229059. if (activeCallbacks.contains (this) && active)
  229060. {
  229061. const MIDIPacket* packet = &pktlist->packet[0];
  229062. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229063. {
  229064. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229065. input, callback);
  229066. packet = MIDIPacketNext (packet);
  229067. }
  229068. }
  229069. }
  229070. MidiInput* input;
  229071. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229072. volatile bool active;
  229073. private:
  229074. MidiInputCallback& callback;
  229075. MidiDataConcatenator concatenator;
  229076. };
  229077. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229078. {
  229079. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229080. }
  229081. }
  229082. const StringArray MidiOutput::getDevices()
  229083. {
  229084. StringArray s;
  229085. const ItemCount num = MIDIGetNumberOfDestinations();
  229086. for (ItemCount i = 0; i < num; ++i)
  229087. {
  229088. MIDIEndpointRef dest = MIDIGetDestination (i);
  229089. if (dest != 0)
  229090. {
  229091. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229092. if (name.isEmpty())
  229093. name = "<error>";
  229094. s.add (name);
  229095. }
  229096. else
  229097. {
  229098. s.add ("<error>");
  229099. }
  229100. }
  229101. return s;
  229102. }
  229103. int MidiOutput::getDefaultDeviceIndex()
  229104. {
  229105. return 0;
  229106. }
  229107. MidiOutput* MidiOutput::openDevice (int index)
  229108. {
  229109. MidiOutput* mo = 0;
  229110. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  229111. {
  229112. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229113. CFStringRef pname;
  229114. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229115. {
  229116. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229117. MIDIPortRef port;
  229118. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229119. {
  229120. mo = new MidiOutput();
  229121. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229122. }
  229123. CFRelease (pname);
  229124. }
  229125. }
  229126. return mo;
  229127. }
  229128. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229129. {
  229130. MidiOutput* mo = 0;
  229131. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229132. MIDIEndpointRef endPoint;
  229133. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229134. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229135. {
  229136. mo = new MidiOutput();
  229137. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229138. }
  229139. CFRelease (name);
  229140. return mo;
  229141. }
  229142. MidiOutput::~MidiOutput()
  229143. {
  229144. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229145. }
  229146. void MidiOutput::reset()
  229147. {
  229148. }
  229149. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229150. {
  229151. return false;
  229152. }
  229153. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229154. {
  229155. }
  229156. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229157. {
  229158. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229159. if (message.isSysEx())
  229160. {
  229161. const int maxPacketSize = 256;
  229162. int pos = 0, bytesLeft = message.getRawDataSize();
  229163. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229164. HeapBlock <MIDIPacketList> packets;
  229165. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229166. packets->numPackets = numPackets;
  229167. MIDIPacket* p = packets->packet;
  229168. for (int i = 0; i < numPackets; ++i)
  229169. {
  229170. p->timeStamp = 0;
  229171. p->length = jmin (maxPacketSize, bytesLeft);
  229172. memcpy (p->data, message.getRawData() + pos, p->length);
  229173. pos += p->length;
  229174. bytesLeft -= p->length;
  229175. p = MIDIPacketNext (p);
  229176. }
  229177. mpe->send (packets);
  229178. }
  229179. else
  229180. {
  229181. MIDIPacketList packets;
  229182. packets.numPackets = 1;
  229183. packets.packet[0].timeStamp = 0;
  229184. packets.packet[0].length = message.getRawDataSize();
  229185. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229186. mpe->send (&packets);
  229187. }
  229188. }
  229189. const StringArray MidiInput::getDevices()
  229190. {
  229191. StringArray s;
  229192. const ItemCount num = MIDIGetNumberOfSources();
  229193. for (ItemCount i = 0; i < num; ++i)
  229194. {
  229195. MIDIEndpointRef source = MIDIGetSource (i);
  229196. if (source != 0)
  229197. {
  229198. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229199. if (name.isEmpty())
  229200. name = "<error>";
  229201. s.add (name);
  229202. }
  229203. else
  229204. {
  229205. s.add ("<error>");
  229206. }
  229207. }
  229208. return s;
  229209. }
  229210. int MidiInput::getDefaultDeviceIndex()
  229211. {
  229212. return 0;
  229213. }
  229214. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229215. {
  229216. jassert (callback != 0);
  229217. using namespace CoreMidiHelpers;
  229218. MidiInput* newInput = 0;
  229219. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229220. {
  229221. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229222. if (endPoint != 0)
  229223. {
  229224. CFStringRef name;
  229225. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229226. {
  229227. MIDIClientRef client = getGlobalMidiClient();
  229228. if (client != 0)
  229229. {
  229230. MIDIPortRef port;
  229231. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229232. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229233. {
  229234. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229235. {
  229236. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229237. newInput = new MidiInput (getDevices() [index]);
  229238. mpc->input = newInput;
  229239. newInput->internal = mpc;
  229240. const ScopedLock sl (callbackLock);
  229241. activeCallbacks.add (mpc.release());
  229242. }
  229243. else
  229244. {
  229245. CHECK_ERROR (MIDIPortDispose (port));
  229246. }
  229247. }
  229248. }
  229249. }
  229250. CFRelease (name);
  229251. }
  229252. }
  229253. return newInput;
  229254. }
  229255. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229256. {
  229257. jassert (callback != 0);
  229258. using namespace CoreMidiHelpers;
  229259. MidiInput* mi = 0;
  229260. MIDIClientRef client = getGlobalMidiClient();
  229261. if (client != 0)
  229262. {
  229263. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229264. mpc->active = false;
  229265. MIDIEndpointRef endPoint;
  229266. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229267. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229268. {
  229269. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229270. mi = new MidiInput (deviceName);
  229271. mpc->input = mi;
  229272. mi->internal = mpc;
  229273. const ScopedLock sl (callbackLock);
  229274. activeCallbacks.add (mpc.release());
  229275. }
  229276. CFRelease (name);
  229277. }
  229278. return mi;
  229279. }
  229280. MidiInput::MidiInput (const String& name_)
  229281. : name (name_)
  229282. {
  229283. }
  229284. MidiInput::~MidiInput()
  229285. {
  229286. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229287. }
  229288. void MidiInput::start()
  229289. {
  229290. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229291. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229292. }
  229293. void MidiInput::stop()
  229294. {
  229295. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229296. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229297. }
  229298. #undef CHECK_ERROR
  229299. #else // Stubs for iOS...
  229300. MidiOutput::~MidiOutput() {}
  229301. void MidiOutput::reset() {}
  229302. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229303. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229304. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229305. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229306. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229307. const StringArray MidiInput::getDevices() { return StringArray(); }
  229308. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229309. #endif
  229310. #endif
  229311. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229312. #else
  229313. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229314. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229315. // compiled on its own).
  229316. #if JUCE_INCLUDED_FILE
  229317. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229318. #define SUPPORT_10_4_FONTS 1
  229319. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229320. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229321. #define SUPPORT_ONLY_10_4_FONTS 1
  229322. #endif
  229323. END_JUCE_NAMESPACE
  229324. @interface NSFont (PrivateHack)
  229325. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229326. @end
  229327. BEGIN_JUCE_NAMESPACE
  229328. #endif
  229329. class MacTypeface : public Typeface
  229330. {
  229331. public:
  229332. MacTypeface (const Font& font)
  229333. : Typeface (font.getTypefaceName())
  229334. {
  229335. const ScopedAutoReleasePool pool;
  229336. renderingTransform = CGAffineTransformIdentity;
  229337. bool needsItalicTransform = false;
  229338. #if JUCE_IOS
  229339. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229340. if (font.isItalic() || font.isBold())
  229341. {
  229342. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229343. for (NSString* i in familyFonts)
  229344. {
  229345. const String fn (nsStringToJuce (i));
  229346. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229347. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229348. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229349. || afterDash.containsIgnoreCase ("italic")
  229350. || fn.endsWithIgnoreCase ("oblique")
  229351. || fn.endsWithIgnoreCase ("italic");
  229352. if (probablyBold == font.isBold()
  229353. && probablyItalic == font.isItalic())
  229354. {
  229355. fontName = i;
  229356. needsItalicTransform = false;
  229357. break;
  229358. }
  229359. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229360. {
  229361. fontName = i;
  229362. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229363. }
  229364. }
  229365. if (needsItalicTransform)
  229366. renderingTransform.c = 0.15f;
  229367. }
  229368. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229369. const int ascender = abs (CGFontGetAscent (fontRef));
  229370. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229371. ascent = ascender / totalHeight;
  229372. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229373. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229374. #else
  229375. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229376. if (font.isItalic())
  229377. {
  229378. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229379. toHaveTrait: NSItalicFontMask];
  229380. if (newFont == nsFont)
  229381. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229382. nsFont = newFont;
  229383. }
  229384. if (font.isBold())
  229385. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229386. [nsFont retain];
  229387. ascent = std::abs ((float) [nsFont ascender]);
  229388. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229389. ascent /= totalSize;
  229390. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229391. if (needsItalicTransform)
  229392. {
  229393. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229394. renderingTransform.c = 0.15f;
  229395. }
  229396. #if SUPPORT_ONLY_10_4_FONTS
  229397. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229398. if (atsFont == 0)
  229399. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229400. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229401. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229402. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229403. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229404. #else
  229405. #if SUPPORT_10_4_FONTS
  229406. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229407. {
  229408. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229409. if (atsFont == 0)
  229410. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229411. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229412. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229413. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229414. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229415. }
  229416. else
  229417. #endif
  229418. {
  229419. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229420. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229421. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229422. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229423. }
  229424. #endif
  229425. #endif
  229426. }
  229427. ~MacTypeface()
  229428. {
  229429. #if ! JUCE_IOS
  229430. [nsFont release];
  229431. #endif
  229432. if (fontRef != 0)
  229433. CGFontRelease (fontRef);
  229434. }
  229435. float getAscent() const
  229436. {
  229437. return ascent;
  229438. }
  229439. float getDescent() const
  229440. {
  229441. return 1.0f - ascent;
  229442. }
  229443. float getStringWidth (const String& text)
  229444. {
  229445. if (fontRef == 0 || text.isEmpty())
  229446. return 0;
  229447. const int length = text.length();
  229448. HeapBlock <CGGlyph> glyphs;
  229449. createGlyphsForString (text, length, glyphs);
  229450. float x = 0;
  229451. #if SUPPORT_ONLY_10_4_FONTS
  229452. HeapBlock <NSSize> advances (length);
  229453. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229454. for (int i = 0; i < length; ++i)
  229455. x += advances[i].width;
  229456. #else
  229457. #if SUPPORT_10_4_FONTS
  229458. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229459. {
  229460. HeapBlock <NSSize> advances (length);
  229461. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229462. for (int i = 0; i < length; ++i)
  229463. x += advances[i].width;
  229464. }
  229465. else
  229466. #endif
  229467. {
  229468. HeapBlock <int> advances (length);
  229469. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229470. for (int i = 0; i < length; ++i)
  229471. x += advances[i];
  229472. }
  229473. #endif
  229474. return x * unitsToHeightScaleFactor;
  229475. }
  229476. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229477. {
  229478. xOffsets.add (0);
  229479. if (fontRef == 0 || text.isEmpty())
  229480. return;
  229481. const int length = text.length();
  229482. HeapBlock <CGGlyph> glyphs;
  229483. createGlyphsForString (text, length, glyphs);
  229484. #if SUPPORT_ONLY_10_4_FONTS
  229485. HeapBlock <NSSize> advances (length);
  229486. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229487. int x = 0;
  229488. for (int i = 0; i < length; ++i)
  229489. {
  229490. x += advances[i].width;
  229491. xOffsets.add (x * unitsToHeightScaleFactor);
  229492. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229493. }
  229494. #else
  229495. #if SUPPORT_10_4_FONTS
  229496. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229497. {
  229498. HeapBlock <NSSize> advances (length);
  229499. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229500. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229501. float x = 0;
  229502. for (int i = 0; i < length; ++i)
  229503. {
  229504. x += advances[i].width;
  229505. xOffsets.add (x * unitsToHeightScaleFactor);
  229506. resultGlyphs.add (nsGlyphs[i]);
  229507. }
  229508. }
  229509. else
  229510. #endif
  229511. {
  229512. HeapBlock <int> advances (length);
  229513. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229514. {
  229515. int x = 0;
  229516. for (int i = 0; i < length; ++i)
  229517. {
  229518. x += advances [i];
  229519. xOffsets.add (x * unitsToHeightScaleFactor);
  229520. resultGlyphs.add (glyphs[i]);
  229521. }
  229522. }
  229523. }
  229524. #endif
  229525. }
  229526. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229527. {
  229528. #if JUCE_IOS
  229529. return false;
  229530. #else
  229531. if (nsFont == 0)
  229532. return false;
  229533. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229534. jassert (path.isEmpty());
  229535. const ScopedAutoReleasePool pool;
  229536. NSBezierPath* bez = [NSBezierPath bezierPath];
  229537. [bez moveToPoint: NSMakePoint (0, 0)];
  229538. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229539. inFont: nsFont];
  229540. for (int i = 0; i < [bez elementCount]; ++i)
  229541. {
  229542. NSPoint p[3];
  229543. switch ([bez elementAtIndex: i associatedPoints: p])
  229544. {
  229545. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229546. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229547. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229548. (float) p[1].x, (float) -p[1].y,
  229549. (float) p[2].x, (float) -p[2].y); break;
  229550. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229551. default: jassertfalse; break;
  229552. }
  229553. }
  229554. path.applyTransform (pathTransform);
  229555. return true;
  229556. #endif
  229557. }
  229558. CGFontRef fontRef;
  229559. float fontHeightToCGSizeFactor;
  229560. CGAffineTransform renderingTransform;
  229561. private:
  229562. float ascent, unitsToHeightScaleFactor;
  229563. #if JUCE_IOS
  229564. #else
  229565. NSFont* nsFont;
  229566. AffineTransform pathTransform;
  229567. #endif
  229568. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  229569. {
  229570. #if SUPPORT_10_4_FONTS
  229571. #if ! SUPPORT_ONLY_10_4_FONTS
  229572. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229573. #endif
  229574. {
  229575. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229576. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229577. for (int i = 0; i < length; ++i)
  229578. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  229579. return;
  229580. }
  229581. #endif
  229582. #if ! SUPPORT_ONLY_10_4_FONTS
  229583. if (charToGlyphMapper == 0)
  229584. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229585. glyphs.malloc (length);
  229586. for (int i = 0; i < length; ++i)
  229587. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  229588. #endif
  229589. }
  229590. #if ! SUPPORT_ONLY_10_4_FONTS
  229591. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229592. class CharToGlyphMapper
  229593. {
  229594. public:
  229595. CharToGlyphMapper (CGFontRef fontRef)
  229596. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229597. idRangeOffset (0), glyphIndexes (0)
  229598. {
  229599. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229600. if (cmapTable != 0)
  229601. {
  229602. const int numSubtables = getValue16 (cmapTable, 2);
  229603. for (int i = 0; i < numSubtables; ++i)
  229604. {
  229605. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229606. {
  229607. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229608. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229609. {
  229610. const int length = getValue16 (cmapTable, offset + 2);
  229611. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229612. segCount = segCountX2 / 2;
  229613. const int endCodeOffset = offset + 14;
  229614. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229615. const int idDeltaOffset = startCodeOffset + segCountX2;
  229616. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229617. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229618. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229619. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229620. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229621. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229622. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229623. }
  229624. break;
  229625. }
  229626. }
  229627. CFRelease (cmapTable);
  229628. }
  229629. }
  229630. ~CharToGlyphMapper()
  229631. {
  229632. if (endCode != 0)
  229633. {
  229634. CFRelease (endCode);
  229635. CFRelease (startCode);
  229636. CFRelease (idDelta);
  229637. CFRelease (idRangeOffset);
  229638. CFRelease (glyphIndexes);
  229639. }
  229640. }
  229641. int getGlyphForCharacter (const juce_wchar c) const
  229642. {
  229643. for (int i = 0; i < segCount; ++i)
  229644. {
  229645. if (getValue16 (endCode, i * 2) >= c)
  229646. {
  229647. const int start = getValue16 (startCode, i * 2);
  229648. if (start > c)
  229649. break;
  229650. const int delta = getValue16 (idDelta, i * 2);
  229651. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  229652. if (rangeOffset == 0)
  229653. return delta + c;
  229654. else
  229655. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  229656. }
  229657. }
  229658. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  229659. return jmax (-1, (int) c - 29);
  229660. }
  229661. private:
  229662. int segCount;
  229663. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  229664. static uint16 getValue16 (CFDataRef data, const int index)
  229665. {
  229666. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  229667. }
  229668. static uint32 getValue32 (CFDataRef data, const int index)
  229669. {
  229670. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  229671. }
  229672. };
  229673. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  229674. #endif
  229675. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  229676. };
  229677. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  229678. {
  229679. return new MacTypeface (font);
  229680. }
  229681. const StringArray Font::findAllTypefaceNames()
  229682. {
  229683. StringArray names;
  229684. const ScopedAutoReleasePool pool;
  229685. #if JUCE_IOS
  229686. NSArray* fonts = [UIFont familyNames];
  229687. #else
  229688. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  229689. #endif
  229690. for (unsigned int i = 0; i < [fonts count]; ++i)
  229691. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  229692. names.sort (true);
  229693. return names;
  229694. }
  229695. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  229696. {
  229697. #if JUCE_IOS
  229698. defaultSans = "Helvetica";
  229699. defaultSerif = "Times New Roman";
  229700. defaultFixed = "Courier New";
  229701. #else
  229702. defaultSans = "Lucida Grande";
  229703. defaultSerif = "Times New Roman";
  229704. defaultFixed = "Monaco";
  229705. #endif
  229706. defaultFallback = "Arial Unicode MS";
  229707. }
  229708. #endif
  229709. /*** End of inlined file: juce_mac_Fonts.mm ***/
  229710. // (must go before juce_mac_CoreGraphicsContext.mm)
  229711. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229712. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229713. // compiled on its own).
  229714. #if JUCE_INCLUDED_FILE
  229715. class CoreGraphicsImage : public Image::SharedImage
  229716. {
  229717. public:
  229718. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229719. : Image::SharedImage (format_, width_, height_)
  229720. {
  229721. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229722. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229723. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  229724. imageData = imageDataAllocated;
  229725. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  229726. : CGColorSpaceCreateDeviceRGB();
  229727. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  229728. colourSpace, getCGImageFlags (format_));
  229729. CGColorSpaceRelease (colourSpace);
  229730. }
  229731. ~CoreGraphicsImage()
  229732. {
  229733. CGContextRelease (context);
  229734. }
  229735. Image::ImageType getType() const { return Image::NativeImage; }
  229736. LowLevelGraphicsContext* createLowLevelContext();
  229737. SharedImage* clone()
  229738. {
  229739. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  229740. memcpy (im->imageData, imageData, lineStride * height);
  229741. return im;
  229742. }
  229743. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  229744. {
  229745. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  229746. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  229747. {
  229748. return CGBitmapContextCreateImage (nativeImage->context);
  229749. }
  229750. else
  229751. {
  229752. const Image::BitmapData srcData (juceImage, false);
  229753. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  229754. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  229755. 8, srcData.pixelStride * 8, srcData.lineStride,
  229756. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  229757. 0, true, kCGRenderingIntentDefault);
  229758. CGDataProviderRelease (provider);
  229759. return imageRef;
  229760. }
  229761. }
  229762. #if JUCE_MAC
  229763. static NSImage* createNSImage (const Image& image)
  229764. {
  229765. const ScopedAutoReleasePool pool;
  229766. NSImage* im = [[NSImage alloc] init];
  229767. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229768. [im lockFocus];
  229769. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229770. CGImageRef imageRef = createImage (image, false, colourSpace);
  229771. CGColorSpaceRelease (colourSpace);
  229772. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229773. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229774. CGImageRelease (imageRef);
  229775. [im unlockFocus];
  229776. return im;
  229777. }
  229778. #endif
  229779. CGContextRef context;
  229780. HeapBlock<uint8> imageDataAllocated;
  229781. private:
  229782. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229783. {
  229784. #if JUCE_BIG_ENDIAN
  229785. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229786. #else
  229787. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229788. #endif
  229789. }
  229790. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  229791. };
  229792. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229793. {
  229794. #if USE_COREGRAPHICS_RENDERING
  229795. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229796. #else
  229797. return createSoftwareImage (format, width, height, clearImage);
  229798. #endif
  229799. }
  229800. class CoreGraphicsContext : public LowLevelGraphicsContext
  229801. {
  229802. public:
  229803. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229804. : context (context_),
  229805. flipHeight (flipHeight_),
  229806. lastClipRectIsValid (false),
  229807. state (new SavedState()),
  229808. numGradientLookupEntries (0)
  229809. {
  229810. CGContextRetain (context);
  229811. CGContextSaveGState(context);
  229812. CGContextSetShouldSmoothFonts (context, true);
  229813. CGContextSetShouldAntialias (context, true);
  229814. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229815. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229816. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229817. gradientCallbacks.version = 0;
  229818. gradientCallbacks.evaluate = gradientCallback;
  229819. gradientCallbacks.releaseInfo = 0;
  229820. setFont (Font());
  229821. }
  229822. ~CoreGraphicsContext()
  229823. {
  229824. CGContextRestoreGState (context);
  229825. CGContextRelease (context);
  229826. CGColorSpaceRelease (rgbColourSpace);
  229827. CGColorSpaceRelease (greyColourSpace);
  229828. }
  229829. bool isVectorDevice() const { return false; }
  229830. void setOrigin (int x, int y)
  229831. {
  229832. CGContextTranslateCTM (context, x, -y);
  229833. if (lastClipRectIsValid)
  229834. lastClipRect.translate (-x, -y);
  229835. }
  229836. void addTransform (const AffineTransform& transform)
  229837. {
  229838. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  229839. .translated (0, flipHeight)
  229840. .followedBy (transform)
  229841. .translated (0, -flipHeight)
  229842. .scaled (1.0f, -1.0f));
  229843. lastClipRectIsValid = false;
  229844. }
  229845. float getScaleFactor()
  229846. {
  229847. CGAffineTransform t = CGContextGetCTM (context);
  229848. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  229849. }
  229850. bool clipToRectangle (const Rectangle<int>& r)
  229851. {
  229852. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229853. if (lastClipRectIsValid)
  229854. {
  229855. // This is actually incorrect, because the actual clip region may be complex, and
  229856. // clipping its bounds to a rect may not be right... But, removing this shortcut
  229857. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  229858. // when calculating the resultant clip bounds, and makes the same mistake!
  229859. lastClipRect = lastClipRect.getIntersection (r);
  229860. return ! lastClipRect.isEmpty();
  229861. }
  229862. return ! isClipEmpty();
  229863. }
  229864. bool clipToRectangleList (const RectangleList& clipRegion)
  229865. {
  229866. if (clipRegion.isEmpty())
  229867. {
  229868. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229869. lastClipRectIsValid = true;
  229870. lastClipRect = Rectangle<int>();
  229871. return false;
  229872. }
  229873. else
  229874. {
  229875. const int numRects = clipRegion.getNumRectangles();
  229876. HeapBlock <CGRect> rects (numRects);
  229877. for (int i = 0; i < numRects; ++i)
  229878. {
  229879. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229880. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229881. }
  229882. CGContextClipToRects (context, rects, numRects);
  229883. lastClipRectIsValid = false;
  229884. return ! isClipEmpty();
  229885. }
  229886. }
  229887. void excludeClipRectangle (const Rectangle<int>& r)
  229888. {
  229889. RectangleList remaining (getClipBounds());
  229890. remaining.subtract (r);
  229891. clipToRectangleList (remaining);
  229892. lastClipRectIsValid = false;
  229893. }
  229894. void clipToPath (const Path& path, const AffineTransform& transform)
  229895. {
  229896. createPath (path, transform);
  229897. CGContextClip (context);
  229898. lastClipRectIsValid = false;
  229899. }
  229900. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229901. {
  229902. if (! transform.isSingularity())
  229903. {
  229904. Image singleChannelImage (sourceImage);
  229905. if (sourceImage.getFormat() != Image::SingleChannel)
  229906. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229907. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  229908. flip();
  229909. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229910. applyTransform (t);
  229911. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229912. CGContextClipToMask (context, r, image);
  229913. applyTransform (t.inverted());
  229914. flip();
  229915. CGImageRelease (image);
  229916. lastClipRectIsValid = false;
  229917. }
  229918. }
  229919. bool clipRegionIntersects (const Rectangle<int>& r)
  229920. {
  229921. return getClipBounds().intersects (r);
  229922. }
  229923. const Rectangle<int> getClipBounds() const
  229924. {
  229925. if (! lastClipRectIsValid)
  229926. {
  229927. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229928. lastClipRectIsValid = true;
  229929. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229930. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229931. roundToInt (bounds.size.width),
  229932. roundToInt (bounds.size.height));
  229933. }
  229934. return lastClipRect;
  229935. }
  229936. bool isClipEmpty() const
  229937. {
  229938. return getClipBounds().isEmpty();
  229939. }
  229940. void saveState()
  229941. {
  229942. CGContextSaveGState (context);
  229943. stateStack.add (new SavedState (*state));
  229944. }
  229945. void restoreState()
  229946. {
  229947. CGContextRestoreGState (context);
  229948. SavedState* const top = stateStack.getLast();
  229949. if (top != 0)
  229950. {
  229951. state = top;
  229952. stateStack.removeLast (1, false);
  229953. lastClipRectIsValid = false;
  229954. }
  229955. else
  229956. {
  229957. jassertfalse; // trying to pop with an empty stack!
  229958. }
  229959. }
  229960. void beginTransparencyLayer (float opacity)
  229961. {
  229962. saveState();
  229963. CGContextSetAlpha (context, opacity);
  229964. CGContextBeginTransparencyLayer (context, 0);
  229965. }
  229966. void endTransparencyLayer()
  229967. {
  229968. CGContextEndTransparencyLayer (context);
  229969. restoreState();
  229970. }
  229971. void setFill (const FillType& fillType)
  229972. {
  229973. state->fillType = fillType;
  229974. if (fillType.isColour())
  229975. {
  229976. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229977. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229978. CGContextSetAlpha (context, 1.0f);
  229979. }
  229980. }
  229981. void setOpacity (float newOpacity)
  229982. {
  229983. state->fillType.setOpacity (newOpacity);
  229984. setFill (state->fillType);
  229985. }
  229986. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229987. {
  229988. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229989. ? kCGInterpolationLow
  229990. : kCGInterpolationHigh);
  229991. }
  229992. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229993. {
  229994. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  229995. }
  229996. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  229997. {
  229998. if (replaceExistingContents)
  229999. {
  230000. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230001. CGContextClearRect (context, cgRect);
  230002. #else
  230003. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230004. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230005. CGContextClearRect (context, cgRect);
  230006. else
  230007. #endif
  230008. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230009. #endif
  230010. fillCGRect (cgRect, false);
  230011. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230012. }
  230013. else
  230014. {
  230015. if (state->fillType.isColour())
  230016. {
  230017. CGContextFillRect (context, cgRect);
  230018. }
  230019. else if (state->fillType.isGradient())
  230020. {
  230021. CGContextSaveGState (context);
  230022. CGContextClipToRect (context, cgRect);
  230023. drawGradient();
  230024. CGContextRestoreGState (context);
  230025. }
  230026. else
  230027. {
  230028. CGContextSaveGState (context);
  230029. CGContextClipToRect (context, cgRect);
  230030. drawImage (state->fillType.image, state->fillType.transform, true);
  230031. CGContextRestoreGState (context);
  230032. }
  230033. }
  230034. }
  230035. void fillPath (const Path& path, const AffineTransform& transform)
  230036. {
  230037. CGContextSaveGState (context);
  230038. if (state->fillType.isColour())
  230039. {
  230040. flip();
  230041. applyTransform (transform);
  230042. createPath (path);
  230043. if (path.isUsingNonZeroWinding())
  230044. CGContextFillPath (context);
  230045. else
  230046. CGContextEOFillPath (context);
  230047. }
  230048. else
  230049. {
  230050. createPath (path, transform);
  230051. if (path.isUsingNonZeroWinding())
  230052. CGContextClip (context);
  230053. else
  230054. CGContextEOClip (context);
  230055. if (state->fillType.isGradient())
  230056. drawGradient();
  230057. else
  230058. drawImage (state->fillType.image, state->fillType.transform, true);
  230059. }
  230060. CGContextRestoreGState (context);
  230061. }
  230062. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230063. {
  230064. const int iw = sourceImage.getWidth();
  230065. const int ih = sourceImage.getHeight();
  230066. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230067. CGContextSaveGState (context);
  230068. CGContextSetAlpha (context, state->fillType.getOpacity());
  230069. flip();
  230070. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230071. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230072. if (fillEntireClipAsTiles)
  230073. {
  230074. #if JUCE_IOS
  230075. CGContextDrawTiledImage (context, imageRect, image);
  230076. #else
  230077. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230078. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230079. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230080. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230081. CGContextDrawTiledImage (context, imageRect, image);
  230082. else
  230083. #endif
  230084. {
  230085. // Fallback to manually doing a tiled fill on 10.4
  230086. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230087. int x = 0, y = 0;
  230088. while (x > clip.origin.x) x -= iw;
  230089. while (y > clip.origin.y) y -= ih;
  230090. const int right = (int) (clip.origin.x + clip.size.width);
  230091. const int bottom = (int) (clip.origin.y + clip.size.height);
  230092. while (y < bottom)
  230093. {
  230094. for (int x2 = x; x2 < right; x2 += iw)
  230095. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230096. y += ih;
  230097. }
  230098. }
  230099. #endif
  230100. }
  230101. else
  230102. {
  230103. CGContextDrawImage (context, imageRect, image);
  230104. }
  230105. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230106. CGContextRestoreGState (context);
  230107. }
  230108. void drawLine (const Line<float>& line)
  230109. {
  230110. if (state->fillType.isColour())
  230111. {
  230112. CGContextSetLineCap (context, kCGLineCapSquare);
  230113. CGContextSetLineWidth (context, 1.0f);
  230114. CGContextSetRGBStrokeColor (context,
  230115. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230116. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230117. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230118. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230119. CGContextStrokeLineSegments (context, cgLine, 1);
  230120. }
  230121. else
  230122. {
  230123. Path p;
  230124. p.addLineSegment (line, 1.0f);
  230125. fillPath (p, AffineTransform::identity);
  230126. }
  230127. }
  230128. void drawVerticalLine (const int x, float top, float bottom)
  230129. {
  230130. if (state->fillType.isColour())
  230131. {
  230132. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230133. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230134. #else
  230135. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230136. // the x co-ord slightly to trick it..
  230137. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230138. #endif
  230139. }
  230140. else
  230141. {
  230142. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230143. }
  230144. }
  230145. void drawHorizontalLine (const int y, float left, float right)
  230146. {
  230147. if (state->fillType.isColour())
  230148. {
  230149. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230150. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230151. #else
  230152. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230153. // the x co-ord slightly to trick it..
  230154. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230155. #endif
  230156. }
  230157. else
  230158. {
  230159. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230160. }
  230161. }
  230162. void setFont (const Font& newFont)
  230163. {
  230164. if (state->font != newFont)
  230165. {
  230166. state->fontRef = 0;
  230167. state->font = newFont;
  230168. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230169. if (mf != 0)
  230170. {
  230171. state->fontRef = mf->fontRef;
  230172. CGContextSetFont (context, state->fontRef);
  230173. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230174. state->fontTransform = mf->renderingTransform;
  230175. state->fontTransform.a *= state->font.getHorizontalScale();
  230176. CGContextSetTextMatrix (context, state->fontTransform);
  230177. }
  230178. }
  230179. }
  230180. const Font getFont()
  230181. {
  230182. return state->font;
  230183. }
  230184. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230185. {
  230186. if (state->fontRef != 0 && state->fillType.isColour())
  230187. {
  230188. if (transform.isOnlyTranslation())
  230189. {
  230190. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230191. CGGlyph g = glyphNumber;
  230192. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230193. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230194. }
  230195. else
  230196. {
  230197. CGContextSaveGState (context);
  230198. flip();
  230199. applyTransform (transform);
  230200. CGAffineTransform t = state->fontTransform;
  230201. t.d = -t.d;
  230202. CGContextSetTextMatrix (context, t);
  230203. CGGlyph g = glyphNumber;
  230204. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230205. CGContextRestoreGState (context);
  230206. }
  230207. }
  230208. else
  230209. {
  230210. Path p;
  230211. Font& f = state->font;
  230212. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230213. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230214. .followedBy (transform));
  230215. }
  230216. }
  230217. private:
  230218. CGContextRef context;
  230219. const CGFloat flipHeight;
  230220. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230221. CGFunctionCallbacks gradientCallbacks;
  230222. mutable Rectangle<int> lastClipRect;
  230223. mutable bool lastClipRectIsValid;
  230224. struct SavedState
  230225. {
  230226. SavedState()
  230227. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230228. {
  230229. }
  230230. SavedState (const SavedState& other)
  230231. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230232. fontTransform (other.fontTransform)
  230233. {
  230234. }
  230235. FillType fillType;
  230236. Font font;
  230237. CGFontRef fontRef;
  230238. CGAffineTransform fontTransform;
  230239. };
  230240. ScopedPointer <SavedState> state;
  230241. OwnedArray <SavedState> stateStack;
  230242. HeapBlock <PixelARGB> gradientLookupTable;
  230243. int numGradientLookupEntries;
  230244. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230245. {
  230246. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230247. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230248. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230249. colour.unpremultiply();
  230250. outData[0] = colour.getRed() / 255.0f;
  230251. outData[1] = colour.getGreen() / 255.0f;
  230252. outData[2] = colour.getBlue() / 255.0f;
  230253. outData[3] = colour.getAlpha() / 255.0f;
  230254. }
  230255. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230256. {
  230257. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  230258. --numGradientLookupEntries;
  230259. CGShadingRef result = 0;
  230260. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230261. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230262. if (gradient.isRadial)
  230263. {
  230264. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230265. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230266. function, true, true);
  230267. }
  230268. else
  230269. {
  230270. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230271. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230272. function, true, true);
  230273. }
  230274. CGFunctionRelease (function);
  230275. return result;
  230276. }
  230277. void drawGradient()
  230278. {
  230279. flip();
  230280. applyTransform (state->fillType.transform);
  230281. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230282. // you draw a gradient with high quality interp enabled).
  230283. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230284. CGContextSetAlpha (context, state->fillType.getOpacity());
  230285. CGContextDrawShading (context, shading);
  230286. CGShadingRelease (shading);
  230287. }
  230288. void createPath (const Path& path) const
  230289. {
  230290. CGContextBeginPath (context);
  230291. Path::Iterator i (path);
  230292. while (i.next())
  230293. {
  230294. switch (i.elementType)
  230295. {
  230296. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230297. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230298. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230299. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230300. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230301. default: jassertfalse; break;
  230302. }
  230303. }
  230304. }
  230305. void createPath (const Path& path, const AffineTransform& transform) const
  230306. {
  230307. CGContextBeginPath (context);
  230308. Path::Iterator i (path);
  230309. while (i.next())
  230310. {
  230311. switch (i.elementType)
  230312. {
  230313. case Path::Iterator::startNewSubPath:
  230314. transform.transformPoint (i.x1, i.y1);
  230315. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230316. break;
  230317. case Path::Iterator::lineTo:
  230318. transform.transformPoint (i.x1, i.y1);
  230319. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230320. break;
  230321. case Path::Iterator::quadraticTo:
  230322. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230323. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230324. break;
  230325. case Path::Iterator::cubicTo:
  230326. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230327. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230328. break;
  230329. case Path::Iterator::closePath:
  230330. CGContextClosePath (context); break;
  230331. default:
  230332. jassertfalse;
  230333. break;
  230334. }
  230335. }
  230336. }
  230337. void flip() const
  230338. {
  230339. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230340. }
  230341. void applyTransform (const AffineTransform& transform) const
  230342. {
  230343. CGAffineTransform t;
  230344. t.a = transform.mat00;
  230345. t.b = transform.mat10;
  230346. t.c = transform.mat01;
  230347. t.d = transform.mat11;
  230348. t.tx = transform.mat02;
  230349. t.ty = transform.mat12;
  230350. CGContextConcatCTM (context, t);
  230351. }
  230352. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230353. };
  230354. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230355. {
  230356. return new CoreGraphicsContext (context, height);
  230357. }
  230358. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230359. const Image juce_loadWithCoreImage (InputStream& input)
  230360. {
  230361. MemoryBlock data;
  230362. input.readIntoMemoryBlock (data, -1);
  230363. #if JUCE_IOS
  230364. JUCE_AUTORELEASEPOOL
  230365. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230366. length: data.getSize()
  230367. freeWhenDone: NO]];
  230368. if (image != nil)
  230369. {
  230370. CGImageRef loadedImage = image.CGImage;
  230371. #else
  230372. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230373. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230374. CGDataProviderRelease (provider);
  230375. if (imageSource != 0)
  230376. {
  230377. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230378. CFRelease (imageSource);
  230379. #endif
  230380. if (loadedImage != 0)
  230381. {
  230382. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230383. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230384. && alphaInfo != kCGImageAlphaNoneSkipLast
  230385. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230386. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230387. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230388. hasAlphaChan, Image::NativeImage);
  230389. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230390. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230391. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230392. CGContextFlush (cgImage->context);
  230393. #if ! JUCE_IOS
  230394. CFRelease (loadedImage);
  230395. #endif
  230396. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230397. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230398. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230399. return image;
  230400. }
  230401. }
  230402. return Image::null;
  230403. }
  230404. #endif
  230405. #endif
  230406. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230407. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230408. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230409. // compiled on its own).
  230410. #if JUCE_INCLUDED_FILE
  230411. class NSViewComponentPeer;
  230412. END_JUCE_NAMESPACE
  230413. @interface NSEvent (JuceDeviceDelta)
  230414. - (float) deviceDeltaX;
  230415. - (float) deviceDeltaY;
  230416. @end
  230417. #define JuceNSView MakeObjCClassName(JuceNSView)
  230418. @interface JuceNSView : NSView<NSTextInput>
  230419. {
  230420. @public
  230421. NSViewComponentPeer* owner;
  230422. NSNotificationCenter* notificationCenter;
  230423. String* stringBeingComposed;
  230424. bool textWasInserted;
  230425. }
  230426. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230427. - (void) dealloc;
  230428. - (BOOL) isOpaque;
  230429. - (void) drawRect: (NSRect) r;
  230430. - (void) mouseDown: (NSEvent*) ev;
  230431. - (void) asyncMouseDown: (NSEvent*) ev;
  230432. - (void) mouseUp: (NSEvent*) ev;
  230433. - (void) asyncMouseUp: (NSEvent*) ev;
  230434. - (void) mouseDragged: (NSEvent*) ev;
  230435. - (void) mouseMoved: (NSEvent*) ev;
  230436. - (void) mouseEntered: (NSEvent*) ev;
  230437. - (void) mouseExited: (NSEvent*) ev;
  230438. - (void) rightMouseDown: (NSEvent*) ev;
  230439. - (void) rightMouseDragged: (NSEvent*) ev;
  230440. - (void) rightMouseUp: (NSEvent*) ev;
  230441. - (void) otherMouseDown: (NSEvent*) ev;
  230442. - (void) otherMouseDragged: (NSEvent*) ev;
  230443. - (void) otherMouseUp: (NSEvent*) ev;
  230444. - (void) scrollWheel: (NSEvent*) ev;
  230445. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230446. - (void) frameChanged: (NSNotification*) n;
  230447. - (void) viewDidMoveToWindow;
  230448. - (void) keyDown: (NSEvent*) ev;
  230449. - (void) keyUp: (NSEvent*) ev;
  230450. // NSTextInput Methods
  230451. - (void) insertText: (id) aString;
  230452. - (void) doCommandBySelector: (SEL) aSelector;
  230453. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230454. - (void) unmarkText;
  230455. - (BOOL) hasMarkedText;
  230456. - (long) conversationIdentifier;
  230457. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230458. - (NSRange) markedRange;
  230459. - (NSRange) selectedRange;
  230460. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230461. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230462. - (NSArray*) validAttributesForMarkedText;
  230463. - (void) flagsChanged: (NSEvent*) ev;
  230464. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230465. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230466. #endif
  230467. - (BOOL) becomeFirstResponder;
  230468. - (BOOL) resignFirstResponder;
  230469. - (BOOL) acceptsFirstResponder;
  230470. - (void) asyncRepaint: (id) rect;
  230471. - (NSArray*) getSupportedDragTypes;
  230472. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230473. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230474. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230475. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230476. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230477. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230478. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230479. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230480. @end
  230481. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230482. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230483. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230484. #else
  230485. @interface JuceNSWindow : NSWindow
  230486. #endif
  230487. {
  230488. @private
  230489. NSViewComponentPeer* owner;
  230490. bool isZooming;
  230491. }
  230492. - (void) setOwner: (NSViewComponentPeer*) owner;
  230493. - (BOOL) canBecomeKeyWindow;
  230494. - (void) becomeKeyWindow;
  230495. - (BOOL) windowShouldClose: (id) window;
  230496. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230497. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230498. - (void) zoom: (id) sender;
  230499. @end
  230500. BEGIN_JUCE_NAMESPACE
  230501. class NSViewComponentPeer : public ComponentPeer
  230502. {
  230503. public:
  230504. NSViewComponentPeer (Component* const component,
  230505. const int windowStyleFlags,
  230506. NSView* viewToAttachTo);
  230507. ~NSViewComponentPeer();
  230508. void* getNativeHandle() const;
  230509. void setVisible (bool shouldBeVisible);
  230510. void setTitle (const String& title);
  230511. void setPosition (int x, int y);
  230512. void setSize (int w, int h);
  230513. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230514. const Rectangle<int> getBounds (const bool global) const;
  230515. const Rectangle<int> getBounds() const;
  230516. const Point<int> getScreenPosition() const;
  230517. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230518. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230519. void setAlpha (float newAlpha);
  230520. void setMinimised (bool shouldBeMinimised);
  230521. bool isMinimised() const;
  230522. void setFullScreen (bool shouldBeFullScreen);
  230523. bool isFullScreen() const;
  230524. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230525. const BorderSize getFrameSize() const;
  230526. bool setAlwaysOnTop (bool alwaysOnTop);
  230527. void toFront (bool makeActiveWindow);
  230528. void toBehind (ComponentPeer* other);
  230529. void setIcon (const Image& newIcon);
  230530. const StringArray getAvailableRenderingEngines();
  230531. int getCurrentRenderingEngine() throw();
  230532. void setCurrentRenderingEngine (int index);
  230533. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230534. for example having more than one juce plugin loaded into a host, then when a
  230535. method is called, the actual code that runs might actually be in a different module
  230536. than the one you expect... So any calls to library functions or statics that are
  230537. made inside obj-c methods will probably end up getting executed in a different DLL's
  230538. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230539. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230540. virtual methods of an object that's known to live inside the right module's space.
  230541. */
  230542. virtual void redirectMouseDown (NSEvent* ev);
  230543. virtual void redirectMouseUp (NSEvent* ev);
  230544. virtual void redirectMouseDrag (NSEvent* ev);
  230545. virtual void redirectMouseMove (NSEvent* ev);
  230546. virtual void redirectMouseEnter (NSEvent* ev);
  230547. virtual void redirectMouseExit (NSEvent* ev);
  230548. virtual void redirectMouseWheel (NSEvent* ev);
  230549. void sendMouseEvent (NSEvent* ev);
  230550. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230551. virtual bool redirectKeyDown (NSEvent* ev);
  230552. virtual bool redirectKeyUp (NSEvent* ev);
  230553. virtual void redirectModKeyChange (NSEvent* ev);
  230554. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230555. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230556. #endif
  230557. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230558. virtual bool isOpaque();
  230559. virtual void drawRect (NSRect r);
  230560. virtual bool canBecomeKeyWindow();
  230561. virtual bool windowShouldClose();
  230562. virtual void redirectMovedOrResized();
  230563. virtual void viewMovedToWindow();
  230564. virtual NSRect constrainRect (NSRect r);
  230565. static void showArrowCursorIfNeeded();
  230566. static void updateModifiers (NSEvent* e);
  230567. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230568. static int getKeyCodeFromEvent (NSEvent* ev)
  230569. {
  230570. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230571. int keyCode = unmodified[0];
  230572. if (keyCode == 0x19) // (backwards-tab)
  230573. keyCode = '\t';
  230574. else if (keyCode == 0x03) // (enter)
  230575. keyCode = '\r';
  230576. else
  230577. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230578. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230579. {
  230580. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230581. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230582. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230583. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230584. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230585. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230586. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230587. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230588. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230589. if (keyCode == numPadConversions [i])
  230590. keyCode = numPadConversions [i + 1];
  230591. }
  230592. return keyCode;
  230593. }
  230594. static int64 getMouseTime (NSEvent* e)
  230595. {
  230596. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230597. + (int64) ([e timestamp] * 1000.0);
  230598. }
  230599. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230600. {
  230601. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230602. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230603. }
  230604. static int getModifierForButtonNumber (const NSInteger num)
  230605. {
  230606. return num == 0 ? ModifierKeys::leftButtonModifier
  230607. : (num == 1 ? ModifierKeys::rightButtonModifier
  230608. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230609. }
  230610. virtual void viewFocusGain();
  230611. virtual void viewFocusLoss();
  230612. bool isFocused() const;
  230613. void grabFocus();
  230614. void textInputRequired (const Point<int>& position);
  230615. void repaint (const Rectangle<int>& area);
  230616. void performAnyPendingRepaintsNow();
  230617. NSWindow* window;
  230618. JuceNSView* view;
  230619. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  230620. static ModifierKeys currentModifiers;
  230621. static ComponentPeer* currentlyFocusedPeer;
  230622. static Array<int> keysCurrentlyDown;
  230623. private:
  230624. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  230625. };
  230626. END_JUCE_NAMESPACE
  230627. @implementation JuceNSView
  230628. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  230629. withFrame: (NSRect) frame
  230630. {
  230631. [super initWithFrame: frame];
  230632. owner = owner_;
  230633. stringBeingComposed = 0;
  230634. textWasInserted = false;
  230635. notificationCenter = [NSNotificationCenter defaultCenter];
  230636. [notificationCenter addObserver: self
  230637. selector: @selector (frameChanged:)
  230638. name: NSViewFrameDidChangeNotification
  230639. object: self];
  230640. if (! owner_->isSharedWindow)
  230641. {
  230642. [notificationCenter addObserver: self
  230643. selector: @selector (frameChanged:)
  230644. name: NSWindowDidMoveNotification
  230645. object: owner_->window];
  230646. }
  230647. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  230648. return self;
  230649. }
  230650. - (void) dealloc
  230651. {
  230652. [notificationCenter removeObserver: self];
  230653. delete stringBeingComposed;
  230654. [super dealloc];
  230655. }
  230656. - (void) drawRect: (NSRect) r
  230657. {
  230658. if (owner != 0)
  230659. owner->drawRect (r);
  230660. }
  230661. - (BOOL) isOpaque
  230662. {
  230663. return owner == 0 || owner->isOpaque();
  230664. }
  230665. - (void) mouseDown: (NSEvent*) ev
  230666. {
  230667. if (JUCEApplication::isStandaloneApp())
  230668. [self asyncMouseDown: ev];
  230669. else
  230670. // In some host situations, the host will stop modal loops from working
  230671. // correctly if they're called from a mouse event, so we'll trigger
  230672. // the event asynchronously..
  230673. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  230674. withObject: ev
  230675. waitUntilDone: NO];
  230676. }
  230677. - (void) asyncMouseDown: (NSEvent*) ev
  230678. {
  230679. if (owner != 0)
  230680. owner->redirectMouseDown (ev);
  230681. }
  230682. - (void) mouseUp: (NSEvent*) ev
  230683. {
  230684. if (! JUCEApplication::isStandaloneApp())
  230685. [self asyncMouseUp: ev];
  230686. else
  230687. // In some host situations, the host will stop modal loops from working
  230688. // correctly if they're called from a mouse event, so we'll trigger
  230689. // the event asynchronously..
  230690. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  230691. withObject: ev
  230692. waitUntilDone: NO];
  230693. }
  230694. - (void) asyncMouseUp: (NSEvent*) ev
  230695. {
  230696. if (owner != 0)
  230697. owner->redirectMouseUp (ev);
  230698. }
  230699. - (void) mouseDragged: (NSEvent*) ev
  230700. {
  230701. if (owner != 0)
  230702. owner->redirectMouseDrag (ev);
  230703. }
  230704. - (void) mouseMoved: (NSEvent*) ev
  230705. {
  230706. if (owner != 0)
  230707. owner->redirectMouseMove (ev);
  230708. }
  230709. - (void) mouseEntered: (NSEvent*) ev
  230710. {
  230711. if (owner != 0)
  230712. owner->redirectMouseEnter (ev);
  230713. }
  230714. - (void) mouseExited: (NSEvent*) ev
  230715. {
  230716. if (owner != 0)
  230717. owner->redirectMouseExit (ev);
  230718. }
  230719. - (void) rightMouseDown: (NSEvent*) ev
  230720. {
  230721. [self mouseDown: ev];
  230722. }
  230723. - (void) rightMouseDragged: (NSEvent*) ev
  230724. {
  230725. [self mouseDragged: ev];
  230726. }
  230727. - (void) rightMouseUp: (NSEvent*) ev
  230728. {
  230729. [self mouseUp: ev];
  230730. }
  230731. - (void) otherMouseDown: (NSEvent*) ev
  230732. {
  230733. [self mouseDown: ev];
  230734. }
  230735. - (void) otherMouseDragged: (NSEvent*) ev
  230736. {
  230737. [self mouseDragged: ev];
  230738. }
  230739. - (void) otherMouseUp: (NSEvent*) ev
  230740. {
  230741. [self mouseUp: ev];
  230742. }
  230743. - (void) scrollWheel: (NSEvent*) ev
  230744. {
  230745. if (owner != 0)
  230746. owner->redirectMouseWheel (ev);
  230747. }
  230748. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  230749. {
  230750. (void) ev;
  230751. return YES;
  230752. }
  230753. - (void) frameChanged: (NSNotification*) n
  230754. {
  230755. (void) n;
  230756. if (owner != 0)
  230757. owner->redirectMovedOrResized();
  230758. }
  230759. - (void) viewDidMoveToWindow
  230760. {
  230761. if (owner != 0)
  230762. owner->viewMovedToWindow();
  230763. }
  230764. - (void) asyncRepaint: (id) rect
  230765. {
  230766. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  230767. [self setNeedsDisplayInRect: *r];
  230768. }
  230769. - (void) keyDown: (NSEvent*) ev
  230770. {
  230771. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230772. textWasInserted = false;
  230773. if (target != 0)
  230774. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  230775. else
  230776. deleteAndZero (stringBeingComposed);
  230777. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  230778. [super keyDown: ev];
  230779. }
  230780. - (void) keyUp: (NSEvent*) ev
  230781. {
  230782. if (owner == 0 || ! owner->redirectKeyUp (ev))
  230783. [super keyUp: ev];
  230784. }
  230785. - (void) insertText: (id) aString
  230786. {
  230787. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  230788. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  230789. if ([newText length] > 0)
  230790. {
  230791. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230792. if (target != 0)
  230793. {
  230794. target->insertTextAtCaret (nsStringToJuce (newText));
  230795. textWasInserted = true;
  230796. }
  230797. }
  230798. deleteAndZero (stringBeingComposed);
  230799. }
  230800. - (void) doCommandBySelector: (SEL) aSelector
  230801. {
  230802. (void) aSelector;
  230803. }
  230804. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  230805. {
  230806. (void) selectionRange;
  230807. if (stringBeingComposed == 0)
  230808. stringBeingComposed = new String();
  230809. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  230810. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230811. if (target != 0)
  230812. {
  230813. const Range<int> currentHighlight (target->getHighlightedRegion());
  230814. target->insertTextAtCaret (*stringBeingComposed);
  230815. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  230816. textWasInserted = true;
  230817. }
  230818. }
  230819. - (void) unmarkText
  230820. {
  230821. if (stringBeingComposed != 0)
  230822. {
  230823. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230824. if (target != 0)
  230825. {
  230826. target->insertTextAtCaret (*stringBeingComposed);
  230827. textWasInserted = true;
  230828. }
  230829. }
  230830. deleteAndZero (stringBeingComposed);
  230831. }
  230832. - (BOOL) hasMarkedText
  230833. {
  230834. return stringBeingComposed != 0;
  230835. }
  230836. - (long) conversationIdentifier
  230837. {
  230838. return (long) (pointer_sized_int) self;
  230839. }
  230840. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  230841. {
  230842. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230843. if (target != 0)
  230844. {
  230845. const Range<int> r ((int) theRange.location,
  230846. (int) (theRange.location + theRange.length));
  230847. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  230848. }
  230849. return nil;
  230850. }
  230851. - (NSRange) markedRange
  230852. {
  230853. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  230854. : NSMakeRange (NSNotFound, 0);
  230855. }
  230856. - (NSRange) selectedRange
  230857. {
  230858. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230859. if (target != 0)
  230860. {
  230861. const Range<int> highlight (target->getHighlightedRegion());
  230862. if (! highlight.isEmpty())
  230863. return NSMakeRange (highlight.getStart(), highlight.getLength());
  230864. }
  230865. return NSMakeRange (NSNotFound, 0);
  230866. }
  230867. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  230868. {
  230869. (void) theRange;
  230870. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  230871. if (comp == 0)
  230872. return NSMakeRect (0, 0, 0, 0);
  230873. const Rectangle<int> bounds (comp->getScreenBounds());
  230874. return NSMakeRect (bounds.getX(),
  230875. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  230876. bounds.getWidth(),
  230877. bounds.getHeight());
  230878. }
  230879. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230880. {
  230881. (void) thePoint;
  230882. return NSNotFound;
  230883. }
  230884. - (NSArray*) validAttributesForMarkedText
  230885. {
  230886. return [NSArray array];
  230887. }
  230888. - (void) flagsChanged: (NSEvent*) ev
  230889. {
  230890. if (owner != 0)
  230891. owner->redirectModKeyChange (ev);
  230892. }
  230893. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230894. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230895. {
  230896. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230897. return true;
  230898. return [super performKeyEquivalent: ev];
  230899. }
  230900. #endif
  230901. - (BOOL) becomeFirstResponder
  230902. {
  230903. if (owner != 0)
  230904. owner->viewFocusGain();
  230905. return true;
  230906. }
  230907. - (BOOL) resignFirstResponder
  230908. {
  230909. if (owner != 0)
  230910. owner->viewFocusLoss();
  230911. return true;
  230912. }
  230913. - (BOOL) acceptsFirstResponder
  230914. {
  230915. return owner != 0 && owner->canBecomeKeyWindow();
  230916. }
  230917. - (NSArray*) getSupportedDragTypes
  230918. {
  230919. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230920. }
  230921. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230922. {
  230923. return owner != 0 && owner->sendDragCallback (type, sender);
  230924. }
  230925. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230926. {
  230927. if ([self sendDragCallback: 0 sender: sender])
  230928. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230929. else
  230930. return NSDragOperationNone;
  230931. }
  230932. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230933. {
  230934. if ([self sendDragCallback: 0 sender: sender])
  230935. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230936. else
  230937. return NSDragOperationNone;
  230938. }
  230939. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230940. {
  230941. [self sendDragCallback: 1 sender: sender];
  230942. }
  230943. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230944. {
  230945. [self sendDragCallback: 1 sender: sender];
  230946. }
  230947. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230948. {
  230949. (void) sender;
  230950. return YES;
  230951. }
  230952. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230953. {
  230954. return [self sendDragCallback: 2 sender: sender];
  230955. }
  230956. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230957. {
  230958. (void) sender;
  230959. }
  230960. @end
  230961. @implementation JuceNSWindow
  230962. - (void) setOwner: (NSViewComponentPeer*) owner_
  230963. {
  230964. owner = owner_;
  230965. isZooming = false;
  230966. }
  230967. - (BOOL) canBecomeKeyWindow
  230968. {
  230969. return owner != 0 && owner->canBecomeKeyWindow();
  230970. }
  230971. - (void) becomeKeyWindow
  230972. {
  230973. [super becomeKeyWindow];
  230974. if (owner != 0)
  230975. owner->grabFocus();
  230976. }
  230977. - (BOOL) windowShouldClose: (id) window
  230978. {
  230979. (void) window;
  230980. return owner == 0 || owner->windowShouldClose();
  230981. }
  230982. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230983. {
  230984. (void) screen;
  230985. if (owner != 0)
  230986. frameRect = owner->constrainRect (frameRect);
  230987. return frameRect;
  230988. }
  230989. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  230990. {
  230991. (void) window;
  230992. if (isZooming)
  230993. return proposedFrameSize;
  230994. NSRect frameRect = [self frame];
  230995. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  230996. frameRect.size = proposedFrameSize;
  230997. if (owner != 0)
  230998. frameRect = owner->constrainRect (frameRect);
  230999. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231000. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231001. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231002. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231003. return frameRect.size;
  231004. }
  231005. - (void) zoom: (id) sender
  231006. {
  231007. isZooming = true;
  231008. [super zoom: sender];
  231009. isZooming = false;
  231010. }
  231011. - (void) windowWillMove: (NSNotification*) notification
  231012. {
  231013. (void) notification;
  231014. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231015. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231016. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231017. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231018. }
  231019. @end
  231020. BEGIN_JUCE_NAMESPACE
  231021. ModifierKeys NSViewComponentPeer::currentModifiers;
  231022. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231023. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231024. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231025. {
  231026. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231027. return true;
  231028. if (keyCode >= 'A' && keyCode <= 'Z'
  231029. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231030. return true;
  231031. if (keyCode >= 'a' && keyCode <= 'z'
  231032. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231033. return true;
  231034. return false;
  231035. }
  231036. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231037. {
  231038. int m = 0;
  231039. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231040. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231041. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231042. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231043. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231044. }
  231045. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231046. {
  231047. updateModifiers (ev);
  231048. int keyCode = getKeyCodeFromEvent (ev);
  231049. if (keyCode != 0)
  231050. {
  231051. if (isKeyDown)
  231052. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231053. else
  231054. keysCurrentlyDown.removeValue (keyCode);
  231055. }
  231056. }
  231057. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231058. {
  231059. return NSViewComponentPeer::currentModifiers;
  231060. }
  231061. void ModifierKeys::updateCurrentModifiers() throw()
  231062. {
  231063. currentModifiers = NSViewComponentPeer::currentModifiers;
  231064. }
  231065. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231066. const int windowStyleFlags,
  231067. NSView* viewToAttachTo)
  231068. : ComponentPeer (component_, windowStyleFlags),
  231069. window (0),
  231070. view (0),
  231071. isSharedWindow (viewToAttachTo != 0),
  231072. fullScreen (false),
  231073. insideDrawRect (false),
  231074. #if USE_COREGRAPHICS_RENDERING
  231075. usingCoreGraphics (true),
  231076. #else
  231077. usingCoreGraphics (false),
  231078. #endif
  231079. recursiveToFrontCall (false)
  231080. {
  231081. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231082. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231083. [view setPostsFrameChangedNotifications: YES];
  231084. if (isSharedWindow)
  231085. {
  231086. window = [viewToAttachTo window];
  231087. [viewToAttachTo addSubview: view];
  231088. }
  231089. else
  231090. {
  231091. r.origin.x = (float) component->getX();
  231092. r.origin.y = (float) component->getY();
  231093. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231094. unsigned int style = 0;
  231095. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231096. style = NSBorderlessWindowMask;
  231097. else
  231098. style = NSTitledWindowMask;
  231099. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231100. style |= NSMiniaturizableWindowMask;
  231101. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231102. style |= NSClosableWindowMask;
  231103. if ((windowStyleFlags & windowIsResizable) != 0)
  231104. style |= NSResizableWindowMask;
  231105. window = [[JuceNSWindow alloc] initWithContentRect: r
  231106. styleMask: style
  231107. backing: NSBackingStoreBuffered
  231108. defer: YES];
  231109. [((JuceNSWindow*) window) setOwner: this];
  231110. [window orderOut: nil];
  231111. [window setDelegate: (JuceNSWindow*) window];
  231112. [window setOpaque: component->isOpaque()];
  231113. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231114. if (component->isAlwaysOnTop())
  231115. [window setLevel: NSFloatingWindowLevel];
  231116. [window setContentView: view];
  231117. [window setAutodisplay: YES];
  231118. [window setAcceptsMouseMovedEvents: YES];
  231119. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231120. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231121. [window setReleasedWhenClosed: YES];
  231122. [window retain];
  231123. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231124. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231125. }
  231126. const float alpha = component->getAlpha();
  231127. if (alpha < 1.0f)
  231128. setAlpha (alpha);
  231129. setTitle (component->getName());
  231130. }
  231131. NSViewComponentPeer::~NSViewComponentPeer()
  231132. {
  231133. view->owner = 0;
  231134. [view removeFromSuperview];
  231135. [view release];
  231136. if (! isSharedWindow)
  231137. {
  231138. [((JuceNSWindow*) window) setOwner: 0];
  231139. [window close];
  231140. [window release];
  231141. }
  231142. }
  231143. void* NSViewComponentPeer::getNativeHandle() const
  231144. {
  231145. return view;
  231146. }
  231147. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231148. {
  231149. if (isSharedWindow)
  231150. {
  231151. [view setHidden: ! shouldBeVisible];
  231152. }
  231153. else
  231154. {
  231155. if (shouldBeVisible)
  231156. {
  231157. [window orderFront: nil];
  231158. handleBroughtToFront();
  231159. }
  231160. else
  231161. {
  231162. [window orderOut: nil];
  231163. }
  231164. }
  231165. }
  231166. void NSViewComponentPeer::setTitle (const String& title)
  231167. {
  231168. const ScopedAutoReleasePool pool;
  231169. if (! isSharedWindow)
  231170. [window setTitle: juceStringToNS (title)];
  231171. }
  231172. void NSViewComponentPeer::setPosition (int x, int y)
  231173. {
  231174. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231175. }
  231176. void NSViewComponentPeer::setSize (int w, int h)
  231177. {
  231178. setBounds (component->getX(), component->getY(), w, h, false);
  231179. }
  231180. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231181. {
  231182. fullScreen = isNowFullScreen;
  231183. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231184. if (isSharedWindow)
  231185. {
  231186. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231187. if ([view frame].size.width != r.size.width
  231188. || [view frame].size.height != r.size.height)
  231189. [view setNeedsDisplay: true];
  231190. [view setFrame: r];
  231191. }
  231192. else
  231193. {
  231194. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231195. [window setFrame: [window frameRectForContentRect: r]
  231196. display: true];
  231197. }
  231198. }
  231199. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231200. {
  231201. NSRect r = [view frame];
  231202. if (global && [view window] != 0)
  231203. {
  231204. r = [view convertRect: r toView: nil];
  231205. NSRect wr = [[view window] frame];
  231206. r.origin.x += wr.origin.x;
  231207. r.origin.y += wr.origin.y;
  231208. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231209. }
  231210. else
  231211. {
  231212. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231213. }
  231214. return Rectangle<int> (convertToRectInt (r));
  231215. }
  231216. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231217. {
  231218. return getBounds (! isSharedWindow);
  231219. }
  231220. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231221. {
  231222. return getBounds (true).getPosition();
  231223. }
  231224. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231225. {
  231226. return relativePosition + getScreenPosition();
  231227. }
  231228. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231229. {
  231230. return screenPosition - getScreenPosition();
  231231. }
  231232. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231233. {
  231234. if (constrainer != 0)
  231235. {
  231236. NSRect current = [window frame];
  231237. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231238. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231239. Rectangle<int> pos (convertToRectInt (r));
  231240. Rectangle<int> original (convertToRectInt (current));
  231241. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231242. if ([window inLiveResize])
  231243. #else
  231244. if ([window respondsToSelector: @selector (inLiveResize)]
  231245. && [window performSelector: @selector (inLiveResize)])
  231246. #endif
  231247. {
  231248. constrainer->checkBounds (pos, original,
  231249. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231250. false, false, true, true);
  231251. }
  231252. else
  231253. {
  231254. constrainer->checkBounds (pos, original,
  231255. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231256. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231257. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231258. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231259. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231260. }
  231261. r.origin.x = pos.getX();
  231262. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231263. r.size.width = pos.getWidth();
  231264. r.size.height = pos.getHeight();
  231265. }
  231266. return r;
  231267. }
  231268. void NSViewComponentPeer::setAlpha (float newAlpha)
  231269. {
  231270. if (! isSharedWindow)
  231271. [window setAlphaValue: (CGFloat) newAlpha];
  231272. else
  231273. [view setAlphaValue: (CGFloat) newAlpha];
  231274. }
  231275. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231276. {
  231277. if (! isSharedWindow)
  231278. {
  231279. if (shouldBeMinimised)
  231280. [window miniaturize: nil];
  231281. else
  231282. [window deminiaturize: nil];
  231283. }
  231284. }
  231285. bool NSViewComponentPeer::isMinimised() const
  231286. {
  231287. return window != 0 && [window isMiniaturized];
  231288. }
  231289. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231290. {
  231291. if (! isSharedWindow)
  231292. {
  231293. Rectangle<int> r (lastNonFullscreenBounds);
  231294. setMinimised (false);
  231295. if (fullScreen != shouldBeFullScreen)
  231296. {
  231297. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231298. {
  231299. fullScreen = true;
  231300. [window performZoom: nil];
  231301. }
  231302. else
  231303. {
  231304. if (shouldBeFullScreen)
  231305. r = Desktop::getInstance().getMainMonitorArea();
  231306. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231307. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231308. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231309. }
  231310. }
  231311. }
  231312. }
  231313. bool NSViewComponentPeer::isFullScreen() const
  231314. {
  231315. return fullScreen;
  231316. }
  231317. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231318. {
  231319. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231320. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231321. return false;
  231322. NSPoint p;
  231323. p.x = (float) position.getX();
  231324. p.y = (float) position.getY();
  231325. NSView* v = [view hitTest: p];
  231326. if (trueIfInAChildWindow)
  231327. return v != nil;
  231328. return v == view;
  231329. }
  231330. const BorderSize NSViewComponentPeer::getFrameSize() const
  231331. {
  231332. BorderSize b;
  231333. if (! isSharedWindow)
  231334. {
  231335. NSRect v = [view convertRect: [view frame] toView: nil];
  231336. NSRect w = [window frame];
  231337. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231338. b.setBottom ((int) v.origin.y);
  231339. b.setLeft ((int) v.origin.x);
  231340. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231341. }
  231342. return b;
  231343. }
  231344. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231345. {
  231346. if (! isSharedWindow)
  231347. {
  231348. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231349. : NSNormalWindowLevel];
  231350. }
  231351. return true;
  231352. }
  231353. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231354. {
  231355. if (isSharedWindow)
  231356. {
  231357. [[view superview] addSubview: view
  231358. positioned: NSWindowAbove
  231359. relativeTo: nil];
  231360. }
  231361. if (window != 0 && component->isVisible())
  231362. {
  231363. if (makeActiveWindow)
  231364. [window makeKeyAndOrderFront: nil];
  231365. else
  231366. [window orderFront: nil];
  231367. if (! recursiveToFrontCall)
  231368. {
  231369. recursiveToFrontCall = true;
  231370. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231371. handleBroughtToFront();
  231372. recursiveToFrontCall = false;
  231373. }
  231374. }
  231375. }
  231376. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231377. {
  231378. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231379. jassert (otherPeer != 0); // wrong type of window?
  231380. if (otherPeer != 0)
  231381. {
  231382. if (isSharedWindow)
  231383. {
  231384. [[view superview] addSubview: view
  231385. positioned: NSWindowBelow
  231386. relativeTo: otherPeer->view];
  231387. }
  231388. else
  231389. {
  231390. [window orderWindow: NSWindowBelow
  231391. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231392. : nil ];
  231393. }
  231394. }
  231395. }
  231396. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231397. {
  231398. // to do..
  231399. }
  231400. void NSViewComponentPeer::viewFocusGain()
  231401. {
  231402. if (currentlyFocusedPeer != this)
  231403. {
  231404. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231405. currentlyFocusedPeer->handleFocusLoss();
  231406. currentlyFocusedPeer = this;
  231407. handleFocusGain();
  231408. }
  231409. }
  231410. void NSViewComponentPeer::viewFocusLoss()
  231411. {
  231412. if (currentlyFocusedPeer == this)
  231413. {
  231414. currentlyFocusedPeer = 0;
  231415. handleFocusLoss();
  231416. }
  231417. }
  231418. void juce_HandleProcessFocusChange()
  231419. {
  231420. NSViewComponentPeer::keysCurrentlyDown.clear();
  231421. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231422. {
  231423. if (Process::isForegroundProcess())
  231424. {
  231425. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231426. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231427. }
  231428. else
  231429. {
  231430. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231431. // turn kiosk mode off if we lose focus..
  231432. Desktop::getInstance().setKioskModeComponent (0);
  231433. }
  231434. }
  231435. }
  231436. bool NSViewComponentPeer::isFocused() const
  231437. {
  231438. return isSharedWindow ? this == currentlyFocusedPeer
  231439. : (window != 0 && [window isKeyWindow]);
  231440. }
  231441. void NSViewComponentPeer::grabFocus()
  231442. {
  231443. if (window != 0)
  231444. {
  231445. [window makeKeyWindow];
  231446. [window makeFirstResponder: view];
  231447. viewFocusGain();
  231448. }
  231449. }
  231450. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231451. {
  231452. }
  231453. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231454. {
  231455. String unicode (nsStringToJuce ([ev characters]));
  231456. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231457. int keyCode = getKeyCodeFromEvent (ev);
  231458. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231459. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231460. if (unicode.isNotEmpty() || keyCode != 0)
  231461. {
  231462. if (isKeyDown)
  231463. {
  231464. bool used = false;
  231465. while (unicode.length() > 0)
  231466. {
  231467. juce_wchar textCharacter = unicode[0];
  231468. unicode = unicode.substring (1);
  231469. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231470. textCharacter = 0;
  231471. used = handleKeyUpOrDown (true) || used;
  231472. used = handleKeyPress (keyCode, textCharacter) || used;
  231473. }
  231474. return used;
  231475. }
  231476. else
  231477. {
  231478. if (handleKeyUpOrDown (false))
  231479. return true;
  231480. }
  231481. }
  231482. return false;
  231483. }
  231484. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231485. {
  231486. updateKeysDown (ev, true);
  231487. bool used = handleKeyEvent (ev, true);
  231488. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231489. {
  231490. // for command keys, the key-up event is thrown away, so simulate one..
  231491. updateKeysDown (ev, false);
  231492. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231493. }
  231494. // (If we're running modally, don't allow unused keystrokes to be passed
  231495. // along to other blocked views..)
  231496. if (Component::getCurrentlyModalComponent() != 0)
  231497. used = true;
  231498. return used;
  231499. }
  231500. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231501. {
  231502. updateKeysDown (ev, false);
  231503. return handleKeyEvent (ev, false)
  231504. || Component::getCurrentlyModalComponent() != 0;
  231505. }
  231506. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231507. {
  231508. keysCurrentlyDown.clear();
  231509. handleKeyUpOrDown (true);
  231510. updateModifiers (ev);
  231511. handleModifierKeysChange();
  231512. }
  231513. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231514. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231515. {
  231516. if ([ev type] == NSKeyDown)
  231517. return redirectKeyDown (ev);
  231518. else if ([ev type] == NSKeyUp)
  231519. return redirectKeyUp (ev);
  231520. return false;
  231521. }
  231522. #endif
  231523. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231524. {
  231525. updateModifiers (ev);
  231526. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231527. }
  231528. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231529. {
  231530. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231531. sendMouseEvent (ev);
  231532. }
  231533. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231534. {
  231535. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231536. sendMouseEvent (ev);
  231537. showArrowCursorIfNeeded();
  231538. }
  231539. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231540. {
  231541. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231542. sendMouseEvent (ev);
  231543. }
  231544. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231545. {
  231546. currentModifiers = currentModifiers.withoutMouseButtons();
  231547. sendMouseEvent (ev);
  231548. showArrowCursorIfNeeded();
  231549. }
  231550. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231551. {
  231552. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231553. currentModifiers = currentModifiers.withoutMouseButtons();
  231554. sendMouseEvent (ev);
  231555. }
  231556. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231557. {
  231558. currentModifiers = currentModifiers.withoutMouseButtons();
  231559. sendMouseEvent (ev);
  231560. }
  231561. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231562. {
  231563. updateModifiers (ev);
  231564. float x = 0, y = 0;
  231565. @try
  231566. {
  231567. x = [ev deviceDeltaX] * 0.5f;
  231568. y = [ev deviceDeltaY] * 0.5f;
  231569. }
  231570. @catch (...)
  231571. {}
  231572. if (x == 0 && y == 0)
  231573. {
  231574. x = [ev deltaX] * 10.0f;
  231575. y = [ev deltaY] * 10.0f;
  231576. }
  231577. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231578. }
  231579. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231580. {
  231581. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231582. if (mouse.getComponentUnderMouse() == 0
  231583. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231584. {
  231585. [[NSCursor arrowCursor] set];
  231586. }
  231587. }
  231588. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  231589. {
  231590. NSString* bestType
  231591. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231592. if (bestType == nil)
  231593. return false;
  231594. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  231595. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  231596. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  231597. if (list == nil)
  231598. return false;
  231599. StringArray files;
  231600. if ([list isKindOfClass: [NSArray class]])
  231601. {
  231602. NSArray* items = (NSArray*) list;
  231603. for (unsigned int i = 0; i < [items count]; ++i)
  231604. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  231605. }
  231606. if (files.size() == 0)
  231607. return false;
  231608. if (type == 0)
  231609. handleFileDragMove (files, pos);
  231610. else if (type == 1)
  231611. handleFileDragExit (files);
  231612. else if (type == 2)
  231613. handleFileDragDrop (files, pos);
  231614. return true;
  231615. }
  231616. bool NSViewComponentPeer::isOpaque()
  231617. {
  231618. return component == 0 || component->isOpaque();
  231619. }
  231620. void NSViewComponentPeer::drawRect (NSRect r)
  231621. {
  231622. if (r.size.width < 1.0f || r.size.height < 1.0f)
  231623. return;
  231624. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  231625. if (! component->isOpaque())
  231626. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  231627. #if USE_COREGRAPHICS_RENDERING
  231628. if (usingCoreGraphics)
  231629. {
  231630. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  231631. insideDrawRect = true;
  231632. handlePaint (context);
  231633. insideDrawRect = false;
  231634. }
  231635. else
  231636. #endif
  231637. {
  231638. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  231639. (int) (r.size.width + 0.5f),
  231640. (int) (r.size.height + 0.5f),
  231641. ! getComponent()->isOpaque());
  231642. const int xOffset = -roundToInt (r.origin.x);
  231643. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  231644. const NSRect* rects = 0;
  231645. NSInteger numRects = 0;
  231646. [view getRectsBeingDrawn: &rects count: &numRects];
  231647. const Rectangle<int> clipBounds (temp.getBounds());
  231648. RectangleList clip;
  231649. for (int i = 0; i < numRects; ++i)
  231650. {
  231651. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  231652. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  231653. roundToInt (rects[i].size.width),
  231654. roundToInt (rects[i].size.height))));
  231655. }
  231656. if (! clip.isEmpty())
  231657. {
  231658. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  231659. insideDrawRect = true;
  231660. handlePaint (context);
  231661. insideDrawRect = false;
  231662. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  231663. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  231664. CGColorSpaceRelease (colourSpace);
  231665. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  231666. CGImageRelease (image);
  231667. }
  231668. }
  231669. }
  231670. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  231671. {
  231672. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  231673. #if USE_COREGRAPHICS_RENDERING
  231674. s.add ("CoreGraphics Renderer");
  231675. #endif
  231676. return s;
  231677. }
  231678. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  231679. {
  231680. return usingCoreGraphics ? 1 : 0;
  231681. }
  231682. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  231683. {
  231684. #if USE_COREGRAPHICS_RENDERING
  231685. if (usingCoreGraphics != (index > 0))
  231686. {
  231687. usingCoreGraphics = index > 0;
  231688. [view setNeedsDisplay: true];
  231689. }
  231690. #endif
  231691. }
  231692. bool NSViewComponentPeer::canBecomeKeyWindow()
  231693. {
  231694. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  231695. }
  231696. bool NSViewComponentPeer::windowShouldClose()
  231697. {
  231698. if (! isValidPeer (this))
  231699. return YES;
  231700. handleUserClosingWindow();
  231701. return NO;
  231702. }
  231703. void NSViewComponentPeer::redirectMovedOrResized()
  231704. {
  231705. handleMovedOrResized();
  231706. }
  231707. void NSViewComponentPeer::viewMovedToWindow()
  231708. {
  231709. if (isSharedWindow)
  231710. window = [view window];
  231711. }
  231712. void Desktop::createMouseInputSources()
  231713. {
  231714. mouseSources.add (new MouseInputSource (0, true));
  231715. }
  231716. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  231717. {
  231718. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  231719. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  231720. // is apparently still available in 64-bit apps..
  231721. if (enableOrDisable)
  231722. {
  231723. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  231724. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231725. }
  231726. else
  231727. {
  231728. SetSystemUIMode (kUIModeNormal, 0);
  231729. }
  231730. }
  231731. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  231732. {
  231733. if (insideDrawRect)
  231734. {
  231735. class AsyncRepaintMessage : public CallbackMessage
  231736. {
  231737. public:
  231738. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  231739. : peer (peer_), rect (rect_)
  231740. {
  231741. }
  231742. void messageCallback()
  231743. {
  231744. if (ComponentPeer::isValidPeer (peer))
  231745. peer->repaint (rect);
  231746. }
  231747. private:
  231748. NSViewComponentPeer* const peer;
  231749. const Rectangle<int> rect;
  231750. };
  231751. (new AsyncRepaintMessage (this, area))->post();
  231752. }
  231753. else
  231754. {
  231755. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  231756. (float) area.getWidth(), (float) area.getHeight())];
  231757. }
  231758. }
  231759. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  231760. {
  231761. [view displayIfNeeded];
  231762. }
  231763. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  231764. {
  231765. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  231766. }
  231767. const Image juce_createIconForFile (const File& file)
  231768. {
  231769. const ScopedAutoReleasePool pool;
  231770. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  231771. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  231772. [NSGraphicsContext saveGraphicsState];
  231773. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  231774. [image drawAtPoint: NSMakePoint (0, 0)
  231775. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  231776. operation: NSCompositeSourceOver fraction: 1.0f];
  231777. [[NSGraphicsContext currentContext] flushGraphics];
  231778. [NSGraphicsContext restoreGraphicsState];
  231779. return Image (result);
  231780. }
  231781. const int KeyPress::spaceKey = ' ';
  231782. const int KeyPress::returnKey = 0x0d;
  231783. const int KeyPress::escapeKey = 0x1b;
  231784. const int KeyPress::backspaceKey = 0x7f;
  231785. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  231786. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  231787. const int KeyPress::upKey = NSUpArrowFunctionKey;
  231788. const int KeyPress::downKey = NSDownArrowFunctionKey;
  231789. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  231790. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  231791. const int KeyPress::endKey = NSEndFunctionKey;
  231792. const int KeyPress::homeKey = NSHomeFunctionKey;
  231793. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  231794. const int KeyPress::insertKey = -1;
  231795. const int KeyPress::tabKey = 9;
  231796. const int KeyPress::F1Key = NSF1FunctionKey;
  231797. const int KeyPress::F2Key = NSF2FunctionKey;
  231798. const int KeyPress::F3Key = NSF3FunctionKey;
  231799. const int KeyPress::F4Key = NSF4FunctionKey;
  231800. const int KeyPress::F5Key = NSF5FunctionKey;
  231801. const int KeyPress::F6Key = NSF6FunctionKey;
  231802. const int KeyPress::F7Key = NSF7FunctionKey;
  231803. const int KeyPress::F8Key = NSF8FunctionKey;
  231804. const int KeyPress::F9Key = NSF9FunctionKey;
  231805. const int KeyPress::F10Key = NSF10FunctionKey;
  231806. const int KeyPress::F11Key = NSF1FunctionKey;
  231807. const int KeyPress::F12Key = NSF12FunctionKey;
  231808. const int KeyPress::F13Key = NSF13FunctionKey;
  231809. const int KeyPress::F14Key = NSF14FunctionKey;
  231810. const int KeyPress::F15Key = NSF15FunctionKey;
  231811. const int KeyPress::F16Key = NSF16FunctionKey;
  231812. const int KeyPress::numberPad0 = 0x30020;
  231813. const int KeyPress::numberPad1 = 0x30021;
  231814. const int KeyPress::numberPad2 = 0x30022;
  231815. const int KeyPress::numberPad3 = 0x30023;
  231816. const int KeyPress::numberPad4 = 0x30024;
  231817. const int KeyPress::numberPad5 = 0x30025;
  231818. const int KeyPress::numberPad6 = 0x30026;
  231819. const int KeyPress::numberPad7 = 0x30027;
  231820. const int KeyPress::numberPad8 = 0x30028;
  231821. const int KeyPress::numberPad9 = 0x30029;
  231822. const int KeyPress::numberPadAdd = 0x3002a;
  231823. const int KeyPress::numberPadSubtract = 0x3002b;
  231824. const int KeyPress::numberPadMultiply = 0x3002c;
  231825. const int KeyPress::numberPadDivide = 0x3002d;
  231826. const int KeyPress::numberPadSeparator = 0x3002e;
  231827. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  231828. const int KeyPress::numberPadEquals = 0x30030;
  231829. const int KeyPress::numberPadDelete = 0x30031;
  231830. const int KeyPress::playKey = 0x30000;
  231831. const int KeyPress::stopKey = 0x30001;
  231832. const int KeyPress::fastForwardKey = 0x30002;
  231833. const int KeyPress::rewindKey = 0x30003;
  231834. #endif
  231835. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231836. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  231837. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231838. // compiled on its own).
  231839. #if JUCE_INCLUDED_FILE
  231840. #if JUCE_MAC
  231841. namespace MouseCursorHelpers
  231842. {
  231843. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  231844. {
  231845. NSImage* im = CoreGraphicsImage::createNSImage (image);
  231846. NSCursor* c = [[NSCursor alloc] initWithImage: im
  231847. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  231848. [im release];
  231849. return c;
  231850. }
  231851. static void* fromWebKitFile (const char* filename, float hx, float hy)
  231852. {
  231853. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  231854. BufferedInputStream buf (fileStream, 4096);
  231855. PNGImageFormat pngFormat;
  231856. Image im (pngFormat.decodeImage (buf));
  231857. if (im.isValid())
  231858. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  231859. jassertfalse;
  231860. return 0;
  231861. }
  231862. }
  231863. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  231864. {
  231865. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  231866. }
  231867. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  231868. {
  231869. const ScopedAutoReleasePool pool;
  231870. NSCursor* c = 0;
  231871. switch (type)
  231872. {
  231873. case NormalCursor: c = [NSCursor arrowCursor]; break;
  231874. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  231875. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  231876. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  231877. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  231878. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  231879. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  231880. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  231881. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  231882. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  231883. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  231884. case UpDownResizeCursor:
  231885. case TopEdgeResizeCursor:
  231886. case BottomEdgeResizeCursor:
  231887. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  231888. case TopLeftCornerResizeCursor:
  231889. case BottomRightCornerResizeCursor:
  231890. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231891. case TopRightCornerResizeCursor:
  231892. case BottomLeftCornerResizeCursor:
  231893. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231894. case UpDownLeftRightResizeCursor:
  231895. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231896. default:
  231897. jassertfalse;
  231898. break;
  231899. }
  231900. [c retain];
  231901. return c;
  231902. }
  231903. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231904. {
  231905. [((NSCursor*) cursorHandle) release];
  231906. }
  231907. void MouseCursor::showInAllWindows() const
  231908. {
  231909. showInWindow (0);
  231910. }
  231911. void MouseCursor::showInWindow (ComponentPeer*) const
  231912. {
  231913. NSCursor* c = (NSCursor*) getHandle();
  231914. if (c == 0)
  231915. c = [NSCursor arrowCursor];
  231916. [c set];
  231917. }
  231918. #else
  231919. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231920. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231921. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231922. void MouseCursor::showInAllWindows() const {}
  231923. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231924. #endif
  231925. #endif
  231926. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231927. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231928. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231929. // compiled on its own).
  231930. #if JUCE_INCLUDED_FILE
  231931. class NSViewComponentInternal : public ComponentMovementWatcher
  231932. {
  231933. Component* const owner;
  231934. NSViewComponentPeer* currentPeer;
  231935. bool wasShowing;
  231936. public:
  231937. NSView* const view;
  231938. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  231939. : ComponentMovementWatcher (owner_),
  231940. owner (owner_),
  231941. currentPeer (0),
  231942. wasShowing (false),
  231943. view (view_)
  231944. {
  231945. [view_ retain];
  231946. if (owner_->isShowing())
  231947. componentPeerChanged();
  231948. }
  231949. ~NSViewComponentInternal()
  231950. {
  231951. [view removeFromSuperview];
  231952. [view release];
  231953. }
  231954. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231955. {
  231956. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231957. // The ComponentMovementWatcher version of this method avoids calling
  231958. // us when the top-level comp is resized, but for an NSView we need to know this
  231959. // because with inverted co-ords, we need to update the position even if the
  231960. // top-left pos hasn't changed
  231961. if (comp.isOnDesktop() && wasResized)
  231962. componentMovedOrResized (wasMoved, wasResized);
  231963. }
  231964. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231965. {
  231966. Component* const topComp = owner->getTopLevelComponent();
  231967. if (topComp->getPeer() != 0)
  231968. {
  231969. const Point<int> pos (topComp->getLocalPoint (owner, Point<int>()));
  231970. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  231971. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231972. [view setFrame: r];
  231973. }
  231974. }
  231975. void componentPeerChanged()
  231976. {
  231977. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  231978. if (currentPeer != peer)
  231979. {
  231980. if ([view superview] != nil)
  231981. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  231982. // override the call and use it as a sign that they're being deleted, which breaks everything..
  231983. currentPeer = peer;
  231984. if (peer != 0)
  231985. {
  231986. [peer->view addSubview: view];
  231987. componentMovedOrResized (false, false);
  231988. }
  231989. }
  231990. [view setHidden: ! owner->isShowing()];
  231991. }
  231992. void componentVisibilityChanged (Component&)
  231993. {
  231994. componentPeerChanged();
  231995. }
  231996. const Rectangle<int> getViewBounds() const
  231997. {
  231998. NSRect r = [view frame];
  231999. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232000. }
  232001. private:
  232002. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  232003. };
  232004. NSViewComponent::NSViewComponent()
  232005. {
  232006. }
  232007. NSViewComponent::~NSViewComponent()
  232008. {
  232009. }
  232010. void NSViewComponent::setView (void* view)
  232011. {
  232012. if (view != getView())
  232013. {
  232014. if (view != 0)
  232015. info = new NSViewComponentInternal ((NSView*) view, this);
  232016. else
  232017. info = 0;
  232018. }
  232019. }
  232020. void* NSViewComponent::getView() const
  232021. {
  232022. return info == 0 ? 0 : info->view;
  232023. }
  232024. void NSViewComponent::resizeToFitView()
  232025. {
  232026. if (info != 0)
  232027. setBounds (info->getViewBounds());
  232028. }
  232029. void NSViewComponent::paint (Graphics&)
  232030. {
  232031. }
  232032. #endif
  232033. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232034. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232035. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232036. // compiled on its own).
  232037. #if JUCE_INCLUDED_FILE
  232038. AppleRemoteDevice::AppleRemoteDevice()
  232039. : device (0),
  232040. queue (0),
  232041. remoteId (0)
  232042. {
  232043. }
  232044. AppleRemoteDevice::~AppleRemoteDevice()
  232045. {
  232046. stop();
  232047. }
  232048. namespace
  232049. {
  232050. io_object_t getAppleRemoteDevice()
  232051. {
  232052. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232053. io_iterator_t iter = 0;
  232054. io_object_t iod = 0;
  232055. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232056. && iter != 0)
  232057. {
  232058. iod = IOIteratorNext (iter);
  232059. }
  232060. IOObjectRelease (iter);
  232061. return iod;
  232062. }
  232063. bool createAppleRemoteInterface (io_object_t iod, void** device)
  232064. {
  232065. jassert (*device == 0);
  232066. io_name_t classname;
  232067. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232068. {
  232069. IOCFPlugInInterface** cfPlugInInterface = 0;
  232070. SInt32 score = 0;
  232071. if (IOCreatePlugInInterfaceForService (iod,
  232072. kIOHIDDeviceUserClientTypeID,
  232073. kIOCFPlugInInterfaceID,
  232074. &cfPlugInInterface,
  232075. &score) == kIOReturnSuccess)
  232076. {
  232077. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232078. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232079. device);
  232080. (void) hr;
  232081. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232082. }
  232083. }
  232084. return *device != 0;
  232085. }
  232086. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232087. {
  232088. if (result == kIOReturnSuccess)
  232089. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232090. }
  232091. }
  232092. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232093. {
  232094. if (queue != 0)
  232095. return true;
  232096. stop();
  232097. bool result = false;
  232098. io_object_t iod = getAppleRemoteDevice();
  232099. if (iod != 0)
  232100. {
  232101. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232102. result = true;
  232103. else
  232104. stop();
  232105. IOObjectRelease (iod);
  232106. }
  232107. return result;
  232108. }
  232109. void AppleRemoteDevice::stop()
  232110. {
  232111. if (queue != 0)
  232112. {
  232113. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232114. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232115. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232116. queue = 0;
  232117. }
  232118. if (device != 0)
  232119. {
  232120. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232121. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232122. device = 0;
  232123. }
  232124. }
  232125. bool AppleRemoteDevice::isActive() const
  232126. {
  232127. return queue != 0;
  232128. }
  232129. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232130. {
  232131. Array <int> cookies;
  232132. CFArrayRef elements;
  232133. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232134. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232135. return false;
  232136. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232137. {
  232138. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232139. // get the cookie
  232140. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232141. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232142. continue;
  232143. long number;
  232144. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232145. continue;
  232146. cookies.add ((int) number);
  232147. }
  232148. CFRelease (elements);
  232149. if ((*(IOHIDDeviceInterface**) device)
  232150. ->open ((IOHIDDeviceInterface**) device,
  232151. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232152. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232153. {
  232154. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232155. if (queue != 0)
  232156. {
  232157. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232158. for (int i = 0; i < cookies.size(); ++i)
  232159. {
  232160. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232161. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232162. }
  232163. CFRunLoopSourceRef eventSource;
  232164. if ((*(IOHIDQueueInterface**) queue)
  232165. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232166. {
  232167. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232168. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232169. {
  232170. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232171. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232172. return true;
  232173. }
  232174. }
  232175. }
  232176. }
  232177. return false;
  232178. }
  232179. void AppleRemoteDevice::handleCallbackInternal()
  232180. {
  232181. int totalValues = 0;
  232182. AbsoluteTime nullTime = { 0, 0 };
  232183. char cookies [12];
  232184. int numCookies = 0;
  232185. while (numCookies < numElementsInArray (cookies))
  232186. {
  232187. IOHIDEventStruct e;
  232188. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232189. break;
  232190. if ((int) e.elementCookie == 19)
  232191. {
  232192. remoteId = e.value;
  232193. buttonPressed (switched, false);
  232194. }
  232195. else
  232196. {
  232197. totalValues += e.value;
  232198. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232199. }
  232200. }
  232201. cookies [numCookies++] = 0;
  232202. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232203. static const char buttonPatterns[] =
  232204. {
  232205. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232206. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232207. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232208. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232209. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232210. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232211. 0x1f, 0x12, 0x04, 0x02, 0,
  232212. 0x1f, 0x12, 0x03, 0x02, 0,
  232213. 0x1f, 0x12, 0x1f, 0x12, 0,
  232214. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232215. 19, 0
  232216. };
  232217. int buttonNum = (int) menuButton;
  232218. int i = 0;
  232219. while (i < numElementsInArray (buttonPatterns))
  232220. {
  232221. if (strcmp (cookies, buttonPatterns + i) == 0)
  232222. {
  232223. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232224. break;
  232225. }
  232226. i += (int) strlen (buttonPatterns + i) + 1;
  232227. ++buttonNum;
  232228. }
  232229. }
  232230. #endif
  232231. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232232. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232233. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232234. // compiled on its own).
  232235. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232236. #if JUCE_MAC
  232237. END_JUCE_NAMESPACE
  232238. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232239. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232240. {
  232241. CriticalSection* contextLock;
  232242. bool needsUpdate;
  232243. }
  232244. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232245. - (bool) makeActive;
  232246. - (void) makeInactive;
  232247. - (void) reshape;
  232248. @end
  232249. @implementation ThreadSafeNSOpenGLView
  232250. - (id) initWithFrame: (NSRect) frameRect
  232251. pixelFormat: (NSOpenGLPixelFormat*) format
  232252. {
  232253. contextLock = new CriticalSection();
  232254. self = [super initWithFrame: frameRect pixelFormat: format];
  232255. if (self != nil)
  232256. [[NSNotificationCenter defaultCenter] addObserver: self
  232257. selector: @selector (_surfaceNeedsUpdate:)
  232258. name: NSViewGlobalFrameDidChangeNotification
  232259. object: self];
  232260. return self;
  232261. }
  232262. - (void) dealloc
  232263. {
  232264. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232265. delete contextLock;
  232266. [super dealloc];
  232267. }
  232268. - (bool) makeActive
  232269. {
  232270. const ScopedLock sl (*contextLock);
  232271. if ([self openGLContext] == 0)
  232272. return false;
  232273. [[self openGLContext] makeCurrentContext];
  232274. if (needsUpdate)
  232275. {
  232276. [super update];
  232277. needsUpdate = false;
  232278. }
  232279. return true;
  232280. }
  232281. - (void) makeInactive
  232282. {
  232283. const ScopedLock sl (*contextLock);
  232284. [NSOpenGLContext clearCurrentContext];
  232285. }
  232286. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232287. {
  232288. const ScopedLock sl (*contextLock);
  232289. needsUpdate = true;
  232290. }
  232291. - (void) update
  232292. {
  232293. const ScopedLock sl (*contextLock);
  232294. needsUpdate = true;
  232295. }
  232296. - (void) reshape
  232297. {
  232298. const ScopedLock sl (*contextLock);
  232299. needsUpdate = true;
  232300. }
  232301. @end
  232302. BEGIN_JUCE_NAMESPACE
  232303. class WindowedGLContext : public OpenGLContext
  232304. {
  232305. public:
  232306. WindowedGLContext (Component* const component,
  232307. const OpenGLPixelFormat& pixelFormat_,
  232308. NSOpenGLContext* sharedContext)
  232309. : renderContext (0),
  232310. pixelFormat (pixelFormat_)
  232311. {
  232312. jassert (component != 0);
  232313. NSOpenGLPixelFormatAttribute attribs [64];
  232314. int n = 0;
  232315. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232316. attribs[n++] = NSOpenGLPFAAccelerated;
  232317. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232318. attribs[n++] = NSOpenGLPFAColorSize;
  232319. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232320. pixelFormat.greenBits,
  232321. pixelFormat.blueBits);
  232322. attribs[n++] = NSOpenGLPFAAlphaSize;
  232323. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232324. attribs[n++] = NSOpenGLPFADepthSize;
  232325. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232326. attribs[n++] = NSOpenGLPFAStencilSize;
  232327. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232328. attribs[n++] = NSOpenGLPFAAccumSize;
  232329. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232330. pixelFormat.accumulationBufferGreenBits,
  232331. pixelFormat.accumulationBufferBlueBits,
  232332. pixelFormat.accumulationBufferAlphaBits);
  232333. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232334. attribs[n++] = NSOpenGLPFASampleBuffers;
  232335. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232336. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232337. attribs[n++] = NSOpenGLPFANoRecovery;
  232338. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232339. NSOpenGLPixelFormat* format
  232340. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232341. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232342. pixelFormat: format];
  232343. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232344. shareContext: sharedContext] autorelease];
  232345. const GLint swapInterval = 1;
  232346. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232347. [view setOpenGLContext: renderContext];
  232348. [format release];
  232349. viewHolder = new NSViewComponentInternal (view, component);
  232350. }
  232351. ~WindowedGLContext()
  232352. {
  232353. deleteContext();
  232354. viewHolder = 0;
  232355. }
  232356. void deleteContext()
  232357. {
  232358. makeInactive();
  232359. [renderContext clearDrawable];
  232360. [renderContext setView: nil];
  232361. [view setOpenGLContext: nil];
  232362. renderContext = nil;
  232363. }
  232364. bool makeActive() const throw()
  232365. {
  232366. jassert (renderContext != 0);
  232367. if ([renderContext view] != view)
  232368. [renderContext setView: view];
  232369. [view makeActive];
  232370. return isActive();
  232371. }
  232372. bool makeInactive() const throw()
  232373. {
  232374. [view makeInactive];
  232375. return true;
  232376. }
  232377. bool isActive() const throw()
  232378. {
  232379. return [NSOpenGLContext currentContext] == renderContext;
  232380. }
  232381. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232382. void* getRawContext() const throw() { return renderContext; }
  232383. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232384. {
  232385. }
  232386. void swapBuffers()
  232387. {
  232388. [renderContext flushBuffer];
  232389. }
  232390. bool setSwapInterval (const int numFramesPerSwap)
  232391. {
  232392. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232393. forParameter: NSOpenGLCPSwapInterval];
  232394. return true;
  232395. }
  232396. int getSwapInterval() const
  232397. {
  232398. GLint numFrames = 0;
  232399. [renderContext getValues: &numFrames
  232400. forParameter: NSOpenGLCPSwapInterval];
  232401. return numFrames;
  232402. }
  232403. void repaint()
  232404. {
  232405. // we need to invalidate the juce view that holds this gl view, to make it
  232406. // cause a repaint callback
  232407. NSView* v = (NSView*) viewHolder->view;
  232408. NSRect r = [v frame];
  232409. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232410. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232411. // repaint message, thus never causing our paint() callback, and never repainting
  232412. // the comp. So invalidating just a little bit around the edge helps..
  232413. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232414. }
  232415. void* getNativeWindowHandle() const { return viewHolder->view; }
  232416. NSOpenGLContext* renderContext;
  232417. ThreadSafeNSOpenGLView* view;
  232418. private:
  232419. OpenGLPixelFormat pixelFormat;
  232420. ScopedPointer <NSViewComponentInternal> viewHolder;
  232421. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232422. };
  232423. OpenGLContext* OpenGLComponent::createContext()
  232424. {
  232425. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  232426. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232427. return (c->renderContext != 0) ? c.release() : 0;
  232428. }
  232429. void* OpenGLComponent::getNativeWindowHandle() const
  232430. {
  232431. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232432. : 0;
  232433. }
  232434. void juce_glViewport (const int w, const int h)
  232435. {
  232436. glViewport (0, 0, w, h);
  232437. }
  232438. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232439. OwnedArray <OpenGLPixelFormat>& results)
  232440. {
  232441. /* GLint attribs [64];
  232442. int n = 0;
  232443. attribs[n++] = AGL_RGBA;
  232444. attribs[n++] = AGL_DOUBLEBUFFER;
  232445. attribs[n++] = AGL_ACCELERATED;
  232446. attribs[n++] = AGL_NO_RECOVERY;
  232447. attribs[n++] = AGL_NONE;
  232448. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232449. while (p != 0)
  232450. {
  232451. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232452. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232453. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232454. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232455. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232456. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232457. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232458. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232459. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232460. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232461. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232462. results.add (pf);
  232463. p = aglNextPixelFormat (p);
  232464. }*/
  232465. //jassertfalse // can't see how you do this in cocoa!
  232466. }
  232467. #else
  232468. END_JUCE_NAMESPACE
  232469. @interface JuceGLView : UIView
  232470. {
  232471. }
  232472. + (Class) layerClass;
  232473. @end
  232474. @implementation JuceGLView
  232475. + (Class) layerClass
  232476. {
  232477. return [CAEAGLLayer class];
  232478. }
  232479. @end
  232480. BEGIN_JUCE_NAMESPACE
  232481. class GLESContext : public OpenGLContext
  232482. {
  232483. public:
  232484. GLESContext (UIViewComponentPeer* peer,
  232485. Component* const component_,
  232486. const OpenGLPixelFormat& pixelFormat_,
  232487. const GLESContext* const sharedContext,
  232488. NSUInteger apiType)
  232489. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232490. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232491. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232492. {
  232493. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232494. view.opaque = YES;
  232495. view.hidden = NO;
  232496. view.backgroundColor = [UIColor blackColor];
  232497. view.userInteractionEnabled = NO;
  232498. glLayer = (CAEAGLLayer*) [view layer];
  232499. [peer->view addSubview: view];
  232500. if (sharedContext != 0)
  232501. context = [[EAGLContext alloc] initWithAPI: apiType
  232502. sharegroup: [sharedContext->context sharegroup]];
  232503. else
  232504. context = [[EAGLContext alloc] initWithAPI: apiType];
  232505. createGLBuffers();
  232506. }
  232507. ~GLESContext()
  232508. {
  232509. deleteContext();
  232510. [view removeFromSuperview];
  232511. [view release];
  232512. freeGLBuffers();
  232513. }
  232514. void deleteContext()
  232515. {
  232516. makeInactive();
  232517. [context release];
  232518. context = nil;
  232519. }
  232520. bool makeActive() const throw()
  232521. {
  232522. jassert (context != 0);
  232523. [EAGLContext setCurrentContext: context];
  232524. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232525. return true;
  232526. }
  232527. void swapBuffers()
  232528. {
  232529. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232530. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232531. }
  232532. bool makeInactive() const throw()
  232533. {
  232534. return [EAGLContext setCurrentContext: nil];
  232535. }
  232536. bool isActive() const throw()
  232537. {
  232538. return [EAGLContext currentContext] == context;
  232539. }
  232540. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232541. void* getRawContext() const throw() { return glLayer; }
  232542. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232543. {
  232544. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232545. if (lastWidth != w || lastHeight != h)
  232546. {
  232547. lastWidth = w;
  232548. lastHeight = h;
  232549. freeGLBuffers();
  232550. createGLBuffers();
  232551. }
  232552. }
  232553. bool setSwapInterval (const int numFramesPerSwap)
  232554. {
  232555. numFrames = numFramesPerSwap;
  232556. return true;
  232557. }
  232558. int getSwapInterval() const
  232559. {
  232560. return numFrames;
  232561. }
  232562. void repaint()
  232563. {
  232564. }
  232565. void createGLBuffers()
  232566. {
  232567. makeActive();
  232568. glGenFramebuffersOES (1, &frameBufferHandle);
  232569. glGenRenderbuffersOES (1, &colorBufferHandle);
  232570. glGenRenderbuffersOES (1, &depthBufferHandle);
  232571. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232572. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232573. GLint width, height;
  232574. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232575. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232576. if (useDepthBuffer)
  232577. {
  232578. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232579. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232580. }
  232581. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232582. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232583. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232584. if (useDepthBuffer)
  232585. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232586. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232587. }
  232588. void freeGLBuffers()
  232589. {
  232590. if (frameBufferHandle != 0)
  232591. {
  232592. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232593. frameBufferHandle = 0;
  232594. }
  232595. if (colorBufferHandle != 0)
  232596. {
  232597. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232598. colorBufferHandle = 0;
  232599. }
  232600. if (depthBufferHandle != 0)
  232601. {
  232602. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  232603. depthBufferHandle = 0;
  232604. }
  232605. }
  232606. private:
  232607. WeakReference<Component> component;
  232608. OpenGLPixelFormat pixelFormat;
  232609. JuceGLView* view;
  232610. CAEAGLLayer* glLayer;
  232611. EAGLContext* context;
  232612. bool useDepthBuffer;
  232613. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  232614. int numFrames;
  232615. int lastWidth, lastHeight;
  232616. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  232617. };
  232618. OpenGLContext* OpenGLComponent::createContext()
  232619. {
  232620. ScopedAutoReleasePool pool;
  232621. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  232622. if (peer != 0)
  232623. return new GLESContext (peer, this, preferredPixelFormat,
  232624. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  232625. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  232626. return 0;
  232627. }
  232628. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232629. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232630. {
  232631. }
  232632. void juce_glViewport (const int w, const int h)
  232633. {
  232634. glViewport (0, 0, w, h);
  232635. }
  232636. #endif
  232637. #endif
  232638. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  232639. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  232640. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232641. // compiled on its own).
  232642. #if JUCE_INCLUDED_FILE
  232643. class JuceMainMenuHandler;
  232644. END_JUCE_NAMESPACE
  232645. using namespace JUCE_NAMESPACE;
  232646. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  232647. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232648. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  232649. #else
  232650. @interface JuceMenuCallback : NSObject
  232651. #endif
  232652. {
  232653. JuceMainMenuHandler* owner;
  232654. }
  232655. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  232656. - (void) dealloc;
  232657. - (void) menuItemInvoked: (id) menu;
  232658. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232659. @end
  232660. BEGIN_JUCE_NAMESPACE
  232661. class JuceMainMenuHandler : private MenuBarModel::Listener,
  232662. private DeletedAtShutdown
  232663. {
  232664. public:
  232665. JuceMainMenuHandler()
  232666. : currentModel (0),
  232667. lastUpdateTime (0)
  232668. {
  232669. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  232670. }
  232671. ~JuceMainMenuHandler()
  232672. {
  232673. setMenu (0);
  232674. jassert (instance == this);
  232675. instance = 0;
  232676. [callback release];
  232677. }
  232678. void setMenu (MenuBarModel* const newMenuBarModel)
  232679. {
  232680. if (currentModel != newMenuBarModel)
  232681. {
  232682. if (currentModel != 0)
  232683. currentModel->removeListener (this);
  232684. currentModel = newMenuBarModel;
  232685. if (currentModel != 0)
  232686. currentModel->addListener (this);
  232687. menuBarItemsChanged (0);
  232688. }
  232689. }
  232690. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  232691. const String& name, const int menuId, const int tag)
  232692. {
  232693. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  232694. action: nil
  232695. keyEquivalent: @""];
  232696. [item setTag: tag];
  232697. NSMenu* sub = createMenu (child, name, menuId, tag);
  232698. [parent setSubmenu: sub forItem: item];
  232699. [sub setAutoenablesItems: false];
  232700. [sub release];
  232701. }
  232702. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  232703. const String& name, const int menuId, const int tag)
  232704. {
  232705. [parentItem setTag: tag];
  232706. NSMenu* menu = [parentItem submenu];
  232707. [menu setTitle: juceStringToNS (name)];
  232708. while ([menu numberOfItems] > 0)
  232709. [menu removeItemAtIndex: 0];
  232710. PopupMenu::MenuItemIterator iter (menuToCopy);
  232711. while (iter.next())
  232712. addMenuItem (iter, menu, menuId, tag);
  232713. [menu setAutoenablesItems: false];
  232714. [menu update];
  232715. }
  232716. void menuBarItemsChanged (MenuBarModel*)
  232717. {
  232718. lastUpdateTime = Time::getMillisecondCounter();
  232719. StringArray menuNames;
  232720. if (currentModel != 0)
  232721. menuNames = currentModel->getMenuBarNames();
  232722. NSMenu* menuBar = [NSApp mainMenu];
  232723. while ([menuBar numberOfItems] > 1 + menuNames.size())
  232724. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  232725. int menuId = 1;
  232726. for (int i = 0; i < menuNames.size(); ++i)
  232727. {
  232728. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  232729. if (i >= [menuBar numberOfItems] - 1)
  232730. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  232731. else
  232732. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  232733. }
  232734. }
  232735. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  232736. {
  232737. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  232738. if (item != 0)
  232739. flashMenuBar ([item menu]);
  232740. }
  232741. void updateMenus (NSMenu* menu)
  232742. {
  232743. if (PopupMenu::dismissAllActiveMenus())
  232744. {
  232745. // If we were running a juce menu, then we should let that modal loop finish before allowing
  232746. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  232747. if ([menu respondsToSelector: @selector (cancelTracking)])
  232748. [menu performSelector: @selector (cancelTracking)];
  232749. }
  232750. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  232751. menuBarItemsChanged (0);
  232752. }
  232753. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  232754. {
  232755. if (currentModel != 0)
  232756. {
  232757. if (commandManager != 0)
  232758. {
  232759. ApplicationCommandTarget::InvocationInfo info (commandId);
  232760. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  232761. commandManager->invoke (info, true);
  232762. }
  232763. currentModel->menuItemSelected (commandId, topLevelIndex);
  232764. }
  232765. }
  232766. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  232767. const int topLevelMenuId, const int topLevelIndex)
  232768. {
  232769. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  232770. if (text == 0)
  232771. text = @"";
  232772. if (iter.isSeparator)
  232773. {
  232774. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  232775. }
  232776. else if (iter.isSectionHeader)
  232777. {
  232778. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232779. action: nil
  232780. keyEquivalent: @""];
  232781. [item setEnabled: false];
  232782. }
  232783. else if (iter.subMenu != 0)
  232784. {
  232785. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232786. action: nil
  232787. keyEquivalent: @""];
  232788. [item setTag: iter.itemId];
  232789. [item setEnabled: iter.isEnabled];
  232790. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  232791. [sub setDelegate: nil];
  232792. [menuToAddTo setSubmenu: sub forItem: item];
  232793. [sub release];
  232794. }
  232795. else
  232796. {
  232797. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232798. action: @selector (menuItemInvoked:)
  232799. keyEquivalent: @""];
  232800. [item setTag: iter.itemId];
  232801. [item setEnabled: iter.isEnabled];
  232802. [item setState: iter.isTicked ? NSOnState : NSOffState];
  232803. [item setTarget: (id) callback];
  232804. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  232805. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  232806. [item setRepresentedObject: info];
  232807. if (iter.commandManager != 0)
  232808. {
  232809. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  232810. ->getKeyPressesAssignedToCommand (iter.itemId));
  232811. if (keyPresses.size() > 0)
  232812. {
  232813. const KeyPress& kp = keyPresses.getReference(0);
  232814. if (kp.getKeyCode() != KeyPress::backspaceKey
  232815. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  232816. // every time you press the key while editing text)
  232817. {
  232818. juce_wchar key = kp.getTextCharacter();
  232819. if (kp.getKeyCode() == KeyPress::backspaceKey)
  232820. key = NSBackspaceCharacter;
  232821. else if (kp.getKeyCode() == KeyPress::deleteKey)
  232822. key = NSDeleteCharacter;
  232823. else if (key == 0)
  232824. key = (juce_wchar) kp.getKeyCode();
  232825. unsigned int mods = 0;
  232826. if (kp.getModifiers().isShiftDown())
  232827. mods |= NSShiftKeyMask;
  232828. if (kp.getModifiers().isCtrlDown())
  232829. mods |= NSControlKeyMask;
  232830. if (kp.getModifiers().isAltDown())
  232831. mods |= NSAlternateKeyMask;
  232832. if (kp.getModifiers().isCommandDown())
  232833. mods |= NSCommandKeyMask;
  232834. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  232835. [item setKeyEquivalentModifierMask: mods];
  232836. }
  232837. }
  232838. }
  232839. }
  232840. }
  232841. static JuceMainMenuHandler* instance;
  232842. MenuBarModel* currentModel;
  232843. uint32 lastUpdateTime;
  232844. JuceMenuCallback* callback;
  232845. private:
  232846. NSMenu* createMenu (const PopupMenu menu,
  232847. const String& menuName,
  232848. const int topLevelMenuId,
  232849. const int topLevelIndex)
  232850. {
  232851. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  232852. [m setAutoenablesItems: false];
  232853. [m setDelegate: callback];
  232854. PopupMenu::MenuItemIterator iter (menu);
  232855. while (iter.next())
  232856. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  232857. [m update];
  232858. return m;
  232859. }
  232860. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  232861. {
  232862. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  232863. {
  232864. NSMenuItem* m = [menu itemAtIndex: i];
  232865. if ([m tag] == info.commandID)
  232866. return m;
  232867. if ([m submenu] != 0)
  232868. {
  232869. NSMenuItem* found = findMenuItem ([m submenu], info);
  232870. if (found != 0)
  232871. return found;
  232872. }
  232873. }
  232874. return 0;
  232875. }
  232876. static void flashMenuBar (NSMenu* menu)
  232877. {
  232878. if ([[menu title] isEqualToString: @"Apple"])
  232879. return;
  232880. [menu retain];
  232881. const unichar f35Key = NSF35FunctionKey;
  232882. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  232883. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  232884. action: nil
  232885. keyEquivalent: f35String];
  232886. [item setTarget: nil];
  232887. [menu insertItem: item atIndex: [menu numberOfItems]];
  232888. [item release];
  232889. if ([menu indexOfItem: item] >= 0)
  232890. {
  232891. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  232892. location: NSZeroPoint
  232893. modifierFlags: NSCommandKeyMask
  232894. timestamp: 0
  232895. windowNumber: 0
  232896. context: [NSGraphicsContext currentContext]
  232897. characters: f35String
  232898. charactersIgnoringModifiers: f35String
  232899. isARepeat: NO
  232900. keyCode: 0];
  232901. [menu performKeyEquivalent: f35Event];
  232902. if ([menu indexOfItem: item] >= 0)
  232903. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  232904. }
  232905. [menu release];
  232906. }
  232907. };
  232908. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232909. END_JUCE_NAMESPACE
  232910. @implementation JuceMenuCallback
  232911. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232912. {
  232913. [super init];
  232914. owner = owner_;
  232915. return self;
  232916. }
  232917. - (void) dealloc
  232918. {
  232919. [super dealloc];
  232920. }
  232921. - (void) menuItemInvoked: (id) menu
  232922. {
  232923. NSMenuItem* item = (NSMenuItem*) menu;
  232924. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232925. {
  232926. // 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
  232927. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232928. // into the focused component and let it trigger the menu item indirectly.
  232929. NSEvent* e = [NSApp currentEvent];
  232930. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232931. {
  232932. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232933. {
  232934. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232935. if (peer != 0)
  232936. {
  232937. if ([e type] == NSKeyDown)
  232938. peer->redirectKeyDown (e);
  232939. else
  232940. peer->redirectKeyUp (e);
  232941. return;
  232942. }
  232943. }
  232944. }
  232945. NSArray* info = (NSArray*) [item representedObject];
  232946. owner->invoke ((int) [item tag],
  232947. (ApplicationCommandManager*) (pointer_sized_int)
  232948. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232949. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232950. }
  232951. }
  232952. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232953. {
  232954. if (JuceMainMenuHandler::instance != 0)
  232955. JuceMainMenuHandler::instance->updateMenus (menu);
  232956. }
  232957. @end
  232958. BEGIN_JUCE_NAMESPACE
  232959. namespace MainMenuHelpers
  232960. {
  232961. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  232962. {
  232963. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232964. {
  232965. PopupMenu::MenuItemIterator iter (*extraItems);
  232966. while (iter.next())
  232967. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232968. [menu addItem: [NSMenuItem separatorItem]];
  232969. }
  232970. NSMenuItem* item;
  232971. // Services...
  232972. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232973. action: nil keyEquivalent: @""];
  232974. [menu addItem: item];
  232975. [item release];
  232976. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232977. [menu setSubmenu: servicesMenu forItem: item];
  232978. [NSApp setServicesMenu: servicesMenu];
  232979. [servicesMenu release];
  232980. [menu addItem: [NSMenuItem separatorItem]];
  232981. // Hide + Show stuff...
  232982. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232983. action: @selector (hide:) keyEquivalent: @"h"];
  232984. [item setTarget: NSApp];
  232985. [menu addItem: item];
  232986. [item release];
  232987. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  232988. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  232989. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  232990. [item setTarget: NSApp];
  232991. [menu addItem: item];
  232992. [item release];
  232993. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  232994. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  232995. [item setTarget: NSApp];
  232996. [menu addItem: item];
  232997. [item release];
  232998. [menu addItem: [NSMenuItem separatorItem]];
  232999. // Quit item....
  233000. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233001. action: @selector (terminate:) keyEquivalent: @"q"];
  233002. [item setTarget: NSApp];
  233003. [menu addItem: item];
  233004. [item release];
  233005. return menu;
  233006. }
  233007. // Since our app has no NIB, this initialises a standard app menu...
  233008. void rebuildMainMenu (const PopupMenu* extraItems)
  233009. {
  233010. // this can't be used in a plugin!
  233011. jassert (JUCEApplication::isStandaloneApp());
  233012. if (JUCEApplication::getInstance() != 0)
  233013. {
  233014. const ScopedAutoReleasePool pool;
  233015. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233016. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233017. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233018. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233019. [mainMenu setSubmenu: appMenu forItem: item];
  233020. [NSApp setMainMenu: mainMenu];
  233021. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233022. [appMenu release];
  233023. [mainMenu release];
  233024. }
  233025. }
  233026. }
  233027. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233028. const PopupMenu* extraAppleMenuItems)
  233029. {
  233030. if (getMacMainMenu() != newMenuBarModel)
  233031. {
  233032. const ScopedAutoReleasePool pool;
  233033. if (newMenuBarModel == 0)
  233034. {
  233035. delete JuceMainMenuHandler::instance;
  233036. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233037. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233038. extraAppleMenuItems = 0;
  233039. }
  233040. else
  233041. {
  233042. if (JuceMainMenuHandler::instance == 0)
  233043. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233044. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233045. }
  233046. }
  233047. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  233048. if (newMenuBarModel != 0)
  233049. newMenuBarModel->menuItemsChanged();
  233050. }
  233051. MenuBarModel* MenuBarModel::getMacMainMenu()
  233052. {
  233053. return JuceMainMenuHandler::instance != 0
  233054. ? JuceMainMenuHandler::instance->currentModel : 0;
  233055. }
  233056. void juce_initialiseMacMainMenu()
  233057. {
  233058. if (JuceMainMenuHandler::instance == 0)
  233059. MainMenuHelpers::rebuildMainMenu (0);
  233060. }
  233061. #endif
  233062. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233063. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233064. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233065. // compiled on its own).
  233066. #if JUCE_INCLUDED_FILE
  233067. #if JUCE_MAC
  233068. END_JUCE_NAMESPACE
  233069. using namespace JUCE_NAMESPACE;
  233070. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233071. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233072. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233073. #else
  233074. @interface JuceFileChooserDelegate : NSObject
  233075. #endif
  233076. {
  233077. StringArray* filters;
  233078. }
  233079. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233080. - (void) dealloc;
  233081. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233082. @end
  233083. @implementation JuceFileChooserDelegate
  233084. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233085. {
  233086. [super init];
  233087. filters = filters_;
  233088. return self;
  233089. }
  233090. - (void) dealloc
  233091. {
  233092. delete filters;
  233093. [super dealloc];
  233094. }
  233095. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233096. {
  233097. (void) sender;
  233098. const File f (nsStringToJuce (filename));
  233099. for (int i = filters->size(); --i >= 0;)
  233100. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233101. return true;
  233102. return f.isDirectory();
  233103. }
  233104. @end
  233105. BEGIN_JUCE_NAMESPACE
  233106. void FileChooser::showPlatformDialog (Array<File>& results,
  233107. const String& title,
  233108. const File& currentFileOrDirectory,
  233109. const String& filter,
  233110. bool selectsDirectory,
  233111. bool selectsFiles,
  233112. bool isSaveDialogue,
  233113. bool warnAboutOverwritingExistingFiles,
  233114. bool selectMultipleFiles,
  233115. FilePreviewComponent* extraInfoComponent)
  233116. {
  233117. const ScopedAutoReleasePool pool;
  233118. StringArray* filters = new StringArray();
  233119. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233120. filters->trim();
  233121. filters->removeEmptyStrings();
  233122. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233123. [delegate autorelease];
  233124. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233125. : [NSOpenPanel openPanel];
  233126. [panel setTitle: juceStringToNS (title)];
  233127. if (! isSaveDialogue)
  233128. {
  233129. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233130. [openPanel setCanChooseDirectories: selectsDirectory];
  233131. [openPanel setCanChooseFiles: selectsFiles];
  233132. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233133. }
  233134. [panel setDelegate: delegate];
  233135. if (isSaveDialogue || selectsDirectory)
  233136. [panel setCanCreateDirectories: YES];
  233137. String directory, filename;
  233138. if (currentFileOrDirectory.isDirectory())
  233139. {
  233140. directory = currentFileOrDirectory.getFullPathName();
  233141. }
  233142. else
  233143. {
  233144. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233145. filename = currentFileOrDirectory.getFileName();
  233146. }
  233147. if ([panel runModalForDirectory: juceStringToNS (directory)
  233148. file: juceStringToNS (filename)]
  233149. == NSOKButton)
  233150. {
  233151. if (isSaveDialogue)
  233152. {
  233153. results.add (File (nsStringToJuce ([panel filename])));
  233154. }
  233155. else
  233156. {
  233157. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233158. NSArray* urls = [openPanel filenames];
  233159. for (unsigned int i = 0; i < [urls count]; ++i)
  233160. {
  233161. NSString* f = [urls objectAtIndex: i];
  233162. results.add (File (nsStringToJuce (f)));
  233163. }
  233164. }
  233165. }
  233166. [panel setDelegate: nil];
  233167. }
  233168. #else
  233169. void FileChooser::showPlatformDialog (Array<File>& results,
  233170. const String& title,
  233171. const File& currentFileOrDirectory,
  233172. const String& filter,
  233173. bool selectsDirectory,
  233174. bool selectsFiles,
  233175. bool isSaveDialogue,
  233176. bool warnAboutOverwritingExistingFiles,
  233177. bool selectMultipleFiles,
  233178. FilePreviewComponent* extraInfoComponent)
  233179. {
  233180. const ScopedAutoReleasePool pool;
  233181. jassertfalse; //xxx to do
  233182. }
  233183. #endif
  233184. #endif
  233185. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233186. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233187. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233188. // compiled on its own).
  233189. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233190. END_JUCE_NAMESPACE
  233191. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233192. @interface NonInterceptingQTMovieView : QTMovieView
  233193. {
  233194. }
  233195. - (id) initWithFrame: (NSRect) frame;
  233196. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233197. - (NSView*) hitTest: (NSPoint) p;
  233198. @end
  233199. @implementation NonInterceptingQTMovieView
  233200. - (id) initWithFrame: (NSRect) frame
  233201. {
  233202. self = [super initWithFrame: frame];
  233203. [self setNextResponder: [self superview]];
  233204. return self;
  233205. }
  233206. - (void) dealloc
  233207. {
  233208. [super dealloc];
  233209. }
  233210. - (NSView*) hitTest: (NSPoint) point
  233211. {
  233212. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233213. }
  233214. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233215. {
  233216. return YES;
  233217. }
  233218. @end
  233219. BEGIN_JUCE_NAMESPACE
  233220. #define theMovie (static_cast <QTMovie*> (movie))
  233221. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233222. : movie (0)
  233223. {
  233224. setOpaque (true);
  233225. setVisible (true);
  233226. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233227. setView (view);
  233228. [view release];
  233229. }
  233230. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233231. {
  233232. closeMovie();
  233233. setView (0);
  233234. }
  233235. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233236. {
  233237. return true;
  233238. }
  233239. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233240. {
  233241. // unfortunately, QTMovie objects can only be created on the main thread..
  233242. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233243. QTMovie* movie = 0;
  233244. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233245. if (fin != 0)
  233246. {
  233247. movieFile = fin->getFile();
  233248. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233249. error: nil];
  233250. }
  233251. else
  233252. {
  233253. MemoryBlock temp;
  233254. movieStream->readIntoMemoryBlock (temp);
  233255. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233256. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233257. {
  233258. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233259. length: temp.getSize()]
  233260. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233261. MIMEType: @""]
  233262. error: nil];
  233263. if (movie != 0)
  233264. break;
  233265. }
  233266. }
  233267. return movie;
  233268. }
  233269. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233270. const bool isControllerVisible_)
  233271. {
  233272. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233273. }
  233274. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233275. const bool controllerVisible_)
  233276. {
  233277. closeMovie();
  233278. if (getPeer() == 0)
  233279. {
  233280. // To open a movie, this component must be visible inside a functioning window, so that
  233281. // the QT control can be assigned to the window.
  233282. jassertfalse;
  233283. return false;
  233284. }
  233285. movie = openMovieFromStream (movieStream, movieFile);
  233286. [theMovie retain];
  233287. QTMovieView* view = (QTMovieView*) getView();
  233288. [view setMovie: theMovie];
  233289. [view setControllerVisible: controllerVisible_];
  233290. setLooping (looping);
  233291. return movie != nil;
  233292. }
  233293. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233294. const bool isControllerVisible_)
  233295. {
  233296. // unfortunately, QTMovie objects can only be created on the main thread..
  233297. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233298. closeMovie();
  233299. if (getPeer() == 0)
  233300. {
  233301. // To open a movie, this component must be visible inside a functioning window, so that
  233302. // the QT control can be assigned to the window.
  233303. jassertfalse;
  233304. return false;
  233305. }
  233306. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233307. NSError* err;
  233308. if ([QTMovie canInitWithURL: url])
  233309. movie = [QTMovie movieWithURL: url error: &err];
  233310. [theMovie retain];
  233311. QTMovieView* view = (QTMovieView*) getView();
  233312. [view setMovie: theMovie];
  233313. [view setControllerVisible: controllerVisible];
  233314. setLooping (looping);
  233315. return movie != nil;
  233316. }
  233317. void QuickTimeMovieComponent::closeMovie()
  233318. {
  233319. stop();
  233320. QTMovieView* view = (QTMovieView*) getView();
  233321. [view setMovie: nil];
  233322. [theMovie release];
  233323. movie = 0;
  233324. movieFile = File::nonexistent;
  233325. }
  233326. bool QuickTimeMovieComponent::isMovieOpen() const
  233327. {
  233328. return movie != nil;
  233329. }
  233330. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233331. {
  233332. return movieFile;
  233333. }
  233334. void QuickTimeMovieComponent::play()
  233335. {
  233336. [theMovie play];
  233337. }
  233338. void QuickTimeMovieComponent::stop()
  233339. {
  233340. [theMovie stop];
  233341. }
  233342. bool QuickTimeMovieComponent::isPlaying() const
  233343. {
  233344. return movie != 0 && [theMovie rate] != 0;
  233345. }
  233346. void QuickTimeMovieComponent::setPosition (const double seconds)
  233347. {
  233348. if (movie != 0)
  233349. {
  233350. QTTime t;
  233351. t.timeValue = (uint64) (100000.0 * seconds);
  233352. t.timeScale = 100000;
  233353. t.flags = 0;
  233354. [theMovie setCurrentTime: t];
  233355. }
  233356. }
  233357. double QuickTimeMovieComponent::getPosition() const
  233358. {
  233359. if (movie == 0)
  233360. return 0.0;
  233361. QTTime t = [theMovie currentTime];
  233362. return t.timeValue / (double) t.timeScale;
  233363. }
  233364. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233365. {
  233366. [theMovie setRate: newSpeed];
  233367. }
  233368. double QuickTimeMovieComponent::getMovieDuration() const
  233369. {
  233370. if (movie == 0)
  233371. return 0.0;
  233372. QTTime t = [theMovie duration];
  233373. return t.timeValue / (double) t.timeScale;
  233374. }
  233375. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233376. {
  233377. looping = shouldLoop;
  233378. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233379. forKey: QTMovieLoopsAttribute];
  233380. }
  233381. bool QuickTimeMovieComponent::isLooping() const
  233382. {
  233383. return looping;
  233384. }
  233385. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233386. {
  233387. [theMovie setVolume: newVolume];
  233388. }
  233389. float QuickTimeMovieComponent::getMovieVolume() const
  233390. {
  233391. return movie != 0 ? [theMovie volume] : 0.0f;
  233392. }
  233393. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233394. {
  233395. width = 0;
  233396. height = 0;
  233397. if (movie != 0)
  233398. {
  233399. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233400. width = (int) s.width;
  233401. height = (int) s.height;
  233402. }
  233403. }
  233404. void QuickTimeMovieComponent::paint (Graphics& g)
  233405. {
  233406. if (movie == 0)
  233407. g.fillAll (Colours::black);
  233408. }
  233409. bool QuickTimeMovieComponent::isControllerVisible() const
  233410. {
  233411. return controllerVisible;
  233412. }
  233413. void QuickTimeMovieComponent::goToStart()
  233414. {
  233415. setPosition (0.0);
  233416. }
  233417. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233418. const RectanglePlacement& placement)
  233419. {
  233420. int normalWidth, normalHeight;
  233421. getMovieNormalSize (normalWidth, normalHeight);
  233422. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  233423. {
  233424. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  233425. placement.applyTo (x, y, w, h,
  233426. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  233427. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  233428. if (w > 0 && h > 0)
  233429. {
  233430. setBounds (roundToInt (x), roundToInt (y),
  233431. roundToInt (w), roundToInt (h));
  233432. }
  233433. }
  233434. else
  233435. {
  233436. setBounds (spaceToFitWithin);
  233437. }
  233438. }
  233439. #if ! (JUCE_MAC && JUCE_64BIT)
  233440. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233441. {
  233442. if (movieStream == 0)
  233443. return false;
  233444. File file;
  233445. QTMovie* movie = openMovieFromStream (movieStream, file);
  233446. if (movie != nil)
  233447. result = [movie quickTimeMovie];
  233448. return movie != nil;
  233449. }
  233450. #endif
  233451. #endif
  233452. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233453. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233454. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233455. // compiled on its own).
  233456. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233457. const int kilobytesPerSecond1x = 176;
  233458. END_JUCE_NAMESPACE
  233459. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233460. @interface OpenDiskDevice : NSObject
  233461. {
  233462. @public
  233463. DRDevice* device;
  233464. NSMutableArray* tracks;
  233465. bool underrunProtection;
  233466. }
  233467. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233468. - (void) dealloc;
  233469. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233470. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233471. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233472. @end
  233473. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233474. @interface AudioTrackProducer : NSObject
  233475. {
  233476. JUCE_NAMESPACE::AudioSource* source;
  233477. int readPosition, lengthInFrames;
  233478. }
  233479. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233480. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233481. - (void) dealloc;
  233482. - (void) setupTrackProperties: (DRTrack*) track;
  233483. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233484. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233485. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233486. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233487. toMedia:(NSDictionary*)mediaInfo;
  233488. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233489. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233490. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233491. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233492. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233493. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233494. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233495. ioFlags:(uint32_t*)flags;
  233496. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233497. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233498. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233499. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233500. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233501. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233502. ioFlags:(uint32_t*)flags;
  233503. @end
  233504. @implementation OpenDiskDevice
  233505. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233506. {
  233507. [super init];
  233508. device = device_;
  233509. tracks = [[NSMutableArray alloc] init];
  233510. underrunProtection = true;
  233511. return self;
  233512. }
  233513. - (void) dealloc
  233514. {
  233515. [tracks release];
  233516. [super dealloc];
  233517. }
  233518. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233519. {
  233520. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233521. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233522. [p setupTrackProperties: t];
  233523. [tracks addObject: t];
  233524. [t release];
  233525. [p release];
  233526. }
  233527. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233528. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233529. {
  233530. DRBurn* burn = [DRBurn burnForDevice: device];
  233531. if (! [device acquireExclusiveAccess])
  233532. {
  233533. *error = "Couldn't open or write to the CD device";
  233534. return;
  233535. }
  233536. [device acquireMediaReservation];
  233537. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233538. [d autorelease];
  233539. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233540. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233541. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233542. if (burnSpeed > 0)
  233543. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233544. if (! underrunProtection)
  233545. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233546. [burn setProperties: d];
  233547. [burn writeLayout: tracks];
  233548. for (;;)
  233549. {
  233550. JUCE_NAMESPACE::Thread::sleep (300);
  233551. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233552. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233553. {
  233554. [burn abort];
  233555. *error = "User cancelled the write operation";
  233556. break;
  233557. }
  233558. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233559. {
  233560. *error = "Write operation failed";
  233561. break;
  233562. }
  233563. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233564. {
  233565. break;
  233566. }
  233567. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233568. objectForKey: DRErrorStatusErrorStringKey];
  233569. if ([err length] > 0)
  233570. {
  233571. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233572. break;
  233573. }
  233574. }
  233575. [device releaseMediaReservation];
  233576. [device releaseExclusiveAccess];
  233577. }
  233578. @end
  233579. @implementation AudioTrackProducer
  233580. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233581. {
  233582. lengthInFrames = lengthInFrames_;
  233583. readPosition = 0;
  233584. return self;
  233585. }
  233586. - (void) setupTrackProperties: (DRTrack*) track
  233587. {
  233588. NSMutableDictionary* p = [[track properties] mutableCopy];
  233589. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233590. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233591. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233592. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233593. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233594. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233595. [track setProperties: p];
  233596. [p release];
  233597. }
  233598. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233599. {
  233600. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233601. if (s != nil)
  233602. s->source = source_;
  233603. return s;
  233604. }
  233605. - (void) dealloc
  233606. {
  233607. if (source != 0)
  233608. {
  233609. source->releaseResources();
  233610. delete source;
  233611. }
  233612. [super dealloc];
  233613. }
  233614. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  233615. {
  233616. }
  233617. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  233618. {
  233619. return true;
  233620. }
  233621. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  233622. {
  233623. return lengthInFrames;
  233624. }
  233625. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  233626. toMedia: (NSDictionary*) mediaInfo
  233627. {
  233628. if (source != 0)
  233629. source->prepareToPlay (44100 / 75, 44100);
  233630. readPosition = 0;
  233631. return true;
  233632. }
  233633. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  233634. {
  233635. if (source != 0)
  233636. source->prepareToPlay (44100 / 75, 44100);
  233637. return true;
  233638. }
  233639. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  233640. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233641. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233642. {
  233643. if (source != 0)
  233644. {
  233645. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  233646. if (numSamples > 0)
  233647. {
  233648. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  233649. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  233650. info.buffer = &tempBuffer;
  233651. info.startSample = 0;
  233652. info.numSamples = numSamples;
  233653. source->getNextAudioBlock (info);
  233654. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  233655. JUCE_NAMESPACE::AudioData::LittleEndian,
  233656. JUCE_NAMESPACE::AudioData::Interleaved,
  233657. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  233658. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  233659. JUCE_NAMESPACE::AudioData::NativeEndian,
  233660. JUCE_NAMESPACE::AudioData::NonInterleaved,
  233661. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  233662. CDSampleFormat left (buffer, 2);
  233663. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  233664. CDSampleFormat right (buffer + 2, 2);
  233665. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  233666. readPosition += numSamples;
  233667. }
  233668. return numSamples * 4;
  233669. }
  233670. return 0;
  233671. }
  233672. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  233673. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  233674. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  233675. ioFlags: (uint32_t*) flags
  233676. {
  233677. zeromem (buffer, bufferLength);
  233678. return bufferLength;
  233679. }
  233680. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  233681. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233682. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233683. {
  233684. return true;
  233685. }
  233686. @end
  233687. BEGIN_JUCE_NAMESPACE
  233688. class AudioCDBurner::Pimpl : public Timer
  233689. {
  233690. public:
  233691. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  233692. : device (0), owner (owner_)
  233693. {
  233694. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  233695. if (dev != 0)
  233696. {
  233697. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  233698. lastState = getDiskState();
  233699. startTimer (1000);
  233700. }
  233701. }
  233702. ~Pimpl()
  233703. {
  233704. stopTimer();
  233705. [device release];
  233706. }
  233707. void timerCallback()
  233708. {
  233709. const DiskState state = getDiskState();
  233710. if (state != lastState)
  233711. {
  233712. lastState = state;
  233713. owner.sendChangeMessage();
  233714. }
  233715. }
  233716. DiskState getDiskState() const
  233717. {
  233718. if ([device->device isValid])
  233719. {
  233720. NSDictionary* status = [device->device status];
  233721. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  233722. if ([state isEqualTo: DRDeviceMediaStateNone])
  233723. {
  233724. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  233725. return trayOpen;
  233726. return noDisc;
  233727. }
  233728. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  233729. {
  233730. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  233731. return writableDiskPresent;
  233732. else
  233733. return readOnlyDiskPresent;
  233734. }
  233735. }
  233736. return unknown;
  233737. }
  233738. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  233739. const Array<int> getAvailableWriteSpeeds() const
  233740. {
  233741. Array<int> results;
  233742. if ([device->device isValid])
  233743. {
  233744. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  233745. for (unsigned int i = 0; i < [speeds count]; ++i)
  233746. {
  233747. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  233748. results.add (kbPerSec / kilobytesPerSecond1x);
  233749. }
  233750. }
  233751. return results;
  233752. }
  233753. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  233754. {
  233755. if ([device->device isValid])
  233756. {
  233757. device->underrunProtection = shouldBeEnabled;
  233758. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  233759. }
  233760. return false;
  233761. }
  233762. int getNumAvailableAudioBlocks() const
  233763. {
  233764. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  233765. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  233766. }
  233767. OpenDiskDevice* device;
  233768. private:
  233769. DiskState lastState;
  233770. AudioCDBurner& owner;
  233771. };
  233772. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  233773. {
  233774. pimpl = new Pimpl (*this, deviceIndex);
  233775. }
  233776. AudioCDBurner::~AudioCDBurner()
  233777. {
  233778. }
  233779. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  233780. {
  233781. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  233782. if (b->pimpl->device == 0)
  233783. b = 0;
  233784. return b.release();
  233785. }
  233786. namespace
  233787. {
  233788. NSArray* findDiskBurnerDevices()
  233789. {
  233790. NSMutableArray* results = [NSMutableArray array];
  233791. NSArray* devs = [DRDevice devices];
  233792. for (int i = 0; i < [devs count]; ++i)
  233793. {
  233794. NSDictionary* dic = [[devs objectAtIndex: i] info];
  233795. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  233796. if (name != nil)
  233797. [results addObject: name];
  233798. }
  233799. return results;
  233800. }
  233801. }
  233802. const StringArray AudioCDBurner::findAvailableDevices()
  233803. {
  233804. NSArray* names = findDiskBurnerDevices();
  233805. StringArray s;
  233806. for (unsigned int i = 0; i < [names count]; ++i)
  233807. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  233808. return s;
  233809. }
  233810. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  233811. {
  233812. return pimpl->getDiskState();
  233813. }
  233814. bool AudioCDBurner::isDiskPresent() const
  233815. {
  233816. return getDiskState() == writableDiskPresent;
  233817. }
  233818. bool AudioCDBurner::openTray()
  233819. {
  233820. return pimpl->openTray();
  233821. }
  233822. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  233823. {
  233824. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  233825. DiskState oldState = getDiskState();
  233826. DiskState newState = oldState;
  233827. while (newState == oldState && Time::currentTimeMillis() < timeout)
  233828. {
  233829. newState = getDiskState();
  233830. Thread::sleep (100);
  233831. }
  233832. return newState;
  233833. }
  233834. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  233835. {
  233836. return pimpl->getAvailableWriteSpeeds();
  233837. }
  233838. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  233839. {
  233840. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  233841. }
  233842. int AudioCDBurner::getNumAvailableAudioBlocks() const
  233843. {
  233844. return pimpl->getNumAvailableAudioBlocks();
  233845. }
  233846. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  233847. {
  233848. if ([pimpl->device->device isValid])
  233849. {
  233850. [pimpl->device addSourceTrack: source numSamples: numSamps];
  233851. return true;
  233852. }
  233853. return false;
  233854. }
  233855. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  233856. bool ejectDiscAfterwards,
  233857. bool performFakeBurnForTesting,
  233858. int writeSpeed)
  233859. {
  233860. String error ("Couldn't open or write to the CD device");
  233861. if ([pimpl->device->device isValid])
  233862. {
  233863. error = String::empty;
  233864. [pimpl->device burn: listener
  233865. errorString: &error
  233866. ejectAfterwards: ejectDiscAfterwards
  233867. isFake: performFakeBurnForTesting
  233868. speed: writeSpeed];
  233869. }
  233870. return error;
  233871. }
  233872. #endif
  233873. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233874. void AudioCDReader::ejectDisk()
  233875. {
  233876. const ScopedAutoReleasePool p;
  233877. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  233878. }
  233879. #endif
  233880. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  233881. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  233882. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233883. // compiled on its own).
  233884. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233885. namespace CDReaderHelpers
  233886. {
  233887. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  233888. {
  233889. forEachXmlChildElementWithTagName (xml, child, "key")
  233890. if (child->getAllSubText().trim() == key)
  233891. return child->getNextElement();
  233892. return 0;
  233893. }
  233894. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  233895. {
  233896. const XmlElement* const block = getElementForKey (xml, key);
  233897. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  233898. }
  233899. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  233900. // Returns NULL on success, otherwise a const char* representing an error.
  233901. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  233902. {
  233903. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  233904. if (xml == 0)
  233905. return "Couldn't parse XML in file";
  233906. const XmlElement* const dict = xml->getChildByName ("dict");
  233907. if (dict == 0)
  233908. return "Couldn't get top level dictionary";
  233909. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  233910. if (sessions == 0)
  233911. return "Couldn't find sessions key";
  233912. const XmlElement* const session = sessions->getFirstChildElement();
  233913. if (session == 0)
  233914. return "Couldn't find first session";
  233915. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  233916. if (leadOut < 0)
  233917. return "Couldn't find Leadout Block";
  233918. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  233919. if (trackArray == 0)
  233920. return "Couldn't find Track Array";
  233921. forEachXmlChildElement (*trackArray, track)
  233922. {
  233923. const int trackValue = getIntValueForKey (*track, "Start Block");
  233924. if (trackValue < 0)
  233925. return "Couldn't find Start Block in the track";
  233926. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  233927. }
  233928. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  233929. return 0;
  233930. }
  233931. static void findDevices (Array<File>& cds)
  233932. {
  233933. File volumes ("/Volumes");
  233934. volumes.findChildFiles (cds, File::findDirectories, false);
  233935. for (int i = cds.size(); --i >= 0;)
  233936. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233937. cds.remove (i);
  233938. }
  233939. struct TrackSorter
  233940. {
  233941. static int getCDTrackNumber (const File& file)
  233942. {
  233943. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  233944. }
  233945. static int compareElements (const File& first, const File& second)
  233946. {
  233947. const int firstTrack = getCDTrackNumber (first);
  233948. const int secondTrack = getCDTrackNumber (second);
  233949. jassert (firstTrack > 0 && secondTrack > 0);
  233950. return firstTrack - secondTrack;
  233951. }
  233952. };
  233953. }
  233954. const StringArray AudioCDReader::getAvailableCDNames()
  233955. {
  233956. Array<File> cds;
  233957. CDReaderHelpers::findDevices (cds);
  233958. StringArray names;
  233959. for (int i = 0; i < cds.size(); ++i)
  233960. names.add (cds.getReference(i).getFileName());
  233961. return names;
  233962. }
  233963. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233964. {
  233965. Array<File> cds;
  233966. CDReaderHelpers::findDevices (cds);
  233967. if (cds[index].exists())
  233968. return new AudioCDReader (cds[index]);
  233969. return 0;
  233970. }
  233971. AudioCDReader::AudioCDReader (const File& volume)
  233972. : AudioFormatReader (0, "CD Audio"),
  233973. volumeDir (volume),
  233974. currentReaderTrack (-1),
  233975. reader (0)
  233976. {
  233977. sampleRate = 44100.0;
  233978. bitsPerSample = 16;
  233979. numChannels = 2;
  233980. usesFloatingPointData = false;
  233981. refreshTrackLengths();
  233982. }
  233983. AudioCDReader::~AudioCDReader()
  233984. {
  233985. }
  233986. void AudioCDReader::refreshTrackLengths()
  233987. {
  233988. tracks.clear();
  233989. trackStartSamples.clear();
  233990. lengthInSamples = 0;
  233991. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  233992. CDReaderHelpers::TrackSorter sorter;
  233993. tracks.sort (sorter);
  233994. const File toc (volumeDir.getChildFile (".TOC.plist"));
  233995. if (toc.exists())
  233996. {
  233997. XmlDocument doc (toc);
  233998. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  233999. (void) error; // could be logged..
  234000. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234001. }
  234002. }
  234003. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234004. int64 startSampleInFile, int numSamples)
  234005. {
  234006. while (numSamples > 0)
  234007. {
  234008. int track = -1;
  234009. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234010. {
  234011. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234012. {
  234013. track = i;
  234014. break;
  234015. }
  234016. }
  234017. if (track < 0)
  234018. return false;
  234019. if (track != currentReaderTrack)
  234020. {
  234021. reader = 0;
  234022. FileInputStream* const in = tracks [track].createInputStream();
  234023. if (in != 0)
  234024. {
  234025. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234026. AiffAudioFormat format;
  234027. reader = format.createReaderFor (bin, true);
  234028. if (reader == 0)
  234029. currentReaderTrack = -1;
  234030. else
  234031. currentReaderTrack = track;
  234032. }
  234033. }
  234034. if (reader == 0)
  234035. return false;
  234036. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234037. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234038. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234039. numSamples -= numAvailable;
  234040. startSampleInFile += numAvailable;
  234041. }
  234042. return true;
  234043. }
  234044. bool AudioCDReader::isCDStillPresent() const
  234045. {
  234046. return volumeDir.exists();
  234047. }
  234048. bool AudioCDReader::isTrackAudio (int trackNum) const
  234049. {
  234050. return tracks [trackNum].hasFileExtension (".aiff");
  234051. }
  234052. void AudioCDReader::enableIndexScanning (bool b)
  234053. {
  234054. // any way to do this on a Mac??
  234055. }
  234056. int AudioCDReader::getLastIndex() const
  234057. {
  234058. return 0;
  234059. }
  234060. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234061. {
  234062. return Array <int>();
  234063. }
  234064. #endif
  234065. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234066. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234067. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234068. // compiled on its own).
  234069. #if JUCE_INCLUDED_FILE
  234070. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234071. for example having more than one juce plugin loaded into a host, then when a
  234072. method is called, the actual code that runs might actually be in a different module
  234073. than the one you expect... So any calls to library functions or statics that are
  234074. made inside obj-c methods will probably end up getting executed in a different DLL's
  234075. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234076. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234077. virtual methods of an object that's known to live inside the right module's space.
  234078. */
  234079. class AppDelegateRedirector
  234080. {
  234081. public:
  234082. AppDelegateRedirector()
  234083. {
  234084. }
  234085. virtual ~AppDelegateRedirector()
  234086. {
  234087. }
  234088. virtual NSApplicationTerminateReply shouldTerminate()
  234089. {
  234090. if (JUCEApplication::getInstance() != 0)
  234091. {
  234092. JUCEApplication::getInstance()->systemRequestedQuit();
  234093. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234094. return NSTerminateCancel;
  234095. }
  234096. return NSTerminateNow;
  234097. }
  234098. virtual void willTerminate()
  234099. {
  234100. JUCEApplication::appWillTerminateByForce();
  234101. }
  234102. virtual BOOL openFile (NSString* filename)
  234103. {
  234104. if (JUCEApplication::getInstance() != 0)
  234105. {
  234106. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234107. return YES;
  234108. }
  234109. return NO;
  234110. }
  234111. virtual void openFiles (NSArray* filenames)
  234112. {
  234113. StringArray files;
  234114. for (unsigned int i = 0; i < [filenames count]; ++i)
  234115. {
  234116. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234117. if (filename.containsChar (' '))
  234118. filename = filename.quoted('"');
  234119. files.add (filename);
  234120. }
  234121. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234122. {
  234123. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234124. }
  234125. }
  234126. virtual void focusChanged()
  234127. {
  234128. juce_HandleProcessFocusChange();
  234129. }
  234130. struct CallbackMessagePayload
  234131. {
  234132. MessageCallbackFunction* function;
  234133. void* parameter;
  234134. void* volatile result;
  234135. bool volatile hasBeenExecuted;
  234136. };
  234137. virtual void performCallback (CallbackMessagePayload* pl)
  234138. {
  234139. pl->result = (*pl->function) (pl->parameter);
  234140. pl->hasBeenExecuted = true;
  234141. }
  234142. virtual void deleteSelf()
  234143. {
  234144. delete this;
  234145. }
  234146. void postMessage (Message* const m)
  234147. {
  234148. messageQueue.post (m);
  234149. }
  234150. private:
  234151. CFRunLoopRef runLoop;
  234152. CFRunLoopSourceRef runLoopSource;
  234153. MessageQueue messageQueue;
  234154. };
  234155. END_JUCE_NAMESPACE
  234156. using namespace JUCE_NAMESPACE;
  234157. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234158. @interface JuceAppDelegate : NSObject
  234159. {
  234160. @private
  234161. id oldDelegate;
  234162. @public
  234163. AppDelegateRedirector* redirector;
  234164. }
  234165. - (JuceAppDelegate*) init;
  234166. - (void) dealloc;
  234167. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234168. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234169. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234170. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234171. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234172. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234173. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234174. - (void) performCallback: (id) info;
  234175. - (void) dummyMethod;
  234176. @end
  234177. @implementation JuceAppDelegate
  234178. - (JuceAppDelegate*) init
  234179. {
  234180. [super init];
  234181. redirector = new AppDelegateRedirector();
  234182. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234183. if (JUCEApplication::isStandaloneApp())
  234184. {
  234185. oldDelegate = [NSApp delegate];
  234186. [NSApp setDelegate: self];
  234187. }
  234188. else
  234189. {
  234190. oldDelegate = 0;
  234191. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234192. name: NSApplicationDidResignActiveNotification object: NSApp];
  234193. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234194. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234195. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234196. name: NSApplicationWillUnhideNotification object: NSApp];
  234197. }
  234198. return self;
  234199. }
  234200. - (void) dealloc
  234201. {
  234202. if (oldDelegate != 0)
  234203. [NSApp setDelegate: oldDelegate];
  234204. redirector->deleteSelf();
  234205. [super dealloc];
  234206. }
  234207. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234208. {
  234209. (void) app;
  234210. return redirector->shouldTerminate();
  234211. }
  234212. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234213. {
  234214. (void) aNotification;
  234215. redirector->willTerminate();
  234216. }
  234217. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234218. {
  234219. (void) app;
  234220. return redirector->openFile (filename);
  234221. }
  234222. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234223. {
  234224. (void) sender;
  234225. return redirector->openFiles (filenames);
  234226. }
  234227. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234228. {
  234229. (void) notification;
  234230. redirector->focusChanged();
  234231. }
  234232. - (void) applicationDidResignActive: (NSNotification*) notification
  234233. {
  234234. (void) notification;
  234235. redirector->focusChanged();
  234236. }
  234237. - (void) applicationWillUnhide: (NSNotification*) notification
  234238. {
  234239. (void) notification;
  234240. redirector->focusChanged();
  234241. }
  234242. - (void) performCallback: (id) info
  234243. {
  234244. if ([info isKindOfClass: [NSData class]])
  234245. {
  234246. AppDelegateRedirector::CallbackMessagePayload* pl
  234247. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234248. if (pl != 0)
  234249. redirector->performCallback (pl);
  234250. }
  234251. else
  234252. {
  234253. jassertfalse; // should never get here!
  234254. }
  234255. }
  234256. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234257. @end
  234258. BEGIN_JUCE_NAMESPACE
  234259. static JuceAppDelegate* juceAppDelegate = 0;
  234260. void MessageManager::runDispatchLoop()
  234261. {
  234262. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234263. {
  234264. const ScopedAutoReleasePool pool;
  234265. // must only be called by the message thread!
  234266. jassert (isThisTheMessageThread());
  234267. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234268. @try
  234269. {
  234270. [NSApp run];
  234271. }
  234272. @catch (NSException* e)
  234273. {
  234274. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234275. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234276. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234277. }
  234278. @finally
  234279. {
  234280. }
  234281. #else
  234282. [NSApp run];
  234283. #endif
  234284. }
  234285. }
  234286. void MessageManager::stopDispatchLoop()
  234287. {
  234288. quitMessagePosted = true;
  234289. [NSApp stop: nil];
  234290. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234291. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234292. }
  234293. namespace
  234294. {
  234295. bool isEventBlockedByModalComps (NSEvent* e)
  234296. {
  234297. if (Component::getNumCurrentlyModalComponents() == 0)
  234298. return false;
  234299. NSWindow* const w = [e window];
  234300. if (w == 0 || [w worksWhenModal])
  234301. return false;
  234302. bool isKey = false, isInputAttempt = false;
  234303. switch ([e type])
  234304. {
  234305. case NSKeyDown:
  234306. case NSKeyUp:
  234307. isKey = isInputAttempt = true;
  234308. break;
  234309. case NSLeftMouseDown:
  234310. case NSRightMouseDown:
  234311. case NSOtherMouseDown:
  234312. isInputAttempt = true;
  234313. break;
  234314. case NSLeftMouseDragged:
  234315. case NSRightMouseDragged:
  234316. case NSLeftMouseUp:
  234317. case NSRightMouseUp:
  234318. case NSOtherMouseUp:
  234319. case NSOtherMouseDragged:
  234320. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234321. return false;
  234322. break;
  234323. case NSMouseMoved:
  234324. case NSMouseEntered:
  234325. case NSMouseExited:
  234326. case NSCursorUpdate:
  234327. case NSScrollWheel:
  234328. case NSTabletPoint:
  234329. case NSTabletProximity:
  234330. break;
  234331. default:
  234332. return false;
  234333. }
  234334. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234335. {
  234336. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234337. NSView* const compView = (NSView*) peer->getNativeHandle();
  234338. if ([compView window] == w)
  234339. {
  234340. if (isKey)
  234341. {
  234342. if (compView == [w firstResponder])
  234343. return false;
  234344. }
  234345. else
  234346. {
  234347. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234348. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234349. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234350. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234351. return false;
  234352. }
  234353. }
  234354. }
  234355. if (isInputAttempt)
  234356. {
  234357. if (! [NSApp isActive])
  234358. [NSApp activateIgnoringOtherApps: YES];
  234359. Component* const modal = Component::getCurrentlyModalComponent (0);
  234360. if (modal != 0)
  234361. modal->inputAttemptWhenModal();
  234362. }
  234363. return true;
  234364. }
  234365. }
  234366. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234367. {
  234368. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234369. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234370. while (! quitMessagePosted)
  234371. {
  234372. const ScopedAutoReleasePool pool;
  234373. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234374. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234375. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234376. inMode: NSDefaultRunLoopMode
  234377. dequeue: YES];
  234378. if (e != 0 && ! isEventBlockedByModalComps (e))
  234379. [NSApp sendEvent: e];
  234380. if (Time::getMillisecondCounter() >= endTime)
  234381. break;
  234382. }
  234383. return ! quitMessagePosted;
  234384. }
  234385. void MessageManager::doPlatformSpecificInitialisation()
  234386. {
  234387. if (juceAppDelegate == 0)
  234388. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234389. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234390. // correctly (needed prior to 10.5)
  234391. if (! [NSThread isMultiThreaded])
  234392. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234393. toTarget: juceAppDelegate
  234394. withObject: nil];
  234395. }
  234396. void MessageManager::doPlatformSpecificShutdown()
  234397. {
  234398. if (juceAppDelegate != 0)
  234399. {
  234400. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234401. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234402. [juceAppDelegate release];
  234403. juceAppDelegate = 0;
  234404. }
  234405. }
  234406. bool juce_postMessageToSystemQueue (Message* message)
  234407. {
  234408. juceAppDelegate->redirector->postMessage (message);
  234409. return true;
  234410. }
  234411. void MessageManager::broadcastMessage (const String& value)
  234412. {
  234413. }
  234414. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234415. {
  234416. if (isThisTheMessageThread())
  234417. {
  234418. return (*callback) (data);
  234419. }
  234420. else
  234421. {
  234422. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234423. // deadlock because the message manager is blocked from running, so can never
  234424. // call your function..
  234425. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234426. const ScopedAutoReleasePool pool;
  234427. AppDelegateRedirector::CallbackMessagePayload cmp;
  234428. cmp.function = callback;
  234429. cmp.parameter = data;
  234430. cmp.result = 0;
  234431. cmp.hasBeenExecuted = false;
  234432. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234433. withObject: [NSData dataWithBytesNoCopy: &cmp
  234434. length: sizeof (cmp)
  234435. freeWhenDone: NO]
  234436. waitUntilDone: YES];
  234437. return cmp.result;
  234438. }
  234439. }
  234440. #endif
  234441. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234442. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234443. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234444. // compiled on its own).
  234445. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234446. #if JUCE_MAC
  234447. END_JUCE_NAMESPACE
  234448. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234449. @interface DownloadClickDetector : NSObject
  234450. {
  234451. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234452. }
  234453. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234454. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234455. request: (NSURLRequest*) request
  234456. frame: (WebFrame*) frame
  234457. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234458. @end
  234459. @implementation DownloadClickDetector
  234460. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234461. {
  234462. [super init];
  234463. ownerComponent = ownerComponent_;
  234464. return self;
  234465. }
  234466. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234467. request: (NSURLRequest*) request
  234468. frame: (WebFrame*) frame
  234469. decisionListener: (id <WebPolicyDecisionListener>) listener
  234470. {
  234471. (void) sender;
  234472. (void) request;
  234473. (void) frame;
  234474. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234475. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234476. [listener use];
  234477. else
  234478. [listener ignore];
  234479. }
  234480. @end
  234481. BEGIN_JUCE_NAMESPACE
  234482. class WebBrowserComponentInternal : public NSViewComponent
  234483. {
  234484. public:
  234485. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234486. {
  234487. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234488. frameName: @""
  234489. groupName: @""];
  234490. setView (webView);
  234491. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234492. [webView setPolicyDelegate: clickListener];
  234493. }
  234494. ~WebBrowserComponentInternal()
  234495. {
  234496. [webView setPolicyDelegate: nil];
  234497. [clickListener release];
  234498. setView (0);
  234499. }
  234500. void goToURL (const String& url,
  234501. const StringArray* headers,
  234502. const MemoryBlock* postData)
  234503. {
  234504. NSMutableURLRequest* r
  234505. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234506. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234507. timeoutInterval: 30.0];
  234508. if (postData != 0 && postData->getSize() > 0)
  234509. {
  234510. [r setHTTPMethod: @"POST"];
  234511. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234512. length: postData->getSize()]];
  234513. }
  234514. if (headers != 0)
  234515. {
  234516. for (int i = 0; i < headers->size(); ++i)
  234517. {
  234518. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234519. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234520. [r setValue: juceStringToNS (headerValue)
  234521. forHTTPHeaderField: juceStringToNS (headerName)];
  234522. }
  234523. }
  234524. stop();
  234525. [[webView mainFrame] loadRequest: r];
  234526. }
  234527. void goBack()
  234528. {
  234529. [webView goBack];
  234530. }
  234531. void goForward()
  234532. {
  234533. [webView goForward];
  234534. }
  234535. void stop()
  234536. {
  234537. [webView stopLoading: nil];
  234538. }
  234539. void refresh()
  234540. {
  234541. [webView reload: nil];
  234542. }
  234543. void mouseMove (const MouseEvent&)
  234544. {
  234545. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234546. // them work is to push them via this non-public method..
  234547. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234548. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234549. }
  234550. private:
  234551. WebView* webView;
  234552. DownloadClickDetector* clickListener;
  234553. };
  234554. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234555. : browser (0),
  234556. blankPageShown (false),
  234557. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234558. {
  234559. setOpaque (true);
  234560. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234561. }
  234562. WebBrowserComponent::~WebBrowserComponent()
  234563. {
  234564. deleteAndZero (browser);
  234565. }
  234566. void WebBrowserComponent::goToURL (const String& url,
  234567. const StringArray* headers,
  234568. const MemoryBlock* postData)
  234569. {
  234570. lastURL = url;
  234571. lastHeaders.clear();
  234572. if (headers != 0)
  234573. lastHeaders = *headers;
  234574. lastPostData.setSize (0);
  234575. if (postData != 0)
  234576. lastPostData = *postData;
  234577. blankPageShown = false;
  234578. browser->goToURL (url, headers, postData);
  234579. }
  234580. void WebBrowserComponent::stop()
  234581. {
  234582. browser->stop();
  234583. }
  234584. void WebBrowserComponent::goBack()
  234585. {
  234586. lastURL = String::empty;
  234587. blankPageShown = false;
  234588. browser->goBack();
  234589. }
  234590. void WebBrowserComponent::goForward()
  234591. {
  234592. lastURL = String::empty;
  234593. browser->goForward();
  234594. }
  234595. void WebBrowserComponent::refresh()
  234596. {
  234597. browser->refresh();
  234598. }
  234599. void WebBrowserComponent::paint (Graphics&)
  234600. {
  234601. }
  234602. void WebBrowserComponent::checkWindowAssociation()
  234603. {
  234604. if (isShowing())
  234605. {
  234606. if (blankPageShown)
  234607. goBack();
  234608. }
  234609. else
  234610. {
  234611. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  234612. {
  234613. // when the component becomes invisible, some stuff like flash
  234614. // carries on playing audio, so we need to force it onto a blank
  234615. // page to avoid this, (and send it back when it's made visible again).
  234616. blankPageShown = true;
  234617. browser->goToURL ("about:blank", 0, 0);
  234618. }
  234619. }
  234620. }
  234621. void WebBrowserComponent::reloadLastURL()
  234622. {
  234623. if (lastURL.isNotEmpty())
  234624. {
  234625. goToURL (lastURL, &lastHeaders, &lastPostData);
  234626. lastURL = String::empty;
  234627. }
  234628. }
  234629. void WebBrowserComponent::parentHierarchyChanged()
  234630. {
  234631. checkWindowAssociation();
  234632. }
  234633. void WebBrowserComponent::resized()
  234634. {
  234635. browser->setSize (getWidth(), getHeight());
  234636. }
  234637. void WebBrowserComponent::visibilityChanged()
  234638. {
  234639. checkWindowAssociation();
  234640. }
  234641. bool WebBrowserComponent::pageAboutToLoad (const String&)
  234642. {
  234643. return true;
  234644. }
  234645. #else
  234646. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234647. {
  234648. }
  234649. WebBrowserComponent::~WebBrowserComponent()
  234650. {
  234651. }
  234652. void WebBrowserComponent::goToURL (const String& url,
  234653. const StringArray* headers,
  234654. const MemoryBlock* postData)
  234655. {
  234656. }
  234657. void WebBrowserComponent::stop()
  234658. {
  234659. }
  234660. void WebBrowserComponent::goBack()
  234661. {
  234662. }
  234663. void WebBrowserComponent::goForward()
  234664. {
  234665. }
  234666. void WebBrowserComponent::refresh()
  234667. {
  234668. }
  234669. void WebBrowserComponent::paint (Graphics& g)
  234670. {
  234671. }
  234672. void WebBrowserComponent::checkWindowAssociation()
  234673. {
  234674. }
  234675. void WebBrowserComponent::reloadLastURL()
  234676. {
  234677. }
  234678. void WebBrowserComponent::parentHierarchyChanged()
  234679. {
  234680. }
  234681. void WebBrowserComponent::resized()
  234682. {
  234683. }
  234684. void WebBrowserComponent::visibilityChanged()
  234685. {
  234686. }
  234687. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  234688. {
  234689. return true;
  234690. }
  234691. #endif
  234692. #endif
  234693. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234694. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  234695. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234696. // compiled on its own).
  234697. #if JUCE_INCLUDED_FILE
  234698. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234699. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  234700. #endif
  234701. #undef log
  234702. #if JUCE_COREAUDIO_LOGGING_ENABLED
  234703. #define log(a) Logger::writeToLog (a)
  234704. #else
  234705. #define log(a)
  234706. #endif
  234707. #undef OK
  234708. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234709. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  234710. {
  234711. if (err == noErr)
  234712. return true;
  234713. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234714. jassertfalse;
  234715. return false;
  234716. }
  234717. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  234718. #else
  234719. #define OK(a) (a == noErr)
  234720. #endif
  234721. class CoreAudioInternal : public Timer
  234722. {
  234723. public:
  234724. CoreAudioInternal (AudioDeviceID id)
  234725. : inputLatency (0),
  234726. outputLatency (0),
  234727. callback (0),
  234728. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234729. audioProcID (0),
  234730. #endif
  234731. isSlaveDevice (false),
  234732. deviceID (id),
  234733. started (false),
  234734. sampleRate (0),
  234735. bufferSize (512),
  234736. numInputChans (0),
  234737. numOutputChans (0),
  234738. callbacksAllowed (true),
  234739. numInputChannelInfos (0),
  234740. numOutputChannelInfos (0)
  234741. {
  234742. jassert (deviceID != 0);
  234743. updateDetailsFromDevice();
  234744. AudioObjectPropertyAddress pa;
  234745. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234746. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234747. pa.mElement = kAudioObjectPropertyElementWildcard;
  234748. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  234749. }
  234750. ~CoreAudioInternal()
  234751. {
  234752. AudioObjectPropertyAddress pa;
  234753. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234754. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234755. pa.mElement = kAudioObjectPropertyElementWildcard;
  234756. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  234757. stop (false);
  234758. }
  234759. void allocateTempBuffers()
  234760. {
  234761. const int tempBufSize = bufferSize + 4;
  234762. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  234763. tempInputBuffers.calloc (numInputChans + 2);
  234764. tempOutputBuffers.calloc (numOutputChans + 2);
  234765. int i, count = 0;
  234766. for (i = 0; i < numInputChans; ++i)
  234767. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234768. for (i = 0; i < numOutputChans; ++i)
  234769. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234770. }
  234771. // returns the number of actual available channels
  234772. void fillInChannelInfo (const bool input)
  234773. {
  234774. int chanNum = 0;
  234775. UInt32 size;
  234776. AudioObjectPropertyAddress pa;
  234777. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234778. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234779. pa.mElement = kAudioObjectPropertyElementMaster;
  234780. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234781. {
  234782. HeapBlock <AudioBufferList> bufList;
  234783. bufList.calloc (size, 1);
  234784. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234785. {
  234786. const int numStreams = bufList->mNumberBuffers;
  234787. for (int i = 0; i < numStreams; ++i)
  234788. {
  234789. const AudioBuffer& b = bufList->mBuffers[i];
  234790. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  234791. {
  234792. String name;
  234793. {
  234794. char channelName [256];
  234795. zerostruct (channelName);
  234796. UInt32 nameSize = sizeof (channelName);
  234797. UInt32 channelNum = chanNum + 1;
  234798. pa.mSelector = kAudioDevicePropertyChannelName;
  234799. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  234800. name = String::fromUTF8 (channelName, nameSize);
  234801. }
  234802. if (input)
  234803. {
  234804. if (activeInputChans[chanNum])
  234805. {
  234806. inputChannelInfo [numInputChannelInfos].streamNum = i;
  234807. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  234808. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234809. ++numInputChannelInfos;
  234810. }
  234811. if (name.isEmpty())
  234812. name << "Input " << (chanNum + 1);
  234813. inChanNames.add (name);
  234814. }
  234815. else
  234816. {
  234817. if (activeOutputChans[chanNum])
  234818. {
  234819. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  234820. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  234821. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234822. ++numOutputChannelInfos;
  234823. }
  234824. if (name.isEmpty())
  234825. name << "Output " << (chanNum + 1);
  234826. outChanNames.add (name);
  234827. }
  234828. ++chanNum;
  234829. }
  234830. }
  234831. }
  234832. }
  234833. }
  234834. void updateDetailsFromDevice()
  234835. {
  234836. stopTimer();
  234837. if (deviceID == 0)
  234838. return;
  234839. const ScopedLock sl (callbackLock);
  234840. Float64 sr;
  234841. UInt32 size = sizeof (Float64);
  234842. AudioObjectPropertyAddress pa;
  234843. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234844. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234845. pa.mElement = kAudioObjectPropertyElementMaster;
  234846. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  234847. sampleRate = sr;
  234848. UInt32 framesPerBuf;
  234849. size = sizeof (framesPerBuf);
  234850. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234851. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  234852. {
  234853. bufferSize = framesPerBuf;
  234854. allocateTempBuffers();
  234855. }
  234856. bufferSizes.clear();
  234857. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  234858. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234859. {
  234860. HeapBlock <AudioValueRange> ranges;
  234861. ranges.calloc (size, 1);
  234862. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234863. {
  234864. bufferSizes.add ((int) ranges[0].mMinimum);
  234865. for (int i = 32; i < 2048; i += 32)
  234866. {
  234867. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234868. {
  234869. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  234870. {
  234871. bufferSizes.addIfNotAlreadyThere (i);
  234872. break;
  234873. }
  234874. }
  234875. }
  234876. if (bufferSize > 0)
  234877. bufferSizes.addIfNotAlreadyThere (bufferSize);
  234878. }
  234879. }
  234880. if (bufferSizes.size() == 0 && bufferSize > 0)
  234881. bufferSizes.add (bufferSize);
  234882. sampleRates.clear();
  234883. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  234884. String rates;
  234885. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  234886. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234887. {
  234888. HeapBlock <AudioValueRange> ranges;
  234889. ranges.calloc (size, 1);
  234890. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234891. {
  234892. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  234893. {
  234894. bool ok = false;
  234895. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234896. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  234897. ok = true;
  234898. if (ok)
  234899. {
  234900. sampleRates.add (possibleRates[i]);
  234901. rates << possibleRates[i] << ' ';
  234902. }
  234903. }
  234904. }
  234905. }
  234906. if (sampleRates.size() == 0 && sampleRate > 0)
  234907. {
  234908. sampleRates.add (sampleRate);
  234909. rates << sampleRate;
  234910. }
  234911. log ("sr: " + rates);
  234912. inputLatency = 0;
  234913. outputLatency = 0;
  234914. UInt32 lat;
  234915. size = sizeof (lat);
  234916. pa.mSelector = kAudioDevicePropertyLatency;
  234917. pa.mScope = kAudioDevicePropertyScopeInput;
  234918. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234919. inputLatency = (int) lat;
  234920. pa.mScope = kAudioDevicePropertyScopeOutput;
  234921. size = sizeof (lat);
  234922. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234923. outputLatency = (int) lat;
  234924. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234925. inChanNames.clear();
  234926. outChanNames.clear();
  234927. inputChannelInfo.calloc (numInputChans + 2);
  234928. numInputChannelInfos = 0;
  234929. outputChannelInfo.calloc (numOutputChans + 2);
  234930. numOutputChannelInfos = 0;
  234931. fillInChannelInfo (true);
  234932. fillInChannelInfo (false);
  234933. }
  234934. const StringArray getSources (bool input)
  234935. {
  234936. StringArray s;
  234937. HeapBlock <OSType> types;
  234938. const int num = getAllDataSourcesForDevice (deviceID, types);
  234939. for (int i = 0; i < num; ++i)
  234940. {
  234941. AudioValueTranslation avt;
  234942. char buffer[256];
  234943. avt.mInputData = &(types[i]);
  234944. avt.mInputDataSize = sizeof (UInt32);
  234945. avt.mOutputData = buffer;
  234946. avt.mOutputDataSize = 256;
  234947. UInt32 transSize = sizeof (avt);
  234948. AudioObjectPropertyAddress pa;
  234949. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234950. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234951. pa.mElement = kAudioObjectPropertyElementMaster;
  234952. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  234953. {
  234954. DBG (buffer);
  234955. s.add (buffer);
  234956. }
  234957. }
  234958. return s;
  234959. }
  234960. int getCurrentSourceIndex (bool input) const
  234961. {
  234962. OSType currentSourceID = 0;
  234963. UInt32 size = sizeof (currentSourceID);
  234964. int result = -1;
  234965. AudioObjectPropertyAddress pa;
  234966. pa.mSelector = kAudioDevicePropertyDataSource;
  234967. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234968. pa.mElement = kAudioObjectPropertyElementMaster;
  234969. if (deviceID != 0)
  234970. {
  234971. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  234972. {
  234973. HeapBlock <OSType> types;
  234974. const int num = getAllDataSourcesForDevice (deviceID, types);
  234975. for (int i = 0; i < num; ++i)
  234976. {
  234977. if (types[num] == currentSourceID)
  234978. {
  234979. result = i;
  234980. break;
  234981. }
  234982. }
  234983. }
  234984. }
  234985. return result;
  234986. }
  234987. void setCurrentSourceIndex (int index, bool input)
  234988. {
  234989. if (deviceID != 0)
  234990. {
  234991. HeapBlock <OSType> types;
  234992. const int num = getAllDataSourcesForDevice (deviceID, types);
  234993. if (isPositiveAndBelow (index, num))
  234994. {
  234995. AudioObjectPropertyAddress pa;
  234996. pa.mSelector = kAudioDevicePropertyDataSource;
  234997. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234998. pa.mElement = kAudioObjectPropertyElementMaster;
  234999. OSType typeId = types[index];
  235000. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235001. }
  235002. }
  235003. }
  235004. const String reopen (const BigInteger& inputChannels,
  235005. const BigInteger& outputChannels,
  235006. double newSampleRate,
  235007. int bufferSizeSamples)
  235008. {
  235009. String error;
  235010. log ("CoreAudio reopen");
  235011. callbacksAllowed = false;
  235012. stopTimer();
  235013. stop (false);
  235014. activeInputChans = inputChannels;
  235015. activeInputChans.setRange (inChanNames.size(),
  235016. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235017. false);
  235018. activeOutputChans = outputChannels;
  235019. activeOutputChans.setRange (outChanNames.size(),
  235020. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235021. false);
  235022. numInputChans = activeInputChans.countNumberOfSetBits();
  235023. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235024. // set sample rate
  235025. AudioObjectPropertyAddress pa;
  235026. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235027. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235028. pa.mElement = kAudioObjectPropertyElementMaster;
  235029. Float64 sr = newSampleRate;
  235030. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235031. {
  235032. error = "Couldn't change sample rate";
  235033. }
  235034. else
  235035. {
  235036. // change buffer size
  235037. UInt32 framesPerBuf = bufferSizeSamples;
  235038. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235039. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235040. {
  235041. error = "Couldn't change buffer size";
  235042. }
  235043. else
  235044. {
  235045. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235046. // correctly report their new settings until some random time in the future, so
  235047. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235048. // to make sure we're using the correct numbers..
  235049. updateDetailsFromDevice();
  235050. sampleRate = newSampleRate;
  235051. bufferSize = bufferSizeSamples;
  235052. if (sampleRates.size() == 0)
  235053. error = "Device has no available sample-rates";
  235054. else if (bufferSizes.size() == 0)
  235055. error = "Device has no available buffer-sizes";
  235056. else if (inputDevice != 0)
  235057. error = inputDevice->reopen (inputChannels,
  235058. outputChannels,
  235059. newSampleRate,
  235060. bufferSizeSamples);
  235061. }
  235062. }
  235063. callbacksAllowed = true;
  235064. return error;
  235065. }
  235066. bool start (AudioIODeviceCallback* cb)
  235067. {
  235068. if (! started)
  235069. {
  235070. callback = 0;
  235071. if (deviceID != 0)
  235072. {
  235073. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235074. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235075. #else
  235076. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235077. #endif
  235078. {
  235079. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235080. {
  235081. started = true;
  235082. }
  235083. else
  235084. {
  235085. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235086. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235087. #else
  235088. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235089. audioProcID = 0;
  235090. #endif
  235091. }
  235092. }
  235093. }
  235094. }
  235095. if (started)
  235096. {
  235097. const ScopedLock sl (callbackLock);
  235098. callback = cb;
  235099. }
  235100. if (inputDevice != 0)
  235101. return started && inputDevice->start (cb);
  235102. else
  235103. return started;
  235104. }
  235105. void stop (bool leaveInterruptRunning)
  235106. {
  235107. {
  235108. const ScopedLock sl (callbackLock);
  235109. callback = 0;
  235110. }
  235111. if (started
  235112. && (deviceID != 0)
  235113. && ! leaveInterruptRunning)
  235114. {
  235115. OK (AudioDeviceStop (deviceID, audioIOProc));
  235116. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235117. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235118. #else
  235119. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235120. audioProcID = 0;
  235121. #endif
  235122. started = false;
  235123. { const ScopedLock sl (callbackLock); }
  235124. // wait until it's definately stopped calling back..
  235125. for (int i = 40; --i >= 0;)
  235126. {
  235127. Thread::sleep (50);
  235128. UInt32 running = 0;
  235129. UInt32 size = sizeof (running);
  235130. AudioObjectPropertyAddress pa;
  235131. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235132. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235133. pa.mElement = kAudioObjectPropertyElementMaster;
  235134. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235135. if (running == 0)
  235136. break;
  235137. }
  235138. const ScopedLock sl (callbackLock);
  235139. }
  235140. if (inputDevice != 0)
  235141. inputDevice->stop (leaveInterruptRunning);
  235142. }
  235143. double getSampleRate() const
  235144. {
  235145. return sampleRate;
  235146. }
  235147. int getBufferSize() const
  235148. {
  235149. return bufferSize;
  235150. }
  235151. void audioCallback (const AudioBufferList* inInputData,
  235152. AudioBufferList* outOutputData)
  235153. {
  235154. int i;
  235155. const ScopedLock sl (callbackLock);
  235156. if (callback != 0)
  235157. {
  235158. if (inputDevice == 0)
  235159. {
  235160. for (i = numInputChans; --i >= 0;)
  235161. {
  235162. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235163. float* dest = tempInputBuffers [i];
  235164. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235165. + info.dataOffsetSamples;
  235166. const int stride = info.dataStrideSamples;
  235167. if (stride != 0) // if this is zero, info is invalid
  235168. {
  235169. for (int j = bufferSize; --j >= 0;)
  235170. {
  235171. *dest++ = *src;
  235172. src += stride;
  235173. }
  235174. }
  235175. }
  235176. }
  235177. if (! isSlaveDevice)
  235178. {
  235179. if (inputDevice == 0)
  235180. {
  235181. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235182. numInputChans,
  235183. tempOutputBuffers,
  235184. numOutputChans,
  235185. bufferSize);
  235186. }
  235187. else
  235188. {
  235189. jassert (inputDevice->bufferSize == bufferSize);
  235190. // Sometimes the two linked devices seem to get their callbacks in
  235191. // parallel, so we need to lock both devices to stop the input data being
  235192. // changed while inside our callback..
  235193. const ScopedLock sl2 (inputDevice->callbackLock);
  235194. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235195. inputDevice->numInputChans,
  235196. tempOutputBuffers,
  235197. numOutputChans,
  235198. bufferSize);
  235199. }
  235200. for (i = numOutputChans; --i >= 0;)
  235201. {
  235202. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235203. const float* src = tempOutputBuffers [i];
  235204. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235205. + info.dataOffsetSamples;
  235206. const int stride = info.dataStrideSamples;
  235207. if (stride != 0) // if this is zero, info is invalid
  235208. {
  235209. for (int j = bufferSize; --j >= 0;)
  235210. {
  235211. *dest = *src++;
  235212. dest += stride;
  235213. }
  235214. }
  235215. }
  235216. }
  235217. }
  235218. else
  235219. {
  235220. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235221. {
  235222. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235223. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235224. + info.dataOffsetSamples;
  235225. const int stride = info.dataStrideSamples;
  235226. if (stride != 0) // if this is zero, info is invalid
  235227. {
  235228. for (int j = bufferSize; --j >= 0;)
  235229. {
  235230. *dest = 0.0f;
  235231. dest += stride;
  235232. }
  235233. }
  235234. }
  235235. }
  235236. }
  235237. // called by callbacks
  235238. void deviceDetailsChanged()
  235239. {
  235240. if (callbacksAllowed)
  235241. startTimer (100);
  235242. }
  235243. void timerCallback()
  235244. {
  235245. stopTimer();
  235246. log ("CoreAudio device changed callback");
  235247. const double oldSampleRate = sampleRate;
  235248. const int oldBufferSize = bufferSize;
  235249. updateDetailsFromDevice();
  235250. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235251. {
  235252. callbacksAllowed = false;
  235253. stop (false);
  235254. updateDetailsFromDevice();
  235255. callbacksAllowed = true;
  235256. }
  235257. }
  235258. CoreAudioInternal* getRelatedDevice() const
  235259. {
  235260. UInt32 size = 0;
  235261. ScopedPointer <CoreAudioInternal> result;
  235262. AudioObjectPropertyAddress pa;
  235263. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235264. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235265. pa.mElement = kAudioObjectPropertyElementMaster;
  235266. if (deviceID != 0
  235267. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235268. && size > 0)
  235269. {
  235270. HeapBlock <AudioDeviceID> devs;
  235271. devs.calloc (size, 1);
  235272. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235273. {
  235274. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235275. {
  235276. if (devs[i] != deviceID && devs[i] != 0)
  235277. {
  235278. result = new CoreAudioInternal (devs[i]);
  235279. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235280. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235281. if (thisIsInput != otherIsInput
  235282. || (inChanNames.size() + outChanNames.size() == 0)
  235283. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235284. break;
  235285. result = 0;
  235286. }
  235287. }
  235288. }
  235289. }
  235290. return result.release();
  235291. }
  235292. int inputLatency, outputLatency;
  235293. BigInteger activeInputChans, activeOutputChans;
  235294. StringArray inChanNames, outChanNames;
  235295. Array <double> sampleRates;
  235296. Array <int> bufferSizes;
  235297. AudioIODeviceCallback* callback;
  235298. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235299. AudioDeviceIOProcID audioProcID;
  235300. #endif
  235301. ScopedPointer<CoreAudioInternal> inputDevice;
  235302. bool isSlaveDevice;
  235303. private:
  235304. CriticalSection callbackLock;
  235305. AudioDeviceID deviceID;
  235306. bool started;
  235307. double sampleRate;
  235308. int bufferSize;
  235309. HeapBlock <float> audioBuffer;
  235310. int numInputChans, numOutputChans;
  235311. bool callbacksAllowed;
  235312. struct CallbackDetailsForChannel
  235313. {
  235314. int streamNum;
  235315. int dataOffsetSamples;
  235316. int dataStrideSamples;
  235317. };
  235318. int numInputChannelInfos, numOutputChannelInfos;
  235319. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235320. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235321. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235322. const AudioTimeStamp* /*inNow*/,
  235323. const AudioBufferList* inInputData,
  235324. const AudioTimeStamp* /*inInputTime*/,
  235325. AudioBufferList* outOutputData,
  235326. const AudioTimeStamp* /*inOutputTime*/,
  235327. void* device)
  235328. {
  235329. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235330. return noErr;
  235331. }
  235332. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235333. {
  235334. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235335. switch (pa->mSelector)
  235336. {
  235337. case kAudioDevicePropertyBufferSize:
  235338. case kAudioDevicePropertyBufferFrameSize:
  235339. case kAudioDevicePropertyNominalSampleRate:
  235340. case kAudioDevicePropertyStreamFormat:
  235341. case kAudioDevicePropertyDeviceIsAlive:
  235342. intern->deviceDetailsChanged();
  235343. break;
  235344. case kAudioDevicePropertyBufferSizeRange:
  235345. case kAudioDevicePropertyVolumeScalar:
  235346. case kAudioDevicePropertyMute:
  235347. case kAudioDevicePropertyPlayThru:
  235348. case kAudioDevicePropertyDataSource:
  235349. case kAudioDevicePropertyDeviceIsRunning:
  235350. break;
  235351. }
  235352. return noErr;
  235353. }
  235354. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235355. {
  235356. AudioObjectPropertyAddress pa;
  235357. pa.mSelector = kAudioDevicePropertyDataSources;
  235358. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235359. pa.mElement = kAudioObjectPropertyElementMaster;
  235360. UInt32 size = 0;
  235361. if (deviceID != 0
  235362. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235363. {
  235364. types.calloc (size, 1);
  235365. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235366. return size / (int) sizeof (OSType);
  235367. }
  235368. return 0;
  235369. }
  235370. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235371. };
  235372. class CoreAudioIODevice : public AudioIODevice
  235373. {
  235374. public:
  235375. CoreAudioIODevice (const String& deviceName,
  235376. AudioDeviceID inputDeviceId,
  235377. const int inputIndex_,
  235378. AudioDeviceID outputDeviceId,
  235379. const int outputIndex_)
  235380. : AudioIODevice (deviceName, "CoreAudio"),
  235381. inputIndex (inputIndex_),
  235382. outputIndex (outputIndex_),
  235383. isOpen_ (false),
  235384. isStarted (false)
  235385. {
  235386. CoreAudioInternal* device = 0;
  235387. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235388. {
  235389. jassert (inputDeviceId != 0);
  235390. device = new CoreAudioInternal (inputDeviceId);
  235391. }
  235392. else
  235393. {
  235394. device = new CoreAudioInternal (outputDeviceId);
  235395. if (inputDeviceId != 0)
  235396. {
  235397. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235398. device->inputDevice = secondDevice;
  235399. secondDevice->isSlaveDevice = true;
  235400. }
  235401. }
  235402. internal = device;
  235403. AudioObjectPropertyAddress pa;
  235404. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235405. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235406. pa.mElement = kAudioObjectPropertyElementWildcard;
  235407. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235408. }
  235409. ~CoreAudioIODevice()
  235410. {
  235411. AudioObjectPropertyAddress pa;
  235412. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235413. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235414. pa.mElement = kAudioObjectPropertyElementWildcard;
  235415. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235416. }
  235417. const StringArray getOutputChannelNames()
  235418. {
  235419. return internal->outChanNames;
  235420. }
  235421. const StringArray getInputChannelNames()
  235422. {
  235423. if (internal->inputDevice != 0)
  235424. return internal->inputDevice->inChanNames;
  235425. else
  235426. return internal->inChanNames;
  235427. }
  235428. int getNumSampleRates()
  235429. {
  235430. return internal->sampleRates.size();
  235431. }
  235432. double getSampleRate (int index)
  235433. {
  235434. return internal->sampleRates [index];
  235435. }
  235436. int getNumBufferSizesAvailable()
  235437. {
  235438. return internal->bufferSizes.size();
  235439. }
  235440. int getBufferSizeSamples (int index)
  235441. {
  235442. return internal->bufferSizes [index];
  235443. }
  235444. int getDefaultBufferSize()
  235445. {
  235446. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235447. if (getBufferSizeSamples(i) >= 512)
  235448. return getBufferSizeSamples(i);
  235449. return 512;
  235450. }
  235451. const String open (const BigInteger& inputChannels,
  235452. const BigInteger& outputChannels,
  235453. double sampleRate,
  235454. int bufferSizeSamples)
  235455. {
  235456. isOpen_ = true;
  235457. if (bufferSizeSamples <= 0)
  235458. bufferSizeSamples = getDefaultBufferSize();
  235459. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235460. isOpen_ = lastError.isEmpty();
  235461. return lastError;
  235462. }
  235463. void close()
  235464. {
  235465. isOpen_ = false;
  235466. internal->stop (false);
  235467. }
  235468. bool isOpen()
  235469. {
  235470. return isOpen_;
  235471. }
  235472. int getCurrentBufferSizeSamples()
  235473. {
  235474. return internal != 0 ? internal->getBufferSize() : 512;
  235475. }
  235476. double getCurrentSampleRate()
  235477. {
  235478. return internal != 0 ? internal->getSampleRate() : 0;
  235479. }
  235480. int getCurrentBitDepth()
  235481. {
  235482. return 32; // no way to find out, so just assume it's high..
  235483. }
  235484. const BigInteger getActiveOutputChannels() const
  235485. {
  235486. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235487. }
  235488. const BigInteger getActiveInputChannels() const
  235489. {
  235490. BigInteger chans;
  235491. if (internal != 0)
  235492. {
  235493. chans = internal->activeInputChans;
  235494. if (internal->inputDevice != 0)
  235495. chans |= internal->inputDevice->activeInputChans;
  235496. }
  235497. return chans;
  235498. }
  235499. int getOutputLatencyInSamples()
  235500. {
  235501. if (internal == 0)
  235502. return 0;
  235503. // this seems like a good guess at getting the latency right - comparing
  235504. // this with a round-trip measurement, it gets it to within a few millisecs
  235505. // for the built-in mac soundcard
  235506. return internal->outputLatency + internal->getBufferSize() * 2;
  235507. }
  235508. int getInputLatencyInSamples()
  235509. {
  235510. if (internal == 0)
  235511. return 0;
  235512. return internal->inputLatency + internal->getBufferSize() * 2;
  235513. }
  235514. void start (AudioIODeviceCallback* callback)
  235515. {
  235516. if (internal != 0 && ! isStarted)
  235517. {
  235518. if (callback != 0)
  235519. callback->audioDeviceAboutToStart (this);
  235520. isStarted = true;
  235521. internal->start (callback);
  235522. }
  235523. }
  235524. void stop()
  235525. {
  235526. if (isStarted && internal != 0)
  235527. {
  235528. AudioIODeviceCallback* const lastCallback = internal->callback;
  235529. isStarted = false;
  235530. internal->stop (true);
  235531. if (lastCallback != 0)
  235532. lastCallback->audioDeviceStopped();
  235533. }
  235534. }
  235535. bool isPlaying()
  235536. {
  235537. if (internal->callback == 0)
  235538. isStarted = false;
  235539. return isStarted;
  235540. }
  235541. const String getLastError()
  235542. {
  235543. return lastError;
  235544. }
  235545. int inputIndex, outputIndex;
  235546. private:
  235547. ScopedPointer<CoreAudioInternal> internal;
  235548. bool isOpen_, isStarted;
  235549. String lastError;
  235550. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235551. {
  235552. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235553. switch (pa->mSelector)
  235554. {
  235555. case kAudioHardwarePropertyDevices:
  235556. intern->deviceDetailsChanged();
  235557. break;
  235558. case kAudioHardwarePropertyDefaultOutputDevice:
  235559. case kAudioHardwarePropertyDefaultInputDevice:
  235560. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235561. break;
  235562. }
  235563. return noErr;
  235564. }
  235565. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  235566. };
  235567. class CoreAudioIODeviceType : public AudioIODeviceType
  235568. {
  235569. public:
  235570. CoreAudioIODeviceType()
  235571. : AudioIODeviceType ("CoreAudio"),
  235572. hasScanned (false)
  235573. {
  235574. }
  235575. ~CoreAudioIODeviceType()
  235576. {
  235577. }
  235578. void scanForDevices()
  235579. {
  235580. hasScanned = true;
  235581. inputDeviceNames.clear();
  235582. outputDeviceNames.clear();
  235583. inputIds.clear();
  235584. outputIds.clear();
  235585. UInt32 size;
  235586. AudioObjectPropertyAddress pa;
  235587. pa.mSelector = kAudioHardwarePropertyDevices;
  235588. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235589. pa.mElement = kAudioObjectPropertyElementMaster;
  235590. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235591. {
  235592. HeapBlock <AudioDeviceID> devs;
  235593. devs.calloc (size, 1);
  235594. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  235595. {
  235596. const int num = size / (int) sizeof (AudioDeviceID);
  235597. for (int i = 0; i < num; ++i)
  235598. {
  235599. char name [1024];
  235600. size = sizeof (name);
  235601. pa.mSelector = kAudioDevicePropertyDeviceName;
  235602. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  235603. {
  235604. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  235605. const int numIns = getNumChannels (devs[i], true);
  235606. const int numOuts = getNumChannels (devs[i], false);
  235607. if (numIns > 0)
  235608. {
  235609. inputDeviceNames.add (nameString);
  235610. inputIds.add (devs[i]);
  235611. }
  235612. if (numOuts > 0)
  235613. {
  235614. outputDeviceNames.add (nameString);
  235615. outputIds.add (devs[i]);
  235616. }
  235617. }
  235618. }
  235619. }
  235620. }
  235621. inputDeviceNames.appendNumbersToDuplicates (false, true);
  235622. outputDeviceNames.appendNumbersToDuplicates (false, true);
  235623. }
  235624. const StringArray getDeviceNames (bool wantInputNames) const
  235625. {
  235626. jassert (hasScanned); // need to call scanForDevices() before doing this
  235627. if (wantInputNames)
  235628. return inputDeviceNames;
  235629. else
  235630. return outputDeviceNames;
  235631. }
  235632. int getDefaultDeviceIndex (bool forInput) const
  235633. {
  235634. jassert (hasScanned); // need to call scanForDevices() before doing this
  235635. AudioDeviceID deviceID;
  235636. UInt32 size = sizeof (deviceID);
  235637. // if they're asking for any input channels at all, use the default input, so we
  235638. // get the built-in mic rather than the built-in output with no inputs..
  235639. AudioObjectPropertyAddress pa;
  235640. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  235641. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235642. pa.mElement = kAudioObjectPropertyElementMaster;
  235643. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  235644. {
  235645. if (forInput)
  235646. {
  235647. for (int i = inputIds.size(); --i >= 0;)
  235648. if (inputIds[i] == deviceID)
  235649. return i;
  235650. }
  235651. else
  235652. {
  235653. for (int i = outputIds.size(); --i >= 0;)
  235654. if (outputIds[i] == deviceID)
  235655. return i;
  235656. }
  235657. }
  235658. return 0;
  235659. }
  235660. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  235661. {
  235662. jassert (hasScanned); // need to call scanForDevices() before doing this
  235663. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  235664. if (d == 0)
  235665. return -1;
  235666. return asInput ? d->inputIndex
  235667. : d->outputIndex;
  235668. }
  235669. bool hasSeparateInputsAndOutputs() const { return true; }
  235670. AudioIODevice* createDevice (const String& outputDeviceName,
  235671. const String& inputDeviceName)
  235672. {
  235673. jassert (hasScanned); // need to call scanForDevices() before doing this
  235674. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  235675. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  235676. String deviceName (outputDeviceName);
  235677. if (deviceName.isEmpty())
  235678. deviceName = inputDeviceName;
  235679. if (index >= 0)
  235680. return new CoreAudioIODevice (deviceName,
  235681. inputIds [inputIndex],
  235682. inputIndex,
  235683. outputIds [outputIndex],
  235684. outputIndex);
  235685. return 0;
  235686. }
  235687. private:
  235688. StringArray inputDeviceNames, outputDeviceNames;
  235689. Array <AudioDeviceID> inputIds, outputIds;
  235690. bool hasScanned;
  235691. static int getNumChannels (AudioDeviceID deviceID, bool input)
  235692. {
  235693. int total = 0;
  235694. UInt32 size;
  235695. AudioObjectPropertyAddress pa;
  235696. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235697. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235698. pa.mElement = kAudioObjectPropertyElementMaster;
  235699. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235700. {
  235701. HeapBlock <AudioBufferList> bufList;
  235702. bufList.calloc (size, 1);
  235703. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235704. {
  235705. const int numStreams = bufList->mNumberBuffers;
  235706. for (int i = 0; i < numStreams; ++i)
  235707. {
  235708. const AudioBuffer& b = bufList->mBuffers[i];
  235709. total += b.mNumberChannels;
  235710. }
  235711. }
  235712. }
  235713. return total;
  235714. }
  235715. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  235716. };
  235717. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  235718. {
  235719. return new CoreAudioIODeviceType();
  235720. }
  235721. #undef log
  235722. #endif
  235723. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  235724. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  235725. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235726. // compiled on its own).
  235727. #if JUCE_INCLUDED_FILE
  235728. #if JUCE_MAC
  235729. namespace CoreMidiHelpers
  235730. {
  235731. bool logError (const OSStatus err, const int lineNum)
  235732. {
  235733. if (err == noErr)
  235734. return true;
  235735. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235736. jassertfalse;
  235737. return false;
  235738. }
  235739. #undef CHECK_ERROR
  235740. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  235741. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  235742. {
  235743. String result;
  235744. CFStringRef str = 0;
  235745. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  235746. if (str != 0)
  235747. {
  235748. result = PlatformUtilities::cfStringToJuceString (str);
  235749. CFRelease (str);
  235750. str = 0;
  235751. }
  235752. MIDIEntityRef entity = 0;
  235753. MIDIEndpointGetEntity (endpoint, &entity);
  235754. if (entity == 0)
  235755. return result; // probably virtual
  235756. if (result.isEmpty())
  235757. {
  235758. // endpoint name has zero length - try the entity
  235759. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  235760. if (str != 0)
  235761. {
  235762. result += PlatformUtilities::cfStringToJuceString (str);
  235763. CFRelease (str);
  235764. str = 0;
  235765. }
  235766. }
  235767. // now consider the device's name
  235768. MIDIDeviceRef device = 0;
  235769. MIDIEntityGetDevice (entity, &device);
  235770. if (device == 0)
  235771. return result;
  235772. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  235773. if (str != 0)
  235774. {
  235775. const String s (PlatformUtilities::cfStringToJuceString (str));
  235776. CFRelease (str);
  235777. // if an external device has only one entity, throw away
  235778. // the endpoint name and just use the device name
  235779. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  235780. {
  235781. result = s;
  235782. }
  235783. else if (! result.startsWithIgnoreCase (s))
  235784. {
  235785. // prepend the device name to the entity name
  235786. result = (s + " " + result).trimEnd();
  235787. }
  235788. }
  235789. return result;
  235790. }
  235791. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  235792. {
  235793. String result;
  235794. // Does the endpoint have connections?
  235795. CFDataRef connections = 0;
  235796. int numConnections = 0;
  235797. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  235798. if (connections != 0)
  235799. {
  235800. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  235801. if (numConnections > 0)
  235802. {
  235803. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  235804. for (int i = 0; i < numConnections; ++i, ++pid)
  235805. {
  235806. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  235807. MIDIObjectRef connObject;
  235808. MIDIObjectType connObjectType;
  235809. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  235810. if (err == noErr)
  235811. {
  235812. String s;
  235813. if (connObjectType == kMIDIObjectType_ExternalSource
  235814. || connObjectType == kMIDIObjectType_ExternalDestination)
  235815. {
  235816. // Connected to an external device's endpoint (10.3 and later).
  235817. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  235818. }
  235819. else
  235820. {
  235821. // Connected to an external device (10.2) (or something else, catch-all)
  235822. CFStringRef str = 0;
  235823. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  235824. if (str != 0)
  235825. {
  235826. s = PlatformUtilities::cfStringToJuceString (str);
  235827. CFRelease (str);
  235828. }
  235829. }
  235830. if (s.isNotEmpty())
  235831. {
  235832. if (result.isNotEmpty())
  235833. result += ", ";
  235834. result += s;
  235835. }
  235836. }
  235837. }
  235838. }
  235839. CFRelease (connections);
  235840. }
  235841. if (result.isNotEmpty())
  235842. return result;
  235843. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  235844. return getEndpointName (endpoint, false);
  235845. }
  235846. MIDIClientRef getGlobalMidiClient()
  235847. {
  235848. static MIDIClientRef globalMidiClient = 0;
  235849. if (globalMidiClient == 0)
  235850. {
  235851. String name ("JUCE");
  235852. if (JUCEApplication::getInstance() != 0)
  235853. name = JUCEApplication::getInstance()->getApplicationName();
  235854. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  235855. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  235856. CFRelease (appName);
  235857. }
  235858. return globalMidiClient;
  235859. }
  235860. class MidiPortAndEndpoint
  235861. {
  235862. public:
  235863. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  235864. : port (port_), endPoint (endPoint_)
  235865. {
  235866. }
  235867. ~MidiPortAndEndpoint()
  235868. {
  235869. if (port != 0)
  235870. MIDIPortDispose (port);
  235871. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235872. MIDIEndpointDispose (endPoint);
  235873. }
  235874. void send (const MIDIPacketList* const packets)
  235875. {
  235876. if (port != 0)
  235877. MIDISend (port, endPoint, packets);
  235878. else
  235879. MIDIReceived (endPoint, packets);
  235880. }
  235881. MIDIPortRef port;
  235882. MIDIEndpointRef endPoint;
  235883. };
  235884. class MidiPortAndCallback;
  235885. CriticalSection callbackLock;
  235886. Array<MidiPortAndCallback*> activeCallbacks;
  235887. class MidiPortAndCallback
  235888. {
  235889. public:
  235890. MidiPortAndCallback (MidiInputCallback& callback_)
  235891. : input (0), active (false), callback (callback_), concatenator (2048)
  235892. {
  235893. }
  235894. ~MidiPortAndCallback()
  235895. {
  235896. active = false;
  235897. {
  235898. const ScopedLock sl (callbackLock);
  235899. activeCallbacks.removeValue (this);
  235900. }
  235901. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  235902. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  235903. }
  235904. void handlePackets (const MIDIPacketList* const pktlist)
  235905. {
  235906. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  235907. const ScopedLock sl (callbackLock);
  235908. if (activeCallbacks.contains (this) && active)
  235909. {
  235910. const MIDIPacket* packet = &pktlist->packet[0];
  235911. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235912. {
  235913. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  235914. input, callback);
  235915. packet = MIDIPacketNext (packet);
  235916. }
  235917. }
  235918. }
  235919. MidiInput* input;
  235920. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  235921. volatile bool active;
  235922. private:
  235923. MidiInputCallback& callback;
  235924. MidiDataConcatenator concatenator;
  235925. };
  235926. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  235927. {
  235928. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  235929. }
  235930. }
  235931. const StringArray MidiOutput::getDevices()
  235932. {
  235933. StringArray s;
  235934. const ItemCount num = MIDIGetNumberOfDestinations();
  235935. for (ItemCount i = 0; i < num; ++i)
  235936. {
  235937. MIDIEndpointRef dest = MIDIGetDestination (i);
  235938. if (dest != 0)
  235939. {
  235940. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  235941. if (name.isEmpty())
  235942. name = "<error>";
  235943. s.add (name);
  235944. }
  235945. else
  235946. {
  235947. s.add ("<error>");
  235948. }
  235949. }
  235950. return s;
  235951. }
  235952. int MidiOutput::getDefaultDeviceIndex()
  235953. {
  235954. return 0;
  235955. }
  235956. MidiOutput* MidiOutput::openDevice (int index)
  235957. {
  235958. MidiOutput* mo = 0;
  235959. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  235960. {
  235961. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  235962. CFStringRef pname;
  235963. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235964. {
  235965. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235966. MIDIPortRef port;
  235967. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  235968. {
  235969. mo = new MidiOutput();
  235970. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  235971. }
  235972. CFRelease (pname);
  235973. }
  235974. }
  235975. return mo;
  235976. }
  235977. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  235978. {
  235979. MidiOutput* mo = 0;
  235980. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235981. MIDIEndpointRef endPoint;
  235982. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  235983. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  235984. {
  235985. mo = new MidiOutput();
  235986. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  235987. }
  235988. CFRelease (name);
  235989. return mo;
  235990. }
  235991. MidiOutput::~MidiOutput()
  235992. {
  235993. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235994. }
  235995. void MidiOutput::reset()
  235996. {
  235997. }
  235998. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235999. {
  236000. return false;
  236001. }
  236002. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236003. {
  236004. }
  236005. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236006. {
  236007. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236008. if (message.isSysEx())
  236009. {
  236010. const int maxPacketSize = 256;
  236011. int pos = 0, bytesLeft = message.getRawDataSize();
  236012. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236013. HeapBlock <MIDIPacketList> packets;
  236014. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236015. packets->numPackets = numPackets;
  236016. MIDIPacket* p = packets->packet;
  236017. for (int i = 0; i < numPackets; ++i)
  236018. {
  236019. p->timeStamp = 0;
  236020. p->length = jmin (maxPacketSize, bytesLeft);
  236021. memcpy (p->data, message.getRawData() + pos, p->length);
  236022. pos += p->length;
  236023. bytesLeft -= p->length;
  236024. p = MIDIPacketNext (p);
  236025. }
  236026. mpe->send (packets);
  236027. }
  236028. else
  236029. {
  236030. MIDIPacketList packets;
  236031. packets.numPackets = 1;
  236032. packets.packet[0].timeStamp = 0;
  236033. packets.packet[0].length = message.getRawDataSize();
  236034. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236035. mpe->send (&packets);
  236036. }
  236037. }
  236038. const StringArray MidiInput::getDevices()
  236039. {
  236040. StringArray s;
  236041. const ItemCount num = MIDIGetNumberOfSources();
  236042. for (ItemCount i = 0; i < num; ++i)
  236043. {
  236044. MIDIEndpointRef source = MIDIGetSource (i);
  236045. if (source != 0)
  236046. {
  236047. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236048. if (name.isEmpty())
  236049. name = "<error>";
  236050. s.add (name);
  236051. }
  236052. else
  236053. {
  236054. s.add ("<error>");
  236055. }
  236056. }
  236057. return s;
  236058. }
  236059. int MidiInput::getDefaultDeviceIndex()
  236060. {
  236061. return 0;
  236062. }
  236063. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236064. {
  236065. jassert (callback != 0);
  236066. using namespace CoreMidiHelpers;
  236067. MidiInput* newInput = 0;
  236068. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  236069. {
  236070. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236071. if (endPoint != 0)
  236072. {
  236073. CFStringRef name;
  236074. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236075. {
  236076. MIDIClientRef client = getGlobalMidiClient();
  236077. if (client != 0)
  236078. {
  236079. MIDIPortRef port;
  236080. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236081. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236082. {
  236083. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236084. {
  236085. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236086. newInput = new MidiInput (getDevices() [index]);
  236087. mpc->input = newInput;
  236088. newInput->internal = mpc;
  236089. const ScopedLock sl (callbackLock);
  236090. activeCallbacks.add (mpc.release());
  236091. }
  236092. else
  236093. {
  236094. CHECK_ERROR (MIDIPortDispose (port));
  236095. }
  236096. }
  236097. }
  236098. }
  236099. CFRelease (name);
  236100. }
  236101. }
  236102. return newInput;
  236103. }
  236104. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236105. {
  236106. jassert (callback != 0);
  236107. using namespace CoreMidiHelpers;
  236108. MidiInput* mi = 0;
  236109. MIDIClientRef client = getGlobalMidiClient();
  236110. if (client != 0)
  236111. {
  236112. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236113. mpc->active = false;
  236114. MIDIEndpointRef endPoint;
  236115. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236116. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236117. {
  236118. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236119. mi = new MidiInput (deviceName);
  236120. mpc->input = mi;
  236121. mi->internal = mpc;
  236122. const ScopedLock sl (callbackLock);
  236123. activeCallbacks.add (mpc.release());
  236124. }
  236125. CFRelease (name);
  236126. }
  236127. return mi;
  236128. }
  236129. MidiInput::MidiInput (const String& name_)
  236130. : name (name_)
  236131. {
  236132. }
  236133. MidiInput::~MidiInput()
  236134. {
  236135. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236136. }
  236137. void MidiInput::start()
  236138. {
  236139. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236140. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236141. }
  236142. void MidiInput::stop()
  236143. {
  236144. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236145. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236146. }
  236147. #undef CHECK_ERROR
  236148. #else // Stubs for iOS...
  236149. MidiOutput::~MidiOutput() {}
  236150. void MidiOutput::reset() {}
  236151. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236152. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236153. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236154. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236155. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236156. const StringArray MidiInput::getDevices() { return StringArray(); }
  236157. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236158. #endif
  236159. #endif
  236160. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236161. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236162. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236163. // compiled on its own).
  236164. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236165. #if ! JUCE_QUICKTIME
  236166. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236167. #endif
  236168. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236169. class QTCameraDeviceInteral;
  236170. END_JUCE_NAMESPACE
  236171. @interface QTCaptureCallbackDelegate : NSObject
  236172. {
  236173. @public
  236174. CameraDevice* owner;
  236175. QTCameraDeviceInteral* internal;
  236176. int64 firstPresentationTime;
  236177. int64 averageTimeOffset;
  236178. }
  236179. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236180. - (void) dealloc;
  236181. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236182. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236183. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236184. fromConnection: (QTCaptureConnection*) connection;
  236185. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236186. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236187. fromConnection: (QTCaptureConnection*) connection;
  236188. @end
  236189. BEGIN_JUCE_NAMESPACE
  236190. class QTCameraDeviceInteral
  236191. {
  236192. public:
  236193. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236194. {
  236195. const ScopedAutoReleasePool pool;
  236196. session = [[QTCaptureSession alloc] init];
  236197. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236198. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236199. input = 0;
  236200. audioInput = 0;
  236201. audioDevice = 0;
  236202. fileOutput = 0;
  236203. imageOutput = 0;
  236204. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236205. internalDev: this];
  236206. NSError* err = 0;
  236207. [device retain];
  236208. [device open: &err];
  236209. if (err == 0)
  236210. {
  236211. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236212. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236213. [session addInput: input error: &err];
  236214. if (err == 0)
  236215. {
  236216. resetFile();
  236217. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236218. [imageOutput setDelegate: callbackDelegate];
  236219. if (err == 0)
  236220. {
  236221. [session startRunning];
  236222. return;
  236223. }
  236224. }
  236225. }
  236226. openingError = nsStringToJuce ([err description]);
  236227. DBG (openingError);
  236228. }
  236229. ~QTCameraDeviceInteral()
  236230. {
  236231. [session stopRunning];
  236232. [session removeOutput: imageOutput];
  236233. [session release];
  236234. [input release];
  236235. [device release];
  236236. [audioDevice release];
  236237. [audioInput release];
  236238. [fileOutput release];
  236239. [imageOutput release];
  236240. [callbackDelegate release];
  236241. }
  236242. void resetFile()
  236243. {
  236244. [fileOutput recordToOutputFileURL: nil];
  236245. [session removeOutput: fileOutput];
  236246. [fileOutput release];
  236247. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236248. [session removeInput: audioInput];
  236249. [audioInput release];
  236250. audioInput = 0;
  236251. [audioDevice release];
  236252. audioDevice = 0;
  236253. [fileOutput setDelegate: callbackDelegate];
  236254. }
  236255. void addDefaultAudioInput()
  236256. {
  236257. NSError* err = nil;
  236258. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236259. if ([audioDevice open: &err])
  236260. [audioDevice retain];
  236261. else
  236262. audioDevice = nil;
  236263. if (audioDevice != 0)
  236264. {
  236265. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236266. [session addInput: audioInput error: &err];
  236267. }
  236268. }
  236269. void addListener (CameraDevice::Listener* listenerToAdd)
  236270. {
  236271. const ScopedLock sl (listenerLock);
  236272. if (listeners.size() == 0)
  236273. [session addOutput: imageOutput error: nil];
  236274. listeners.addIfNotAlreadyThere (listenerToAdd);
  236275. }
  236276. void removeListener (CameraDevice::Listener* listenerToRemove)
  236277. {
  236278. const ScopedLock sl (listenerLock);
  236279. listeners.removeValue (listenerToRemove);
  236280. if (listeners.size() == 0)
  236281. [session removeOutput: imageOutput];
  236282. }
  236283. void callListeners (CIImage* frame, int w, int h)
  236284. {
  236285. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236286. Image image (cgImage);
  236287. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236288. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236289. CGContextFlush (cgImage->context);
  236290. const ScopedLock sl (listenerLock);
  236291. for (int i = listeners.size(); --i >= 0;)
  236292. {
  236293. CameraDevice::Listener* const l = listeners[i];
  236294. if (l != 0)
  236295. l->imageReceived (image);
  236296. }
  236297. }
  236298. QTCaptureDevice* device;
  236299. QTCaptureDeviceInput* input;
  236300. QTCaptureDevice* audioDevice;
  236301. QTCaptureDeviceInput* audioInput;
  236302. QTCaptureSession* session;
  236303. QTCaptureMovieFileOutput* fileOutput;
  236304. QTCaptureDecompressedVideoOutput* imageOutput;
  236305. QTCaptureCallbackDelegate* callbackDelegate;
  236306. String openingError;
  236307. Array<CameraDevice::Listener*> listeners;
  236308. CriticalSection listenerLock;
  236309. };
  236310. END_JUCE_NAMESPACE
  236311. @implementation QTCaptureCallbackDelegate
  236312. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236313. internalDev: (QTCameraDeviceInteral*) d
  236314. {
  236315. [super init];
  236316. owner = owner_;
  236317. internal = d;
  236318. firstPresentationTime = 0;
  236319. averageTimeOffset = 0;
  236320. return self;
  236321. }
  236322. - (void) dealloc
  236323. {
  236324. [super dealloc];
  236325. }
  236326. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236327. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236328. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236329. fromConnection: (QTCaptureConnection*) connection
  236330. {
  236331. if (internal->listeners.size() > 0)
  236332. {
  236333. const ScopedAutoReleasePool pool;
  236334. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236335. CVPixelBufferGetWidth (videoFrame),
  236336. CVPixelBufferGetHeight (videoFrame));
  236337. }
  236338. }
  236339. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236340. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236341. fromConnection: (QTCaptureConnection*) connection
  236342. {
  236343. const Time now (Time::getCurrentTime());
  236344. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236345. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236346. #else
  236347. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236348. #endif
  236349. int64 presentationTime = (hosttime != nil)
  236350. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236351. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236352. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236353. if (firstPresentationTime == 0)
  236354. {
  236355. firstPresentationTime = presentationTime;
  236356. averageTimeOffset = timeDiff;
  236357. }
  236358. else
  236359. {
  236360. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236361. }
  236362. }
  236363. @end
  236364. BEGIN_JUCE_NAMESPACE
  236365. class QTCaptureViewerComp : public NSViewComponent
  236366. {
  236367. public:
  236368. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236369. {
  236370. const ScopedAutoReleasePool pool;
  236371. captureView = [[QTCaptureView alloc] init];
  236372. [captureView setCaptureSession: internal->session];
  236373. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236374. setView (captureView);
  236375. }
  236376. ~QTCaptureViewerComp()
  236377. {
  236378. setView (0);
  236379. [captureView setCaptureSession: nil];
  236380. [captureView release];
  236381. }
  236382. QTCaptureView* captureView;
  236383. };
  236384. CameraDevice::CameraDevice (const String& name_, int index)
  236385. : name (name_)
  236386. {
  236387. isRecording = false;
  236388. internal = new QTCameraDeviceInteral (this, index);
  236389. }
  236390. CameraDevice::~CameraDevice()
  236391. {
  236392. stopRecording();
  236393. delete static_cast <QTCameraDeviceInteral*> (internal);
  236394. internal = 0;
  236395. }
  236396. Component* CameraDevice::createViewerComponent()
  236397. {
  236398. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236399. }
  236400. const String CameraDevice::getFileExtension()
  236401. {
  236402. return ".mov";
  236403. }
  236404. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236405. {
  236406. stopRecording();
  236407. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236408. d->callbackDelegate->firstPresentationTime = 0;
  236409. file.deleteFile();
  236410. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236411. // out wrong, so we'll put some audio in there too..,
  236412. d->addDefaultAudioInput();
  236413. [d->session addOutput: d->fileOutput error: nil];
  236414. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236415. for (;;)
  236416. {
  236417. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236418. if (connection == 0)
  236419. break;
  236420. QTCompressionOptions* options = 0;
  236421. NSString* mediaType = [connection mediaType];
  236422. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236423. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236424. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236425. : @"QTCompressionOptions240SizeH264Video"];
  236426. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236427. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236428. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236429. }
  236430. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236431. isRecording = true;
  236432. }
  236433. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236434. {
  236435. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236436. if (d->callbackDelegate->firstPresentationTime != 0)
  236437. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236438. return Time();
  236439. }
  236440. void CameraDevice::stopRecording()
  236441. {
  236442. if (isRecording)
  236443. {
  236444. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236445. isRecording = false;
  236446. }
  236447. }
  236448. void CameraDevice::addListener (Listener* listenerToAdd)
  236449. {
  236450. if (listenerToAdd != 0)
  236451. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236452. }
  236453. void CameraDevice::removeListener (Listener* listenerToRemove)
  236454. {
  236455. if (listenerToRemove != 0)
  236456. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236457. }
  236458. const StringArray CameraDevice::getAvailableDevices()
  236459. {
  236460. const ScopedAutoReleasePool pool;
  236461. StringArray results;
  236462. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236463. for (int i = 0; i < (int) [devs count]; ++i)
  236464. {
  236465. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236466. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236467. }
  236468. return results;
  236469. }
  236470. CameraDevice* CameraDevice::openDevice (int index,
  236471. int minWidth, int minHeight,
  236472. int maxWidth, int maxHeight)
  236473. {
  236474. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236475. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236476. return d.release();
  236477. return 0;
  236478. }
  236479. #endif
  236480. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236481. #endif
  236482. #endif
  236483. END_JUCE_NAMESPACE
  236484. #endif
  236485. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236486. #endif
  236487. #endif